nemo_automodel.components.distributed
nemo_automodel.components.distributed
Subpackages
nemo_automodel.components.distributed.blockdiag_cpnemo_automodel.components.distributed.context_parallelnemo_automodel.components.distributed.pipelining
Submodules
nemo_automodel.components.distributed.activation_checkpointingnemo_automodel.components.distributed.confignemo_automodel.components.distributed.cp_vision_frame_shardnemo_automodel.components.distributed.ddpnemo_automodel.components.distributed.fsdp2nemo_automodel.components.distributed.fsdp_patchesnemo_automodel.components.distributed.grad_utilsnemo_automodel.components.distributed.init_utilsnemo_automodel.components.distributed.megatron_fsdpnemo_automodel.components.distributed.meshnemo_automodel.components.distributed.mesh_utilsnemo_automodel.components.distributed.model_parallelizernemo_automodel.components.distributed.multimodal_fsdpnemo_automodel.components.distributed.optimized_tp_plansnemo_automodel.components.distributed.parallel_stylesnemo_automodel.components.distributed.parallelizernemo_automodel.components.distributed.parallelizer_utilsnemo_automodel.components.distributed.recompute_replaynemo_automodel.components.distributed.tensor_utilsnemo_automodel.components.distributed.thd_utilsnemo_automodel.components.distributed.tp_replicasnemo_automodel.components.distributed.utils
Package Contents
Classes
Functions
API
Additional configuration for DDP distributed training.
Note: DDP does not support tensor parallelism, pipeline parallelism, or expert parallelism. Only dp_size is relevant (inferred from world_size).
Enable activation checkpointing. True or
"full" keeps the existing full activation checkpointing behavior. "selective" wraps transformer
blocks with PyTorch selective activation checkpointing.
Which extracted
layer groups activation checkpointing should wrap. "all"
selects every extracted group. Scoped values such as
"language", "vision", and "multimodal" are filtered
to trainable layers before generic wrapping.
If set, recipes can wrap the forward pass in
torch.autocast(device_type="cuda", dtype=autocast_dtype). Set to None to disable.
Can be set from YAML as a string (e.g. autocast_dtype: bfloat16).
Synchronize module buffers before each forward.
DDP gradient bucket size in MiB. None uses PyTorch’s default.
Forwarded to PyTorch DDP for models with conditionally unused trainable parameters.
Make gradients views into DDP buckets after the first iteration.
Tell DDP the used/unused parameter set is stable.
Convert config to dictionary.
Holds information about the distributed training environment.
The backend used for torch.distributed (e.g., ‘nccl’).
The device assigned to the current process.
True if the process is the main process (rank 0).
The rank of the current process.
The total number of processes.
Resolved distributed topology and execution policies.
Keep the compatibility bundle and its MeshContext policy in sync.
Create a resolved distributed setup from sizes and policy configs.
Intentionally, this function is forgiving wrt the input types, allowing strings for the strategy and dicts for the pipeline and MoE configs.
Additional configuration for FSDP2 distributed training.
Note: Size parameters (dp_size, dp_replicate_size, tp_size, pp_size, cp_size, ep_size)
are grouped separately in ParallelismSizes.
Enable activation checkpointing. True or
"full" keeps the existing full activation checkpointing behavior. "selective" wraps transformer
blocks with PyTorch selective activation checkpointing.
Which extracted
layer groups activation checkpointing should wrap. "all"
selects every extracted group. Scoped values such as
"language", "vision", and "multimodal" are filtered
to trainable layers before generic wrapping.
If set, wraps the forward pass in
torch.autocast(device_type="cuda", dtype=autocast_dtype). Use with
output_dtype=float32 in mp_policy to keep the residual stream in fp32
while running matmuls in lower precision. Set to None to disable.
Can be set from YAML as a string (e.g. autocast_dtype: bfloat16).
Defer FSDP gradient sync to final micro-batch.
Enable async tensor parallelism via
torch._inductor.config._micro_pipeline_tp. Overlaps ReduceScatter with
compute in row-parallel layers. Requires sequence_parallel=True (forced
automatically with a warning if not set). Also enables symmetric memory for
the TP group.
Apply per-layer torch.compile to transformer decoder
layers (with NO_REENTRANT activation checkpointing inside each compiled layer).
Skips whole-model compile so that checkpoint loading does not produce
_orig_mod key-prefix mismatches.
Enable explicit forward/backward prefetch chains
between FSDP2 sharded layers. Default True.
Number of FSDP units to prefetch during
backward pass. 2 hides AllGather behind compute; 1 reduces peak
memory at a small throughput cost. Default 2.
Number of FSDP units to prefetch during
forward pass. Default 1.
MixedPrecisionPolicy for FSDP2.
If None (default), uses bf16 forward/backward compute with fp32
gradient reduction, preserving the dtypes of module inputs and outputs.
Pair this with model.torch_dtype: float32 for
the Megatron-style fp32 master-weights pattern. Override from YAML
using the _target_ pattern::
mp_policy: target: torch.distributed.fsdp.MixedPrecisionPolicy param_dtype: bfloat16 reduce_dtype: float32 output_dtype: null cast_forward_inputs: false
See docs/guides/mixed-precision-training.md for the full set of recommended
patterns and the bf16-storage trap.
Policies for resolved multimodal modules that use the text model’s distributed axes.
CPUOffloadPolicy for CPU offloading.
Patch transformers._is_packed_sequence to always
return Python False. This does two things: (1) removes a CPU-GPU sync per
attention layer (aten::is_nonzero triggered by HF when batch_size==1), and
(2) ensures static attention shapes for torch.compile. Safe for standard
(non-packed) training only. Disable if using packed-sequence training
(position_ids that reset to 0 mid-sequence). Default False.
Override layer-level FSDP2 resharding.
None preserves AutoModel’s heuristic: pipeline-parallel layers do
not reshard after forward, while non-pipeline layers reshard all but
the last layer. Set False for a ZeRO-2-like benchmark where
gathered parameters stay resident after forward. Set True to force
resharding everywhere, including pipeline-parallel layers, which may
reduce throughput by adding per-microbatch all-gathers.
Enable sequence parallelism in TP plan.
Custom TP plan. If None, auto-selected based on model type.
Convert config to dictionary (shallow, preserves policy objects).
Additional configuration for MegatronFSDP distributed training.
Note: Size parameters (dp_size, tp_size, cp_size) are grouped separately in
ParallelismSizes. MegatronFSDP does not
support pp_size, dp_replicate_size, or ep_size.
Enable activation checkpointing for transformer MLP layers to save memory.
Average in collective if True.
Calculate per token loss if True.
Legacy buffer-level gradient NaN check. BREAKING CHANGE on megatron-fsdp 0.5.0: this flag is a no-op, preserved only for config compatibility. 0.5.0 removed the buffer-level NaN check entirely, so gradient NaN checking is now OFF regardless of this value; a truthy value is dropped with a one-time warning. The default is kept True for config compatibility, but has no effect. To restore gradient NaN checking, enable report_nan_in_param_grad instead.
Disable bucketing if True.
Use double buffer if True.
Reduce gradients in fp32 if True.
Initialize MegatronFSDP with meta device if True.
Keep fp8 transpose cache when using custom FSDP if True.
Class paths of the submodules to wrap
as individual MegatronFSDP units. When None (the default), the wrap classes
are auto-derived from the model’s _no_split_modules so the real instantiated
block classes are used regardless of backend (HF or NeMo-custom).
Use NCCL UBs if True.
Overlap gradient reduction if True.
Overlap parameter gathering if True.
Preserve fp32 weights if True.
Enable megatron-fsdp 0.5.0’s precise per-parameter gradient NaN check. This is the replacement for the removed check_for_nan_in_grad and is OFF by default; enabling it can significantly reduce training throughput.
Data parallel sharding strategy.
Convert config to dictionary (shallow, preserves objects).
Resolved runtime context for model parallelization.
Parallelism sizes (tp_size, pp_size, etc.) are not stored as
fields; they are @property accessors that read directly from the
attached DeviceMesh / moe_mesh. When no mesh is present the
properties return safe defaults (1 for sizes, None for dp / hsdp).
All DeviceMesh objects passed in must use axis names from
MeshAxisName; a ValueError is raised on construction if
any unknown name is encountered.
Lifecycle
- Recipes parse YAML to obtain sizes and strategy configs.
- Sizes are passed to
buildto buildDeviceMeshobjects. MeshContextis created with those meshes; axis names are validated automatically in__post_init__.
Alternatively, from_meshes constructs an instance directly from
DeviceMesh objects (used by NeMoAutoModel.from_pretrained).
Resolved activation-checkpointing mode.
Ring-attention factor of the context-parallel axis.
Context-parallel degree (from device_mesh, default 1).
Ulysses factor of the context-parallel axis. None
lets the consumer use the full context-parallel axis.
Device mesh for distributed training.
HSDP replication degree (from device_mesh, default None).
DP shard degree (from device_mesh, default 1).
Data-parallel degree (from device_mesh, default None).
Expert-parallel degree (from moe_mesh, default 1).
MoE-specific device mesh.
Optional MoE-specific parallelization policy.
True when pp_size > 1.
Pipeline-parallel degree (from device_mesh, default 1).
Optional model-local group for recipe-level collectives that must not involve ranks outside this mesh.
Optional callback run after model surgery and before distributed wrapping.
Resolved DDP, FSDP2, or Megatron-FSDP policy.
Tensor-parallel degree (from device_mesh, default 1).
DP axis names for FSDP mesh slicing.
Build a resolved MeshContext from sizes and execution policy.
Parameters:
Already-instantiated distributed strategy config.
Requested data, tensor, pipeline, context, and expert
parallelism sizes. If None, defaults to no parallelism with
DP inferred from world_size.
Optional MoE-specific parallelization policy.
Activation-checkpointing mode applied by the model sidecar.
Optional callback run after model surgery and before distributed wrapping.
Ring-attention factor of the context-parallel axis.
Ulysses factor of the context-parallel axis.
Total process count. If None, inferred from the
distributed environment.
Optional timeout for process groups created by
DeviceMesh axes.
Optional ordered global ranks to use for the mesh. When omitted, the mesh uses every rank in the default process group.
Build a MeshContext from DeviceMesh objects.
This is the entry-point used by NeMoAutoModel.from_pretrained /
from_config where the caller has raw meshes rather than a parsed
YAML config.
Parameters:
Primary device mesh.
Optional MoE-specific device mesh.
Resolved DDP, FSDP2, or Megatron-FSDP policy.
Optional MoE-specific parallelization policy.
Activation-checkpointing mode applied by the model sidecar.
Optional callback run after model surgery and before distributed wrapping.
Ring-attention factor of the context-parallel axis.
Ulysses factor of the context-parallel axis.
Axis-name kwargs for parallelize_fn (EP/FSDP, no pp_axis_name).
Axis-name kwargs for AutoPipeline.
Configuration for MoE model parallelization (EP + FSDP settings).
Single model-owned parallelization sidecar contract.
Apply the shared dense FSDP2 implementation.
Wrap the model’s submodules into FSDP2 units.
Model-owned sidecar strategies deriving from this class override this
hook to change how parameters are grouped into FSDP units without
reimplementing the surrounding TP/AC/mixed-precision flow. Override
_fully_shard_module when a model needs a different primitive.
Apply the FSDP2 primitive used by this model sidecar.
Give large trainable untied embedding tables independent FSDP buffers.
The generic dense path otherwise leaves both tables in the root FSDP unit.
With fp32 gradient reduction, that unit allocates one contiguous
reduce-scatter input containing both gradients. Keeping the two trainable
leaf modules in separate FSDP units bounds that allocation by the larger
table instead of their sum. This pass skips tied tables to preserve aliasing,
and frozen tables because they have no gradient communication buffer
to split. Tables already wrapped as FSDP units retain their existing
reshard policy. With an explicit reshard_after_forward=True, a
container-hosted head reshards while a newly split top-level head stays
gathered. FusedLinearCrossEntropy handles the sharded weight with correct
gradients, at the cost of an extra all-gather.
Parameters:
Model whose input and output embedding modules may be sharded.
Device mesh that owns the FSDP shards.
Mixed-precision policy used by the surrounding FSDP units.
Optional offload policy used by the surrounding FSDP units.
Whether the input embedding unit reshards its parameters after forward.
Return whether this model safely opts into whole-layer checkpointing.
Validate the model’s attention topology against its TP mesh.
Apply every requested parallelism and return the parallelized model.
Distributed policies for resolved multimodal modules.
Controls fully frozen multimodal modules such as
vision/audio towers and projectors. "root" (default) keeps
their parameters in an always-run outer FSDP root, which is safe
when modality execution differs across ranks. "per_layer"
uses normal layer/container FSDP units and requires every rank in
the FSDP group to execute or skip the module identically on every
microbatch. "replicate" excludes the frozen parameters from
FSDP roots so each rank keeps a full copy. Modules with any
trainable parameters use normal layer/container sharding
regardless of this setting.
Policies that apply specifically to resolved vision modules.
Build-time requested parallelism sizes.
This is durable user intent, not runtime topology. MeshContext derives
its size properties from live DeviceMesh objects after build.
Configuration for pipeline parallel training.
Note: Device mesh (world_mesh, moe_mesh) is passed separately on the from_pretrained/from_config method signature. Pipeline parallelism is enabled when pp_size > 1. Axis names are inferred automatically from the device mesh structure.
Data type for pipeline computation. If None, uses the model’s default dtype.
Number of transformer layers per pipeline stage. If None, layers are split evenly across stages.
Loss function used for pipeline training. Required when pipeline is enabled. The function signature should be compatible with the model’s output format.
Explicit specification of which module FQNs belong to each model part/stage. If provided, overrides automatic layer splitting.
Apply pipeline patches to the CausalLM wrapper model. Defaults to True.
Apply pipeline patches to the inner model (e.g., the base transformer in a CausalLM wrapper). Defaults to True.
Patch stage backward to use no_sync context for gradient accumulation efficiency. Useful when combining PP with FSDP.
Total batch size per pipeline stage. Must be divisible by pp_microbatch_size.
Size of each microbatch for pipeline execution. pp_batch_size must be divisible by pp_microbatch_size.
Pool the per-microbatch P2P recv buffers into a ring sized to the 1F1B in-flight depth instead of pre-allocating one buffer set per microbatch and direction. Cuts pipeline-stage buffer memory roughly by num_microbatches / (num_stages - stage_index + slack) on early/middle stages. For native interleaved 1F1B, receives are pooled using the lowered schedule’s actual lifetimes. Inputs are copied into independent leaves before forward, and gradients are copied before backward to protect checkpoint recomputation and escaping aliases. Other schedules are ignored with a warning. Defaults to False.
Extra buffer sets beyond the 1F1B in-flight depth when pp_recv_buffer_pool is enabled. Defaults to 2.
Pipeline schedule type. Supported values: “1f1b” (one-forward-one-backward), “gpipe”, “interleaved_1f1b”, “looped_bfs”, “dfs”, “v_schedule”, “zero_bubble”. Defaults to “1f1b”.
Path to a CSV file defining a custom pipeline schedule. If provided, overrides pp_schedule.
Sequence length hint for pipeline parallel shape inference. If None, it will be inferred from the dataset config.
When using virtual stages (interleaved schedules), round the number of virtual stages to a multiple of pp_size. “up” rounds up, “down” rounds down. If None, no rounding is applied.
Scale gradients within the pipeline schedule (by 1/n_microbatches). If False, gradients must be scaled externally. Defaults to False.
Validate the recv-buffer-pool knobs.
Convert config to dictionary.
Initialize the torch.distributed environment and core model parallel infrastructure.
This function sets the device based on the local rank, configures the process group, and calls torch.distributed.init_process_group with the appropriate parameters. It also registers a cleanup function to properly destroy the process group at exit.
Parameters:
The backend to use for torch.distributed (e.g., ‘nccl’).
Timeout (in minutes) for distributed initialization. Defaults to 1.
Returns:
An instance containing the distributed environment configuration.