nemo_automodel.components.models.common.packing
nemo_automodel.components.models.common.packing
Model-derived packing contracts and native metadata normalization.
HF flash attention consumes the public varlen kwargs built by dataset collaters. Native FA4 and recurrent consumers use separate unpadded document metadata. Neither path modifies Transformers globals.
Module Contents
Classes
Functions
Data
API
Typed attention selection carried by a built custom model.
Selected native attention backend.
Model whose attention layers invoke Automodel’s native FA4 callable.
Model that owns masking and consumes compact document IDs.
Model-owned requirements for dataset packing and model adaptation.
Model that needs dataset-constructed metadata for packed recurrent state.
Model whose active attention path dispatches through its HF config.
Whether HF’s dispatch key controls attention rather than backend.attn.
Flatten packed metadata once after pipeline microbatch splitting.
Parameters:
Native FA4 model receiving the forward call.
Positional model inputs. Tensor entries retain their model-specific layouts and are returned unchanged.
Model inputs containing packed_token_indices of shape
[batch, sequence] or [tokens] and cu_seqlens of shape
[batch, max_documents + 1] or [documents + 1].
Returns: tuple[tuple[Any, ...], dict[str, Any]] | None
Updated positional and keyword inputs whose packed token indices have
Raises:
ValueError: If pre-packed THD is requested, only one metadata tensor is supplied, or either layout is inconsistent with the current microbatch.
Install the once-per-forward native FA4 metadata normalizer.
Return the packing-relevant attention backend an already-built model runs with.
model.config._attn_implementation is a Transformers dispatch key, whose
vocabulary is wider than the mask layouts packing knows about: when flash
attention is requested but only the kernels package provides it,
Transformers records a kernels-hub id instead of the mainline name. Those ids
are mapped back so a model genuinely running varlen flash attention is packed
as such. Other live string keys are returned unchanged and therefore use
packing’s conservative block-causal default.
Keep dataset-only NEAT offsets away from a legacy THD consumer.
Parameters:
Model that does not require explicit NEAT metadata.
Positional model inputs, returned unchanged in their original layouts.
Model inputs. packed_token_indices of shape [batch, sequence]
or [tokens] identifies NEAT metadata; its companion cu_seqlens
has shape [batch, max_documents + 1] or [documents + 1].
Returns: tuple[tuple[Any, ...], dict[str, Any]] | None
Inputs without NEAT token indices, cumulative lengths, and integer
Raise if model’s forward cannot receive the typed packing contract.
A model consumes the contract when its forward accepts **kwargs (HF
models thread FlashAttentionKwargs this way), names _packed_seq_ids
(the custom-model document map), or names all four varlen kwargs explicitly.
A forward whose signature cannot be introspected is rejected.
Parameters:
Already-built model, or a DDP wrapper exposing .module.
Configure the model consumer and return its dataset packing contract.
HF flash attention receives public varlen kwargs from the collater, without modifying Transformers globals. Native FA4 receives batch-major metadata flattened at model entry after microbatch splitting. Other consumers strip unused native metadata so it cannot accidentally select their THD path.
Parameters:
Attention implementation used by the built model.
Optional built model declaring additional packed-metadata needs.
Returns: PackingCapabilities
Structural packed-data requirements for the dataset collater.
Raises:
RuntimeError: If HF flash attention cannot consume the public varlen contract.
Configure local pipeline stages and combine their dataset requirements.
Parameters:
Nonempty sequence of built model stages consuming the same batch.
Returns: PackingCapabilities
Packing contract with metadata enabled if any stage needs it.
Raises:
ValueError: If there are no models or their packed mask layouts disagree.
Normalize batch-major packed metadata to a single flat token stream.
Parameters:
Tensor of shape [batch, sequence] containing
row-local token indices with -1 padding, or a pre-flattened
tensor of shape [tokens] containing indices into [batch, sequence].
Tensor of shape [batch, max_documents + 1] containing
row-local cumulative lengths with -1 padding, or a pre-flattened
tensor of shape [documents + 1].
Batch dimension of the padded token layout.
Sequence dimension of the padded token layout.
Returns: torch.Tensor
Flat token indices of shape [tokens] into the padded [batch, sequence]
Raises:
ValueError: If the layouts, boundaries, or represented token counts are inconsistent.
Return the NEAT/BSHD attention implementation used by a built model.
Custom models expose a typed backend.attn. Hugging Face models record
their resolved dispatch key on model.config; this reflects preload and
fallback decisions that are intentionally absent from the recipe config.
Models mixing native and HF attention declare which dispatch handles BSHD.
A separate pre-packed THD path does not determine the NEAT mask layout.
Parameters:
Constructed model, optionally wrapped in DDP.
Returns: str
The active attention backend or HF dispatch key, normalized for packing.
Raises:
TypeError: If model is not a torch.nn.Module.
Map a model attention implementation to semantic packed-data requirements.
Parameters:
Attention implementation resolved from the built model.
Optional built model, inspected through explicit packed-metadata, mask, and native-FA4 consumer capabilities.
Returns: PackingCapabilities
Structural capabilities consumed by dataset packing. Backend names do not
Raises:
ValueError: If native FA4 packing is requested without a native consumer.
Return True iff attention_mask is an Automodel-style indexed packing mask.
The Automodel neat_packed_vlm_collater (and the LLM equivalent) encode
packed-sample boundaries by marking document i (1-based) with the
integer i and using 0 for padding (e.g. [1, 1, 1, 2, 2, 3, 3, 0, 0]).
Any value greater than 1 is therefore a sufficient signal that two or
more documents are packed into the same row. A standard 0/1 attention mask
never has values > 1.
Fail loudly when flash neat packing cannot be consumed by the backend or model.
Neat packing under flash attention relies on the varlen FlashAttention
contract: the collater emits FlashAttentionKwargs (cu_seq_lens_q/
cu_seq_lens_k/max_length_q/max_length_k) which HuggingFace threads
into flash_attn_varlen_func. This function verifies, before training
starts, that (1) the installed Transformers build exposes that contract and
(2) the model’s forward can actually receive it — either as **kwargs,
explicit varlen parameters, or the custom-model _packed_seq_ids map. Any
gap raises here instead of silently dropping the cumulative lengths and
enabling cross-document attention.
Non-flash backends (sdpa / eager) use a 4D block-causal mask built by
the collater and need no validation.
Parameters:
The attention implementation the model runs with.
Optional already-built model (or DDP wrapper) to check for the
ability to receive the typed packing contract. Skipped when None
or when the model’s forward signature cannot be introspected.
Raises:
RuntimeError: If a flash backend is requested but the installed Transformers_flash_attention_forwarddoes not accept the public varlen kwargs, or the model’sforwardcan consume neither the varlen kwargs nor_packed_seq_ids.