advanced25 min studyLesson 623 in Engineering

Truncate conversations without breaking their targets

Preserve meaningful context and recompute aligned masks when a multi-turn example exceeds its token budget.

On this page

What you’ll understand

  • Count fully serialized context rather than only answer length.
  • Choose a documented whole-turn or partial-target truncation policy.
  • Keep role boundaries, attention, and target masks consistent after truncation or packing.

A conversation can exceed the training context even when each individual answer is short. Blindly removing tokens can leave an assistant answer without its question, cut a role marker, or teach a response based on information no longer present. Truncation therefore changes the task, not just memory use. Define what context may be removed, which targets remain meaningful, and how their masks are recomputed after serialization.

The budget includes every serialized span

Count system text, earlier turns, tool content, role markers, boundaries, and the current assistant target using the actual tokenizer. Character limits and message counts are poor substitutes. If the model's maximum length includes a prefix or special token, reserve it explicitly. Training and inference budgets may differ, but evaluation should expose whether the deployed prompt supplies the context the adapted behavior relies on. A preprocessing stage that silently truncates twice can produce a different example from the one inspected earlier.

A whole-turn policy can preserve a system instruction and the latest self-contained user-answer pair while dropping older pairs. That policy is invalid for examples whose latest question depends on removed facts, such as 'use the previous table.' Those examples need a different selection, summarization with validated semantics, or rejection. Keeping the most recent bytes is not a universal correctness criterion. Decide whether assistant turns earlier in the conversation are targets or context, and preserve the intended role structure.

∑j∈Knj≤Lmax⁡\sum_{j\in\mathcal K}n_j\leq L_{\max}
nj counts tokens in retained serialized span j, including its declared formatting, and K is the retained set. Lmax is a token budget. The inequality checks length only; it does not establish that the retained question and answer remain semantically supported.↔ Scroll wide equations horizontally.

Rebuild masks at the actual kept boundaries

A left crop can remove an opening role marker while retaining its content. A right crop can cut an assistant answer before its end token. Training on a partial answer may be intentional, but it then has a different stopping and target policy; do not invent a terminal token claiming the original answer was complete. Apply the same retained indices to IDs and aligned labels, or preferably regenerate validated spans and masks through the supported pipeline. Never leave old mask offsets attached to a new sequence.

Packing several examples introduces another boundary question. Concatenating tokens can permit attention across records unless the chosen implementation supplies isolation or the objective intentionally allows that context. Separator tokens alone do not necessarily enforce attention independence. Inspect the trainer's versioned packing behavior and loss alignment, especially for padding-free or variable-length kernels. A throughput improvement is not acceptable if a target can now condition on another record's answer in a way the intended task did not permit.

Mkept=∑t∈IkeptmtM_{\rm kept}=\sum_{t\in\mathcal I_{\rm kept}}m_t
This counts supervised target positions only after a valid retained-index mapping and causal alignment. Removing spans or adding separators can require rebuilding that mapping. A positive count does not prove preserved context or correct inter-example attention.↔ Scroll wide equations horizontally.

Validate the processed example, then measure loss

Inspect examples that barely fit, miss the limit by one token, contain a long tool response, or end in an incomplete assistant turn. Track how many records are shortened or rejected by task and source, since aggressive truncation can change the training mixture. Compare the distribution of selected target counts before and after preprocessing. A lower loss on shortened easy answers may reflect a changed task rather than better learning, so retain an unambiguous held-out evaluation format.

The function lab is a limited size-growth illustration. Reset and set both a=1, x=1, predict y=1; Reset and re-set a=1, x=2, predict y=4, then inspect. The quadratic can represent normalized full-attention score-count growth for a fixed architecture, not an actual trainer memory budget. It has no conversations, masks, packing, or truncation. Explain why reducing sequence length can save work yet still require a separate semantic check that the retained targets have the needed context.

Drop an old pair, keep a self-contained last turn

A declared serialized conversation has spans S=4, U 1=10, A 1=8, U 2=12, A 2=20 tokens, including each span's formatting. Maximum length is 40. U 2 is self-contained, and policy permits dropping the older U 1/A 1 pair while retaining S.

  1. The original sequence is 4+10+8+12+20=54 tokens. A blind fourteen-token left crop would remove S and U 1, leaving A 1 without its question.

  2. Dropping the complete old pair removes 18 tokens, leaving S+U 2+A 2=4+12+20=36, which fits. The last answer is retained whole under the stated self-contained premise.

  3. Regenerate the retained role boundaries and target mask, rather than preserving old positional offsets. If U 2 depended on U 1 or A 1, this same length arithmetic would not make the shortened training example valid.

The result

A token budget chooses among semantic policies. Complete-turn removal can be correct only when the remaining target remains supported.

Explore the model

Interactive lab

Interactive lab · function

A length saving is not a context proof

Reset, set a=1, x=1, predict y=1. Reset and re-set a=1, x=2, predict y=4. This fixed quadratic illustrates normalized score-count growth only, not actual training memory, tokenization, packing, or target preservation.

A length saving is not a context proofThis 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 forReducing length can reduce work while changing what the model is being asked to learn.

Check your understanding

After dropping an earlier turn, why must the target mask be checked again?

Try it yourself

A 32-token budget must retain a four-token system span, a nine-token self-contained latest question, and a fifteen-token latest answer. An older question-answer pair has lengths six and eight. Find total length before and after dropping that pair, and explain one remaining mask check.

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

Give me a hint

All supplied lengths already include formatting;do not add markers again.

Compare with the solution

Before removal the total is 4+9+15+6+8=42 tokens. Dropping the complete old pair leaves 28, within the 32-token budget. Recompute or verify assistant targets and end-of-turn inclusion against the retained sequence and causal alignment. Length alone does not prove the latest pair remained meaningful or that packing prevents unintended cross-record attention.

Take it with you

  • Count all serialized context and formatting against the budget.
  • Truncation must preserve a meaningful task and consistent role/target boundaries.
  • Packing throughput requires an explicit attention and loss-boundary contract.

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.