Skip to navigation

nemo_automodel.components.datasets.utils

View as MarkdownOpen in Claude

Module Contents

Classes

NameDescription
SFTSingleTurnPreprocessorGeneric single-turn text-to-text SFT (supervised-fine-tuning) pre-processor.

Functions

NameDescription
batchifyEnsures that the input tensor has at least two dimensions by adding an extra batch dimension if necessary.
default_collaterDefault batch collator that handles padding and batching.
extract_key_from_dictsExtracts the value of the given key from each dictionary in a list of dictionaries.
find_last_non_pad_tokenReturn the last non-padding index before a trailing padding run.
get_pad_token_from_keyReturn the default pad token id for a batch field name.
is_scalar_fieldReturn whether a batch field holds one scalar per example.
make_attention_mask_from_labelsBuild an attention mask from labels with trailing ignored positions.
neat_packed_collaterCollater for neat-packed LLM sequences.
pack_features_for_thdConcatenate loose single-sequence features into one pre-packed THD record.
packed_sequence_thd_collaterCollater for packed sequences in THD (total, hidden, depth) format.
packed_sequence_thd_collater_vlmTHD collater adapter for the VLM recipe’s (examples, processor) call convention.
pad_within_microPads each list in a batch of lists to the same length with a specified token.

API

class nemo_automodel.components.datasets.utils.SFTSingleTurnPreprocessor(
tokenizer
)

Generic single-turn text-to-text SFT (supervised-fine-tuning) pre-processor.

Parameters:

tokenizer

Pre-trained tokenizer (HF).

preprocessing_num_workers
= 1
nemo_automodel.components.datasets.utils.SFTSingleTurnPreprocessor._compute_dataset_max_len(
tokenized_ds
)
nemo_automodel.components.datasets.utils.SFTSingleTurnPreprocessor._pad_function(
max_len
)
nemo_automodel.components.datasets.utils.SFTSingleTurnPreprocessor._tokenize_function(
examples,
dataset
)
nemo_automodel.components.datasets.utils.SFTSingleTurnPreprocessor.process(
raw_dataset,
ds
)

Main processor entry.

Parameters:

raw_dataset
datasets.DatasetDict

the dataset (e.g. returned by load_dataset)

ds
dataset

the dataset with get_target method.

Returns:

datasets.DatasetDict: tokenized + optionally padded datasets (all splits preserved).

nemo_automodel.components.datasets.utils.batchify(
tensor,
default_tensor_cls = torch.LongTensor
)

Ensures that the input tensor has at least two dimensions by adding an extra batch dimension if necessary.

Parameters:

tensor
torch.Tensor

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.

nemo_automodel.components.datasets.utils.default_collater(
batch: list[dict[str, list[int] | torch.Tensor]],
pad_seq_len_divisible: int | None = None,
omit_empty_padding_mask: bool = False
) -> dict[str, torch.Tensor]

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:

batch
list[dict[str, list[int] | torch.Tensor]]

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.

pad_seq_len_divisible
int | NoneDefaults to None

If set, round padded S up to a multiple of this value.

omit_empty_padding_mask
boolDefaults to False

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];

nemo_automodel.components.datasets.utils.extract_key_from_dicts(
batch,
key
)

Extracts the value of the given key from each dictionary in a list of dictionaries.

Parameters:

batch
List[dict]

A list of dictionaries.

key
str

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

nemo_automodel.components.datasets.utils.find_last_non_pad_token(
lst: list[int],
value: int
) -> int | None

Return the last non-padding index before a trailing padding run.

nemo_automodel.components.datasets.utils.get_pad_token_from_key(
val: str,
pad_token_ids: dict[str, int] | None = None
) -> int | None

Return the default pad token id for a batch field name.

nemo_automodel.components.datasets.utils.is_scalar_field(
value
) -> bool

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.

nemo_automodel.components.datasets.utils.make_attention_mask_from_labels(
ids: list[int],
ignore_token: int = -100
) -> list[int]

Build an attention mask from labels with trailing ignored positions.

nemo_automodel.components.datasets.utils.neat_packed_collater(
batch: list[dict],
attn_implementation: str | None = None,
) -> dict

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:

batch
list[dict]

Sample mappings from neat_pack_dataset. Each holds input_ids, labels, position_ids, and indexed attention_mask tensors or lists of shape [sequence].

attn_implementation
str | NoneDefaults to None

Deprecated attention-backend name retained for Python-call compatibility during the packing-contract migration.

packing
PackedSequenceContractDefaults to DEFAULT_PACKED_SEQUENCE_CONTRACT

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

nemo_automodel.components.datasets.utils.pack_features_for_thd(
features: list[dict],
ignore_index: int = -100
) -> dict

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:

features
list[dict]

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).

ignore_index
intDefaults to -100

label fill value for examples without labels.

Returns: dict

One pre-packed feature record (plain lists), suitable as a batch item

nemo_automodel.components.datasets.utils.packed_sequence_thd_collater(
batch
)

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:

batch
List[dict]

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
nemo_automodel.components.datasets.utils.packed_sequence_thd_collater_vlm(
examples,
processor = None,
kwargs = {}
)

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:

examples

Batch of samples, forwarded to packed_sequence_thd_collater.

processor
Defaults to None

Unused; accepted only for VLM-recipe call-convention compatibility.

Returns:

THD-format batch (see packed_sequence_thd_collater).

nemo_automodel.components.datasets.utils.pad_within_micro(
batch,
pad_token_id,
pad_seq_len_divisible = None
)

Pads each list in a batch of lists to the same length with a specified token.

Parameters:

batch
List[List[int]]

A batch of sequences (e.g., token IDs), where each sequence is a list of integers.

pad_token_id
int

The token ID to use for padding shorter sequences.

pad_seq_len_divisible
intDefaults to None

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