Skip to navigation

nemo_automodel.components.datasets.llm.neat_packing

View as MarkdownOpen in Claude

Neat packing (greedy knapsack) for LLM datasets.

This module provides an alternative packing strategy that uses a greedy knapsack algorithm (min-heap) for better bin-packing utilization compared to the sequential first-fit approach in packed_sequence.py.

The packed output uses an indexed attention mask (1, 2, 3, … per sub-sequence, 0 for padding) and reset position IDs so that it works with eager / SDPA attention backends — no Transformer Engine dependency.

Module Contents

Functions

NameDescription
_pack_chunkLay out consecutive packs: concatenate each pack’s samples and pad it to pack_size.
_packed_schemaReturn the column types of a NEAT-packed dataset.
greedy_knapsackBin-pack sample indices using a greedy knapsack (min-heap) algorithm.
neat_pack_datasetPack tokenized samples into fixed-length rows with a greedy knapsack.

Data

CROSS_ENTROPY_IGNORE_IDX

_PACKS_PER_CHUNK

logger

API

nemo_automodel.components.datasets.llm.neat_packing._pack_chunk(
input_ids: pyarrow.ListArray,
labels: pyarrow.ListArray,
loss_mask: pyarrow.ListArray | None,
lengths: numpy.ndarray,
order: numpy.ndarray,
per_pack: numpy.ndarray,
pack_size: int,
padding_idx: int,
schema: pyarrow.Schema
) -> pyarrow.RecordBatch

Lay out consecutive packs: concatenate each pack’s samples and pad it to pack_size.

Parameters:

input_ids
pa.ListArray

Token ids of every sample, one list per sample.

labels
pa.ListArray

Labels of every sample, one list per sample, aligned with input_ids.

loss_mask
pa.ListArray | None

Optional per-token mask of every sample; labels where it is 0 become -100.

lengths
np.ndarray

int64 array of shape [samples], the token count of every sample.

order
np.ndarray

int64 array of shape [chunk_samples], the samples of these packs in pack order, as indices into input_ids.

per_pack
np.ndarray

int64 array of shape [chunk_packs], how many consecutive entries of order each pack holds.

pack_size
int

Length of every packed row.

padding_idx
int

input_ids value of the padding after a pack’s last document.

schema
pa.Schema

Column types of the packed rows.

Returns: pa.RecordBatch

One row per pack. input_ids, labels, attention_mask and position_ids

nemo_automodel.components.datasets.llm.neat_packing._packed_schema(
token_min: int,
token_max: int,
max_documents: int
) -> pyarrow.Schema

Return the column types of a NEAT-packed dataset.

Dataset.from_dict narrows input_ids to int32 and attention_mask to int8 when every value fits (datasets.arrow_writer.OptimizedTypedSequence), and stores the other columns as int64. Packed datasets keep exactly those types.

Parameters:

token_min
int

Smallest value stored in input_ids, padding included.

token_max
int

Largest value stored in input_ids, padding included.

max_documents
int

Largest number of documents in one pack.

Returns: pa.Schema

A schema with list columns input_ids, labels, attention_mask and position_ids.

nemo_automodel.components.datasets.llm.neat_packing.greedy_knapsack(
lengths: list[int],
max_length: int
) -> list[list[int]]

Bin-pack sample indices using a greedy knapsack (min-heap) algorithm.

Samples are sorted by length in descending order. Each sample is assigned to the bin with the smallest current total that can still accommodate it. If no bin fits, a new bin is created.

Parameters:

lengths
list[int]

Length of each sample.

max_length
int

Maximum capacity of each bin.

Returns: list[list[int]]

A list of bins, where each bin is a list of sample indices.

nemo_automodel.components.datasets.llm.neat_packing.neat_pack_dataset(
dataset: datasets.Dataset | datasets.DatasetDict | torch.utils.data.Dataset | collections.abc.Iterable[dict],
split: str,
pack_size: int,
max_packs: int | None = None,
padding_idx: int = 0,
drop_long_samples: bool = False,
num_proc: int = 1
) -> datasets.Dataset

Pack tokenized samples into fixed-length rows with a greedy knapsack.

The samples are first materialized into one Arrow table (tokenize_dataset_parallel, which tokenizes a lazy dataset). Sample lengths then come from the list offsets, and the packs are assembled with NumPy, _PACKS_PER_CHUNK packs at a time.

Parameters:

dataset
Dataset | DatasetDict | torch.utils.data.Dataset | Iterable[dict]

Samples with list fields input_ids and labels of equal length and an optional loss_mask of the same length, which sets labels to -100 where it is 0. A HuggingFace Dataset, a DatasetDict holding split, or a dataset that tokenizes each sample on access (e.g. ChatDataset).

split
str

Dataset split key (e.g. "train").

pack_size
int

Target packed sequence length.

max_packs
int | NoneDefaults to None

Optional cap on number of packs to create.

padding_idx
intDefaults to 0

Token ID for padding.

drop_long_samples
boolDefaults to False

If True, silently drop samples longer than pack_size; otherwise raise ValueError.

num_proc
intDefaults to 1

Worker processes that tokenize the samples; values above 1 need an indexable dataset (see tokenize_dataset_parallel).

Returns: Dataset

A HuggingFace Dataset with one row per pack and list columns input_ids,

Raises:

  • ValueError: If a sample is longer than pack_size and drop_long_samples is False, if a sample’s labels or loss_mask length differs from its input_ids length, or if no sample remains.
nemo_automodel.components.datasets.llm.neat_packing.CROSS_ENTROPY_IGNORE_IDX = -100
nemo_automodel.components.datasets.llm.neat_packing._PACKS_PER_CHUNK = 1024
nemo_automodel.components.datasets.llm.neat_packing.logger = logging.getLogger(__name__)