nemo_automodel.components.distributed.pipelining.functional
nemo_automodel.components.distributed.pipelining.functional
Module Contents
Classes
Functions
Data
API
Callable protocol for applying distributed parallelism to a model.
Reject an explicit partition that omits, repeats, invents or reorders a decoder layer.
A trimmed stage sees only its own modules, so a layer that no stage retains runs zero times, a layer that two stages retain runs twice, and layers assigned to stages out of order run out of order, while the stages’ wire contracts still match.
Fail fast if a stage re-initialization would run dynamic metadata inference.
reset_pp_stage_shapes runs on each rank when its own sequence length changes.
Dynamic inference would run a real forward/backward and an FSDP reshard on that
rank only, so its DP peers would never post the matching collectives.
Extract hidden_size and vocab_size from a model config.
Handles both flat configs (LLM) and nested configs where these attributes
live under text_config (VLM models such as Qwen3-VL, LLaVA, etc.).
Precompute input/output meta tensors for each pipeline stage to bypass serial shape inference.
By default, PipelineStage performs shape inference at runtime via a serial P2P chain: stage 0 → send → stage 1 → send → … → stage N-1. This is O(N) in the number of pipeline stages and becomes a bottleneck for large world sizes.
This function installs static input/output metadata on each stage before the first
step() call, so runtime shape inference is never invoked and the serial chain is
completely eliminated.
Parameters:
The local pipeline stages (already parallelized).
The HuggingFace model config (model.config).
Microbatch size used by the pipeline schedule.
Sequence length of the input data.
Returns: int
Maximum local token count across stage outputs for runtime initialization.
Keep stage re-initialization free of FSDP side effects in static metadata mode.
_initialize_pp_stages ends by calling _post_metadata_inference_cleanup
on every stage, which reshards every FSDP module of the stage and sets
param.grad = None. Upstream that is safe: it assumes initialization happens
once, before any real step, and only undoes the side effects of dynamic
metadata inference.
reset_pp_stage_shapes breaks that assumption. It re-initializes the stages
whenever this rank’s sequence length changes. Under gradient accumulation the
cleanup would discard the gradients accumulated so far, and in evaluation the
reshard makes only the re-initialized rank gather again, so its DP peers never
post the matching all-gathers and the ranks hang.
With static metadata no inference forward/backward runs, so nothing is gathered, no gradients are stale and nothing is stored. Skip the cleanup in that case, and leave dynamic mode alone, where the cleanup is doing real work.
Parameters:
The local pipeline stages to protect.
Set static pipeline metadata across supported PyTorch APIs.
Return the decoder layers a stage retains under the splitter’s rules.
The splitter keeps a module whole when its FQN is listed, so a listed ancestor of the layer container
(model.layers or model) retains every layer; otherwise a layer is retained when its own FQN is
listed.
Select static metadata when every Torch 2.12 pipeline stage supports it.
Initialize the pairwise NCCL communicators used by a pipeline stage.
Make a pipeline stage’s forward emit a tensor, not a ModelOutput.
Custom *ForCausalLM / *ForConditionalGeneration models now return a
CausalLMOutputWithPast from forward (fused-linear cross-entropy
support). torch.distributed.pipelining
requires every stage to emit a tensor (or tuple/list of tensors):
PipelineStage._validate_fwd_outputs and the inter-stage P2P send/recv
treat the output as tensor leaves and read .shape on each, which raises
AttributeError: 'CausalLMOutputWithPast' object has no attribute 'shape'.
The stage’s outer forward is left intact (a) for models that opt out of
patching via _pp_keep_self_forward and (b) for MoE configs that set
patch_causal_lm_model=False so only the inner model is patched. In both
cases the kept outer forward returns a ModelOutput. This wraps it so
the return is unwrapped to its .logits tensor:
Those forwards put the projected logits there on the final stage
and the pass-through hidden_states on non-final stages (lm_head is None) — exactly the tensor each stage must forward, and the logits the
last-stage loss (PipelineCausalLMLoss / MaskedCrossEntropy) consumes.
No-op when forward already returns a tensor or a tuple (the patched
create_pipeline_forward_causal_lm path, and MTP models that emit a
(logits, *mtp, seq_idx) tuple), since only ModelOutput is unwrapped.
Builds a pipeline schedule for the given job configuration and stages.
Parameters:
The path to the pipeline parallel schedule csv file.
The name of the pipeline parallel schedule.
The microbatch size.
The local batch size.
The stages to be scheduled.
The loss function.
Returns: _PipelineSchedule
A schedule whose step() and eval() discard outputs by default.
Calculate virtual pipeline stages and layers per stage.
Generates module names for each pipeline stage for HuggingFace models.
Example
generate_hf_model_split(4, 32) might return: [ [“model.embed_tokens”, “model.layers.0”, …, “model.layers.7”], [“model.layers.8”, …, “model.layers.15”], [“model.layers.16”, …, “model.layers.23”], [“model.layers.24”, …, “model.layers.31”, “model.norm”, “lm_head”] ]
Parameters:
Number of pipeline stages
Total number of transformer layers in the model
Whether to include embedding layer in first stage
Whether to include lm_head in last stage (for CausalLM models)
Whether to include common vision/audio encoder modules in stage 0
Optional list of extra module FQNs to include in stage 0
Returns: list[list[str]]
List of lists containing module names for each stage
HF-specific pipeline model splitting.
Reset pipeline stage infrastructure and recompute shapes for a new sequence length.
VLM training produces batches with highly variable sequence lengths (image tokens expand
the sequence dramatically). PyTorch’s PipelineStage locks in output shapes and recv
buffer sizes on the first schedule.step() call (_stages_initialized = True).
Subsequent steps with a different seq_len therefore hit a shape-mismatch error.
This function resets the per-stage infrastructure so that _initialize_stages re-runs
on the next step() call. It then calls _precompute_stage_shapes to set the
correct shapes analytically — avoiding the expensive real-valued forward pass that
_shape_inference would otherwise perform.
Parameters:
The active pipeline schedule.
The local pipeline stages for this rank.
The HuggingFace model config (model.config).
Per-microbatch batch size used by the schedule.
Sequence length of the upcoming batch (e.g. input_ids.shape[1]).
Returns: int
Maximum local token count across the recomputed stage outputs.
Scale pipeline stage gradients by a common divisor when supported.
Splits a HuggingFace model for pipeline parallelism.
Parameters:
The HuggingFace model to split
Pipeline parallel device mesh
Name of pipeline parallelism schedule
Device to place stages on
Optional manual specification of modules per stage
Number of pipeline stages (used if module_names_per_stage not provided)
Returns: list[PipelineStage]
Tuple of (stages, models) where stages are PipelineStage objects and models are the
Compute the stage ids for the stages that will run on this pp rank for either a looped or V style schedule