nemo_automodel.components.datasets.llm.packed_sequence
nemo_automodel.components.datasets.llm.packed_sequence
Module Contents
Functions
Data
API
Converts a pack into tensors. Pack comes in as a dict of lists and is converted to tensors.
Pool initializer: keep the dataset a forked worker inherited for its tasks.
Parameters:
The map-style dataset the parent passed to tokenize_dataset_parallel.
Pad an aligned pack to its fixed token budget.
Parameters:
Token tensors input_ids, labels and position_ids [tokens], plus real document lengths seq_lens [documents].
Input padding token.
Physical token budget, including alignment padding.
Label value excluded from loss.
CP geometry used by generic THD packing.
Additional per-document alignment independent of CP.
Returns: PACK_TYPE
Tensor mapping with token fields [packed_sequence_size], real seq_lens
Convert tokenized sample dicts to an Arrow table.
Dataset.from_dict picks the column types, so input_ids becomes int32 and
attention_mask int8 whenever the values fit, as datasets.Dataset.map stores them.
Parameters:
Tokenized samples, each value a list of ints or a mapping. Missing keys are represented as nulls rather than dropping fields absent from the first row.
Returns: pa.Table
A table with one row per sample and one column per key.
If max packs is set, stop packing when we reach that number.
Finalize complete documents and carry the last document into the next pack.
Parameters:
Lists of tokens [tokens] and real lengths [documents].
Output list receiving one tensorized, padded pack.
Physical token offset before the last document.
Fixed physical token budget, including alignment.
Input padding token.
Padding label.
Generic THD context-parallel size.
Additional document alignment.
Returns: PACK_TYPE
List-valued token fields and lengths for the remaining document, preserving order.
Tensorize and pad one pack using the layout documented by _pad_pack.
Parameters:
Lists of token fields [tokens] and document lengths [documents].
Input padding token.
Fixed physical token budget.
Padding label.
Generic THD context-parallel size.
Additional document alignment.
Returns: PACK_TYPE
Tensor mapping with token fields [packed_sequence_size] and lengths [documents].
Worker task: tokenize dataset[i] for i in range(*bounds) into one Arrow table.
Parameters:
(start, stop) indices into the worker’s dataset.
Returns: pa.Table
The tokenized rows of that range, in index order.
Build a [B, 1, T, T] additive block-causal mask directly on device.
In-document causal attention is allowed (0); cross-document and padding
positions are finfo(dtype).min. seq_lens is the [B, max_docs]
0-padded per-document length tensor; each row’s non-zero entries sum to
seq_length (trailing pad folded into the final document).
Raises ValueError if seq_lens is not 2D or any row does not sum to
seq_length — a malformed row would otherwise silently misbucket the
boundary cumsum (e.g. isolating the final token into a phantom document)
and train the draft on wrong-context supervision with no error. This mirrors
the fail-loud sum check the FlashAttention varlen path already performs in
_seq_lens_to_cu_seqlens.
Creates causal mask block for specified lengths.
In particular, given a batch tensor of seq lens defining the lengths of samples in each pack, Construct a 2D block causal mask for each pack in the batch. For example, if a single sample’s seq_lens is [3, 2, 1], the mask would be:: mask = [ [1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1], ]
Parameters:
Sequence lengths of samples in each pack in the batch, shape (batch_size, n), where n is the max number of sequences in a pack and can vary across packs.
Returns: torch.Tensor
Block causal mask of shape (batch_size, packed_sequence_size, packed_sequence_size).
Pack the dataset to defined length.
In particular, it will iterate through the dataset. Use a buffer to hold samples until packed_sequence_size, then append the buffer to packs as a single “packed” sample. Continue until max_packs or end of dataset.
Parameters:
Actual dataset (can be ‘train’, ‘val’ or ‘test’)
Whether the dataset is ‘train’, ‘val’ or ‘test’
Number of tokens in a pack
Maximum number of packs. Default: None
If True, drop samples that are longer than packed_sequence_size.
Context parallel size. When > 1, each sequence will be padded to be divisible by 2*cp_size for context parallel processing. Default: 1 (no CP).
Align each document’s physical span to this many tokens, including this padding in the pack budget. Real lengths and shifted labels are preserved. Default: 1. This alignment is independent of context-parallel size.
Returns: Dataset
Arrow dataset of fixed-length input_ids, already-shifted labels and position_ids
Create a 2D block causal document mask for a batch of packed sequences.
Parameters:
Sequence lengths of samples in each pack in the batch, shape (batch_size, n), where n is the max number of sequences in a pack and can vary across packs.
Returns:
BlockMask or Tensor if torch version < 2.5.0.
Materialize a lazily tokenizing dataset into an Arrow-backed Dataset.
Iterating a lazily tokenizing dataset (e.g. ChatDataset) tokenizes each sample
serially in a single process, which dominates the cost of preparing a packed dataset.
With num_proc > 1, worker processes call the dataset’s own __getitem__ on
contiguous index ranges and return each range as an Arrow table; with num_proc == 1
the dataset is iterated in this process, as serial packing does. Either way the rows
come back in order, in one contiguous Arrow table that pack_dataset and
neat_pack_dataset consume unchanged.
Caveats:
- With
num_proc > 1,datasetmust be indexable (__len__+__getitem__) and its__getitem__must be a deterministic pure function of the index. Rows are produced in separate processes, so a__getitem__that consults process-global state (RNG-driven augmentation, counters) would diverge from serial iteration. The caller inPackingConfiggates on indexability. - Workers are forked: they inherit
datasetwithout pickling it and must not use CUDA. Each tokenized range is pickled back to this process as an Arrow table. - Tokenizes the whole dataset, so it does not stop early at
max_packs. - Runs independently on each data-parallel rank;
dp_local_ranks * num_procshould not oversubscribe the node’s CPUs. Nothing is cached between runs.
Parameters:
A dataset whose items are tokenized dicts (input_ids, labels
and, optionally, loss_mask), each a list[int]. Must be indexable
when num_proc > 1.
Number of worker processes used for tokenization; 1 tokenizes
in this process.
Returns: Dataset
A HuggingFace Dataset of the tokenized rows in original order, backed by a