nemo_automodel.components.training.utils
nemo_automodel.components.training.utils
Module Contents
Classes
Functions
Data
API
Context manager that temporarily moves a module between CPU and CUDA.
All-reduce a 0-dim norm accumulator over mesh, communicating on the mesh device.
The norm math stays on the gradients’ own device, which under FSDP2
CPUOffloadPolicy is CPU while the mesh’s process group is NCCL and has no CPU
backend. Only the scalar hops to mesh.device_type for the collective and comes
straight back, so a genuinely-CPU (gloo) mesh is never forced onto an accelerator.
Parameters:
0-dim tensor to reduce, on the gradients’ device.
Reduction operation.
Device mesh whose process group performs the collective.
Mesh dimension to reduce over, or None for the whole mesh.
Returns: torch.Tensor
The reduced scalar on scalar’s original device. Callers must use the return
Compute and clip the norm of local and DTensor gradients.
Parameters:
One parameter tensor or an iterable of parameter tensors with arbitrary shapes. DTensors retain their declared mesh and placements.
Maximum allowed global gradient norm.
Norm exponent, including inf.
Whether to raise for a non-finite global norm.
Optional foreach implementation preference for clipping.
Optional pipeline mesh over which the scalar norm is reduced.
Local L2 reducer. "triton" uses this PR’s FP64
multi-tensor kernel; "te" uses Transformer Engine where eligible.
Returns: torch.Tensor
Scalar tensor containing the pre-clipping global gradient norm.
Reduce local gradients with Transformer Engine where supported.
Parameters:
Plain local tensors of arbitrary shape, without DTensor placements. Contiguous CUDA FP16/BF16/FP32 tensors use TE, grouped by device and dtype. Other layouts, devices, and dtypes use PyTorch’s FP64 vector norm. Inputs are read-only and may alias parameter gradients.
Device for the returned scalar; only scalars move between devices.
Returns: torch.Tensor
Independent scalar FP64 L2 norm on target_device. TE squares and accumulates
Raises:
RuntimeError: If eligible CUDA gradients require TE but TE is unavailable.
Whether the fused multi-tensor reduction applies to this group.
Only the 2-norm and inf-norm are implemented by the kernel, and the whole group has to be CUDA — a mixed CPU/CUDA group would silently take two different reduction paths.
Apply sharding-aware gradient clipping.
Handles all parallelism strategies (TP, PP, EP/MoE) with automatic sharding-aware grouping. Returns the gradient norm as a scalar tensor on the gradients’ device, or 0.0 if clipping is skipped. This function does not synchronize TP-replicated gradients; optimizer loops must do that exactly once before calling this function.
This function automatically:
- Groups parameters by sharding pattern (device mesh + placements)
- Computes norms correctly across different sharding strategies
- Handles MoE with separate DP/EP meshes
- Reduces norms across pipeline parallel stages when enabled
Parameters:
Maximum gradient norm. If None, skips clipping.
List of model modules to clip.
Type of norm to use (default: 2.0 for L2).
Whether pipeline parallelism is enabled.
Device mesh for parallelism.
Pipeline parallel axis name.
Whether to use foreach implementation for clipping.
Use PyTorch’s optimized regular-tensor clipping path when possible.
Local L2 reducer, either "triton" or "te".
Returns: torch.Tensor | float
Scalar tensor containing the total gradient norm without synchronizing it to the host,
Counts the total number of padding token in the tail of labels
e.g. labels = torch.tensor([ [-100, 1, 1, -100, -100], # 2 tail -100s [-100, -100, 2, 3, 4], # 0 tail -100s [5, 6, -100, -100, -100], # 3 tail -100s ]) count_tail_padding will return 5. Please do note there’s more than 5 ignore labels. Args: labels (torch.Tensor): the labels ignore_label (int, optional): ignore label index. Defaults to -100.
Returns:
total number of ignored tokens in the labels input.
Return the TP token-replication factor for custom-MoE expert gradients.
The custom-MoE tensor-parallel path keeps the token path (attention,
router) replicated across TP ranks, so every TP rank feeds the same tokens
into the expert-parallel all-gather and each expert gradient is accumulated
tp_size times. scale_grads_and_clip_grad_norm divides expert
gradients by this factor to restore the correct scale.
Move a model and its buffers to a device and release stale CUDA cache.
Disable first-microbatch flag after the first forward-backward pass.
Called after the first microbatch in gradient accumulation so that subsequent microbatches reuse cached FP8 weights instead of re-quantizing.
Prepare model parts before the final backward pass.
This is typically called before the final gradient accumulation step to prepare FSDP states for gradient synchronization and resharding.
Parameters:
List of model parts (modules) to prepare.
Whether pipeline parallelism is enabled.
Prepare model parts before starting gradient accumulation.
This is typically called once at the start of gradient accumulation to prepare FSDP states for the upcoming forward and backward passes.
Parameters:
List of model parts (modules) to prepare.
Whether pipeline parallelism is enabled.
Scale gradients for PP/EP and model-owned shards, then clip.
The caller must synchronize TP-replicated gradients once after accumulation and before calling this function. This helper does not synchronize replicas.
- PP scaling: divide all local grads by (num_label_tokens / dp_group_size).
- EP scaling: for parameters on the expert axis, divide grads by
(dp_group_size / ep_shard_size) * expert_tp_replication_factor. - Owner-sharded scaling: divide each marked gradient by the explicit factor declared by its model-owned sharding contract.
- Finally, perform grad clipping with PP/EP-aware reductions.
Parameters:
Maximum global gradient norm, or None to skip clipping.
Model modules whose parameters have gradients of arbitrary shape. Gradients retain their original local or DTensor layout and are scaled in place.
Norm order.
Whether pipeline-parallel normalization is required.
Training mesh used for gradient norm reductions.
Expert-parallel mesh used to normalize expert gradients.
Expert axis in the parameter mesh.
Pipeline axis in the training mesh.
Whether to use foreach for in-place clipping.
Global supervised-token count for PP normalization.
Data-parallel group size, including CP when configured.
Number of identical TP copies of expert tokens.
Prefer PyTorch’s regular-tensor clipping fast path.
Local L2 reducer, either "triton" or "te".
Returns: torch.Tensor | float
Scalar tensor containing the total gradient norm without synchronizing it to the host,