Megatron tokenization pipeline
Description
In this PR I’m including the MegatronTokenizerWriter, which tokenizes and produces the .bin and .idx files required for training with Megatron and its dataloading solution.
- The
.binfile contains the tokenized documents. We will use 4 bytes per token if the vocabulary size is greater than2**16; otherwise, we’ll use 2 bytes per token. - The
.idxfile contains metadata about the.binfile, mainly the number of tokenized documents and their lengths. More details about this can be found in theclosemethod ofMegatronTokenizerWriter.
At first, I tried creating a CompositeStage using TokenizerStage, but as we already discussed, TokenizerStage caused OOM issues. To address this, I added a batch_size argument that controls how many documents we tokenize at once, write to disk, and then immediately discard.
I’ve also included the tokenizer-test folder, which contains the test.sh script I used to verify that the produced files match those created by Megatron’s preprocess_data.py script. To run the checks, you only need to set the DATA_ROOT folder in the script and execute it; it will clone Megatron, start the Ray server, download and convert the TinyStories dataset to JSONL, tokenize the dataset with 8 different configurations, and finally confirm that the files generated by Curator and the Megatron script match.
We perform this validation using 4 different tokenizers, including in the dataset one sample with all tokenizer-specific special tokens, and toggling the append_eod config (also present in the Megatron script). Of these 4 tokenizers, GPT-2 uses 2 bytes per token since its vocabulary size is ≤ 2**16.
I’m now writing some unit tests, similar to the ones in tests/stages/text/io/writer/test_jsonl.py. I’d like to know whether…
- I should write any specific documentation
- I should include any tutorial. Perhaps I could add an option to use the
MegatronTokenizerWriterintutorials/text/tinystories/main.py— what do you think?
Let me know your thoughts!
Usage
# Define the processing stages
stages = [
# Read the data from the JSONL files
JsonlReader(
file_paths="data/raw"
fields="text",
),
# Tokenize the data
MegatronTokenizerWriter(
path="data/tokenized-dataset",
model_identifier="unsloth/Mistral-Nemo-Instruct-2407-bnb-4bit",
append_eod=True,
text_field="text",
),
]
# Create a pipeline with the stages
pipeline = Pipeline(
name="megatron-tokenize",
description="Tokenize dataset for Megatron-LM.",
stages=stages,
)
Checklist
- [x] I am familiar with the Contributing Guide.
- [ ] New or Existing tests cover these changes.
- [ ] The documentation is up to date with these changes.
Greptile Overview
Greptile Summary
This PR introduces MegatronTokenizerWriter, a new stage that tokenizes documents and produces .bin and .idx files compatible with Megatron-LM's dataloader. Key changes:
- New tokenization writer: Implements Megatron-LM compatible file format with proper byte encoding (2 bytes for vocab ≤ 65536, 4 bytes otherwise)
- Batch processing: Added
tokenization_batch_sizeparameter to control memory usage during tokenization - Error handling: Proper cleanup of partial files on failure
- Tutorial and documentation: Includes comprehensive tutorial with TinyStories dataset example
Confidence Score: 4/5
- This PR is safe to merge with minor considerations around error handling edge cases
- Well-structured implementation following existing codebase patterns. Comprehensive tests cover key functionality. Minor type annotation inconsistency in _sequence_pointers method doesn't affect runtime behavior.
- nemo_curator/stages/text/io/writer/megatron_tokenizer.py - verify .bin cleanup on .idx write failure
Important Files Changed
File Analysis
| Filename | Score | Overview |
|---|---|---|
| nemo_curator/stages/text/io/writer/megatron_tokenizer.py | 4/5 | New MegatronTokenizerWriter class that tokenizes documents and produces .bin/.idx files for Megatron-LM training. Handles error cleanup and token encoding with configurable batch sizes. |
| nemo_curator/stages/text/io/writer/utils.py | 5/5 | Added batched() utility function based on itertools recipe. Clean implementation with proper validation. |
| tests/stages/text/io/writer/test_megatron_tokenizer.py | 4/5 | Comprehensive test suite covering tokenization, batch sizes, EOD handling, and file overwrite behavior. |
| tutorials/text/megatron-tokenizer/main.py | 5/5 | Tutorial demonstrating MegatronTokenizerWriter usage with TinyStories dataset. |
Sequence Diagram
sequenceDiagram
participant P as Pipeline
participant M as MegatronTokenizerWriter
participant T as HF Tokenizer
participant FS as Filesystem
P->>M: setup_on_node()
M->>T: snapshot_download(model_identifier)
T-->>M: Model cached
P->>M: setup()
M->>T: AutoTokenizer.from_pretrained(local_files_only=True)
T-->>M: Tokenizer loaded
P->>M: process(DocumentBatch)
M->>M: Generate filename (hash or UUID)
loop For each batch
M->>T: batch_encode_plus(texts)
T-->>M: input_ids
M->>M: Append EOD if enabled
M->>FS: Write tokens to .bin file
end
M->>FS: Write metadata to .idx file
M-->>P: FileGroupTask([.bin, .idx])