Build Aligned Input and Target Batches

Build integer input and target tensors with shape (B,T), preserve independent batch rows, and flatten batch and time together only at the loss boundary.

A batch groups BB examples without joining their token streams. For context length T=4T=4, both input IDs and targets have shape (B,4)(B,4):

I,Y:(B,T).I,Y:(B,T).

With the first two corpus sequences, one batch is

I=[01230124],Y=[12371247].I= \begin{bmatrix} 0&1&2&3\\ 0&1&2&4 \end{bmatrix}, \qquad Y= \begin{bmatrix} 1&2&3&7\\ 1&2&4&7 \end{bmatrix}.

The batch axis indexes independent sequences. Attention may mix positions within a row under its mask; it must never mix row 0 with row 1.

IDs Stay Integer-Valued

Embedding lookup requires integer token IDs. In PyTorch, the batch therefore uses an integer dtype such as torch.long:

The two arrays are shown together because their row and position alignment is the point of the example. Converting IDs to floating-point numbers does not make them model features; it makes them invalid indices for the embedding lookup.

Assert the Batch Contract

Check the cheap invariants before every new data pipeline is trusted:

These assertions cannot prove that the target is shifted correctly. Add a content check while constructing examples:

Flatten Only at the Loss Boundary

The decoder returns logits (B,T,V)(B,T,V). PyTorch cross-entropy can consume the same predictions after flattening batch and time:

(B,T,V)(BT,V),(B,T)(BT).(B,T,V)\rightarrow(BT,V), \qquad (B,T)\rightarrow(BT).

The reshape does not change which logits row belongs to which target because both tensors use the same row-major order. Transposing one tensor first would silently pair predictions with the wrong targets while retaining valid shapes.

Q1. Trace batch and loss shapes

For B=3B=3, T=4T=4, and V=8V=8, give the input shape, logits shape, flattened logits shape, and flattened target shape.

Answer it first, then check.

Hint
BT=12BT=12.
Solution
The shapes are (3,4)(3,4), (3,4,8)(3,4,8), (12,8)(12,8), and (12)(12).
Not attempted
Review

Not marked done.

A Valid Shape Is Necessary, Not Sufficient

Before training, decode random batch rows back to tokens and show their targets. Human-readable examples catch off-by-one and boundary mistakes that shape assertions cannot see.

Pause and reflect

In your own words, note what you understood, what remains unclear, or what you want to revisit. The note stays with this lesson.

0 of 1 exercises marked done

Review

Not marked done.