nemo_automodel.components.datasets.utils
nemo_automodel.components.datasets.utils
Module Contents
Classes
Functions
API
Generic single-turn text-to-text SFT (supervised-fine-tuning) pre-processor.
Parameters:
Pre-trained tokenizer (HF).
Main processor entry.
Parameters:
the dataset (e.g. returned by load_dataset)
the dataset with get_target method.
Returns:
datasets.DatasetDict: tokenized + optionally padded datasets (all splits preserved).
Ensures that the input tensor has at least two dimensions by adding an extra batch dimension if necessary.
Parameters:
The input tensor to be batchified.
Returns:
torch.Tensor: The tensor with an extra dimension added if it was originally 1-dimensional.
A 1-D tensor is unsqueezed in place and returned as the same object, so the
caller’s tensor is reshaped from [S] to [1, S] as a side effect. Do not
pass a tensor owned by someone else — add the batch axis with unsqueeze(0)
instead.
Default batch collator that handles padding and batching.
Sequence-list fields are padded and stacked. Pre-batched tensor fields are concatenated along their first axis, preserving all trailing axes, dtype, and device.
Parameters:
Local examples. A list-valued field has shape [S_i] for example i, where S_i is its
sequence length, and becomes [B, S] after padding, where B is the number of examples and
S is the padded maximum. A tensor-valued field is already batched as [B_i, ...] with
arbitrary trailing axes and becomes [sum_i(B_i), ...]. The optional
___PAD_TOKEN_IDS___ entry is removed from the first input mapping in place. Apart from
that removal, the input examples and their tensors are left unmodified.
If set, round padded S up to a multiple of this value.
Omit padding_mask when it excludes no tokens. This opt-in check
runs during collation, normally on CPU, so models can use their implicit unpadded-input
path without a device synchronization in every forward. Masks containing padding remain.
Returns: dict[str, torch.Tensor]
Mapping of fields to tensors. List-valued inputs become torch.int64 tensors shaped [B, S];
Extracts the value of the given key from each dictionary in a list of dictionaries.
Parameters:
A list of dictionaries.
The key whose values are to be extracted from each dictionary.
Returns:
A list of values associated with the specified key, in the same order as
Return the last non-padding index before a trailing padding run.
Return the default pad token id for a batch field name.
Return whether a batch field holds one scalar per example.
Blended pretraining datasets attach per-sample provenance (dataset_id)
as a bare numpy/Python scalar alongside sequence-valued fields. Such a field
must be stacked to [B], not padded as a ragged sequence — len() of a
numpy scalar raises TypeError.
Build an attention mask from labels with trailing ignored positions.
Collater for neat-packed LLM sequences.
Stacks input_ids, labels, position_ids and converts the
indexed attention_mask to the representation requested by packing.
document_ids keeps the indexed 2D mask [B, S] and
block_causal converts the mask to [B, 1, S, S]. Models may
independently request flat-token metadata through the same contract.
flash_varlen emits HF varlen kwargs without an attention mask.
Parameters:
Sample mappings from neat_pack_dataset. Each holds
input_ids, labels, position_ids, and indexed
attention_mask tensors or lists of shape [sequence].
Deprecated attention-backend name retained for Python-call compatibility during the packing-contract migration.
Structural model contract selecting the packed mask representation. Native mask/Flash collation requires a model-derived contract supplying the attention conversion; recipes provide it automatically.
Returns: dict
Mapping with input_ids, labels, and position_ids of shape
Concatenate loose single-sequence features into one pre-packed THD record.
Each input feature holds one unpadded variable-length sequence
(input_ids and optionally labels). The output is a single record in
the pre-packed schema packed_sequence_thd_collater accepts: flat
input_ids/labels, position_ids restarting at every sequence
boundary, and per-sequence seq_lens/seq_lens_padded (no separator
tokens, so the two are equal).
Deciding which sequences share a pack is the caller’s job (the sampler, or an RL framework’s microbatcher); this helper only executes the concatenation.
Parameters:
per-example dicts with input_ids and optional labels
(list[int] or 1-D tensors). An example without labels
contributes ignore_index at every position (no loss).
label fill value for examples without labels.
Returns: dict
One pre-packed feature record (plain lists), suitable as a batch item
Collater for packed sequences in THD (total, hidden, depth) format.
This collater is designed for THD format, where multiple variable-length sequences are concatenated with/without padding tokens between them. The THD format represents sequences as (total_tokens, hidden_dim, depth) where total_tokens is the sum of all sequence lengths in the batch.
Unlike traditional padding-based approaches (BSHD/SBHD formats), this THD format:
- Concatenates sequences directly: [a a a b b c c c c]
- Uses seq_lens to identify sequence boundaries for attention computation
- Supports optional identifier or padding tokens between sequences via seq_lens_padded
This collater supports both pipeline parallelism (PP) and non-PP use cases by:
- Stacking token-level tensors (input_ids, labels, position_ids) along batch dimension
- Padding and stacking seq_lens and seq_lens_padded with sentinel value -1000
- Including ‘qkv_format’: ‘thd’ in the output to indicate THD format
When batch items lack packed-sequence metadata (seq_lens, seq_lens_padded, position_ids), such as samples from ChatDataset, this collater synthesizes the missing fields so that each sample is treated as a single-sequence “pack”. Variable-length sequences are padded to the longest length in the batch. This enables using THD format with TE context parallelism without requiring the dataset to perform actual sequence packing.
Parameters:
A list of dictionaries, where each dictionary represents one example.
For pre-packed data, each dictionary should contain:
- ‘input_ids’: List[int] - Token IDs for all packed sequences (must be same length across batch)
- ‘labels’: List[int] - Labels for all packed sequences (must be same length across batch)
- ‘position_ids’: List[int] - Position IDs for all tokens (must be same length across batch)
- ‘seq_lens’: List[int] - Actual sequence lengths for each packed sequence
- ‘seq_lens_padded’: List[int] - Sequence lengths including identifier/padding tokens
For non-packed data (e.g. ChatDataset), each dictionary needs only:
- ‘input_ids’: List[int] - Token IDs (variable length across batch)
- ‘labels’: List[int] - Labels (same length as input_ids)
- ‘attention_mask’: List[int] - (optional) 1 for real tokens, 0 for padding
Example batch with 2 packed examples, both with 6 total tokens: [ { ‘input_ids’: [1, 2, 3, 99, 4, 5], # Two sequences: [1,2,3] and [4,5] with sep token 99 ‘labels’: [1, 2, 3, -100, 4, 5], ‘position_ids’: [0, 1, 2, 0, 0, 1], ‘seq_lens’: [3, 2], # Actual sequence lengths (excluding separator) ‘seq_lens_padded’: [4, 2] # Including separator token }, { ‘input_ids’: [6, 7, 99, 8, 9, 10], # Two sequences with separator ‘labels’: [6, 7, -100, 8, 9, 10], ‘position_ids’: [0, 1, 0, 0, 1, 2], ‘seq_lens’: [2, 3], ‘seq_lens_padded’: [3, 3] } ]
Returns:
A dictionary with batched tensors:
- ‘input_ids’: tensor of shape [batch_size, seq_len] - stacked token sequences
- ‘labels’: tensor of shape [batch_size, seq_len] - stacked labels
- ‘position_ids’: tensor of shape [batch_size, seq_len] - stacked position IDs
- ‘seq_lens’: tensor of shape [batch_size, max_num_packs] - padded sequence lengths
- ‘seq_lens_padded’: tensor of shape [batch_size, max_num_packs] - padded lengths with separators
- ‘qkv_format’: str - Always ‘thd’ to indicate THD format
THD collater adapter for the VLM recipe’s (examples, processor) call convention.
recipes/vlm/finetune.py:build_dataloader invokes the configured collate as
collate_cfg.instantiate(examples=examples, processor=processor), whereas
packed_sequence_thd_collater takes only batch. This thin adapter accepts
(and ignores) processor and any extra kwargs so pre-tokenized ChatDataset
samples can use THD / context-parallel batching inside the VLM recipe.
Parameters:
Batch of samples, forwarded to packed_sequence_thd_collater.
Unused; accepted only for VLM-recipe call-convention compatibility.
Returns:
THD-format batch (see packed_sequence_thd_collater).
Pads each list in a batch of lists to the same length with a specified token.
Parameters:
A batch of sequences (e.g., token IDs), where each sequence is a list of integers.
The token ID to use for padding shorter sequences.
The value to use for padding sequence length so that it is divisible by pad_seq_len_divisible.
Returns:
List[List[int]]: A batch of sequences where each inner list has been padded with the pad