bridge.data.datasets.gpt_sft#
Module Contents#
Classes#
Deterministically blend several compatible GPT SFT datasets. |
|
Dataset class for chat-based fine-tuning with optional HuggingFace chat template support. |
Functions#
Returns the root directory for NeMo datasets, creating it if it doesn’t exist. |
Data#
API#
- bridge.data.datasets.gpt_sft.DEFAULT_NEMO_CACHE_HOME#
None
- bridge.data.datasets.gpt_sft.NEMO_CACHE_HOME#
‘Path(…)’
- bridge.data.datasets.gpt_sft.DEFAULT_NEMO_DATASETS_CACHE#
None
- bridge.data.datasets.gpt_sft.NEMO_DATASETS_CACHE#
‘Path(…)’
- bridge.data.datasets.gpt_sft.DEFAULT_NEMO_MODELS_CACHE#
None
- bridge.data.datasets.gpt_sft.NEMO_MODELS_CACHE#
‘Path(…)’
- bridge.data.datasets.gpt_sft.logger#
‘getLogger(…)’
- bridge.data.datasets.gpt_sft.PREFIX_STR#
‘\x00’
- bridge.data.datasets.gpt_sft.__idx_version__#
‘0.2’
- bridge.data.datasets.gpt_sft.__idx_suffix__#
‘idx’
- bridge.data.datasets.gpt_sft.get_dataset_root(name: str) pathlib.Path#
Returns the root directory for NeMo datasets, creating it if it doesn’t exist.
- Parameters:
name (str) – The name of the dataset, used to create a subdirectory within the NeMo datasets cache.
- Returns:
The path to the dataset’s root directory.
- Return type:
Path
- class bridge.data.datasets.gpt_sft.GPTSFTDataset(
- file_path: str,
- tokenizer: megatron.bridge.training.tokenizers.tokenizer.MegatronTokenizer,
- max_seq_length: int = 1024,
- min_seq_length: int = 1,
- pad_seq_length_to_mult: int = 16,
- add_bos: bool = False,
- add_eos: bool = True,
- add_sep: bool = False,
- sep_id: int = None,
- max_num_samples: int = None,
- seed: int = 1234,
- label_key: str = 'answer',
- answer_only_loss: bool = True,
- truncation_field: str = 'text',
- pad_to_max_length: bool = False,
- index_mapping_dir: str = None,
- prompt_template: str = None,
- virtual_tokens: int = 0,
- tokens_to_generate: int = 0,
- memmap_workers: int | None = None,
- hf_dataset: bool = False,
- global_sample_mapping: bool = False,
- truncation_method: str = 'right',
- special_tokens: Mapping[str, str] | None = None,
- is_test: bool = False,
- output_original_text: bool = False,
- ceil_to_power_2: bool = False,
- get_attention_mask_from_fusion: bool = True,
- prompt_completion_config: megatron.bridge.data.sft_processing.PromptCompletionSFTPreprocessingConfig | None = None,
- enable_in_batch_packing: bool = False,
- in_batch_packing_pad_to_multiple_of: int = 1,
- return_padding_mask: bool = False,
- enable_global_batch_packing: bool = False,
- global_batch_packing_pad_to_multiple_of: int = 1,
- fold_alignment_padding: bool = False,
Bases:
torch.utils.data.DatasetInitialization
file_path: Path to a JSONL GPT supervised fine-tuning dataset. Data is formatted as multiple JSON lines with each line formatted as follows: { 'input': 'John von NeumannVon Neumann made fundamental contributions … Q: What did the math of artificial viscosity do?’, ‘output’: ‘smoothed the shock transition without sacrificing basic physics’ } tokenizer: Tokenizer for the dataset. Instance of a class that inherits MegatronTokenizer (ex: SentencePiece). max_seq_length (int): maximum sequence length for each dataset examples. Examples will either be truncated to fit this length or dropped if they cannot be truncated. min_seq_length (int): min length of each data example in the dataset. Data examples will be dropped if they do not meet the min length requirements. add_bos (bool): Whether to add a beginning of sentence token to each data example add_eos (bool): Whether to add an end of sentence token to each data example add_sep (bool): Whether to add a separation token to each data example (goes between prompt and answer) tokens_to_generate (int): (inference only) Number of tokens to generate during inference seed: Random seed for data shuffling. max_num_samples: Maximum number of samples to load. This can be > dataset length if you want to oversample data. If None, all samples will be loaded. label_key: Key to use for the label in your JSONL file answer_only_loss: If True, will compute the loss only on the answer part of the input. If False, will compute the loss on the entire input. truncation_field: Field to use for truncation. (Options: keys in prompt_template). Field to be used for truncation if the combined length exceeds the max sequence length. pad_to_max_length: Whether to pad the input to the max sequence length. If False, will pad to the max length of the current batch. return_padding_mask: Emit a boolean token-validity mask for MoE routing. True entries identify padding, independently of the supervision mask. index_mapping_dir: Directory to save the index mapping to. If None, will write to the same folder as the dataset. prompt_template: Prompt template to inject via an fstring. Formatted like Q: {context_key}
A: {label_key} hf_dataset: Whether to load the json file with the HuggingFace dataset. Otherwise, will load the jsonl file with the JSONLMemMapDataset. global_sample_mapping: Whether to shuffle all data together, or shuffle the dataset within each epoch truncation_method: Truncation from which position. Options: [‘left’, ‘right’] special_tokens: special tokens for the chat prompts, a dictionary of {token_type: token}. Default: { ‘system_turn_start’: ‘<extra_id_0>’, ‘turn_start’: ‘<extra_id_1>’, ‘label_start’: ‘<extra_id_2>’, ‘end_of_turn’: ‘ ‘, ‘end_of_name’: ‘ ‘ } is_test: Whether this dataset is the test split. output_original_text (bool): if true, will keep the original text in the output alongside the tokenized ids. get_attention_mask_from_fusion (bool): if true, lets attention kernel handle creation of causal mask instead of adding it to the batch dict. prompt_completion_config: Explicit paired-text preprocessing that replaces the legacy prompt-template settings when set. enable_in_batch_packing: Whether to concatenate the logical microbatch into one physical THD row during collation. in_batch_packing_pad_to_multiple_of: Per-sequence alignment multiple used by in-batch packing for context and sequence parallelism. enable_global_batch_packing: Whether to yield one unpacked sample per row for Megatron-Core’s online sequence-packing scheduler instead of a batch. global_batch_packing_pad_to_multiple_of: Per-sequence alignment multiple used by global-batch packing for context and sequence parallelism. fold_alignment_padding: Whether to report each row’s alignment padding as part of the sequence (still loss-masked) so packed bins carry no padding between sequences; see
megatron.bridge.data.packing.global_batch.fold_alignment_padding.- _load_dataset()#
- _maybe_validate_prompt_template()#
- _build_samples_mapping()#
- __len__()#
Return the total number of samples in this dataset.
- __getitem__(idx)#
- _separate_template(prompt_template_values: list[str])#
Combine contexts and label based on prompt_template into a list of strings and a list of keys.
- Parameters:
prompt_template_values (list[str]) – the list of context and label strings extrated from jsonl file with prompt_template_keys.
- Returns:
separated prompt_template with contexts/label placeholder filled with corresponding strings template_strings_keys (list[str]): strings point to placeholder keys or
- Return type:
template_strings (list[str])
.. rubric:: Examples
prompt_template = ‘Context: {context} Question: {question} Answer: {label}’ prompt_template_values = [‘xxx’, ‘yyy’, ‘zzz’]
tokenizer.space_sensitive = True#
template_strings = [‘Context:’, ‘ xxx’, ‘ Question:’, ‘ yyy’, ‘ Answer:’, ‘ zzz’]
tokenizer.space_sensitive = False#
template_strings = [‘Context:’, ‘ xxx’, ‘Question:’, ‘yyy’, ‘Answer:’, ‘zzz’]
template_strings_keys = [’’, ‘context’, ‘’, ‘question’, ‘’, ‘label’]
- _multiple_truncation(
- template_ids: list[list[int]],
- template_ids_keys: list[str],
Calculate total tokens and truncate multiple contexts in truncation_fields.
- Parameters:
template_ids (list[list[int]]) – the list of separate prompt_template ids.
template_ids_keys (list[str]) – the list of placeholder keys or (used to check key in truncation_fields).
- Returns:
all context ids. label_ids (list[int]): all label ids.
- Return type:
context_ids (list[int])
- _truncation(ids, expect_length)#
- _process_example(example)#
Create an example by concatenating text and answer. Truncation is carried out when needed, but it is performed only on the prompt side. BOS, EOS, and SEP, are added if specified.
- _maybe_cast_to_list(x)#
- _ceil_to_nearest(n, m)#
- _collate_item(item, max_length, pad_id)#
- _is_autogenerated(processed_example)#
- _build_padding_mask(
- batch: list[dict[str, Any]],
- max_length: int,
Exclude right padding and synthetic rows while retaining prompt tokens.
- _build_loss_mask(processed_example)#
Pad input_ids in batch to max batch length while building loss mask
- _create_attention_mask(max_length)#
Creates an upper-triangular causal attention mask.
- Parameters:
input_ids – A 1D tensor that holds the indices of tokens.
- _collate_unpacked_rows(
- batch: list[dict[str, Any]],
Return one unpacked scheduler sample per row for global-batch packing.
Megatron-Core’s online packing scheduler forms the THD bins itself (over the global batch, across DP x CP ranks), so this collate only shifts labels, builds the loss mask, and pads each sequence to the CP alignment multiple.
- _collate_in_batch(
- batch: list[dict[str, Any]],
Collate processed SFT rows into one physical THD batch row.
- collate_fn(batch)#
Collate a list of samples into a batch dictionary for model training or evaluation.
This function takes a list of individual processed samples (from
__getitem__) and groups them into a batch. It handles padding of sequences to the maximum length found in the batch (orself.max_seq_lengthifpad_to_max_lengthis True), and prepares all necessary tensors for the model.- Parameters:
batch (List[dict]) – A list of dictionaries, where each dictionary is a sample processed by
_process_example.- Returns:
A dictionary of batched tensors ready for model input. Key tensors include ‘tokens’, ‘labels’, ‘loss_mask’, ‘position_ids’, and ‘attention_mask’.
- Return type:
dict
- class bridge.data.datasets.gpt_sft.GPTSFTBlendDataset(
- datasets: collections.abc.Sequence[bridge.data.datasets.gpt_sft.GPTSFTDataset],
- weights: collections.abc.Sequence[float] | None,
- *,
- size: int | None = None,
- seed: int = 1234,
Bases:
torch.utils.data.DatasetDeterministically blend several compatible GPT SFT datasets.
Source selection uses a low-discrepancy weighted schedule. Samples within each source are shuffled without replacement for every source-local pass and repeat only when the requested blend size exceeds that source’s size.
- Parameters:
datasets – Compatible GPT SFT datasets, one per logical source.
weights – Positive relative sampling weights. When omitted, weights are proportional to source lengths, so the default-size blend includes every source row exactly once.
size – Number of rows exposed by the blend. Defaults to the sum of the source lengths.
seed – Seed for deterministic source-local shuffling.
Initialization
- __len__() int#
Return the configured number of blended rows.
- __getitem__(idx: int) dict[str, Any]#
Return the row selected by the blend mapping.
- collate_fn(
- batch: list[dict[str, Any]],
Collate blended samples with the common source collator.
- _build_indices() tuple[numpy.ndarray, numpy.ndarray]#
Build deterministic source and source-local sample mappings.
- class bridge.data.datasets.gpt_sft.GPTSFTChatDataset(
- file_path: str,
- tokenizer: megatron.bridge.training.tokenizers.tokenizer.MegatronTokenizer,
- use_hf_tokenizer_chat_template: bool = True,
- loss_mode: Literal[assistant, last_turn, full] = 'assistant',
- tool_schemas: str | dict | None = None,
- **kwargs,
Bases:
bridge.data.datasets.gpt_sft.GPTSFTDatasetDataset class for chat-based fine-tuning with optional HuggingFace chat template support.
Supports both legacy special token-based formatting and modern HuggingFace chat templates.
Initialization
Initialize GPTSFTChatDataset with optional HuggingFace chat template support.
Accepts conversational data in ShareGPT format. If use_hf_tokenizer_chat_template is True, the dataset will accept both ShareGPT and HuggingFace chat template format. In the case of ShareGPT format, it will try to convert to HuggingFace format.
ShareGPT format: {“conversations”: [{“value”: “…”, “from”: “User”}, {“value”: “…”, “from”: “Assistant”}]}
HuggingFace chat template format: { “messages”: [ {“role”: “system”, “content”: “…”}, {“role”: “user”, “content”: “…”}, {“role”: “assistant”, “content”: “…”} ] }
- Parameters:
file_path – Path to the dataset file
tokenizer – Tokenizer instance
use_hf_tokenizer_chat_template – If True, use HuggingFace tokenizer’s
apply_chat_template. Defaults to True; set to False only for the legacy special-token formatter.loss_mode – Assistant-only, final-assistant-turn, or full-sequence loss.
tool_schemas – Tool schemas for function calling (JSON string or dict)
**kwargs – Additional arguments passed to parent GPTSFTDataset
- _maybe_validate_prompt_template()#
- _build_samples_mapping()#
- _process_example(example)#
Create an example by concatenating text and answer. Truncation is carried out when needed, but it is performed only on the prompt side. BOS, EOS, and SEP, are added if specified.
- collate_fn(batch)#
Collates a list of processed chat examples into a batch for model input.
This function takes a list of individual processed chat samples (from
__getitem__, which internally uses_process_example) and groups them into a batch. It handles padding of sequences to the maximum length in the batch (orself.max_seq_lengthifpad_to_max_lengthis True), and prepares all necessary tensors for the model, similar to the base class collate_fn but specific to chat data structure.- Parameters:
batch (List[dict]) – A list of dictionaries, where each dictionary is a sample processed by
_process_example.- Returns:
A dictionary of batched tensors ready for model input. Key tensors include ‘tokens’, ‘labels’, ‘loss_mask’, ‘position_ids’, and ‘attention_mask’.
- Return type:
dict