Skip to navigation

nemo_automodel.components.attention.utils

View as MarkdownOpen in Claude

Module Contents

Classes

NameDescription
_TEAttentionKwargsTE keywords produced by this component’s attention preprocessing.
_TEAttentionModuleThe native TE module contract used by the call adapter.

Functions

NameDescription
_call_te_attentionReuse TE plans by adding empty trailing documents at the TE boundary.
_fa4_interface_sha256Identify the installed dependency once before selecting a validated layout.
initialize_attn_module_and_funcInitialize an attention backend module and callable.
postprocess_output_for_attnPostprocess attention output based on attn_impl requirements.
preprocess_args_and_kwargs_for_attnPreprocess attention inputs based on backend requirements.

Data

_FA4_ORIGINAL_INTERFACE_SHA256

_FA4_PHYSICAL_INTERFACE_SHA256

_FA4_PREVIOUS_INTERFACE_SHA256

API

class nemo_automodel.components.attention.utils._TEAttentionKwargs

Bases: typing.TypedDict

TE keywords produced by this component’s attention preprocessing.

attention_mask
Tensor | None
attn_mask_type
str
cu_seqlens_kv
Tensor | None
cu_seqlens_kv_padded
Tensor | None
cu_seqlens_q
Tensor | None
cu_seqlens_q_padded
Tensor | None
max_seqlen_kv
int
max_seqlen_q
int
pad_between_seqs
bool
qkv_format
str
window_size
tuple[int, int]
class nemo_automodel.components.attention.utils._TEAttentionModule()
Protocol

The native TE module contract used by the call adapter.

attention_dropout
float
cp_group
ProcessGroup | list[ProcessGroup] | None
qkv_format
str
nemo_automodel.components.attention.utils._TEAttentionModule.__call__(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
) -> torch.Tensor

Call native TE with BSHD or THD Q/K/V and TE sequence metadata.

Parameters:

q
torch.Tensor

Tensor [batch, sequence, heads, head_dim] or [tokens, heads, head_dim].

k
torch.Tensor

Tensor with the same layout as q, with KV heads and KV tokens.

v
torch.Tensor

Tensor with the same layout as k, with value head dimension.

**kwargs
Unpack[_TEAttentionKwargs]Defaults to {}

TE keywords; cumulative offsets are int32 [documents + 1], attention_mask is [batch, 1, 1, sequence].

Returns: torch.Tensor

Tensor [batch, sequence, heads * value_dim] or [tokens, heads * value_dim].

nemo_automodel.components.attention.utils._call_te_attention(
quantization_enabled: typing.Callable[[], bool],
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
) -> torch.Tensor

Reuse TE plans by adding empty trailing documents at the TE boundary.

Parameters:

module
_TEAttentionModule

Original TE module, retaining its parameters and parallel setup.

quantization_enabled
Callable[[], bool]

TE’s active quantization-context query.

q
torch.Tensor

Tensor [batch, sequence, heads, head_dim] or packed [tokens, heads, head_dim].

k
torch.Tensor

Tensor with the same layout as q, with KV heads and KV tokens.

v
torch.Tensor

Tensor with the same layout as k, with value head dimension.

**kwargs
Unpack[_TEAttentionKwargs]Defaults to {}

TE keywords. Logical and optional physical cumulative offsets are int32 [documents + 1] on the input device. Q and KV must have the same document count, but may have different lengths and offsets. attention_mask, when provided, is [batch, 1, 1, sequence].

Returns: torch.Tensor

Native TE output [batch, sequence, heads * value_dim] or

nemo_automodel.components.attention.utils._fa4_interface_sha256() -> str | None

Identify the installed dependency once before selecting a validated layout.

The external FA4 API does not advertise whether unused physical rows are initialized. Source identity is a conservative compatibility boundary until the dependency exposes that guarantee; unavailable source uses compact THD.

nemo_automodel.components.attention.utils.initialize_attn_module_and_func(
attn_impl: str,
num_attention_heads: int,
num_qk_channels: int,
num_v_channels: int,
softmax_scale: float,
attn_mask_type: str = 'causal',
qkv_format: str = 'bshd',
num_gqa_groups: int | None = None,
kwargs: typing.Any = {}
) -> tuple[torch.nn.Module | None, typing.Callable[..., torch.Tensor]]

Initialize an attention backend module and callable.

nemo_automodel.components.attention.utils.postprocess_output_for_attn(
x: torch.Tensor,
attn_impl: str
) -> torch.Tensor

Postprocess attention output based on attn_impl requirements.

nemo_automodel.components.attention.utils.preprocess_args_and_kwargs_for_attn(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
attention_mask: torch.Tensor | None,
attn_impl: str,
fa4_physical_layout: bool = False,
kwargs: typing.Any = {}
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, dict[str, typing.Any]]

Preprocess attention inputs based on backend requirements.

Parameters:

q
torch.Tensor

Query tensor of shape [batch, sequence, heads, head_dim] or [tokens, heads, head_dim] for THD input.

k
torch.Tensor

Key tensor of shape [batch, sequence, kv_heads, head_dim] or [tokens, kv_heads, head_dim] for THD input.

v
torch.Tensor

Value tensor with the same leading layout as k and an optional distinct value head dimension.

attention_mask
torch.Tensor | None

Optional tensor of shape [batch, sequence] for padding or indexed packing, or [batch, 1, sequence, sequence] for an explicit dense mask. TE accepts only a binary [batch, sequence] padding mask (1/True for valid tokens, 0/False for padding). Packed TE inputs require None and THD sequence metadata instead.

attn_impl
str

Attention backend name.

fa4_physical_layout
boolDefaults to False

Model-owned eligibility for physical-prefix THD and a conservative host maximum. False preserves compact dispatch. The dependency compatibility check still gates physical buffer use.

**kwargs
AnyDefaults to {}

Backend metadata. Prepared THD FA4 uses private compact offsets [documents + 1] and indices [valid_tokens] computed once at model entry; outputs retain [physical_tokens, heads, channels] layout. Packed FA4 accepts cu_seqlens of shape [documents + 1] and packed_token_indices of shape [tokens]. For SDPA and FA4, a positive left window_size counts visible keys including the current token; negative/None means unbounded. The legacy TE branch forwards its backend-specific distances unchanged. Packed TE accepts cu_seqlens of shape [documents + 1] and optional cu_seqlens_padded with the same shape, both int32, together with an integer max_seqlen.

Returns: torch.Tensor

Query, key, and value tensors in the backend layout plus its keyword

Raises:

  • ValueError: If the selected backend cannot consume the input layout.
nemo_automodel.components.attention.utils._FA4_ORIGINAL_INTERFACE_SHA256 = 'c3895b66051bf09ca3e98f63e0f4c84e608d2300e2024eb315db9d4ee77c8cd0'
nemo_automodel.components.attention.utils._FA4_PHYSICAL_INTERFACE_SHA256 = 'de3781369943fcfa1df9344999c7ad7496bfb607d80e852406e07ebf8e28ed22'
nemo_automodel.components.attention.utils._FA4_PREVIOUS_INTERFACE_SHA256 = '4d31465cd46d1737290862bf99fad54e929d7c37cc36807bf2fe56ac56f26646'