advanced24 min studyLesson 535 in Engineering

Pack tokens without changing which tokens can interact

Measure useful-token capacity and preserve attention, positions, targets, and loss weighting when replacing padded examples with packed sequences.

On this page

What you’ll understand

  • Compute padding waste for a declared batch layout.
  • Define boundary-aware attention and target rules for independent examples.
  • Separate useful-token utilization from realized compute speedup.

A language-model batch allocates twelve token positions to every example even when most examples are short. Packing several examples into one container can recover otherwise padded positions. But simply concatenating independent examples can let one example attend to another or create a next-token target across their boundary. That changes the learning problem. A valid packing optimization begins with the intended objective and preserves its information flow and weighting while measuring actual kernel and input-path performance.

Count useful positions against the allocated layout

For a padded batch, useful-token utilization is the number of real tokens divided by all allocated positions, using a consistent treatment of required separators and special tokens. State whether loss-bearing tokens or all input tokens are being counted; prompts may be real inputs while their labels are intentionally masked. Padding waste is one minus the chosen utilization. Bucketing similar lengths can reduce padding, while packing can place several shorter examples in one container. Neither approach guarantees a particular speedup because attention kernels, masks, memory layout, and the model's token-level work still determine cost.

Packing is a constrained placement problem, not merely sorting every batch by length. Choose the container capacity, rules for splitting long examples, separators, and whether order affects sampling. Retain mappings from packed positions back to source identity and original token position. Dropping an inconvenient remainder or repeatedly preferring short examples can change the experiment's visitation distribution. Measure both utilization and tokens contributing to the objective. An increase in allocated tokens processed per second can hide a decrease in useful training tokens if much of the new work remains padding or carries ignored labels.

η=∑iℓiBL,BL>0\eta=\frac{\sum_i \ell_i}{B L},\qquad B L>0
For B equal-capacity containers of L token positions, ℓ_i counts the consistently defined useful tokens assigned to them and must fit the layout. η is dimensionless and at most 1; zero allocated positions need an empty-batch outcome rather than division.↔ Scroll wide equations horizontally.

Preserve boundaries, labels, and positions deliberately

If the intended task treats examples independently, attention must prevent tokens from reading another example's content. A block-diagonal causal rule permits only earlier or current positions in the same example. Boundary-aware target construction must also prevent an unintended prediction of the next example's first token from the previous example's last token. Position identifiers and any segment-dependent operations must follow the model's intended semantics. The packing paper by Krell and colleagues studies avoiding cross-contamination; its equivalence argument is tied to its model and masking construction, not every architecture or arbitrary concatenation.

Some training objectives intentionally treat concatenated documents as a continuous stream; those are different declared semantics, not automatically incorrect. Decide which experiment is intended before choosing masks. Recheck loss normalization as well: averaging each sequence equally differs from averaging all loss-bearing tokens equally when lengths vary. Packing should not silently change either weighting. Positional encoding, sequence-level heads, dropout behavior, and batch-dependent operations can introduce additional differences even when attention boundaries look right. Use small reference examples to compare outputs and losses under the supported implementation and identify the precise equivalence claim you can justify.

Mij={0,d(i)=d(j) ∧ j≤i,−∞,otherwise,M_{ij}=\begin{cases}0,&d(i)=d(j)\ \land\ j\leq i,\\-\infty,&\text{otherwise},\end{cases}
For an additive causal attention mask, d(i) is the example identity of a valid token at packed position i. This rule describes independent examples; padded or invalid positions require additional handling, and framework mask conventions may differ.↔ Scroll wide equations horizontally.

Optimize the executed work, not only the token count

A dense attention implementation may still perform work over a whole packed container even when the mask forbids cross-example attention. A compatible variable-length or block-aware kernel can exploit structure, but its performance and correctness need separate checks. Packing also consumes CPU time, metadata, and potentially a staging buffer while it finds compatible lengths. Include those costs and rank balance in the end-to-end comparison. Report useful tokens per second, step latency, and the objective's actual normalization rather than claim that doubling utilization necessarily halves training time.

The function lab illustrates one limited cost scaling: for each separate view, Reset, set both a=1 and x to 1 or 2, predict y=ax², then inspect. Doubling this abstract length ratio changes the quadratic value from one to four. The instrument is not an attention implementation or a bin-packing solver, and real model cost includes nonquadratic operations and kernel effects. Use it to see why a more populated longer dense container can have a different compute bill from several independent shorter containers, then measure the actual supported masked kernel.

Pack a small layout and preserve its semantics

Four fictional independent examples have lengths 3, 5, 7, 9 tokens, already including any required boundary tokens. Every container has capacity 12. Assume examples may be combined without splitting and the implementation correctly preserves their independent objective.

  1. One example per container allocates 4×12=48 positions for 24 useful tokens. Utilization is 24/48=50%, so 24 positions are padding.

  2. Pack lengths 9+3 and 7+5 into two containers. They allocate 24 positions for the same 24 useful tokens, giving 100% utilization in this special exact-fit case.

  3. Retain example boundaries, targets, intended position semantics, and loss weighting. The capacity reduction from 48 to 24 positions does not alone establish a two-times runtime speedup or equivalence for an unsupported model.

The result

The specified layout removes 24 padding positions while preserving the declared 24 useful tokens. Correct semantics and actual performance remain explicit implementation checks.

Explore the model

Interactive lab

Interactive lab · function

Inspect a quadratic length-cost analogy

For each view: Reset, set both coefficient a=1 and x, predict, then inspect. Compare x=1 with x=2: y changes from 1 to 4. These reachable values illustrate y=ax² only; this is not an attention kernel, sequence packer, or measured transformer cost model.

Inspect a quadratic length-cost analogyThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. 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 forPacking utilization and executed attention cost are different quantities. Validate boundaries and measure the actual implementation before inferring training speedup.

Check your understanding

Independent examples are concatenated into a causal container, but attention and labels cross their boundary. What follows?

Try it yourself

Three examples have lengths 4, 6, 8, including required boundary tokens. Containers hold ten tokens. Compare three separate padded containers with packs (6+4) and (8). What are the utilizations?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

The useful-token total stays eighteen; compare thirty and twenty allocated positions.

Compare with the solution

Separate containers use 18/30=60% utilization. The two stated packs use 18/20=90%, leaving two padding positions. Preserve boundary and loss semantics; the utilization change alone does not specify the runtime speedup.

Take it with you

  • Define useful tokens and compare them with the actual allocated layout.
  • Independent-example packing must preserve information flow, targets, and weighting.
  • Higher token utilization is valuable but not a universal compute-speedup formula.

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.