nemo_automodel.components.datasets.vlm.neat_packing_vlm
nemo_automodel.components.datasets.vlm.neat_packing_vlm
Neat packing for VLM (vision-language model) pre-tokenized datasets.
Packing is split into two phases:
- Plan (instant) — scan raw dataset for estimated token lengths,
run
greedy_knapsackto assign samples to bins. No tokenization, no media loading. - Materialize (lazy, in
__getitem__) — when the DataLoader requests pack k, load + tokenize + shift + concat the samples assigned to bin k. Runs in DataLoader worker processes, fully parallel.
This keeps the packing setup O(N) and lightweight, while the expensive
tokenization + media loading is distributed across num_workers.
Module Contents
Classes
Functions
Data
API
Construction-time configuration for the VLM neat-packing pipeline.
Optional packed-mask backend override used only with context parallelism.
If True, use VT-balanced knapsack to distribute visual tokens evenly.
Optional maximum padded length used by the packed collator.
If True, samples whose estimated length exceeds pack_size are dropped.
Optional cap on the total number of packs produced.
Target packed sequence length (after autoregressive shift).
Packed collator format. thd emits Transformer Engine sequence metadata.
Knapsack bin fill ratio. Values below 1.0 leave headroom for estimation errors.
Build a neat-packed VLM dataset from this config.
Parameters:
PreTokenizedDatasetWrapper for per-sample tokenization.
Runtime tokenizer padding token ID.
Raw conversations dataset for fast length estimation. Falls back to
len(dataset) when None.
Optional model.get_rope_index callable for mRoPE support.
Optional HuggingFace processor for accurate media token estimation.
Bases: Dataset
A Dataset that materializes packs lazily in __getitem__.
The constructor only stores bin assignments (which sample indices go into each pack). The actual tokenization, media loading, shift, and concatenation happen when a pack is requested — inside DataLoader worker processes, fully parallel.
Parameters:
The PreTokenizedDatasetWrapper that tokenizes
individual samples.
List of bins from greedy_knapsack, where each bin is a
list of sample indices into inner_dataset.
Target packed sequence length (after shift).
Token ID for padding.
Optional model.get_rope_index for mRoPE.
Max retries when a sample fails to tokenize.
Materialize one pack: tokenize + shift + concat all samples in the bin.
Wrap collate_fn with retry logic, delegating to inner dataset.
Construction-time configuration for :class:PackedDatasetWrapper.
Max retries when a sample fails to tokenize during materialization.
Target packed sequence length (after autoregressive shift).
Build a :class:PackedDatasetWrapper from this config.
Parameters:
The tokenizing dataset (e.g. PreTokenizedDatasetWrapper).
Bin assignments from greedy_knapsack / neat_pack_dataset_vlm.
Runtime tokenizer padding token ID.
Optional model.get_rope_index callable for mRoPE support.
Concatenate multiple shifted VLM samples into one packed sample.
Compute mRoPE 3D position IDs for a single sample.
Parameters:
Pretokenized sample dict holding input_ids of shape [seq]
(or [1, seq]) plus optional image_grid_thw/video_grid_thw/
attention_mask/mm_token_type_ids tensors mirroring it.
Bound model.get_rope_index callable. When its
signature requires mm_token_type_ids and the sample lacks it, the
tensor is rebuilt from the bound model config’s image/video token ids.
Returns: torch.Tensor | None
Position ids of shape [3, seq_len], or None if not applicable.
Estimate token count for one image from its [height, width] metadata.
Estimate token count from raw conversation without tokenization.
Uses pre-computed _text_tokens (from precompute_tokens.py) when
available, otherwise falls back to chars // 3. Media tokens are
estimated via smart_resize when processor configs are provided,
otherwise falls back to 500 per media item.
Parameters:
If True, return (total_tokens, media_tokens)
instead of just total_tokens.
Estimate token count for one video from its
[total_frames, height, width, fps, duration] metadata.
Apply per-sample autoregressive shift before concatenation.
Pack samples with standard FFD, then interleave bins by VT for balance.
Uses the standard greedy knapsack (FFD) for optimal packing efficiency, then reorders bins so that consecutive packs have similar visual token counts. This ensures data-parallel ranks in the same training step process packs with comparable VIT workload, reducing straggler effects.
Parameters:
Total token length (text + media) per sample.
Maximum capacity per pack.
Number of media tokens per sample.
Returns: list[list[int]]
A list of bins, where each bin is a list of sample indices.
Create a lazily-packed VLM dataset.
- Estimates token lengths from
ds_raw(no tokenization). - Runs knapsack to assign samples to bins. When
balance_media_tokens=True(default), uses a two-phase algorithm that balances visual token counts across packs, reducing VIT compute/memory imbalance and straggler effects. - Returns a
PackedDatasetWrapperwhose__getitem__tokenizes and builds packs on-the-fly in DataLoader workers.
Parameters:
PreTokenizedDatasetWrapper for per-sample tokenization.
Target packed sequence length (after shift).
Token ID for padding.
Drop samples whose estimated length exceeds
pack_size.
Optional cap on number of packs.
Optional model.get_rope_index for mRoPE.
Raw dataset (conversations) for fast length estimation.
Falls back to len(dataset) if not provided.
Fill ratio for knapsack bins (default 1.0).
E.g. 0.9 means knapsack only fills bins to pack_size * 0.9,
leaving 10% headroom to absorb estimation errors. This reduces
overflow drops at __getitem__ time. The actual pack_size
is still used as the hard limit.
Optional HuggingFace processor (e.g. Qwen2VLProcessor).
Used to extract image_processor / video_processor configs
for accurate media token estimation via smart_resize.
If True (default), use VT-balanced knapsack that distributes visual tokens evenly across packs. Falls back to standard knapsack if no media tokens are detected.
Returns: PackedDatasetWrapper
A PackedDatasetWrapper (torch Dataset).