Unit 10 of 11 · about 5 hours · implement
Deterministic shards, restart position and document-to-batch lineage
A run that cannot be resumed exactly, or a batch that cannot be traced to its documents, turns every later question (a loss spike, a deletion request, a contamination finding) into guesswork. Deterministic data order is also what lets a second person reproduce your result.
You'll be able to
- Implement shard assignment and batch order as pure functions of the dataset version, seed, epoch and step, with a manifest that lists every shard and its checksum, so that any batch can be regenerated without replaying earlier steps.
- Resume from a saved position and show that the remaining batches, and the documents in them, equal those of an uninterrupted run; find the omitted or repeated documents when a framework loses part of the state.
- Keep a lineage index from batch to sequence to document spans to raw record ids, and use it to answer which documents were in step and which steps saw document .
Covers
Read
In this order, only the parts listed
0 of 4 done
- Project: Tokenizer and Corpus PipelineTokenizer and Corpus Pipeline
'Core requirements' and 'Architecture constraints' (a manifest, never directory-order discovery), Milestone C, the failure injections of Milestone D, and 'Correctness requirements' (complete, nonoverlapping, checksummed, atomically published shards)
Take the sharding, resume and lineage requirements only; the tokenizer parts belong to earlier units.
- Hugging Face Datasets: StreamHugging Face Datasets: Stream
Sections 'Shard', 'Shuffle', 'Interleave', and 'Save a dataset checkpoint and resume iteration', including its tip on shuffle buffers (page read 2026-10-17, behavior re-run with datasets 5.1.0)
Use a tiny local dataset. Do not stream a web-scale corpus or push anything to the Hub.
- Dolma Toolkit: data formatDolma Toolkit
'Dolma Document Format' (the
sourceandidpair) and 'Dolma Toolkit Attributes Format' (attribute files that line up row for row with the documents); and in https://github.com/allenai/dolma/blob/669f534823b08d266a8fff01f8a1c916a5a56576/docs/taggers.md therandom_number_v1tagger for split assignment - Gopher, Appendix A (Rae et al., 2021)Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix A
Appendix A.1.2 'Constructing Token Sequences' (p. 42), steps 1 to 7 from drawing a document to shuffling and batching
Focus on
- Make position a value, not a hidden state. If the order of epoch is a function of the seed and alone, for example
np.random.Generator(np.random.PCG64([seed, epoch])).permutation(n), then batch is the slice of it and a resume needs only the epoch and step. A single random generator shared across epochs needs replaying to reach epoch 2. - Shard by a stable hash of the document id and list the result in the manifest. Python's built-in
hashof a string differs between processes, and changing the shard count moves most documents, so a shard is a manifest entry and not a directory listing. - Resume has to give each record exactly once. The documented tip says that with
.shuffle()the examples in the shuffle buffer are lost on resume; the reproduce step measures how many. - Lineage is a join. Keep one record per packed sequence with its
(doc_id, start, end)spans, join on the stablesourceandidpair, and build the inverse index from document to steps so that a deletion or contamination finding can name the batches and checkpoints affected.
Common mistakes · 3
- Losing records on resume while the loss looks fine. With datasets 5.1.0, a dataset of 40 rows in 4 shards,
shuffle(seed=7, buffer_size=8)and an interruption after 13 rows, the resumed run skipped 5 rows and repeated 1. Only a comparison of document ids with an uninterrupted run shows it. - Letting worker count change the data. If every worker shuffles its own shards, the content of batch depends on the number of workers and a rerun on other hardware gives different batches. Define batch content globally and let workers only fetch.
- Forgetting the unused tail. A partial last batch that is dropped means some sequences are not seen in that epoch, and with a new permutation each epoch it is a different set each time. Write the dropped sequence ids into the lineage record, or you cannot say that every document was seen.
Try it yourself
Closed-book, before checking anything
batch(version, seed, epoch, step) that returns the (doc_id, start, end) spans of that batch, taking the order of sequences from np.random.Generator(np.random.PCG64([seed, epoch])).permutation(n_sequences). Show that a run resumed at step 61 reproduces steps 61 onward of an uninterrupted run exactly (1,003 sequences, batch size 8, 125 steps, 3 sequences unused per epoch). Assign documents doc-000000 to doc-019999 to shards with the first eight bytes of a SHA-256 digest modulo , and show that only 20.0% keep their shard when goes from 4 to 5. Then break it twice: use the built-in hash and see the assignment change between fresh processes (in one run hash('doc-000001') % 4 gave 3, 0, 1, 3, 0, 3 over six processes), and resume a shuffled Hugging Face IterableDataset.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does computing the epoch order from
(seed, epoch)make resuming cheap, while one generator shared across epochs does not?AnswerThe permutation of any epoch can be recomputed directly, so a resume needs only the epoch and step. With one shared generator, the state at epoch 2 exists only after the earlier permutations have consumed it, so you must either store the generator state or replay the epochs, and a fresh generator gives a different permutation.
2.Documents are assigned to shards by a hash modulo . You change from 4 to 5. What happens, and what does it mean for lineage?Answer
About four in five documents move to another shard (20.0% stayed in the run above). Any record that names a shard becomes wrong, so lineage should refer to document ids and the manifest version, and a change of shard count must create a new dataset version.
3.The loss jumps after a resume. Name three data-side causes you can check from lineage.Answer
The shuffle buffer or other loader state was lost, so records are missing or repeated; the epoch, seed or worker count differs, so the order changed; or the dataset version or tail handling differs. Compare the document ids of steps to of the resumed run with those of an uninterrupted run.
4.A document must be removed. How do you find which batches and checkpoints are affected?Answer
Invert the lineage: document id to the sequences that contain its spans, to the (epoch, step) of each such sequence, to the first checkpoint saved after the earliest of those steps. The index must keep the dropped-tail sequences too, or you will miss documents that were never trained on.
Practice
- Hugging Face Datasets: checkpoint and resume an iterable dataset
'Save a dataset checkpoint and resume iteration': reproduce the documented example, then repeat it after
.shuffle(seed=7, buffer_size=8)on 40 rows in 4 shardsCount the rows missing and repeated against an uninterrupted run, then replace the shuffle with the order function from the reproduce step and show the counts go to zero. The section mini-project covers the batch-lineage index and the regenerate-any-batch test on your own corpus.
You're done when
Given a dataset version, seed, epoch and step, your code regenerates the same batch of token ids in two separate processes and after a simulated interruption, and your lineage index answers both the batch-to-documents and document-to-batches questions.
Only when you can do this without notes.
Leads to
- Immutable dataset versions, manifests, data cards and checkpoint linkageName the dataset version that every batch id refers to, and link it to checkpoints.
- Exact and statistical resume equivalence, and data discontinuity diagnosticsTest exact and statistical resume equivalence of the whole training state, using this data position.
Notes
Resources · 4 for this unit, 17 more in the section
- Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix ADeepMind · support
Read Appendix A.1 for the exact quality rules behind "Gopher-style" filters (50 to 100,000 words, mean word length 3 to 10, symbol ratios, bullet and ellipsis lines, the stop-word test) and A.5 for the datasheet. The rules are English-specific.
- Dolma ToolkitAllen Institute for AI · required
Read
docs/data-format.md(stable source and id, attributes aligned row for row),docs/taggers.md,docs/deduplication.mdanddocs/mixer.mdafter your CS336 pipeline works. Its deduplication is a Bloom filter over document keys or paragraphs, with possible false positives, not MinHash; record which production concerns your smaller pipeline omits. - Tokenizer and Corpus PipelineRoadmap-Final · support
Reuse the project correctness, lineage and contamination contracts. Extend the artifact instead of starting another tokenizer implementation.
- Hugging Face Datasets: StreamHugging Face · reference
Read Shard, Shuffle, Interleave, and Save a dataset checkpoint and resume iteration, including the tip that shuffle-buffer contents are lost when resuming. Use tiny local data and check resume by comparing document ids with an uninterrupted run; do not stream a web-scale corpus or upload to the Hub.
Also in this section
- CS336 Assignment 4 - DataStanford University · primary
Implement the handout functions in Sections 2.2 to 2.7 (
extract_text,language_identification, the PII masks, the harmful-content classifiers,gopher_quality_filter,classify_quality) and Section 3 (exact_deduplication,minhash_deduplication) until the 21 tests intests/pass on CPU. The 8-GPU leaderboard run is out of reach: replace it with one small local training comparison on a filtered sample and keep the retained-token and source-mix tables as evidence. - CS336 2026 - Data Lectures 13 and 14Stanford University · required
Step through the Lecture 13 trace (sources: WebText, Common Crawl, CCNet, C4, The Pile, MassiveText, RefinedWeb, Dolma, DCLM, Nemotron-CC, copyright) and the Lecture 14 trace (KenLM and fastText filters, importance resampling, Bloom filters, MinHash and LSH) at
cs336.stanford.edu/lectures/?trace=lecture_13and?trace=lecture_14. Reconcile each lecture claim with your Assignment 4 implementation. - Deduplicating Training Data Makes Language Models Better (Lee et al., 2022)Google Research · required
Read Section 4 (exact substring matching with suffix arrays, 50-token threshold justified in Appendix B, and MinHash near-duplicate removal) Section 5 (how much each dataset loses, including train-test overlap) and Section 6 (effects on perplexity and memorization). This is the method behind Assignment 4 Section 3; the 50-token threshold is tuned to English web text.
- Dolma: an Open Corpus of Three Trillion Tokens for Language Model Pretraining Research (Soldaini et al., 2024)Allen Institute for AI · support
Read Section 4.2 (data ablations) and Table 1 (the corpus card) as the template for your own data card. The token count depends on the tokenizer used to count.
- FineWeb Paper and DataTrove PipelineHugging Face · support
Read FineWeb Section 3 (each extraction, filtering and per-snapshot MinHash decision ablated on small models) and trace
examples/fineweb.pyin DataTrove at commit 1977fbb (14 bands x 8 hashes = 112 hashes, 5-gram words).LanguageFilter()with no arguments keeps every language above 0.65, so passlanguagesyourself; the cluster script is a reference, not a local run. - Resiliparse, fastText and datasketch on Four DocumentsOpen source · support
Build one CPU exercise: extract text with Resiliparse
extract_plain_text(it keeps navigation unless you passmain_content=True), identify language with fastTextlid.176.binandpredict(text, k=1), and find near duplicates with datasketchMinHashLSH. Check every candidate against exact shingle Jaccard: atthreshold=0.9the index uses 5 bands x 25 rows, so it is a candidate filter, not a hard cutoff. - Language Model Tokenizers Introduce Unfairness Between Languages (Petrov et al., 2023)University of Oxford · support
Read Section 3 (tokenization parity and premium) and Sections 4 and 5 (premiums on FLORES-200, cost and context consequences), then measure the premium of your own tokenizer on a parallel slice.
- Analysing the Impact of Sequence Composition on Language Model Pre-Training (Zhao et al., 2024)University of Edinburgh · support
Read Section 2 (random, same-source and retrieval packing; causal versus intra-document masking) and Table 1 (perplexity for each strategy). It is the source for testing cross-document attention leakage in your packed batches.
- Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus (Dodge et al., 2021)Allen Institute for AI · support
Read Sections 3 to 5: what C4 contains, what its filters removed, and how the blocklist removed text from and about minority groups. Use it to audit the trade-offs of your own PII and harm filters; it audits, it does not propose a recipe.
- Data Cards PlaybookGoogle Research · support
Follow the guide steps and use the templates to write the card for your filtered corpus: sources, rights, filters with removal rates, known gaps and intended use.
- Modern LLM Notebook - Data EngineeringWalking Labs · support
Work through
notebooks-en/part2-training/15-data-engineering.ipynb(extraction, quality filtering, deduplication, mixing). Reproduce its compact examples, then compare their assumptions with the stricter CS336 tests. - TensorTonic - Data Processing SetTensorTonic · support
Solve Perform Stable Exact Deduplication (
cs336-l14-stable-exact-deduplication), Build Deterministic MinHash Signatures (cs336-l14-minhash-signatures) and Compute Temperature-Based Data Mixtures (cs336-l14-temperature-data-mixture). Its MinHash uses SHA-256 of a seed and shingle, so outputs will not match datasketch. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - DataComp for Language ModelsDataComp-LM Team · depth
Read Section 4.4 and Table 4 (a fastText classifier keeping the top 10% of documents beat other filters), Figure 4 (removal at each stage) and the Section 3 compute table after the bounded data experiment. The repository dedups with a Bloom-filter tool (BFF), not MinHash, and CORE scores changed between v1 and v2, so never compare them directly.
- Unicode Standard Annex #15: Unicode Normalization FormsUnicode Consortium · reference
Read Sections 1.1 and 1.2: canonical versus compatibility equivalence, the four forms NFD, NFC, NFKD and NFKC, and why the compatibility forms can remove distinctions that matter. Use it to decide which form belongs to a matching key and which, if any, to stored text.
- Tulu 3: Pushing Frontiers in Open Language Model Post-Training, Section 3.2Allen Institute for AI · support
Read Section 3.2 'Prompt Decontamination' (p. 14 of arXiv:2411.15124v5): the comparison of full-string, n-gram and embedding matching, the 8-gram rule on prompts only, the 50% token-coverage test per instance and the 2% rule per dataset. Use it as a worked example of choosing the match unit and thresholds from the evaluation items.
- FLORES-200 parallel sentencesMeta AI · support
Use the devtest split (1,012 sentences, the same sentences in the same order for every language) to measure tokenizer premiums and per-language language-ID retention. The dataset card lists CC BY-SA 4.0 (page read 2026-10-16). The repository is archived and points to a successor; keep the original release for results you want to compare with Petrov et al.
- Scaling Data-Constrained Language Models (Muennighoff et al., 2023)Hugging Face · support
Read Section 3.1 (Equation 5, the effective-data term for repeated tokens), Section 6 with Figure 1 (return on compute when repeating data) and Appendix A (the derivation and the fitted constants). Use it to convert epochs into effective tokens and to see how far that fit reaches: models up to 9B parameters on C4 subsets.