Pack documents without changing who can attend to whom
Construct independent-document causal blocks, shifted loss masks, position policies, and isolation fixtures for efficient sequence packing.
On this page
The question for today
What you’ll understand
- Derive an allowed-key predicate combining causality and document identity.
- Count real tokens, scored targets, and padding separately.
- Design a fixture that tests document isolation rather than merely checking mask shape.
Packing places several short documents into one storage block to reduce unused positions. That storage decision need not change the objective, but only if attention, positions, labels, and loss eligibility preserve the chosen conditioning policy. A single triangular mask prevents access to the future while still allowing access to earlier documents. Independent-document pretraining needs a further boundary condition. Validate the packed implementation against separately evaluated documents before trusting a throughput gain; a faster run that leaks extra context has changed the learning task.
Intersect causal order with document identity
Assign each real input position a document identifier and an ordinal within its packed storage row. For independent documents, a query may read a key only when that key is in the same document and is not later than the query. Self-attention to the current input position is allowed because that input predicts the next token. This is different from allowing the target token to enter its own context. The shifted-label fixture must establish which positions carry inputs and which carry targets.
Write the allowed relation as an abstract predicate before translating it into a framework API. In PyTorch 2.9 scaled_dot_product_attention, a Boolean True means participation, while other APIs can use a different Boolean convention. A float bias can instead add zero to allowed scores and negative infinity to forbidden scores under supported semantics. Check the actual selected implementation's broadcast shapes and supported combinations rather than assuming an is_causal flag also implements document boundaries.
Position resets and loss masks solve separate problems
A chosen positional encoding may reset indices at each document start or use another documented convention. Resetting indices does not remove an attention edge. Conversely, blocking cross-document attention does not by itself establish the desired position numbers. Preserve both policies when comparing packed with separate execution, especially for learned absolute positions or relative-position mechanisms whose behavior depends on the indices. A packing implementation should expose the generated document IDs, position IDs, and target eligibility in a small inspectable fixture.
For [BOS,a,b,EOS] followed by [BOS,c,EOS], seven real input tokens occupy the row. Under the declared independent policy, only five next-token targets are scored: three from the first document and two from the second. Padding the row to eight positions creates no additional language-model target. Avoid evaluating undefined padding-query attention rows, or use a framework-supported safe treatment and exclude their outputs as required. A finite final loss can conceal incorrect attention if those intermediate rows are never checked.
Compare separate and packed execution under controlled conditions
Turn off dropout and other stochastic effects for a numerical equivalence fixture, then compare each document's logits at corresponding scored positions using the same model and position policy. Also alter one packed document while keeping its neighbor fixed; independent masks should prevent the neighbor's predictions from changing beyond the declared numerical tolerance. Check a deliberately broken cross-document mask as a positive control so the fixture demonstrates that it can detect the forbidden information path.
The modular lab illustrates only a local-position counter for fixed-length documents. Reset, set both modulus m=4 and additive step a=1, predict positions zero, one, two, three, zero, then take four Steps. Reset and set both m=3,a=1 for a different fixed length. Each half-second Step advances one integer addition. The lab neither builds attention matrices nor supports mixed document lengths, padding queries, token labels, or a Transformer; its wraparound shows why a position reset is one small component of packing correctness.
Work it through
Inspect one packed attention row
Pack A=[BOS,a,b,EOS] into storage positions 0–3 and B=[BOS,c,EOS] into positions 4–6, then pad position 7. Use independent causal attention and local position resets, with the next-token policy defined above.
The query at position 5 contains c from B. Its allowed real keys are positions 4 and 5: B's BOS and c itself. Positions 0–3 belong to A and are forbidden even though they are earlier.
Position 6 contains B's EOS and is later than the query, so it is forbidden as a key for position 5. Position 7 is padding and is also forbidden. The query at 5 predicts EOS without reading that target.
The block stores seven real tokens and one padding token but scores only (4−1)+(3−1)=5 targets. Local positions are [0,1,2,3] for A and [0,1,2] for B; these resets supplement rather than replace the attention predicate.
The c query reads exactly two real keys and predicts EOS causally. Storage occupancy, position numbers, attention permissions, and scored-target count remain separate quantities.
The living notebook
Explore the model
Interactive lab · modular
Inspect a local-position reset without pretending it is a mask
Reset → set both m=4,a=1; predict 0,1,2,3,0 and take four Steps. Reset → set both m=3,a=1 for a separate fixed-length comparison. This additive orbit has no attention, variable-length packer, token labels, or padding-query semantics.
- Residue r0
- 0
- Orbit period · m/gcd(m,a)
- 12
- Distinct residues visited
- 1 of 12
Addition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forA position counter can reset while an attention mask still permits unwanted cross-document context.
Pause & reason
Check your understanding
Your turn
Try it yourself
Two serialized independent documents have lengths five and three, including their BOS and EOS. They fill an eight-position storage block. How many next-token targets are scored, and may the first query of the second document read the last token of the first?
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Apply the declared per-document count and the conjunction of causal order with document identity.
Compare with the solution
The valid target count is (5−1)+(3−1)=6, despite all eight storage positions containing real input tokens. The first query of the second document may read its own BOS but cannot read the first document's final token under the independent policy. That earlier token satisfies causality but fails document identity. The label after the first EOS must also be excluded so packing does not add a cross-document prediction.
Keep the idea
Take it with you
- Packing correctness requires attention, position, and target policies to agree.
- Causality alone does not isolate earlier packed documents.
- Compare packed and separate execution with controlled randomness and a forbidden-context fixture.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.