nemo_automodel.components.models.beam.layers
nemo_automodel.components.models.beam.layers
Beam gated attention, root10 SSMax, rotary precision, and SwiGLU/router overrides.
Module Contents
Classes
Functions
Data
API
Bases: Module
Gated attention with per-head q/k RMSNorm and full-width output gating.
Layer type selects full/sliding attention and RoPE or NoPE+SSMax.
Run backend attention with the correct packed and sliding-window conventions.
Parameters:
Tensor of shape [batch, sequence, heads, head_dim] or packed [tokens, heads, head_dim], local under CP and in the compute dtype.
Tensor with q’s leading axes and shape […, kv_heads, head_dim].
Tensor with the same shape/dtype/device as k.
Optional [batch, sequence] valid-token mask or backend-supported [batch, 1, sequence, sequence] bool/additive mask.
bshd for batched input or thd for packed input.
Backend metadata. Integer cu_seqlens/cu_seqlens_padded tensors have shape [documents + 1]; max_seqlen and CP size/rank are scalars.
Returns: torch.Tensor
Attention output with q’s leading axes and either [heads, head_dim]
Set training-only dropout on the preprocessed SDPA arguments.
Parameters:
Mutable SDPA call mapping. Any attn_mask tensor has broadcast layout [batch, heads, query_sequence, key_sequence]; tensor values and storage are unchanged. Only the scalar dropout_p entry is updated.
Select TE’s CP exchange for this sliding-window layer from the input layout.
Automodel’s CP setup gives sliding-window layers TE’s all_gather exchange. With packed (thd) input that
exchange fails before the first step in TE 2.18 (cudaErrorIllegalInstruction), so packed input uses
a2a, which matches all_gather numerically; batched (bshd) input keeps all_gather. a2a splits
heads across the CP group, so the CP size must divide both head counts. Full-attention layers are not touched.
Parameters:
bshd for batched input or thd for packed input.
Apply gated attention with HF-compatible RoPE or NoPE query scaling.
Parameters:
Tensor of shape [batch, sequence, hidden] or packed [tokens, hidden], in the compute dtype; sequence/tokens are local under CP.
Original FP32 concatenated half-width cosine/sine tensor of shape [batch, sequence, head_dim] or [tokens, head_dim] for unfused RoPE. Fused layout follows position_ids_to_freqs_cis; None for NoPE.
Optional original FP32 (cos, sin) pair, each of shape [batch, sequence, 1, head_dim] or [tokens, 1, head_dim]. Shared with other layers without mutation. When absent, derived from freqs_cis.
Integer tensor of shape [batch, sequence] or [tokens]. Normally local under CP; full-length positions can be selected using cp_size/cp_rank.
Optional [batch, sequence] valid-token mask (1/True = attend), or backend-supported [batch, 1, sequence, sequence] bool/additive mask.
Backend metadata: integer cu_seqlens/cu_seqlens_padded tensors of shape [documents + 1], scalar max_seqlen, qkv_format, cp_size/cp_rank.
Returns: torch.Tensor
Tensor with the same shape as x, in the output projection’s compute dtype.
Initialize projection and normalization parameters; buffer_device follows the model initializer API.
Bases: Gate
Normalize top-1 routing like HF, including its epsilon and gradients.
The override also serves the CUDA-graph routing core via Gate._route_scores.
Route scores with HF’s normalization for top-1 as well as larger top-k.
Parameters:
Tensor of shape [tokens, experts], using the shared Gate score dtype.
Returns: torch.Tensor
Routing weights [tokens, topk], integer expert indices [tokens, topk], and
Bases: MLP
Shared dense MLP with HF’s fp32 SwiGLU boundary, preserving parameter names and MLP dispatch.
Compute SwiGLU in FP32 before the down projection.
Parameters:
Tensor of shape […, hidden], with arbitrary leading dimensions, in the projection compute dtype.
Returns: torch.Tensor
Tensor of shape […, hidden] with the same leading dimensions. The FP32
Bases: MoE
Shared MoE with BeamGate installed before loading or parallelization.
Shared compiled SwiGLU preserves the FP32 activation boundary; Dynamo eager fallback can lose it. Unlike HF, default expert routing weights apply before the down projection and expert outputs accumulate in FP32.
Bases: Module
One Beam decoder layer: sandwich norms + depth-scaled residual adds.
Dispatch to the dense MLP or the routed experts.
Parameters:
Tensor of shape [batch, sequence, hidden] or packed [tokens, hidden], local to this rank under CP, in the layer compute dtype.
Optional bool tensor matching x’s leading axes; True skips routing.
Returns: torch.Tensor
Tensor with the same shape as x.
Apply attention, feedforward computation and depth-scaled residuals.
Parameters:
Tensor [batch, sequence, hidden] or packed [tokens, hidden], local under CP; only x is cast to the FSDP compute dtype.
FP32 rotary tensor […, head_dim], aligned with x’s leading axes; concatenated half-width cos/sin when unfused, fused layout otherwise. None for NoPE.
Optional FP32 (cos, sin), each […, 1, head_dim], shared across layers without mutation or casting; leading axes match x.
Integer tensor [batch, sequence] or [tokens], absolute within each document.
Optional [batch, sequence] bool/0-1 mask; True/1 means valid.
Optional bool tensor matching x’s leading axes; True skips routing.
Backend metadata: qkv_format (bshd/thd), integer cu_seqlens and cu_seqlens_padded [documents + 1], scalar max_seqlen, cp_size and cp_rank.
Returns: torch.Tensor
Tensor with x’s shape, covering this rank’s local positions.
Initialize the layer’s norms, attention, MLP and router buffers on buffer_device.
Select the two load-balanced sequence chunks owned by this CP rank.
Parameters:
Integer tensor of shape [batch, global_sequence] or [global_sequence], or the corresponding already-local shape.
Tokens per local sequence, equal to global_sequence / cp_size; must be even when selecting the two head/tail chunks.
Number of context-parallel ranks.
Zero-based context-parallel rank.
Returns: torch.Tensor
Position tensor of shape [batch, local_len] or [local_len]. Already-local
Apply HF Beam’s rotary expression and preserve its backward rounding.
Do not eagerly cast x to FP32: HF rounds each product’s gradient to x.dtype.
Parameters:
Query/key tensor of shape [batch, sequence, heads, head_dim] or packed [tokens, heads, head_dim], in the activation dtype.
Original FP32 cosine tensor of shape [batch, sequence, 1, head_dim] or [tokens, 1, head_dim], broadcastable to x and on the same device.
Original FP32 sine tensor with the same shape/device as cos.
Returns: torch.Tensor
New tensor with x’s shape/dtype/device, computed as
(sublayer_scale, residual_scale) for the depth-scaled residual add.
1-based residual-add index: 2L for attention, 2L + 1 for the MLP; the sublayer output is
scaled by 1/sqrt(idx) and the residual stream by sqrt((idx - 1)/idx).
Expand original FP32 rotary tables into HF’s duplicated-half layout.
Parameters:
FP32 tensor of shape […, head_dim], with arbitrary leading axes corresponding to [batch, sequence] or packed [tokens]. The last axis concatenates half-width cosine and sine values, in that order.
Returns: torch.Tensor
Pair (cos, sin), each a new FP32 tensor of shape […, 1, head_dim] on the
Beam marks every layer "dense" or "sparse" in config.mlp_layer_types.
Return the layer type’s RoPE parameters, or None for NoPE+SSMax.
Reject flat pre-Beam configs and non-default rope_type rather than silently changing positional encoding.
Construct a block-diagonal causal mask for packed SDPA.
Parameters:
Integer tensor of shape [documents + 1], beginning at zero and ending at total_tokens, with strictly increasing document boundaries.
Number of tokens in the concatenated packed buffer.
Number of visible tokens, including the query, or None.
Returns: torch.Tensor
Bool tensor of shape [1, 1, tokens, tokens] on cu_seqlens.device, where
Reject padding on Beam’s unmasked-only flex backend without a device synchronization.
Parameters:
Optional tensor, normally [batch, sequence]; any non-None value is rejected without inspecting its contents. Use TE or SDPA for padded input.
Apply HF’s half-vector rotation.
Parameters:
Tensor of shape […, head_dim], with arbitrary leading axes and even head_dim.
Returns: torch.Tensor
New tensor of the same shape/dtype/device, concatenating -x’s second half
Compute HF Beam’s NoPE query scale in FP32.
Parameters:
Integer tensor of shape [batch, sequence] or packed [tokens], containing absolute per-document positions, local to this rank under CP.
Returns: torch.Tensor
FP32 tensor with the same shape/device as position_ids:
Translate the visible-token window W: SDPA uses W, TE/FA use inclusive offsets (W-1, 0).
Flex takes sliding_window=W directly.