Sub topic 2
Positional Information and Training a Decoder-Only Model
Assume you know basic Python, vectors, matrix multiplication, probability distributions, and the general idea of neural networks. This chapter connects token positions, transformer blocks, generation, and pretraining.
Positional information: telling the model where tokens are
Self-attention compares token representations, but attention alone does not know order. The sequences “dog bites man” and “man bites dog” contain the same tokens. Position information makes their representations different.
A model adds a position vector to each token embedding. Position vectors may be fixed sinusoidal values or learned parameters. The result is a position-aware representation:
h₀[i] = token_embedding[i] + position_embedding[i]
The model can then use both word identity and location when computing attention.
The transformer block
A decoder-only transformer repeats blocks containing:
- Causal self-attention, which prevents a position from reading future tokens.
- A feed-forward network, which transforms each position independently through learned nonlinear layers.
- Residual connections, which add a block’s input to its output.
- Layer normalization, which stabilizes the values passed between layers.
A simplified block is:
h' = h + Attention(LayerNorm(h))
h_next = h' + FeedForward(LayerNorm(h'))
The residual paths help gradients flow through many stacked layers.
The full decoder-only model
The model converts token IDs into embeddings, adds positional information, and applies many transformer blocks. A final linear layer maps each hidden vector to one logit per vocabulary token. Softmax converts logits into probabilities. Generation selects one token, appends it to the context, and repeats.
Pretraining: cross-entropy loss and gradient descent
Pretraining supplies sequences of tokens. At every position, the target is the next token. Cross-entropy loss penalizes low probability assigned to that target:
loss = -mean(log P(target token))
Gradient descent computes how each weight affected the loss, then updates the weights slightly in the direction that reduces future loss. Repeating this over many batches teaches statistical patterns rather than storing a simple lookup table.
Exercise
Why does a decoder-only model need both causal masking and positional information?
Show answer
Causal masking prevents future-token access, while positional information lets attention distinguish different token orders.