Skip to main content

From tokenized corpus to training examples

Input-target shifting, windows, documents, padding, and tensor shapes

Note

This page belongs to the Build path (training-example preparation, G2). Consult it directly to study target construction and teacher forcing. Return to the Build path.

An autoregressive model learns to predict the next token from the available context. Training turns a token stream into aligned input-target pairs. A one-index error, faulty mask, or unintended document boundary changes the objective being optimized.

Learning objectives

  • Construct a one-token-shifted input-target pair.
  • Explain teacher forcing and distinguish it from feeding generated tokens back during inference.
  • Distinguish context length, stride, batch size, and vocabulary size.
  • Compare sliding windows with packed sequences.
  • Separate document boundaries, attention masks, and loss masks.
  • Check tensor shapes and detect alignment errors.

1. Shift inputs and targets

Suppose the tokenizer produced IDs [t0, t1, t2, t3, t4]. With input length 4:

  • input: x = [t0, t1, t2, t3]
  • target: y = [t1, t2, t3, t4]

flowchart TB
    A["Stream: t0 t1 t2 t3 t4"] --> B["Input x: t0 t1 t2 t3"]
    A --> C["Target y: t1 t2 t3 t4"]
    B --> D["Prediction at each position"]
    D --> C

Input and target have equal lengths. The target is shifted one position in the source stream: each position predicts the following token. The final input token provides context; it is not its own target.

Try before reading on: for stream [8, 3, 3, 9, 2, 7] with length 3, write the first two input-target pairs. Check that each target is exactly the next token in the stream.

Solution and alignment check
  • Example 1: input [8, 3, 3], target [3, 3, 9].
  • Example 2, with stride 1: input [3, 3, 9], target [3, 9, 2].

At position 0 of the first example, the model receives token 8 and must predict 3; at position 2, it receives context [8, 3, 3] and predicts 9. An ID can repeat: alignment depends on position in the stream, not on the uniqueness of token values.

Teacher forcing: conditioning on the observed prefix during training

In standard autoregressive training, the model receives observed corpus tokens as context and predicts the following tokens. For a shifted pair x = [t0, …, t(L−1)] and y = [t1, …, tL], the logit at position i is compared with target y[i].

This is called teacher forcing because the prefix supplied to the model is the reference prefix from the data, not a sequence of tokens generated by the model. The causal mask remains essential: at position i, computation may use only x[0] through x[i], never future tokens. The model can therefore process the sequence positions in one forward pass, then compute a loss against the shifted targets.

Teacher forcing is a conditioning strategy. It is neither the prediction objective, the loss function, nor the optimizer. The usual objective is expressed through cross-entropy or NLL on aligned targets. At inference, reference tokens are unavailable: the token selected by the model is appended to the context for the next prediction.

The reference function sliding_input_target_pairs only constructs windows and shifted targets; it does not implement a trainable forward pass, executed teacher forcing, or parameter updates. This distinction is conceptual and describes the contract of training examples.

2. Sliding windows and stride

Stride is the number of positions by which the window start moves between examples. It is distinct from context length.

Input-window length Stride Consequence for input windows
4 4 Adjacent input windows do not overlap
4 2 Input windows overlap and reuse context
4 5 Some positions may be skipped

For the stream [0, 1, 2, 3, 4, 5, 6, 7], compare the first two input windows.

  • Stride 4 · [0, 1, 2, 3] then [4, 5, 6, 7].
  • Stride 2 · [0, 1, 2, 3] then [2, 3, 4, 5].

The table describes input windows only. For next-token training, each window also needs a one-token-shifted target; the last input token therefore needs a successor in the source stream. The corpus tail must be handled explicitly (for example, by dropping an incomplete example or using a deliberate end-of-sequence convention).

Worked example: what stride repeats

Take the stream [0, 1, 2, 3, 4, 5, 6, 7, 8], input length \(L=4\), and one-token-shifted targets.

Stride Start Input \(x\) Target \(y\)
4 0 [0, 1, 2, 3] [1, 2, 3, 4]
4 4 [4, 5, 6, 7] [5, 6, 7, 8]
2 0 [0, 1, 2, 3] [1, 2, 3, 4]
2 2 [2, 3, 4, 5] [3, 4, 5, 6]
2 4 [4, 5, 6, 7] [5, 6, 7, 8]

With stride 2, the inputs share two consecutive tokens, and targets in successive windows also repeat positions (for example, 3 and 4). These repetitions increase the number of training occurrences; they do not create new independent observations. With stride 4, the input windows are adjacent and the targets cover the following positions without overlap in this example.

This table assumes that the stream provides a successor for every target position. It illustrates windowing, not a complete packing or batching policy.

A smaller stride generally increases the number of examples and overlap. There is no universally optimal stride: the choice depends on the pipeline, compute budget, and handling of the corpus tail. A pedagogical sliding window does not necessarily represent a production pipeline.

The reference NumPy implementation and its unit tests deliberately cover a restricted case: building sliding input windows with one-token-shifted targets (sliding_input_target_pairs). A window is kept only when its target is complete; an incomplete corpus tail is dropped, with no padding and no invented end-of-stream token.

This reference does not implement corpus loading or tokenization, document packing, boundary markers, padding, attention or loss masks, batching through a Dataset/DataLoader, or train/validation splits. Production windowing choices do not follow directly from it.

The tests check exact alignment of every target with the following token in the source stream, window counts and overlap for several strides, explicit corpus-tail handling, determinism, absence of input mutation, and rejection of invalid inputs. They support the announced scope of this reference; they do not prove that any stride is optimal or representative of a production pretraining pipeline.

3. Document boundaries and packing

Concatenating documents can create windows that cross document boundaries. Keep three decisions separate:

  • Packing: combine documents in a sequence to reduce padding.
  • Boundary marker: insert an end-of-document or separator token.
  • Cross-document masking: decide whether attention may cross the boundary.

flowchart LR
    A["Document A"] --> B["Optional separator"]
    B --> C["Document B"]
    C --> D["Packed sequence"]
    D --> E["Check targets and masks"]

An end-of-document token does not by itself block attention. Cross-document masking is an implementation choice, not a universal rule. Inspect the actual mask and check that transitions between documents match the intended objective.

4. Padding and loss masks

Padding makes sequences of different lengths compatible with a rectangular tensor. Padding positions should generally not contribute to next-token loss unless the objective explicitly requires it.

flowchart TB
    A["Targets: 12 8 4 PAD PAD"] --> C["Compute loss"]
    B["Loss mask: 1 1 1 0 0"] --> C
    C --> D["Only valid positions contribute"]

Worked example: exclude padding from the reduction

Consider the following per-position losses, which are illustrative:

Position Target Loss mask (m_i) Loss (ell_i)
0 12 1 0.2
1 8 1 1.1
2 4 1 0.7
3 PAD 0 4.0
4 PAD 0 3.0

The mean over valid positions only is:

\[ \mathcal{L}=\frac{\sum_i m_i\ell_i}{\sum_i m_i} =\frac{0.2+1.1+0.7}{3} =\frac{2}{3}\approx 0.667. \]

The illustrative losses at PAD positions do not contribute. A naive mean over all five positions would be (1.8), making the objective depend on the amount of padding. In practice, the exact reduction convention (sum, per-sequence mean, or valid-token mean) must be stated; this example illustrates only the valid-token mean.

The attention mask determines which positions may be attended to. The loss mask determines which targets contribute to the optimization objective. They have distinct roles and are not interchangeable.

Dynamic padding at batch time

Padding does not have to be applied once at the maximum length of the entire corpus. For variable-length examples, a collator can pad each batch to the length of its longest example. This is dynamic padding: it avoids computing over unnecessary PAD positions in shorter batches.

Strategy Padding length Trade-off
Global padding A fixed length chosen for the dataset or model Simple shapes, but potentially many unnecessary positions
Dynamic padding Maximum length observed in each batch Less wasted computation, but batch shapes vary

In Transformers, DataCollatorWithPadding illustrates this mechanism for tasks where inputs alone are padded. The collator receives already-tokenized examples and builds batch tensors. It does not replace the tokenizer, causal mask, or target construction.

Do not confuse three roles:

  • Padding makes tensor dimensions rectangular.
  • The attention mask indicates which positions are real context or padding, according to the model’s convention.
  • The loss mask indicates which targets actually contribute to the objective; it may exclude PAD positions.

An attention-mask value of zero does not by itself guarantee that the corresponding target is ignored by the loss: the collator and loss computation must agree. In causal training, how PAD labels are handled depends on the collator and model in use; do not automatically reuse a classification collator for a causal language-model objective.

Left versus right padding also depends on the model and use case. Check the checkpoint’s conventions and test label positions after collation.

See Hugging Face — Processing the data, which demonstrates dynamic padding with DataCollatorWithPadding. This API is an implementation example, not a universal rule for every objective.

5. Tensor shapes

Let B be batch size, L sequence length, and V vocabulary size.

flowchart LR
    A["input_ids: [B, L]"] --> C["Causal model"]
    C --> D["logits: [B, L, V]"]
    B["targets: [B, L]"] --> E["Loss on valid targets"]
    D --> E

  • input_ids: [B, L], input token IDs.
  • targets: [B, L], expected IDs shifted by one token.
  • logits: [B, L, V], unnormalized scores for every vocabulary token at every position.
  • loss: often a scalar after reduction over valid positions.

The model produces logits at each position, not one prediction for the entire sequence. Flattening and reduction must preserve alignment among logits, targets, and masks.

6. Debugging checklist

When loss is unexpectedly low, high, or unstable, check:

  1. Is every target the next token in the source stream?
  2. Are input and target lengths compatible?
  3. Is the final token without a successor handled explicitly?
  4. Are padding positions excluded from loss as intended?
  5. Do causal, padding, and loss masks have distinct roles?
  6. Are cross-document transitions intentional?
  7. Do axes B, L, and V match the loss function’s expectations?
  8. Can a future target be accessed by the context used to predict it?
TipRevision sheet — constructing autoregressive examples
  • Alignment: for input \(x=[t_0,\ldots,t_{L-1}]\), the target is shifted by one token, \(y=[t_1,\ldots,t_L]\). Each position predicts its successor.
  • Teacher forcing: the observed prefix supplies context; the causal mask prevents access to future tokens. This conditioning strategy is neither the loss nor the optimizer.
  • Windowing: length determines the available context; stride determines the displacement between windows and therefore their overlap.
  • Masks: the causal mask controls information access; the loss mask controls which targets contribute to the reduction. A document separator does not automatically block attention.
  • Shapes: input_ids and targets have shape \([B,L]\), while logits have shape \([B,L,V]\). Alignment must be preserved through loss calculation.

Limitations

This page explains core mechanisms without prescribing a universal strategy for packing, cross-document masking, padding, or loss reduction. Choices depend on the objective, architecture, data, and implementation.

Language: Français · English

Practice

The questions and exercises for this lesson are collected on its dedicated practice page.

Supplementary resources Experiment, explore further, and practise the ideas from this lesson.

Further reading

To revisit the input stage, see From text to tokens. To continue the conceptual course, see cross-entropy and the Transformer. The tensor and mathematical training-chain pages are supporting references, not prerequisites to master before moving on.