Unit 8 of 11 · about 3 hours · implement
Document packing, boundary tokens and cross-document attention leakage
Packing is how short documents fill a fixed context. With a plain causal mask a later document can read an earlier, unrelated one, so the model trains on contexts that never occur at inference, and nothing in the loss tells you.
You'll be able to
- Pack tokenized documents into fixed-length sequences with an end-of-document token, a stated truncation and tail rule, and a record of the document id and offsets of every span.
- Build the intra-document causal mask and the loss mask from per-token document ids, and test that changing one document leaves another document's logits unchanged.
- State what packing and masking change in the training signal, and what they cost, using the evidence in the packing paper and your own test.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Analyzing the Impact of Sequence Composition on Language Model Pre-Training (Zhao et al., 2024)Analysing the Impact of Sequence Composition on Language Model Pre-Training (Zhao et al., 2024)
Section 2.1 (packing: random, same-source and retrieval-based), Section 2.2 (causal versus intra-document causal masking), Table 1 (perplexity per packing and masking strategy) and Appendix A (the FlashAttention-2 implementation and its cost)
Stop after Table 1 and Appendix A. The downstream-task sections measure in-context learning and memorization, which this unit does not need.
- 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): cropping, BOS and EOS, concatenating crops, splitting at the sequence length, dropping the short final chunk
- Modern LLM Notebook: Data EngineeringModern LLM Notebook - Data Engineering
Section 8 'From Tokenize to Training Stream', 8.1 'Sequence Packing' (the first-fit-decreasing cell) and 8.2 'Block-Diagonal Attention Mask' (the mask cell)
Skip 8.3 on fill-in-the-middle. The notebook says position ids must restart for every document; with rotary positions they need not, as the reproduce step shows.
Focus on
- Two masks, two jobs. The attention mask says which earlier tokens a position may read; the loss mask says which positions have a valid target. The position that holds an end-of-document token predicts the first token of the next document, which its own document cannot predict. Pipelines differ here: the Assignment 5 supplement trains on every packed position, others mask that one, so choose and record it. Padding positions are always masked.
- With a plain causal mask a token in the second document attends to the first. Zhao et al. train 1.3B models on the same 150B tokens with and without intra-document masking, and the masked model has the lowest average perplexity: 8.410 against 9.172 at 2K context and 8.079 against 9.065 at 8K (Table 1).
- With rotary position embeddings the attention score depends only on the offset between two positions, so a document's logits are the same whether its positions start at 0 or at its offset in the sequence, up to floating-point error. Zhao et al. apply rotary embeddings before the variable-length attention call and do not reset positions. With learned absolute positions you must reset them.
- Decide the tail and truncation rules and record them: Gopher drops the final short chunk, and a document longer than the context is split. A document continued in the next sequence has lost its beginning, so keep each span's
doc_id, start and end offsets.
Common mistakes · 3
- Testing equality with
==ortorch.equal. A packed batch and a single document run different matrix shapes, so the results differ in the last bits; assert closeness with a tolerance, and assert exact zero only for the case where one document's tokens are replaced inside the same packed run. - Building the attention mask and forgetting the loss mask, so that padding tokens count in the loss denominator, or the end-token position is trained on the next document's first token when your design meant to mask it.
- Treating a continued document as a new one. When a long document is split across two sequences, the second part starts mid-document with no left context; mark it as a continuation in the span record so that later counts of documents and tokens stay correct.
Try it yourself
Closed-book, before checking anything
torch.manual_seed(0)) and pack document A (6 tokens), an end token, document B (5 tokens) and an end token. Build a plain causal mask and an intra-document mask from per-token document ids (the end token belongs to the document it closes). Show that replacing A changes B's logits under the causal mask (max absolute difference about 0.4 in the run, PyTorch 2.14.1 on CPU) and changes nothing under the intra-document mask (0.0). Then show that B's logits from the packed intra-document run match B run alone with torch.allclose(a, b, atol=1e-5), while torch.equal is False (max absolute difference 3.6e-07), and that resetting positions per document changes them by at most about 2e-07.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Two documents are packed in one sequence with a plain causal mask. Does changing the first document's tokens change the loss on the second? Which mask removes the effect?Answer
Yes: every token of the second document can attend to the first, so its hidden states depend on it. A block-diagonal causal mask built from the document ids removes the dependence, which the swap test above checks.
2.Should the loss at the position holding the end token be kept in packed pretraining?Answer
It is a design choice to record. Its target is the first token of the next document, which the current document cannot predict, so under an intra-document mask that position can only learn how documents tend to begin. Many pipelines keep it (the Assignment 5 supplement trains on every position) and others mask it. If you mask it, the model still learns to emit the end token, because that is the target at the previous position, whose loss is kept.
3.Why do the logits of a document not change when its rotary positions start at an offset instead of 0?Answer
The rotary score of a query and key depends only on the difference of their positions, which is unchanged by a common offset, so within one document the attention scores are the same up to rounding. A learned absolute embedding depends on the position itself, so there the offset matters.
4.Zhao et al. report intra-document masking lowers perplexity at both context lengths. What does that not show?Answer
It shows this effect for 1.3B models on 150B tokens of one corpus (SlimPajama), measured on documents scored one at a time. It does not show the size of the effect for other models or data, nor that the masking is free: they measured a 4% slowdown with FlashAttention-2, and much larger ones with an explicit mask.
Practice
- CS336 Assignment 5 supplement: Problem (
data_loading)Supplement Section 4.2.1 (pp. 9 to 10); connect
get_packed_sft_datasetandrun_iterate_batchesintests/adapters.pyand passtest_packed_sft_datasetandtest_iterate_batchesintests/test_data.pyThe tests run on CPU with a tokenizer stored in the repository. They check the stored tokenization of a small file, the constant sequence length, the dropped tail chunk and the batch shapes. They do not test attention leakage, so add the swap test from the reproduce step beside your solution. The section mini-project covers the packed-batch test on your own corpus. Do not publish solutions.
You're done when
Your packing code passes the two data tests, the span record lets you read off the document and offsets of any token, and your swap test shows exact independence under the intra-document mask and dependence under the plain one.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 18 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.
- 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.
- 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.
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 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. - 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.
- 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.
- 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. - Tokenizer and Corpus PipelineRoadmap-Final · support
Reuse the project correctness, lineage and contamination contracts. Extend the artifact instead of starting another tokenizer implementation.
- 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.
- 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.