nemo_automodel.components.datasets.llm
nemo_automodel.components.datasets.llm
Subpackages
Submodules
nemo_automodel.components.datasets.llm.agent_chatnemo_automodel.components.datasets.llm.chat_datasetnemo_automodel.components.datasets.llm.column_mapped_text_instruction_datasetnemo_automodel.components.datasets.llm.column_mapped_text_instruction_iterable_datasetnemo_automodel.components.datasets.llm.delta_lake_datasetnemo_automodel.components.datasets.llm.dspark_cachenemo_automodel.components.datasets.llm.eagle3nemo_automodel.components.datasets.llm.eagle3_cachenemo_automodel.components.datasets.llm.formatting_utilsnemo_automodel.components.datasets.llm.hellaswagnemo_automodel.components.datasets.llm.length_grouped_samplernemo_automodel.components.datasets.llm.megatron_datasetnemo_automodel.components.datasets.llm.mocknemo_automodel.components.datasets.llm.mock_iterable_datasetnemo_automodel.components.datasets.llm.mock_packednemo_automodel.components.datasets.llm.mock_prefix_treenemo_automodel.components.datasets.llm.mock_seq_clsnemo_automodel.components.datasets.llm.nanogpt_datasetnemo_automodel.components.datasets.llm.neat_packingnemo_automodel.components.datasets.llm.offline_cachenemo_automodel.components.datasets.llm.packed_sequencenemo_automodel.components.datasets.llm.prefix_treenemo_automodel.components.datasets.llm.retrieval_collatornemo_automodel.components.datasets.llm.retrieval_datasetnemo_automodel.components.datasets.llm.retrieval_dataset_inlinenemo_automodel.components.datasets.llm.retrieval_dataset_normalizednemo_automodel.components.datasets.llm.retrieval_distill_collatornemo_automodel.components.datasets.llm.seq2seqnemo_automodel.components.datasets.llm.seq_clsnemo_automodel.components.datasets.llm.squadnemo_automodel.components.datasets.llm.xlam
Package Contents
Classes
Functions
API
Collator for encoder retrieval training.
This collator handles tokenization of queries and documents at batch time, which is more memory-efficient than pre-tokenization and allows for dynamic padding based on batch max length.
Based on EncoderCollator from nemo-retriever-research but adapted for Automodel.
Collate a batch of examples.
Parameters:
List of examples, each with ‘question’, ‘doc_text’, ‘doc_image’ keys
Returns: Dict[str, torch.Tensor]
Dictionary with:
Convert dictionary of lists to list of dictionaries.
Example: Input: {‘a’: [1, 2], ‘b’: [3, 4]} Output: [{‘a’: 1, ‘b’: 3}, {‘a’: 2, ‘b’: 4}]
Merge query and document batches into a single dictionary.
Adapted from nemo-retriever-research/src/loaders/loader_utils.py
Collator for bi-encoder distillation with explicit positive/negative splits.
Bases: Dataset
Dataset for OpenAI-format tool-calling chat transcripts.
Each row should contain a messages list in OpenAI chat format (role /
content), potentially including tool calls and tool responses. Rows that
instead carry a ShareGPT conversations list (from / value, as used by
PerfectBlend and similar) are auto-converted, so no manual column rename is
needed. The conversation is formatted via the tokenizer’s chat template to
produce input_ids, labels, and attention_mask suitable for SFT.
In place, keep only the final contiguous supervised run; mask the rest.
Supervised positions are those != unsupervised_value (0 for loss_mask,
-100 for labels). Used for mask_history: a multi-turn conversation has
one supervised run per assistant turn separated by unsupervised user turns;
this collapses it to the last turn so the supervised tokens form a single
suffix.
Bases: Dataset
Generic instruction-tuning dataset that maps arbitrary column names.
The class is intentionally lightweight: it simply loads the raw samples (either from HF or from local JSON/JSONL files) and remaps the columns so that downstream components can rely on a consistent field interface.
Optionally, if answer_only_loss_mask is requested, the dataset will also compute a loss_mask indicating which tokens should contribute to the loss (typically only those belonging to the assistant answer).
Returns the item at the given index.
Parameters:
The index of the item to return.
Returns:
A dictionary with the mapped columns.
Returns the length of the dataset.
Returns: int
The length of the dataset.
Tokenize a mapped sample and compute auxiliary fields.
If the tokenizer is provided:
- If the tokenizer supports a chat template, the dataset will be tokenized in a conversation style.
- Otherwise, the dataset will be tokenized in a simple prompt-completion style.
Parameters:
A dictionary with the mapped columns.
Returns: Dict[str, List[int]]
A dictionary with the tokenized columns.
Bases: IterableDataset, ColumnMappedTextInstructionDataset
Streaming iterable variant that reuses the column-mapping/tokenization logic.
This wraps a Hugging Face streaming dataset (IterableDataset from datasets)
or Delta Lake table and yields tokenized samples compatible with the non-streaming
variant, while supporting sharding and epoch-setting for deterministic shuffles upstream.
Supports the following data sources:
- HuggingFace Hub datasets
- Local JSON/JSONL files
- Delta Lake tables (via delta://, dbfs:/, or local directories with _delta_log)
Bases: DataCollatorWithPadding
Collate query-document pairs for cross-encoder reranking.
Save the training format as a standard named tokenizer chat template.
The reranking template accepts flat query/document messages. It includes
the tokenizer’s single-sequence special-token prefix and suffix because
tokenizer chat templates bypass automatic special-token insertion.
Sentence Transformers restores the special-token suffix after truncation.
Raises:
ValueError: If truncation is not right-sided, the prompt ends in fixed text, or the tokenizer does not use a portable special-token prefix/suffix with zero token type IDs.
HuggingFace datasets-compatible wrapper for Delta Lake tables.
This class provides better integration with the HuggingFace datasets library, supporting features like sharding, shuffling, and epoch setting for distributed training scenarios.
Parameters:
Path to the Delta Lake table.
Optional list of column names to read.
Optional dict of storage options for cloud authentication.
Optional specific version of the Delta table to read.
Get a specific row by index.
Iterate over rows in the dataset.
Return the number of rows in the table.
Set the current epoch for deterministic shuffling.
Parameters:
The epoch number.
Shard the dataset for distributed processing.
Parameters:
Total number of shards.
Index of this shard (0-based).
Returns: 'DeltaLakeDataset'
Self for method chaining.
Configure shuffling for the dataset.
Note: For streaming Delta Lake datasets, shuffling is performed on-the-fly using a shuffle buffer. The actual shuffling happens during iteration.
Parameters:
Size of the shuffle buffer.
Random seed for reproducibility.
Returns: 'DeltaLakeDataset'
Self for method chaining.
Limit the dataset to the first n samples.
Parameters:
Number of samples to take.
Returns: 'DeltaLakeDataset'
A new DeltaLakeDataset limited to n samples.
Bases: IterableDataset
Dataset class for NanoGPT Dataset.
A NanoGPT Dataset is a dataset that stores tokens in a binary file. The header contains:
- 256x4-byte header (magic number, version, num_tokens, dtype.itemsize)
- And the tokens themselves.
Optionally, a corresponding .bos.idx file can be present alongside each .bin file
containing precomputed BOS token positions for efficient alignment when
align_to_bos=True. If the index file is not present, the dataset falls back
to linear search for BOS tokens.
Parameters:
str | Sequence[str]
Glob pattern (e.g. "data/fineweb_*_train_*.bin") or an explicit
list of file paths.
int
Length of the training sample returned (not counting the next-token
target). labels are simply inputs[1:].
bool, default False Shuffle the order of shards each epoch/iteration.
bool, default False
Ensure that every slice starts with bos_token. When enabled, the
dataset searches forward from the current position until it finds the
next BOS token and starts there. Uses .bos.idx files when available
for efficient search, falls back to linear search otherwise.
Requires bos_token to be provided.
int, optional, default None. Token ID marking beginning-of-document.
Iterate over training samples from the dataset.
Generate training samples from all assigned files, handling infinite iteration.
Parameters:
List of files assigned to this worker
Random number generator for shuffling
Whether we’re splitting a single file among workers
Starting position in file (for single file splitting)
Ending position in file (for single file splitting)
Process tokens from a single file and yield training samples.
Parameters:
Path to the .bin file to process
Whether we’re splitting a single file among workers
Starting position in the file (for single file splitting)
Ending position in the file (for single file splitting)
Set up worker-specific context including file assignment and splitting parameters.
Returns: tuple[List[str], random.Random, bool, int, int]
Tuple of (worker_files, rng, split_single_file, file_start_pos, file_end_pos)
Expose one method of a multimodal processor as a dataloader collator.
Return the passage prefix owned by the underlying processor.
Return the query prefix owned by the underlying processor.
Collate retrieval examples with the resolved processor method.
Parameters:
Retrieval examples for one local batch.
Returns: dict[str, object]
Processor-produced tensor batch.
Check if a path refers to a Delta Lake table.
A path is considered a Delta Lake path if:
- It starts with “delta://” protocol prefix
- It’s a local directory containing a “_delta_log” subdirectory
- It starts with “dbfs:/” (Databricks file system)
Parameters:
The path to check.
Returns: bool
True if the path is a Delta Lake table, False otherwise.
Load a multi-turn function-calling SFT dataset.
Exactly one of dataset_name (HuggingFace Hub id) or path (local
JSON/JSONL file or list of files) must be provided. The loaded examples
are lazily rendered through the tokenizer’s chat template; tool/user
tokens are excluded from the loss via answer_only_loss_mask=True.
Parameters:
HuggingFace tokenizer with a chat template.
HF Hub dataset id, e.g. llamafactory/glaive_toolcall_en.
Local JSON/JSONL file path or list of paths.
Dataset split (only used with dataset_name).
Optional Hugging Face dataset revision. Agent trace repositories
may expose training-ready rows under refs/convert/parquet.
If True, discard incomplete traces that contain no assistant message and therefore have no supervised target.
If True, discard traces that still exceed seq_length
after whole-exchange history truncation. This avoids token-level
truncation changing chat-template prefixes while answer-only loss
masks are constructed.
If True, discard messages after the final assistant message so an unfinished user turn cannot replace the supervised target during history truncation.
Optional Jinja template string or file path overriding
tokenizer.chat_template.
Optional max sequence length for the tokenizer.
If set, keep only the first N examples.
Padding strategy forwarded to the tokenizer.
Truncation strategy forwarded to the tokenizer.
If True, exclude assistant reasoning_content
(thinking) tokens from the loss while still rendering them into the
prompt. Requires a chat template that emits reasoning_content.
Defaults to False, which trains on reasoning tokens like any other
assistant content.
If True, exclude from the loss the tokens of each
assistant turn that the chat template’s generation prompt supplies at
inference: the role header and any template-inserted empty reasoning
block (for example the <think></think> Nemotron templates
emit for non-thinking turns). The model never generates
those tokens, so supervising them only reinforces template
boilerplate. Detected per template by rendering the generation
prompt, so no tag strings are hardcoded. Defaults to False.
If True, supervise only the final assistant
turn of each dialogue (mask_history); all earlier assistant
turns are excluded from the loss. Defaults to False, which
supervises every assistant turn.
If True, strip reasoning_content
from all but the final assistant turn so historical thinking is not
rendered into the prompt (matching inference, where prior-turn
thinking is not visible). Orthogonal to mask_reasoning_content:
this controls whether history thinking appears in the prompt at all,
the latter controls whether rendered thinking contributes to loss.
Defaults to False, which keeps every turn’s reasoning_content.
If True and seq_length is set, drop the oldest
conversation exchanges (keeping any leading system message, the tool
definitions, and the final exchange) until the dialogue fits
seq_length. Unlike token-level truncation, which clips from
the tokenizer side and usually drops the final assistant answer,
this preserves the supervised target. Defaults to False.
Returns: LazyMappedDataset
A LazyMappedDataset yielding dicts with input_ids, labels
Build a normalized portable retrieval dataset from local Arrow bundles.
Parameters:
Bundle path or source entries. Use either this field or data_dir_list.
Retrieval model type, either bi_encoder or cross_encoder.
Dataset mode, either train or eval.
Number of passages per training query, including the positive passage.
Number of negative passages per evaluation query.
Random seed used for source sampling and optional shuffling.
Whether to shuffle before applying max_train_samples.
Optional cap on the combined training rows.
Starting row for the training sample cap.
Whether to attach corpus query and passage instructions.
Whether to cycle through positive documents by epoch.
Whether image documents should also include their text.
Legacy alias for data_path used by existing retrieval configs.
Returns: Any
A Hugging Face dataset with a lazy retrieval transform attached.
Load and return dataset in retrieval format for encoder training.
Entries in data_dir_list can be local corpus JSON or inline JSONL file paths or hf:// URIs
pointing to a Hugging Face dataset repository (for example,
hf://nvidia/embed-nemotron-dataset-v1/SciFact). A source can also be
provided as {"path": path_or_uri, "num_samples": N} to sample a fixed
subset once while loading. Uses set_transform() for lazy evaluation —
tokenization is handled by the collator.
Parameters:
Path(s) to corpus JSON or inline JSONL files, hf:// URIs, or dictionary entries with path and
num_samples.
“bi_encoder” (default) or “cross_encoder”
Type of data (“train” or “eval”)
Number of passages (1 positive + n-1 negatives)
Number of negative documents for evaluation
Random seed for reproducibility (for shuffling if needed)
Shuffle dataset rows before subset selection. Only applied when
max_train_samples is set; otherwise iteration order is controlled by
the dataloader’s sampler (e.g. StatefulDistributedSampler).
Maximum number of training samples to use
Offset for selecting training samples
Whether to use instruction from dataset’s metadata
Whether training should cycle through positive documents across epochs.
Defaults to False (always use the first positive document). Set to True only
when a query has multiple positive documents and you want to rotate through them by epoch.
Whether image documents should also include their text.
Returns:
A HuggingFace Dataset where each example is a dict with keys:
Direct hf:// loading currently supports HF datasets that already follow
the Automodel retrieval schema (corpus-id based layout used by
nvidia/embed-nemotron-dataset-v1 subsets such as FEVER and
SyntheticClassificationData). For other HF dataset formats, implement a
custom adapter/preprocessor before calling this loader.
Tokenization should be handled by a collator (e.g., BiEncoderCollator) which is more efficient for batch padding and supports dynamic processing.
Load and preprocess a SQuAD-style QA dataset for model fine-tuning.
This function retrieves the specified split of the SQuAD dataset, applies
either a simple prompt–completion format or a chat‐template format
(if tokenizer.chat_template is set), tokenizes each example,
constructs input_ids and labels, and optionally pads
all sequences to a fixed length.
Parameters:
A Hugging Face tokenizer with attributes
eos_token_id, optional bos_id, optional eos_id, and
optionally chat_template/apply_chat_template.
If set, pad/truncate each example to this length.
If set, limit the number of examples loaded from the split.
Flag for future use (e.g., mixed precision). Currently unused.
Which split of the dataset to load (e.g. ‘train’, ‘validation’).
Identifier for the Hugging Face dataset (default “rajpurkar/squad”).
Optional padding strategy.
Optional truncation strategy.
Optional Jinja template string or path overriding tokenizer.chat_template.
Returns:
A Hugginggth Face Dataset where each example is a dict with keys:
Turns a method of a processor into a collator function.
Parameters:
The processor instance.
The name of the processor method to turn into a collator function.
Returns: Callable[[list[dict[str, object]]], dict[str, object]]
A collator for vision/multimodal retrieval datasets.
Load and preprocess the xLAM function-calling dataset to OpenAI messages compatible with the bulbasaur chat template (tool-calling aware).
Each example is formatted as:
- user: the natural language query
- assistant: emits tool_calls with serialized arguments
- tools: OpenAI function schema derived from the dataset tool specs