Fall 2026
  • Discord
  • Gradescope
  • Syllabus
  • Spring 2026

On this page

  • The Block
  • Training
  • Generation
  • Steering Vectors
  • Linear Probes

Transformer

In self-attention, we saw how a token can draw on the words around it. For language modeling, we’d like to use the words we’ve seen so far to predict the one that comes next. We’ll study a decoder-only transformer. It processes a single sequence of tokens. At each position, attention can draw on that token and the ones before it, so the model can use its vector there to predict the next token.

How does a transformer learn to generate text?


We’ll follow a token’s vector through the network to see how we train the model and generate text. Once we have a trained model, we can experiment with its vectors to see what information they contain and how changing them affects what the model writes.

The Block

To predict what comes next, a token needs information from earlier in the sentence. A transformer block lets each token collect that information with attention, then process what it collected with a feedforward network (an MLP).

We start with an embedding for each token and give the model information about its position in the sequence. Each block adds the attention output to the token’s vector, then adds the MLP output to the result. We call this running sum the residual stream. By the time a token reaches the next block, its vector already reflects what it gathered in this one.

Let \(\mathbf X\in\mathbb R^{n\times d}\) hold the vectors entering a block, with one row per token. We’ll use the version of the block from depth enablers that applies layer normalization (\(\operatorname{LN}\)) before each branch. Writing \(\mathbf U\) for the stream after attention, a block computes \[ \begin{aligned} \mathbf U &= \mathbf X+\operatorname{MultiHead}(\operatorname{LN}(\mathbf X)),\\ \mathbf X_{\rm next} &= \mathbf U+\operatorname{MLP}(\operatorname{LN}(\mathbf U)). \end{aligned} \] The next block receives \(\mathbf X_{\rm next}\). Both the MLP and layer normalization operate on each row separately. Attention is where information passes between tokens.

To see what these additions look like in a trained model, we’ll use GPT-2 for our experiments. Its weights are public, and the small version runs on a CPU, so we can record the vectors inside every block and reproduce the figures in the course notebook. GPT-2 starts the residual stream by adding a learned position embedding to each token embedding.

Let’s follow the Once-ler’s line from The Lorax, “This thing is a Thneed.” GPT-2 splits Thneed into two tokens, Th and need. Choose a block and either branch to see one addition for need, just before the period. The first group of bars gives the incoming coordinates, the second gives the update, and the third gives their sum. We show the same eight coordinates on the same scale in each group.

Each block adds a masked attention update and then an MLP update. The sum becomes the input to the next block. After the last block, GPT-2 normalizes the stream and projects to vocabulary logits.

Attention Heads

What goes into the attention update we just added? Recall that one attention head gives each token a weighted average of the values in its prefix. Sometimes we’d like to draw on several earlier words for different reasons. Multi-head attention lets each head learn its own weights over those words, then combines the results into one update.

Each head sees the whole normalized input and learns its own queries, keys, and values. As in self-attention, we mask the scores before taking softmax so that each token can use only its prefix. Compare two heads from block 7 of GPT-2. In the row for need, head 10 puts almost all its weight on This. Head 9 gives its largest weight to Th, the first token of the same word. Hover over a square to compare the weights on that pair of tokens.

In each head, a row gives one token’s attention weights over its prefix.

How do we get one update from all these heads? Each heatmap above shows a head’s attention weights. Multiplying those weights by that head’s value matrix gives its output. We put the head outputs side by side, keeping each token in its own row. If there are \(h\) heads of width \(p=d/h\), this gives us \(hp=d\) coordinates per token. We then multiply by a learned \(d\times d\) matrix \(\mathbf W_O\) to mix those coordinates.

The figure shows this multiplication one head at a time. Follow the blue row: the head’s output has one row per token, and its two columns multiply the first two rows of \(\mathbf W_O\). This gives the blue head a contribution to every coordinate of every token. The green head uses the remaining rows of \(\mathbf W_O\). Hover over a square in the attention update to see the two contributions that add there.

For each head, multiply its output by its rows of the output projection. Add the resulting matrices entry by entry to get the attention update.

Writing \(\mathbf H_j\) for head \(j\)’s output and \(\mathbf W_{O,j}\) for its rows of the output weights, the two ways of doing the multiplication give the same matrix: \[ [\,\mathbf H_1\mid\cdots\mid\mathbf H_h\,]\mathbf W_O =\sum_{j=1}^{h}\mathbf H_j\mathbf W_{O,j}. \] We add this matrix to \(\mathbf X\), updating each token’s row in the residual stream.

Training

After the last block we have a vector at every position. What should we train each vector to predict? In next-token prediction, the target at each position is the token immediately after it in the training text. The text supplies its own labels.

In the Once-ler’s line, the target after This is thing, and the target after Th is need. We’d like to learn from both in the same forward pass. But if the input contains the whole sentence, what stops a position from reading its answer? This is why we put a causal mask in every block.

Claim: If every block uses the causal mask above, the vector at position \(i\) depends only on the tokens at positions \(1,\ldots,i\).

Proof

At the input, the vector at \(i\) depends only on token \(i\) and its position. Suppose each row entering a block depends only on its prefix. At row \(i\), masked attention uses the query at \(i\) and keys and values from rows \(1,\ldots,i\). Even the softmax denominator involves only those keys. By assumption, none of those rows depends on a token after \(i\). The remaining operations act within each row, so the same property holds after the block. Induction gives the claim.

For a sequence of vocabulary indices \(c_1,\ldots,c_n\), take the vector at position \(i\) after the final layer normalization and append a \(1\). Call the result \(\mathbf h_i\). As in linear regression, the last column of the weight matrix accounts for the bias. The output layer gives us one logit per vocabulary item. Applying softmax across the vocabulary gives the next-token probabilities \(\mathbf p_i\). We train the transformer to assign high probability to the token that came next, \(c_{i+1}\): \[ \mathbf z_i=\mathbf W_{\rm out}\mathbf h_i, \qquad \mathbf p_i=\operatorname{softmax}(\mathbf z_i), \qquad \mathcal L=-\frac{1}{n-1}\sum_{i=1}^{n-1}\log [\mathbf p_i]_{c_{i+1}} . \] The mask lets us evaluate all \(n-1\) terms in one forward pass and backpropagate their average loss through the whole network.

Generation

Once we’ve trained the model, we can use its next-token distribution to write more than one token. In autoregressive generation, we choose a token, append it to the text, and use that longer prefix to predict again. Earlier positions still have the same prefixes, so we can reuse their keys and values in every block.

How should we choose a token from the distribution? Greedy decoding always takes the most likely one. Sampling also gives the other tokens a chance. The temperature \(\tau>0\) controls how much we favor the leading candidates when we sample. Let \(\mathbf z_i\) be the logits after the prefix ending at position \(i\), and let \(V\) be the vocabulary size. We divide each logit by \(\tau\) before applying softmax. The probability of choosing vocabulary item \(c\) as the next token is \[ \mathbf p_i(\tau)=\operatorname{softmax}\!\left(\frac{\mathbf z_i}{\tau}\right), \qquad [\mathbf p_i(\tau)]_c= \frac{\exp([\mathbf z_i]_c/\tau)} {\sum_{j=1}^{V}\exp([\mathbf z_i]_j/\tau)} . \] At \(\tau=1\) we recover the distribution we trained. To see what happens as we lower \(\tau\), take two tokens whose logits differ by \(g>0\). The denominator is the same for both, so the higher-scoring token is \(e^{g/\tau}\) times as likely as the other. Lowering \(\tau\) increases that advantage.

Let’s go back to Thneed. The figure shows GPT-2’s four most likely next tokens. Compare the candidates just after Th with those after need. Then keep the prefix fixed and lower the temperature. The candidates keep their order, but the probability of the first one grows. Green marks the word that actually came next in our example when it appears among the four.

Each word in the training sentence serves as the target for the prefix ending one token earlier.

Steering Vectors

Lowering the temperature makes a model more likely to pick the token it already favors. What if we want to change which token it favors? Every prediction depends on a vector in the residual stream. If we can find a direction associated with a subject or a writing style, we can add a little of that direction to the stream as the model generates. We call this direction a steering vector.

How can we find one? We give the model the same prompts twice. In one set we ask for the behavior we want. In the other we leave it unspecified. At each block, we scale each answer token’s residual vector to unit length and average those vectors to get one vector per answer. Then we average the answers in each set. We subtract the ordinary average from the average for the behavior we asked for and scale the difference to unit length. This gives us a steering direction \(\mathbf v_\ell\) for block \(\ell\).

To steer a new completion, let \(\mathbf h_i^{(\ell)}\) be the residual vector for token \(i\) leaving block \(\ell\). For a model with \(L\) blocks, we apply the update \[ \mathbf h_i^{(\ell)}\leftarrow\mathbf h_i^{(\ell)}+\alpha\mathbf v_\ell, \qquad \ell=1,\ldots,L. \] The next block receives the edited vector. We can apply the update at every block as each new token passes through the network. The strength \(\alpha\) controls how far we move along each unit direction. Setting \(\alpha=0\) gives us the original model.

Let’s try to steer GPT-2 toward topics associated with Elon Musk. For each interview question, we asked GPT-2 to complete one answer attributed to Musk and another attributed to an unnamed interviewee. We combined the directions from several interview phrasings and normalized the result at each block. Now give GPT-2 a new question and the first few words of an answer. Both runs use the same random seed. In the steered run, we start adding the direction just after the first word of the supplied answer.

The notebook shows the full generations for all four prompts with and without the steering vector.

When we ask “What is the best car ever?” the original model completes “The best car ever is” with “the Toyota Tacoma.” With steering, it writes “the Tesla Model 3.” We use the same steering strength for all four starters. The demo reproduces the completions.

Linear Probes

Steering lets us change a prediction by editing a token’s vector. We can also ask what we can read from that vector while leaving the transformer frozen. A linear probe is a linear model we train on the transformer’s saved vectors to predict a label we know. By fitting a separate probe at each block, we can see where a label becomes easier to recover.

Let \(\mathbf h\) be the saved vector with a \(1\) appended. For each of the \(K\) possible labels, we learn a weight vector \(\mathbf w_j\). The probe predicts the label with the highest score: \[ \widehat{a}=\underset{1\leq j\leq K}{\arg\max}\;\mathbf w_j^\top\mathbf h. \]

Let’s see whether we can read the answer to a subtraction problem from GPT-2’s vector at the equals sign. Each problem has a difference between 1 and 8. For each block, we fit the eight scores to one-hot answer labels by regularized least squares. We train on 50 first operands, pairing each with all eight differences. We test on 20 new first operands, giving us 160 held-out questions with the same number of examples for each answer.

Here’s one held-out prompt. The first two lines give GPT-2 the format. We save the vector at the last equals sign:

18 - 15 = 3
22 - 16 = 6
58 - 51 =

Hover over a block to see the probe’s eight scores for this question. When 7 has the highest score, the probe has recovered the answer.

The plot compares the fitted probe with GPT-2’s own readout at each block.

What else could we do with a probe?

  • Look for signs of lying. Give a model questions it can answer and ask it to respond honestly on some trials and lie on others. Can a probe distinguish the two on questions it hasn’t seen?
  • Predict a behavior. Before the model generates an answer, use its vector to estimate the probability that it will refuse a request. We can check those probabilities against how often the model actually refuses on new requests.
  • Trace a concept through the network. Fit a probe at each block to predict whether a sentence’s subject is singular or plural. At which block can we first read out that distinction reliably? In positional embeddings, we’ll try this with a token’s position.