Unit 5 of 7 · about 4 hours · derive, implement

From documents to training examples: packing and loss masks

Packing changes which tokens become context and which predictions enter the loss. An EOS token marks a boundary, but it does not enforce attention isolation or remove an unwanted target.

You'll be able to

  • Derive shifted inputs, targets and valid-loss positions for packed documents, including EOS and padding.
  • Implement packing with document lineage, a declared truncation/tail policy and separate attention and loss masks.
  • Keep split ownership fixed before fitting a tokenizer or packing, so evaluation text cannot become training context.

Covers

Documents, boundary tokens, truncation and packingCausal loss masks across packed document boundariesSplit-before-fit and split-before-pack discipline
1

Read

In this order, only the parts listed

0 of 3 done

  1. Shifted targets and sliding windowsLLMs from Scratch companion - tokenization and data loading

    Section 2.4: EOS between independent sources; Section 2.6, Data sampling with a sliding window: GPTDatasetV1 and stride/context-length examples

    Stop before Section 2.7. The single-text loader is a baseline; it does not supply document isolation or split-safe corpus construction.

  2. Data loader intuition with integersLLMs from Scratch companion - tokenization and data loading

    Data sampling with a sliding window with number data: GPTDatasetV1, then max_length=4 with stride=1 and stride=4

    Stop before Finally, a data loader with shuffling. Track indices and the last omitted tail rather than running the full number file.

  3. Split ownership and packed boundary contractTokenizer and Corpus Pipeline - reduced foundation slice

    Core requirements: split assignment before leakage-causing transforms and deterministic sample/pack construction with document-boundary/loss-mask policy; Architecture constraints: evaluation data cannot influence vocabulary/filters/mixture; Correctness requirements: fixed split ownership and packed masks

    Apply these requirements to a few local documents. Do not implement the full project or distributed corpus processing.

2

Focus on

  • Declare whether packed documents may attend to earlier documents. Continuous-stream training and isolated-document training are different objectives; neither policy is created by EOS alone.
  • For isolated documents, attention allows only within the same document. The loss mask separately excludes padding targets and cross-document next-token transitions.
  • Attach EOS to the document it ends. Predicting that EOS is valid; predicting the next document's first token from that EOS is masked under the isolated policy.
  • Split raw documents or duplicate groups before fitting and packing. Record token spans back to document IDs, and account for every retained, padded or deliberately dropped tail token.
Common mistakes · 3
  • Masking EOS as if it were padding. The last content token should usually learn to predict its own document's EOS.
  • Using only a block-diagonal attention mask. The shifted label after one document's EOS can still be the next document's first token unless loss is masked too.
  • Splitting after packing or overlapping-window construction. The same document can enter both splits, even when their packed rows differ.
3

Try it yourself

Closed-book, before checking anything

Closed-book, pack and with EOS=9 into . For and , derive and isolated-document loss mask . Build the lower-triangular same-document attention mask for and explain which prediction it does not remove by itself.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.In Reproduce, which target is excluded and why?Answer

    Target 21 at position 2 is excluded: its context token is 's EOS, but 21 belongs to . Predictions of either document's EOS remain valid.

  2. 2.Does masking a loss position stop that token from being used as context?Answer

    No. Loss masking removes a prediction from the objective. Attention masking controls which input tokens can influence later representations.

  3. 3.With ten tokens, context length four and stride four, how many complete shifted windows does the notebook loader produce?Answer

    Two, starting at 0 and 4. Each needs five stream tokens to make four input-target pairs; the remaining suffix cannot form another complete window.

  4. 4.Why split before fitting the tokenizer if no evaluation examples enter model training?Answer

    Fitting on evaluation text still uses held-out distribution information to choose the representation. Fit on training data unless a separate, declared evaluation protocol permits otherwise.

You're done when

Your packer matches the hand-derived inputs, targets and both masks on two documents, padding and an overlength document, with no document ID shared across splits.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 5 more in the section
  • LLMs from Scratch companion - tokenization and data loadingSebastian Raschka · primary

    Work through the ch02 main notebook, 05_bpe-from-scratch and 04_bonus_dataloader-intuition. Rebuild byte-level BPE, serialization and packed windows in blank files, then add multilingual, control, whitespace and chunk-boundary properties.

  • Tokenizer and Corpus Pipeline - reduced foundation sliceRoadmap-Final · support

    Use the byte, identity, split, deduplication, contamination, packing, manifest and restart correctness requirements. Keep the corpus small and stop before distributed processing or internet-scale filtering.

Also in this section

  • Stanford CS336 Assignment 1 - tokenizer contractStanford University · required

    Read the Assignment 1 tokenizer handout and use the named unicode1, unicode2, train_bpe, tokenizer and tokenizer_experiments specifications plus public tests as an acceptance contract. Implement independently in your own repository and do not copy or modify course solutions.

  • Modern LLM Notebook - tokenization and data experimentsWalking Labs · support

    Run English notebooks 01-tokenizer-basics and 02-bpe-tokenizer. Use only the quality, deduplication and mixture examples from 15-data-engineering. Change the corpus and tie cases, then verify every quantitative claim independently.

  • Hugging Face LLM Course - tokenizer translationHugging Face · optional

    After the blank-file tokenizer passes, use the tokenizer chapters to map vocabulary, special tokens, fast tokenizers and batching into library APIs. Do not replace the deterministic implementation gate with a pretrained tokenizer call.

  • Python unicodedata - normalization formsPython Software Foundation · reference

    Read unicodedata.normalize for canonical and compatibility equivalence, and unidata_version for recording the normalization database version.

  • Hugging Face Datasets - streaming, sharding and resumeHugging Face · reference

    Read Shard, Interleave, Save a dataset checkpoint and resume iteration, and Export. Use tiny local data and inspect the warning that shuffle buffers are lost on resume; do not download web-scale corpora or upload to the Hub.