Skip to content
ImagineWorld

Attention

node_idnode-book_50-ml-projects-to-understand-llms_chapter-06-attention
node_typechapter_node
schema_profileworld.chapter_node.v1
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
statusactive
chapter_num6
chapter_titleAttention
sections6.33 Project 33: QKV weights characteristics, 6.34 Project 34: QKV activation characteristics, 6.35 Project 35: Raw and softmax attention scores, 6.36 Project 36: Characteristics of attention adjustment magnitudes, 6.37 Project 37: Token prediction and attention KL divergences, 6.38 Project 38: Laminar profile of RSA and category selectivity, 6.39 Project 39: Token frequency, attention adjustments, QK-transpose, 6.40 Project 40: Downstream impacts of head silencing, 6.41 Project 41: Patching heads in IOI
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

The transformer layer comprises two blocks: attention and MLP. This chapter focuses on extracting, analyzing, and visualizing data from the attention block. I will introduce the attention block and its key equation, before starting with the projects.

The goal of the attention block is to integrate information across token pairs within a sequence, in order to identify relevant content and load it onto the hidden-state vectors.

The attention block implements the following key equation. I’ll describe each piece below.

A=σ(QK⊤dh+M)VWO(6.1)A = \sigma\left(\frac{QK^\top}{\sqrt{d_h}} + M\right) V W_O \tag{6.1}

A

This is the attention activations matrix. It is a tensor of size batch × sequence length × embeddings dimensionality. These are the context-rich adjustments that are added back onto the hidden-state vectors before being passed into the MLP block for further adjustments.

QK^⊤

This is a matrix multiplication between two matrices known as the “queries” (Q) and the “keys” (K). They are each of size batch × sequence length × embeddings dimension (although it’s more accurate to describe head dimensions; I’ll explain this in the next subsection). Their dot products QK^⊤ are a tensor of size batch × tokens × tokens.

The QK^⊤ product is stored as a tensor, but it’s best to think of it as a collection of vectors — one vector for each token position. Briefly, the queries vectors represent what each token position is “looking for,” while the keys vectors represent what each token position “offers.” Their dot product encodes how much each token position “matches” with each previous position, which in turn determines how much information is passed back into the hidden-state vectors.

For this reason, it’s useful to think of QK^⊤ as dot products between pairs of token vectors, and the matrix multiplication is just an efficient way of implementing the vector dot products. I will refer to these values as “raw attention scores.”

dh\sqrt{d_h}

This is the square root of the head dimensionality. I’ll describe the attention heads more in the next subsection, but briefly: the attention matrices are segmented into submatrices that implement the same calculations but using different weights, and therefore can extract different features from the same text data. dh\sqrt{d_h} is the dimensionality of each head, and is a scalar normalization. You’ll learn why this is important in Project 35.

M

This is a mask matrix. It prevents the model from being able to “attend to” future tokens when predicting the next token. This mask is used in autoregressive models like GPT, but is not used in masked-token-prediction models like BERT.

σ()

This is the softmax transformation. It’s exactly the same mathematical function as what you used in Chapter 4. However, it serves a different purpose here. These softmax values are not used to sample tokens probabilistically, but instead are used to calculate a weighted sum of vectors in the V matrix. I will refer to the output of the softmax as “softmax activation scores.”

V

This is called the “values” matrix, and it contains the information that is aggregated and incorporated back into the hidden-state vectors. That information gets weighted according to the softmax attention scores, such that token position pairs that provide relevant context get boosted, whereas pairs that provide no relevant context are suppressed. Notice that QK^⊤ is inside the softmax function while V is outside.

W_O

This is the output (also called mixing or projections) matrix that linearly combines the information generated by each attention head.

Where do the Q, K, and V vectors come from? They are the products of the hidden-state vectors (X) and the weights.

Q=XWQ(6.2)Q = X W_Q \tag{6.2} K=XWK(6.3)K = X W_K \tag{6.3} V=XWV(6.4)V = X W_V \tag{6.4}

The weights matrices W are adjusted through training via the gradient descent algorithm, but are fixed in a trained model. Thus, because we’re only working with trained models in this book, the weights are exactly the same regardless of the text you give to the model. On the other hand, the activations (Q, K, and V) are dynamic and data-dependent. They are the product of the weights with the hidden-state vectors X, which means they will change with each text prompt.

You will investigate the weights matrices in Project 33, and the other matrices in the rest of the chapter.

What would be better than having one attention equation? Having many of them! That’s the idea of multihead attention. The queries, keys, and values matrices I described above are reshaped into a number of submatrices (e.g., 12 heads in GPT-2-small, 16 in GPT-2-medium), which implement the same calculations but using different weights. The idea is that each head develops its own “spotlight of attention” that learns to be sensitive to different features of the text and time-scales of context relevance, which increases the diversity and richness of their calculations. After the heads independently process the text, the “views” from all heads are combined via the mixing matrix.

Importantly, all embeddings dimensions are mixed into each Q_h in the multiplication XW_Q. Thus, it is not the case that splitting Q into heads is simply segmenting the embeddings space. Instead, the splitting allows each head to access a different dimension-reduced view of the embeddings space. The dimensionality of each head is the embeddings dimensionality divided by the number of heads. For example, in GPT-2-small, the embeddings dimensionality is 768 and there are 12 heads, and thus the head dimensionality is 768∕12 = 64.

With this in mind, we can rewrite Equation 6.1.

Ah=σ(QhKh⊤dh+M)Vh(6.5)A_h = \sigma\left(\frac{Q_h K_h^\top}{\sqrt{d_h}} + M\right) V_h \tag{6.5}

The W_O matrix seems to be missing from Equation 6.5. However, it is not part of the per-head calculations. Instead, it mixes the information together across the individual heads (the ∥ symbol between matrices indicates concatenation):

A=[A1∥A2∥…∥Ah]WO(6.6)A = [A_1 \| A_2 \| \ldots \| A_h] W_O \tag{6.6}

Thus, the W_O linearly combines all the context-relevant information learned by the individual heads, to be passed back into the hidden-state vectors.

day-mode Bookmark

QKV weights characteristics

The goal of Project 33 is to explore the weights matrices of various GPT-2 models. You won’t need a tokenizer, because there is no text, no tokens, and no activations. Instead, you will explore the weights — the parameters of the model that remain unchanged after training.

You will also learn about separating the attention heads to isolate their weights.

In order to compare the distributions of weights characteristics across different sizes of GPT-2, it will be convenient to have four models, and key parameters, stored in a dictionary.

Task

Create two dictionaries, one called models and one called params. Both dictionaries have four keys corresponding to four GPT-2 sizes: small, medium, large, and xl. The corresponding value in the models dictionary are the models themselves. This will allow you to access, e.g., GPT-2-large using models[’large’].

The second dictionary (params) has the same keys as above, but each item is itself another dictionary, which contains the following keys: the number of transformer layers (n_layers), the embeddings dimensionality (n_emb), the number of heads (n_heads), and the head dimensionality (head_dim). You can find these parameters in the .config property of each model.

Create and print a table of model sizes and their parameters as shown below.

You can confirm some of the keys of the dictionary, for example:

“models” keys:  dict_keys([’small’, ’medium’, ’large’, ’xl’])

“params[’small’]” keys:

dict_keys([’n_layers’, ’n_emb’,
’n_heads’, ’head_dim’])

And here is the table of parameters:

  Model | Embed.dim | Layers | n heads | head.dim --------+-----------+--------+---------+---------  small  |     768   |   12   |    12   |   64 medium  |    1024   |   24   |    16   |   64

large | 1280 | 36 | 20 | 64
xl | 1600 | 48 | 25 | 64

Once you have all the models imported, you can access weights matrices from specific layers. For example, the following code extracts the QKV weights matrix from the 6^th transformer layer. models[’small’].transformer.h[5].attn.c_attn.weight

Task

Count and report the total number of trainable attention parameters in each model. The number of trainable parameters is the number of weights plus the number of bias terms. Hint: All layers have exactly the same sized weights matrices.

You should get the following results (I rounded the results to the nearest 10^th of a million).

 28.3M attention weights in GPT-2-small 100.8M attention weights in GPT-2-medium 236.1M attention weights in GPT-2-large 491.8M attention weights in GPT-2-xl

Now you have all the models imported; it’s time to begin characterizing.

Part 2: Distributions of attention weights in GPT-2-small

Section titled “Part 2: Distributions of attention weights in GPT-2-small”

OpenAI LLMs like GPT store the three attention matrices as one wide matrix. That is, instead of storing three separate 768 × 768 matrices, there is one 768 × 2304 matrix corresponding to W_Q, W_K, and W_V. This is done for convenience, and not all LLMs use this organization. You can use the torch.split() function to separate the wide matrix into the individual matrices, by inputting the size of each matrix and the dimension along which to split. Figuring out how to specify the inputs in part of the first task.

We’ll focus on GPT-2-small here to develop the code, and then compare across models later.

The goals here are to (1) split the W_Q, W_K, and W_V matrices from their concatenated tensor, (2) visualize histograms of the weights values, and (3) measure and plot the means and standard deviations of the weights matrices.

I will ignore the bias terms for the rest of this project. Bias terms are necessary for non-centered data, but there are very few bias terms in the model (hundreds of biases vs. millions of weights) and they thus make a negligible contribution to the overall statistics.

Task

Extract the concatenated weights matrix from GPT-2-small from layer index 6. The matrix is stored in the c_attn layer, and each individual matrix has a dimensionality of the embeddings (variable n_emb). Visualize the wide matrix as in Figure 6.1, and draw vertical white dashed lines demarcating where the matrix is split into three.

I’ve labeled the x-axis as queries/keys/values dimensions instead of embeddings dimensions because those are formally distinct: The dimensionality of the attention calculations can differ from the dimensionality of the embeddings. That said, square W matrices is common convention in LLMs including all the models you’ll work with in this book.

Figure 6.1: The concatenated attention weights matrix from one transformer layer.

Task

Split the wide matrix you just extracted into W_Q, W_K, and W_V matrices. Calculate histograms of the values in each matrix, and visualize as line plots as in Figure 6.2.

Next, extract those histograms in a for-loop over all layers. Use the same bin boundaries for all layers, and store the histogram density values in a matrix of size 12 × N × 3, where 12 corresponds to the number of transformer layers, N is the number of bins in your histogram (I used 81), and 3 corresponds to the W_Q, W_K, and W_V matrices. Show the results in a heatmap as in Figure 6.3, in which the rows (y-axis) are transformer layers, the columns (x-axis) are the weights values, and color is the density (the height in the histogram).

Finally, extract the mean and standard deviation of each weights matrix and show the results in scatter plots as in Figure 6.4.

Splitting the wide QKV matrix into its constituent parts can be done using torch.split using the following code: q,k,v = torch.split(W,n_emb,dim=1) Where W is the wide (concatenated) matrix. You will often split matrices when working with the attention block.

The line plots of the histograms from one layer are nearly perfectly overlapping and quite Gaussian-looking (one central peak, smooth and symmetric decays left and right of the mean), as you see in Figure 6.2.

Figure 6.2: Distributions of weight values in the three attention weights matrices in one transformer layer.

Is the overlap just a quirk for this one layer? Perhaps the other layers look more distinct? Let’s find out in Figure 6.3. The x-axis corresponds to the weight value, the y-axis corresponds to the transformer layer, and the color indicates probability density.

Figure 6.3: Distributions of weight values in the three attention weights matrices over all transformer layers. Each row is a transformer and the color corresponds to density. Color scaling is the same for all three heatmaps.

The results are… not terribly interesting, in that there are only some minor differences in the weights distributions over the layers. Or perhaps that is the interesting finding, considering how it contrasts with the results you’ll see for the activations in the rest of the projects in this chapter.

Figure 6.4 shows the means and standard deviations. Don’t try to over-interpret the apparent fluctuations in the left panel: These are mostly random fluctuations are zero — check the y-axis tick labels. The right panel does reveal some trends that are less easily visualizable from the heatmaps. In particular, the distribution of weights values gets smaller with increasing depth for W_Q and W_K, while increasing for W_V.

Figure 6.4: Means (left panel) and standard deviations (right panel) of the three weights matrices over transformer layers (x-axis).

Part 3: Comparing distributions across models

Section titled “Part 3: Comparing distributions across models”

With increasing dimensionality, data visualization becomes increasingly difficult. One might say, “mo’ dimensions, mo’ problems.”

One of the themes I’d like to stress in this book is the balance between showing a lot of data to convey as many patterns in the results as possible, vs. keeping the graphs simple and interpretable and allowing you and your audience to understand the key patterns.

Specifically in this project, it is difficult to visualize the histograms of all attention weights vectors for all layers and all model variants in a compact way. So, the analyses will be the same as in Part 2 but the visualization will be reduced.

Task

Loop over the four model variants, and over all layers within each model. Split the attention weights into the W_Q, W_K, and W_V matrices, and calculate and store their means and standard deviations.

Visualize the descriptive characteristics using line plots for each model as in Figure 6.5. What features seem consistent across models? Base your answer on visual inspection; you don’t need to do any quantitative analyses.

The left-column plots show that the means of the weights matrices are all very close to — but not exactly equal to — zero. That’s interesting for two reasons: (1) there are no systematic shifts in the activations trivially introduced by the weights, and (2) the fact that the weights are mean-centered is not trivially imposed (otherwise the means would be exact zero, some precision error notwithstanding) but instead is learned by the models during training.

Figure 6.5: Same as Figure 6.4 but for the four GPT-2 variants.

The standard deviations do appear to show systematic changes with increasing depth into the models. In particular, the W_Q and W_K standard deviations decrease while the W_V standard deviations increase. That’s a pattern you observed in Part 2 with GPT-2-small, and here you see it replicate across all four model variants.

W_Q and W_K shape how much each previous token in the sequence should impact the currently-processed token, while W_V shapes the token-specific information that is passed forwards to adjust the hidden-state vector. Thus, the intuition is that later transformer blocks have already encoded the most important token-pair information, thus shifting the focus more on the information content of the token pairs. Of course, the variance of the weights is not the information, but more variance provides a larger space in which richer information can be represented (by contrast, a vector with zero variance can represent only one number, even in a thousand-dimensional space).

A tangent discussion about calculating standard deviation: The NumPy default ddof parameter in the standard deviation function is 0. ddof stands for “denominator degrees of freedom,” and determines whether the result is the population (ddof=0) or the sample (ddof=1) standard deviation. The question here is whether the elements of the attention weights matrices are sampled estimates of some true underlying Platonic Weights matrix, or whether they are the population. The weights are trained from random numbers, which is consistent with the “samples” argument. On the other hand, two models randomly initialized and then trained on the exact same dataset will have distinct weights, which argues against the Platonic Weights concept (that is, the expected value of the average of the weights is zero, which would produce a useless LLM). Furthermore, the weights of one matrix are inextricably tied to the rest of the model, so it is not possible to resample the W_Q matrix without re-training the entire model. Anyway, this is more of an armchair-theoretical question than one with serious implications: The difference between scaling by 1∕N vs. 1∕(N − 1) is vanishingly tiny as N increases into the hundreds, let alone millions.

Part 4: Cosine similarity within heads (one model)

Section titled “Part 4: Cosine similarity within heads (one model)”

Perhaps there is more interesting information embedded in the relationships between weights vectors? The rest of this project explores that question.

The goal of Part 4 is to isolate the individual attention heads, and calculate cosine similarity within and across the heads.

Separating the attention heads is easy, and uses the same torch.split function you’ve already been using to extract the W matrices from their concatenated wide matrix. So, to isolate the attention heads, first split the wide weights matrix into W_Q, W_K, and W_V, and then split W_Q into H heads.

Important caveat: The weights matrices technically can be split or reshaped into “heads”, but that is not how per-head processing is implemented during a forward pass. In particular, Q is split into heads after being defined as the matrix product XW_Q. Splitting W_Q into “heads” gives you more experience with PyTorch functions and splitting tensors, and it provides an excellent comparison to the per-attention head analysis in later projects. But it is artificial in the sense that the splitting in this project is not implemented in actual model calculations.

Task

Use GPT-2-small. Create two list variables called WQ_h and WK_h in which each element of the list is one attention head from one layer (I used layer index 6). Confirm that the number of tensors in the list equals the number of heads, and that the size of each head equals the embeddings dimensionality times the head dimensionality.

Visualize the heads weights matrices as in Figure 6.6 (I used the plasma color map). Make sure you have the correct orientation (embeddings on the x-axis, head dimension on the y-axis).

If you’re using GPT-2-small, you should get 12 heads, each with a size of 768 × 64.

The heads weights matrices are tall (embeddings × head dimension), but because I wanted the figure to be wider than tall, I transposed the weights matrices. To confirm the accuracy of your axis labels, I recommend leaving the axis ticks on to see whether the axis labels match the axis ticks. The “shadow” effect of the head label is accomplished by drawing the text twice using different colors with small offsets.

Figure 6.6: Heatmaps of the W_Q matrix separated into “heads.”

The heatmaps of the matrices look like random noise. Of course, they are definitely not just random numbers, but they lack visually interpretable large-scale structure. Instead, the important patterns are distributed across the matrices.

Task

Calculate the cosine similarity matrix of one head. Make sure the matrix is 64 × 64; thus, each element is the pairwise similarity over all embeddings dimensions for each head dimension.

Show the matrix as a heatmap, and show the non-redundant and non-trivial elements of the matrix as a histogram, as in Figure 6.7.

Figure 6.7: Cosine similarity and histogram of dot products between pairs of W_Q vectors of one attention head in layer 6.

The cosine similarities are all quite small and centered around zero. In fact, it looks like the similarity profile of random noise. Again, the weights are definitely not noise, but they lack a systematic and intrinsic relational structure.

Instead, the weights vectors are almost pairwise orthogonal, which allows them to span the entire head-dimensional space. You can contrast that with the embeddings vectors that you explored in Chapter 3, which were dominated by positive similarity values; and with the attention activations that you’ll explore later in this chapter.

Yet again, this finding indicates that the important information in LLMs is carried by the activations, which is how the weights shape the hidden-state vectors.

On the other hand, we shouldn’t make grand conclusions based on data from one head in one layer in one model. Perhaps we can gain more insights when comparing similarities within one head vs. across different heads?

Part 5: Cosine similarity within- vs. across-heads (one model)

Section titled “Part 5: Cosine similarity within- vs. across-heads (one model)”

Each attention head learns to implement its own calculations and its own dimension-reduced view of the embeddings space. Therefore, one could imagine that vectors within each head are more similar to each other, compared to vectors across heads. That’s what you’ll examine here using the weights, and you’ll repeat this analysis using activations in Project 34.

Task

Inside a double-for loop over all heads (still just using matrices from one layer), calculate the cosine similarities between all vectors in head i with vectors in head j. Extract the non-redundant similarity values and store them across all pairs. Be mindful that the within-head similarity matrix contains redundant and trivial values whereas the across-head similarity matrix does not. That is, S_c(i_k,j_k) = S_c(j_k,i_k) only when i_k and j_k come from the same head.

Run these calculations for the W_Q and W_K vectors.

Visualize the results using histograms as in Figure 6.8.

This analysis is tricky to setup; feel free to check my solution if you understand the concept but struggle with the implementation.

Figure 6.8: Distribution of cosine similarities within- vs. across-attention heads in layer 6.

A few notes about this analysis:

  1. The inner loop can start from the outer loop’s iteration. That is, if the outer loop is defined as for i in range(0,h), then the inner loop can be defined as for j in range(i,h).

  2. When extracting the non-redundant elements of the cosine similarity matrix, remember that the similarity matrix is symmetric only when multiplying a data matrix by itself. That is, X^⊤X (same head) is symmetric while X^⊤Y (different heads) is not.

  3. In my solution code, I run the analysis separately per head-pair. You can also run the analysis on the full (non-split) W_Q matrix, in which case you’d calculate only one cosine similarity matrix and then identify the block-diagonal elements that correspond to within- vs. across-head similarities. That might be more efficient but also more prone to errors. Knowing how to split and work with heads is a good skill that you can practice here.

  4. If you look carefully at my code solution, you’ll see that I convert the cosine similarity matrix (variable cs) from a PyTorch tensor to a NumPy array for W_Q, but not for W_K. I included that difference to illustrate that mixing variable types (in this case, initializing a NumPy array but populating it with PyTorch tensors) sometimes works (as in this demo), sometimes works but issues a warning, and sometimes produces an error. For example, you’ll get a warning message if you convert the divisive normalization vector into NumPy, though the results will still be correct. In general, it is good coding hygiene to be consistent about using data types with matching library functions (that is, NumPy functions on NumPy arrays and PyTorch functions on PyTorch tensors), although it’s also good to know that mixing data types is sometimes fine.

So, what have we learned after all these calculations and complicated code? For one thing, the cosine similarities again are fairly small in magnitude, Gaussian-distributed, and centered on zero. Visually, the within-head similarities seem smaller (higher peak at zero and steeper slopes). Again, these observations are consistent with the idea that the weights vectors are largely orthogonal, which can allow the activations to fill the entire 64-dimensional space instead of being restricted to a smaller informational pocket.

On the other hand, that analysis was just in one layer of one model. The goal now is to repeat the analysis for all layers (still just using GPT-2-small). Showing 12 sets of heatmaps and histograms (one per layer) is technically possible but doesn’t reveal laminar changes, so we’ll switch to showing descriptive statistics of the cosine similarities.

Task

Copy the code from above into a new code block, and place it inside a for-loop over layers. Be mindful of what code needs to be adjusted (e.g., extracting each layer’s weights matrices). Use common histogram bins of 101 linearly spaced numbers between -.4 and .4 for all distributions. Calculate the mean and standard deviations for the cosine similarities within-head and across-heads, for W_Q and W_K.

Plot the distributions as heatmaps as in Figure 6.9 (use the same color limits for all images), and plot the means and standard deviations as line plots as in Figure 6.10.

The observations from one layer seem consistent across all layers.

Figure 6.9: Distribution of cosine similarities within- vs. across-attention heads across all transformer layers. color limits are the same in all plots.

The line plots in Figure 6.10 also show that the cosine similarities are centered around zero.

Figure 6.10: Characteristics of cosine similarity distributions, separated for W_Q and W_K weights, across all layers of GPT-2-small.

There are two visually recognizable patterns in the standard deviations. First, the distributions are wider after the first transformer block, then decrease in later layers. Second, the standard deviations are consistently smaller for the within-head vs. across-head similarities after layer 5. That complements the observation from Figure 6.8, where the within-head similarities were more tightly distributed around zero.

Part 6: W_Q, W_K, and W_V similarities across models

Section titled “Part 6: W_Q, W_K, and W_V similarities across models”

The final part of this project is to compare the characteristics of the cosine similarities across models. We again face a dimension-explosion issue: Showing distributions of similarities for within- vs. across-head, per layer, and per model risks overwhelming your audience and potentially obscuring meaningful patterns.

So, we’ll keep it simple and just focus on similarities within W_Q, W_K, and W_V without splitting into heads.

Task

Loop over the four models, and loop over all transformer layers within each model. Inside that double-for loop, extract the W_Q, W_K, and W_V matrices, calculate each cosine similarity matrix, and store the mean and standard deviation.

Inside the inner loop, print out status updates for each layer like the following:

Working on GPT-2-small (12 layers): 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

Visualize the results as a collection of line plots where the rows correspond to the GPT-2 variants and the columns correspond to the statistic (mean or standard deviation), as in Figure 6.11.

The conclusion of this analysis is the same as that of all the other analyses in this project: Nothing terribly interesting emerges.

Figure 6.11: Laminar characteristics of cosine similarities across all transformer layers and for the GPT-2 model variants.

I’d like to discuss my code solution before drawing final conclusions for this project, because it is slightly different from how I solved earlier parts. Here’s the thing: Extracting the upper-triangular elements of a matrix is fast for small matrices, but can become slow and memory-intensive for large matrices (e.g., 1600 × 1600 for GPT-2-xl). My solution here was to create a matrix of Booleans that is 1 above the diagonal and 0 everywhere else, and then extract the similarity matrices from that mask. The mask code looks like this:

N = params[whichmod][’n_emb’] onesmat = torch.ones(N,N,dtype=torch.bool) mask = torch.triu(onesmat,diagonal=1)

Then I extracted the similarity values as cs[mask]. That’s considerably faster than the solution I wrote for GPT-2-small. It’s also fully in PyTorch (using .item() to extract the float out of the PyTorch tensor). In general, it is useful to know several solutions to problems. Think of each solution variant as a tool in your toolkit, and the more diverse your toolkit, the better you’ll be able to solve other problems in the future.

Conclusions from this project I hope you’re not disappointed in the results! You learned a lot about working with weights matrices and extracting data out of models. And I think you will be find these results very interesting to compare against the results of the next project, where the analyses are similar but done on activations instead of static weights. The take-home message is this: The information in the weights is extremely important. So important, that companies like OpenAI, Anthropic, Meta, and Google, go to great lengths to keep these weights matrices secured and inaccessible. That said, the beauty and power of the weights is in how they shape and transform the hidden-state vectors, not in their distributional characteristics.

This is also a major challenge for understanding how LLMs represent and transform information, because it means that we cannot gain much meaningful insight just by analyzing the weights. Instead, we can understand LLMs only by getting data from the weights in action: processing language and making predictions about new tokens or text classification. That itself is an enormous challenge, because LLM internal dynamics are highly dependent on context, as you’ve already seen in the previous chapter and will continue to see in this and the next chapters.

Anyway, I’m sure you’re curious to explore the characteristics of the attention activations (the products of the weights matrices with the data). Time to move on to Project 34!

day-mode Bookmark

QKV activation characteristics

The goal of this project is to extract and characterize activations from the attention block.

Unlike the trained weights, the attention activations are text-dependent, and so we must create and implant hook functions to grab the activations during a forward pass.

By the end of Part 1, you’ll have all the data you need for the rest of the project.

Task

Import GPT-2-large and its tokenizer. Switch the model to eval mode. Define variables for the embeddings dimensionality and the number of transformer layers.

Import the text for the Great Gatsby book from gutenberg.org. Tokenize the book and find all instances of the token “ like” (note the preceding space).

Create a batch of 114×51 for the 114 target token appearances and the 50 context-providing tokens before each target token. Check whether any target tokens appear within the first 50 tokens of the book, and if so, exclude them.

Here are the last 10 tokens of the first few batch sequences:

“Whenever you feel like , but I’m supposed to look like  of the world, the Middle West now seemed like house together in a commuting town, it sounded like

stood on my shelf in red and gold like

For the rest of this project, we’ll use the final token in each sequence as the “target” and the penultimate token as the “non-target.” It’s an interesting comparison because (1) the context is identical for both tokens with the exception that the penultimate token also provides context for the final token; (2) the target token is identical in all batches but has sequence-unique contexts. Thus, any target-related differences or variability across sequences can only be attributed to the context.

The next task is to obtain the activation values of the matrices inside the attention equation. In particular, the part of the model accessed with model.transformer.h[i].attn.c_attn is the Q, K, and V matrices from transformer layer i. They are stored as one wide matrix and calculated as:

QKV=X[WQ∥WK∥WV](6.7)QKV = X [W_Q \| W_K \| W_V] \tag{6.7}

Splitting QKV using torch.split gives the individual Q, K, and V matrices.

Task

Write a hook function to get attention activations from the attn.c_attn output. Store the QKV matrix in a dictionary called activations, with the key name including the layer number (e.g., attn_4_qkv). Implant the hook into all transformer layers.

Run a forward pass of the batch. Print out all the dictionary keys and their shapes, and make sure you understand what the tensor sizes correspond to.

The forward pass takes some time on a CPU (3 minutes when I ran it on Colab’s CPU). It would, of course, be much faster with a GPU, but it is the only forward pass in this project, and the rest of the project does not benefit from a GPU.

Printing out hooked data labels and sizes is always a good idea when working on code; it helps you spot coding mistakes, and helps you learn the ordering of dimensions inside the model. I won’t include all the layers here, but your print-out should look like this:

attn_0_qkv has shape [114, 51, 3840] attn_1_qkv has shape [114, 51, 3840] attn_2_qkv has shape [114, 51, 3840] … attn_35_qkv has shape [114, 51, 3840]

The 3840 corresponds to an embeddings dimensionality of 1280 for the three attention matrices (query, keys, values) concatenated.

Task

Visualize the activation matrices for the target token in layer index 6 as a heatmap as in Figure 6.12.

This image is similar to the heatmap of the concatenated weights matrix from the previous project, although the full dataset here is a tensor (a cube) and Figure 6.12 is merely one slice through the final token in the batch sequences.

Figure 6.12: Heatmap of the wide (concatenated) matrix of activations for the target token.

There are several prominent features of this image, including the vertical stripes and the narrow colors of the K activations. The vertical stripes indicate that dimensions exhibit similar activation values across all batches, and the pink-dominated values activations indicates a smaller range of numerical activations.

This heatmap is just from the target token, but you can modify the code to show the non-target token.

Although these matrices are not split into heads, you can imagine that the heads are represented as tall, thin bars spanning this matrix.

The goal here is to explore the characteristics of the attention activations using bar plots and histograms. Choose one transformer layer to focus on for now; I used layer index 6.

We’ll focus on three descriptive statistics here:

xˉ=n−1∑i=1nxi(6.8)\bar{x} = n^{-1} \sum_{i=1}^{n} x_i \tag{6.8} xˉl1=n−1∑i=1n∣xi∣(6.9)\bar{x}_{l1} = n^{-1} \sum_{i=1}^{n} |x_i| \tag{6.9} σx2=(n−1)−1∑i=1n(xi−xˉ)2(6.10)\sigma_x^2 = (n-1)^{-1} \sum_{i=1}^{n} (x_i - \bar{x})^2 \tag{6.10}

Task

Split the activations matrix into Q, K, and V matrices. Confirm that the sizes of the matrices match your expectations. For this task, use only the Q vectors.

Calculate the three descriptive statistics listed above, for the target (final token) and non-target (penultimate token). Make sure you’re averaging the activations vectors; you should have one statistical characteristic for each of the 114 sequences.

Average over the 114 values to create bar plots as in Figure 6.13. Interpret the differences between target and non-target, and the differences between the different descriptive statistics.

Answer these questions: (1) Are you surprised that the bars for arithmetic and L_1 means are so dissimilar, while the L_1 means and variances are closer? (2) Are you surprised that the variances for the target and non-target are roughly equal? What does that tell you about the information represented in the attention matrices?

Each of the Q, K, and V matrices have size 114 × 51 × 1280, corresponding to 114 sequences in the batch, 51 tokens in the sequence, and 1280 embeddings dimensions.

You can use the PyTorch functions mean and var to calculate the mean and variance, and getting the L_1 average involves taking the mean of the absolute values. For example, the following code calculates the L_1 mean. torch.mean(abs(Q[:,-1,:]),dim=-1).mean()

Notice that I first average over the last dimension (embeddings) using a function, and then average over tokens using a method. The order of averaging matters when there are nonlinear operations (such as absolute value or squaring). I chose to store the data as two 3-element tensors, one for the target and one for the non-target token positions.

Figure 6.13 shows the bar plot.

Figure 6.13: Bar plots showing descriptive characteristics of the Q activations matrix in layer 6.

To answer the first question: The arithmetic mean is close to zero because it sums over positive and negative numbers. The differences between the arithmetic and L_1 averages tell us that the activation values are roughly equally spread around zero, with positive and negative activation values canceling. That will be interesting to compare against the QK^⊤ dot products that you’ll explore later in this project.

Given that the arithmetic means are close to zero, it’s no surprise that the L_1 mean and variance are closer to each other. Look back at the equations and notice that the two characteristics involve summing positive values (the reason why the variance divides by n − 1 is that the mean-centering takes away one degree of freedom). That said, L_1 mean and variance are distinct statistical quantities: The L_1 mean is a measure of the average magnitudes in the data, whereas variance is a measure of the dispersion of the data around the (arithmetic) mean.

To answer the second question, it is useful to remember that the attention vectors are not the embeddings or hidden-state vectors; instead, they are the adjustments to those hidden-state vectors (well, the Q activations themselves are not the adjustments, but they form part of the mechanism that calculates the adjustment). In other words, these Q vectors do not correspond to the token “ like”; instead, they correspond to part of the algorithm that calculates a context-dependent change to the token representation. That context (the preceding 50 tokens) is nearly identical for the targets and non-targets, and thus it is no surprise that their descriptive statistics are comparable. Furthermore, although the target token is identical in all 114 batches, the context is different for each batch.

Task

Calculate and visualize six histograms, corresponding to the activation values of the three attention matrices for the target and non-target tokens (Figure 6.14). Use bin edges of -7 to 7 in 234 steps for all histograms.

Figure 6.14: Distributions of attention activation values for the target and non-target token positions in layer 6.

All distributions are similar in that they are roughly Gaussian-shaped and appear to be symmetric around zero. This will be interesting to compare against the distribution of QK^⊤ dot products in Part 5. The distributions are also quite similar between targets and non-targets.

On the other hand, the widths of the distributions are strikingly different.

Thus far, we haven’t seen strong indications of differences between target and non-target activations. That might be surprising, considering that the target token is identical whereas the non-target token changes each sentence. But again, the matrices inside the attention algorithm do not encode tokens as the hidden-state vectors do; instead, they encode how the hidden-state vectors should be adjusted based on context, and the context is nearly identical for the target and non-target token positions.

Section titled “Part 3: Laminar trends in activation descriptives”

The end result of Part 3 will be visual characterizations of the three descriptive characteristics you investigated in Part 2, over all transformer layers. Because that involves a lot of repeated calculations, it will be helpful to have a helper function to keep the main code clean and readable.

Task

Write a helper function, called meansAndVar, that takes a PyTorch activations tensor as input, and returns a 2×3 tensor as output. The first row of the output contains the three descriptive characteristics for the target, and the second row is for the non-target.

In a for-loop over layers, get the descriptives for each layer, for the three attention matrices, and for the target and non-target positions. Store the results in one 4D matrix for layers × attention matrix × characteristic × target or non-target.

Show the results in two sets of line plots. The first (Figure 6.15) is the results averaged across target and non-target. The second (Figure 6.16) shows the differences between target and non-target. You can use the .diff() method on the results tensor, but make sure you know which direction the difference goes, i.e., whether a negative difference values means a larger mean for targets or non-targets.

These plots show the same information as in the bar plots in Figure 6.13, but over layers.

Figure 6.15: Descriptive characteristics for the three attention activations matrices across all layers.

The fluctuations of the arithmetic means around zero may seem large and chaotic when zoomed in, but notice that the numbers are around 1-2 orders of magnitude smaller than the L_1 means.

In general, the K vectors have the largest means and variances, while the V vectors have the smallest.

Next, let’s look at the difference plots.

Figure 6.16: Differences in descriptive characteristics for target vs. non-target token positions.

The differences are small compared to the overall effects — compare the y-axis values between Figures 6.15 and 6.16.

Section titled “Part 4: Laminar trends in activation distributions”

The goal here is to examine whether the distributions of attention activation values change with depth in the model. If the bin boundaries are the same for all layers, then all distribution lines can be visualized in one heatmap.

Task

Write a helper function that takes a tensor of size batch × tokens × embeddings dimension, calculates the histogram probability densities of the final (target) and penultimate (non-target) activations, and returns a tuple of the two density vectors. Use histogram bin boundaries of -4 to 4 in 101 steps.

In a for-loop over all transformer layers, split the wide attention matrix into Q, K, and V, and then input each of those matrices into the helper function. Store the results in a PyTorch tensor of size layers × 3 (Q, K, V) × bins × 2 (target, non-target). Visualize slices of the tensor to show the laminar profiles for the three matrices and for target and non-target, as in Figure 6.17.

In the heatmaps, the x-axis shows the activation values, the y-axis shows the depth into the model, and the color indicates the densities.

Figure 6.17: Distributions of attention activations for target (top row) and non-target (bottom row) positions, over all layers (y-axis).

The distributions of activations widen deeper in the model, although the rate at which the dispersion increases differs by activation matrix.

Part 5: Extracting and characterizing heads

Section titled “Part 5: Extracting and characterizing heads”

As you know from the intro to this chapter and from Project 33, the heads are stacked in each of the Q, K, and V matrices, just like those three matrices are stacked into the wide QKV matrix. There are two ways to extract the heads from each matrix: by reshaping and by splitting. You learned how to split into heads in Project 33, and here I’ll show you the reshaping method.

The code below reshapes the Q matrix so that it has an additional dimension.

n_heads = model.config.n_head head_dim = n_emb // n_heads B,T = batch.shape Qh = Q.view(B,T,n_heads,head_dim)

As you know from before, variable Q is size [114, 51, 1280]. Variable Q_h is size [114, 51, 20, 64]. In other words, the embeddings dimensionality (1280) has been reshaped to (heads × head-dimension).

Whether to reshape or to split depends partly on personal preferences and partly on the subsequent analyses. You’ll become familiar with both approaches in the next few projects.

Task

Reshape the Q matrix in layer 6 so it has an additional heads dimension. Print the sizes of the Q and Q_h tensors. Visualize all heads as in Figure 6.18, using the function plt.pcolor. Each heatmap is tokens × head dimensions for one head, using data from the first sequence in the batch. All maps use the same color scaling of -2 to 2.

Figure 6.18: Heatmaps showing Q activations for each head in layer 6. All maps have the same color scaling.

There is some structure in the results that is visible from these maps. For example, the activations across the first several tokens appear “flat”, suggesting similar adjustment calculations in the beginning of the sequence. It also seems that some dimensions have consistent biases for responding with positive or negative activations (note the horizontal bands of yellow vs. purple).

Let’s follow up on that observation, by quantifying the variability across the tokens within each head dimension.

Task

In a for-loop over transformer layers, split each QKV activations matrix into the three constituent matrices, then reshape each of those to have a “heads” dimension. Calculate the standard deviation along the tokens, and average over all heads and all batches.

Visualize the data in scatter plots as in Figure 6.19. Use the same colors and marker types as in Figure 6.15.

To be clear, this analysis quantifies the standard deviation along the rows in Figure 6.18; if a particular dimension has a similar activation value for all 51 tokens (solid color in that row), its standard deviation will be relatively small.

Figure 6.19: Standard deviations of activation values for the three attention matrices.

The results show consistent differences in standard deviation across the three matrices, with all variabilities increasing after the earlier layers. Not surprisingly, this pattern is similar to the observations in part 3, where the activation values have the most variability in the keys activations, followed by the queries and then the values.

day-mode Bookmark

Raw and softmax attention scores

In the previous project, you explored the activation values in the Q, K, and V matrices. However, those values are not used directly by the LLMs. Instead, they interact to calculate how much each token pair should contribute to the adjustment, and what information should be adjusted.

Thus, the goal of Project 35 is to explore the “raw attention scores” (QK^⊤) and the “softmax attention scores” (σ(QK⊤/dh)\sigma(QK^\top / \sqrt{d_h})) in the attention heads. You will discover that the raw attention scores have a negative distributional shift, which promotes sparsity in the softmax attention scores. You’ll also explore the distinct properties of self-attention and the first token in a sequence.

But before getting to the LLM data, I want to guide you through a simulation so you understand why the scaling factor of dh\sqrt{d_h} is used inside the attention softmax transformation.

The issue is this: The product of two numbers is likely to have a larger magnitude than either individual number (e.g., 2 × 3 = 6). The dot product, as the sum of many products, is also likely to have a larger magnitude. And a collection of dot products (e.g., matrix multiplication) will have variances that increase with the number of products, i.e., the lengths of the vectors.

This means that dot products can increase the range of numerical values in a deep learning model. In a shallow model, that’s unlikely to cause problems, but LLMs involve so many matrix multiplications that this issue can lead to numerical instabilities. This is one of the reasons why layerNorm is important. But layerNorm on its own isn’t enough.

Inside the softmax transform in the attention equation, the variance inflation acts as an implicit temperature manipulation. Therefore, the increase in expected variance is normalized by scaling by the number of elements in the dot product. In practice, that corresponds to dividing the Q_hK_h^⊤ dot products by dh\sqrt{d_h} where d_h is the dimensionality of the heads (e.g., 64 for GPT-2-medium).

The goal of Part 1 is to demonstrate this variance inflation — and its correction — using simulated data.

Task

In a for-loop over integers from N = 5 to N = 100, create two N × N matrices of Gaussian random numbers, and multiply them together. Use standard matrix multiplication with the @ symbol, not element-wise multiplication with the * symbol.

Create a second matrix defined as the product matrix scaled by N\sqrt{N}. Calculate and plot the standard deviations as in Figure 6.20. Then draw a line corresponding to the square root of the matrix sizes.

The red line is the predicted standard deviation and the red hexagons are the observed standard deviations from the random matrices without scaling. The green boxes show that the normalization appropriately counteracts the variance inflation, regardless of the dimensionality of the vectors.

Figure 6.20: Simulation showing the variance inflation across a set of dot products, and its correction by dimension-division.

The goal of Part 2 is to obtain attention activations to analyze in the rest of this project.

Task

Import GPT-2-medium. Implant a hook function into the c_attn layer of transformer 6, that stores the activations in a dictionary. Store the hook handle so it can be removed later.

Tokenize the text about the color purple that is in the online code file. Push the tokens through the model and confirm that the size of the attention activations is 1 × 115 × 3072.

If you’d like an extra challenge, you can write the hook function from scratch instead of copying it from previous projects.

The goal here is to split the activations into Q and K matrices, and then split again into attention heads.

In the previous two projects you learned how to extract heads by splitting (Project 33) and by reshaping (Project 34). Here in Project 35 you should use the torch.split function to produce a list of tensors where each element in the list is a head.

Task

Define variables for the number of layers, the embeddings dimensionality, the number of heads, the head dimensionality, and dh\sqrt{d_h}. Confirm that there are 16 heads, each with 64 dimensions.

Separate the activations matrix from Part 2 into the queries, keys, and values matrices, and then split the Q and K matrices further into lists of heads.

Show the activations heatmaps from all Q heads as in Figure 6.21. The x-axis shows token positions and the y-axis shows the head dimensionality. This is similar to the figure from Project 34 but you’ll need to modify the code to account for the different data organization.

When splitting the matrices, you should find that each of the attention matrices is 115 × 1024, and that each of the 16 heads is 115 × 64. Remember that the sum of all heads dimensions equals the embeddings dimension (in this case, 64 × 16 = 1024), but the W_Q matrix mixes the embeddings dimensions; thus it’s not the case that, for example, the first head is just the first 64-dimensional slice of the hidden-state vector. Instead, every head receives information from every embeddings dimension.

Figure 6.21: Heatmaps of attention head activations from the Q matrix in layer 6.

The horizontal stripes indicate that some head dimensions have a general negative or positive bias for all the tokens in this sequence. That’s a nice replication of an observation from the previous project, because here you’re using a different model and different text.

Let’s start exploring the QK^⊤ dot products.

Note: This project involves calculating dot products both within heads and across heads. In actual model calculations, attention scores are not calculated across heads; they are calculated only within each head. The information across heads is combined by the W_O (output) mixing matrix, but that happens after the softmax attention scores are calculated.

However, you will discover that the raw attention scores are shifted negative, and the across-head calculations provide an excellent reference distribution that demonstrates the findings are not trivial. In other words, the across-heads dot products act as a kind of permutation-based null-hypothesis distribution against which to evaluate the within-heads results (although we won’t calculate p-values here).

Task

Create a double for-loop over the 16 heads. For each pair of heads (i,j), calculate Q_iK_j^⊤/dh/\sqrt{d_h}, but only for the scores of the final token in Q with all previous tokens in K excluding the first token. Store the resulting attention scores in one of two vectors, depending on whether the dot products are calculated between Q and K from within the same head (that is, when i = j) vs. across different heads (when i≠j).

The dot products are PyTorch tensors, but store the results in NumPy arrays.

Report the number of dot products for the within vs. across heads pairs. What implication does the sample size counts have for creating and comparing histograms?

Show the results in violin and scatter plots as in Figure 6.22A (include random x-axis jitter to highlight the variability), and show the distributions of dot products as in Figure 6.22B.

Regarding the integration of PyTorch and NumPy, it turns out that you don’t need to explicitly convert from PyTorch tensors to NumPy arrays for this exercise, but doing so is good coding hygiene and is necessary in other situations. In my solution, I calculated the dot products as PyTorch tensors and then converted to NumPy:

dp = Q_h[qi][-1,:] @ K_h[ki][1:-1,:].t() / sqrtD dp = dp.numpy()

Because there are many more non-matching than matching head-pairs in the double for-loop, there is an order of magnitude difference in data size between the two sets of results:

There are 27120 values in “across head”       and  1808 values in “within head”

The implication for histograms is that it is necessary to convert the data from counts to proportion. You can do this manually by dividing the counts (first output of the np.histogram function) by the total counts, although it’s easier to set the density flag when calling the function.

Figure 6.22: Distributions of QK^⊤ scores within and across attention heads in layer 6. The across-heads dot products are used here as a reference distribution; they are not calculated in LLMs.

The insight from the reference distribution is that the negative shift in attention scores is not a trivial result of the analysis, but instead is due to the models learning that next-token prediction performance is enhanced when most attention scores are negative. Importantly, all of the dot products come from the same vectors, just separated depending on whether the pairing is the same or different heads.

By the way, there was no theoretically motivated reason to use only the final token for Q while excluding the final token from K, except to give you more experience selecting tokens in analyses. We’ll get back to this in Part 7.

So, it seems that the raw attention scores are shifted negative in one layer. We will now investigate two follow-up questions: Are the scores equally negatively shifted across all layers (Part 5)? And what is the implication of that negative shift (Parts 6-8)?

Part 5: Attention score distributions over layers

Section titled “Part 5: Attention score distributions over layers”

The goal is simple: Reproduce the analysis from Part 4 over all the layers. But as is typical in this book, the visualizations for one layer don’t scale to all the layers. Thus, the secondary goal of Part 5 is to visualize the laminar profiles of the attention score distributions in different ways.

Task

Remove the hook that you installed in Part 2. Implant a new set of hooks that is the same as in Part 2 but for all layers.

Run the same tokens through the model, and confirm that the activations dictionary now contains 24 keys.

Repeat the dot products and histogram analysis from Part 4 but in an additional for-loop over all the layers. Use bin boundaries of -20 to 20 in 101 steps, for all histograms in all layers. Store the histogram density values in a 3D array of size layers × pair type (within vs. across head) × histogram bins. Visualize the histograms as heatmaps as in Figure 6.23.

Figure 6.23: Laminar profiles of QK^⊤ dot products within and across heads. x-axis indicates the activation values, y-axis indicates the transformer layers, and the color is the probability density. Both heatmaps have the same color scaling.

Not surprisingly, the distributions of the dot products across different heads is comparable across layers.

The within-head analysis, on the other hand, shows an interesting systematic pattern of the activation values shifting increasingly negative in middle layers, and closer to zero (though still shifted negative) in the first few and final few layers.

Task

Calculate the mean and standard deviation across layers for each pair category. Visualize the results as lines corresponding to the layer-averaged density, and the areas around the lines corresponding to one standard deviation above and below the line. See in Figure 6.24.

There are several ways to draw areas in Python graphs; for this application I think plt.fill_between() is the easiest approach.

Figure 6.24: Means and standard deviations of distributions across layers. The shaded region indicates one standard deviation on either side of the mean.

Part 6: Laminar distributions of raw and softmax scores

Section titled “Part 6: Laminar distributions of raw and softmax scores”

The raw attention scores are shifted negative across all layers, though some layers seem to have a stronger shift than others. What does that mean? I will discuss the answer at the end of this part, and I’d like you to think of an answer as you see the results.

As a reminder, the softmax part of the attention algorithm is this:

A=σ(QK⊤dh+M)(6.11)A = \sigma\left(\frac{QK^\top}{\sqrt{d_h}} + M\right) \tag{6.11}

The M matrix is a mask that prevents causal autoregressive models like GPT from using future tokens to make predictions about current tokens (BERT-like models, in contrast, do not have this mask matrix). We will ignore that mask for now, and see how it plays into self- vs. cross-attention, and the first token of the sequence, in Part 7.

Task

In a for-loop over transformer layers, split the layer-specific hooked activations into Q, K, and V, and then reshape Q and K to have a head dimension in the tensors. This is the head-separating approach taken in Project 34 as opposed to the split function you’ve used so far here in Project 35.

Calculate the softmax attention scores. You need to permute the Q and K tensors such that the order of dimensions is batch × head × tokens × head-dimension. Then calculate QK^⊤ using the .transpose method on K to transpose the final two dimensions (tokens and head-dimension).

Calculate and visualize the mean of the QK^⊤ raw scores as in Figure 6.25A, the histogram of the raw scores as in Figure 6.25B (using 200 histogram bins between -15 and 15), and the histogram of the softmax attention scores as in Figure 6.25C. Note that the F.softmax function works only on PyTorch tensors, not on NumPy arrays. Therefore, you should run these analysis using PyTorch functions instead of NumPy functions.

I mentioned earlier in this project that some heads-based analyses are easier done by splitting into one tensor per head while other analyses are easier done by reshaping. The analysis here could be implemented by splitting and including an additional for-loop, but the reshaping method is more elegant and efficient (though admittedly trickier to code the permuting and transposing).

Figure 6.25: Importance of negative dot products in the attention algorithm. Panel A shows the average QK^⊤ scores (markers) and one standard deviation above and below (lines) for each layer. Panel B shows the histograms from each layer, with the color coding indicating the layer (see colors in panel A and colorbar in panel C). Panel C shows histograms of the same data in panel B after the softmax transformation. The y-axis is log-scaled to highlight the skewed distribution (most values are very close to zero).

Panels A and B show that the distributions of the raw attention scores are roughly Gaussian, and become increasingly negative deeper into the model, only to rebound closer to zero at the end. This is similar to, but not entirely redundant with, Figure 6.23 from Part 5 because that analysis included only a subset of token pairs.

Panel C answers the question I posed at the outset of this part: The impact of the negative raw attention scores is that their softmax probability values are nearly all close to zero. In fact, I recommend replotting the histograms with a linear y-axis scale for comparison.

The negative raw scores create probability distributions that are dominated by a large number of very small values, which in turn enforces sparsity when the softmax attention scores multiply the vectors in V. In other words, although each token pair makes some contribution to the adjustment of the hidden-state vectors, only a very small number of pairs has a meaningful impact, because the contribution of most pairs is scaled down by a factor closer to zero.

Part 7: Softmax probabilities for self- vs. cross-attention

Section titled “Part 7: Softmax probabilities for self- vs. cross-attention”

The next two parts of this project focus on separating the softmax attention scores for self- vs. cross-attention, first in one layer to develop the code and visualize the results (Part 7), and then looping over all layers to characterize the laminar shifts (Part 8).

But first, let me introduce you to the causal mask (M). You’ll create a small version of the causal mask matrix for visualization and comprehension, and then incorporate that code into the analyses.

Task

Create a causal mask for a sequence of five tokens. First, create a 5 × 5 triangular PyTorch tensor of ones above the diagonal and zeros on and below, and visualize as in Figure 6.26A. Second, modify that mask to turn the ones into −∞ (use torch.inf) and visualize as in Figure 6.26B. Finally, apply the softmax transform across the rows to produce Figure 6.26C. Use the same color scaling for all panels.

Panel B is the M matrix in Equation 6.11. When added to the QK^⊤ scores, the upper triangle becomes −∞ while the diagonal and below remain unchanged. In other words, nearly half of the QK^⊤ scores are obliterated before the softmax is applied. Because the matrix is sequence tokens × tokens, the raw QK^⊤ scores for each token pair involving future tokens is turned into −∞, whereas scores involving current and past tokens are preserved.

Figure 6.26: Illustration of the causal mask used in autoregressive LLMs.

Panel C shows how that matrix “hides” future tokens when processing each current token. The softmax transformation sets the −∞ to 0 (because e^−∞ = 0), and sets the non-zero elements such that they sum to 1. That is, the first row is [1,0,0,0,0], the second row is [.5,.5,0,0,0], and so on. Thus, when summing the softmax attention scores over rows, “future” tokens are zeroed out while current and past tokens are weighted according to their QK^⊤ scores.

Now let’s get back to the real data. In particular, you will calculate all softmax attention scores and separate them into three groups:

  1. Final to previous: These are the dot products between the final token in the sequence and all previous tokens but excluding the first token.

  2. Self-attention: These are the dot products of each token with itself, again excluding the first token in the sequence.

  3. Self-attention first token: The dot product of the first token with itself.

Task

Extract the Q and K matrices from layer #6, and separate into heads using the split function. Setup a for-loop over the heads. For each head, translate Equation 6.11 (page §) into code (apply the softmax transformation across the final dimension). Separate the softmax attention scores into the three groups described above, and concatenate them into three NumPy arrays to pool together the results from all heads. (Hint: The self-attention scores are on the diagonal of a tokens-by-tokens matrix.)

Visualize the results using violin plots with overlaid scatter plots for each group, as in Figure 6.27.

You can calculate the masked softmax attention scores using the following code.

attn_scores = (Q_h[qi] @ K_h[qi].t()) / sqrtD pastmask = torch.triu(torch.ones(ntoks,ntoks),1) pastmask[pastmask==1] = -torch.inf attn_scores += pastmask

Figure 6.27 shows several striking results.

Figure 6.27: Violin plots showing softmax attention scores for different token position pairs. The third grouping (first token) has all values of 1.

Perhaps the first striking result is that all the self-attention scores of the first tokens are 1. That is a trivial result of the temporal causality mask being −∞ for all row elements except the first. The softmax probability of one number is trivially 1. This observation is another reason why the first token in a sequence often provides unusual values.

The other two distributions are striking in that most values are suppressed towards zero. In fact, you have to look carefully to see the width of the violin plots behind the dots. In other words, nearly all of the data values are very close to zero, and a relatively small number of values are larger.

Part 8: Laminar softmax, self- vs. cross-attention

Section titled “Part 8: Laminar softmax, self- vs. cross-attention”

Now let’s examine the distributions of softmax attention scores across the layers.

Task

Repeat the histogram analysis from Part 6, while integrating the causal attention mask and token-pair categories from Part 7, in a for-loop over all layers. Store the histogram data in a matrix of size 24 (layers) × 3 (final to previous tokens, self-attention tokens, first token) × 90 (histogram bins between 0 and 1).

Visualize the results in heatmaps as in Figure 6.28, where the x-axis is the softmax probability score, the y-axis is the transformer layer, and the color is the histogram density value. Use color limits of 0 to .5 for all three heatmaps.

I implemented the causal masking in a different way compared to Part 7. This wasn’t in the instructions, but provides a good learning opportunity. In particular, I created the matrix mask as ones on and below the diagonal (instead of zeros), and then set the zero-valued mask elements to −∞ without summing matrices. Here’s how it looks:

attn_scores = (Q_h[qi] @ K_h[qi].t()) / sqrtD pastmask = torch.tril(torch.ones(ntokens,ntokens)) attn_scores[pastmask==0] = -torch.inf

This code shows that translating equations in code does not always involve a direct mapping of math to code. In this case, the equation states to add M but the implementation is to replace the upper-diagonal elements with −∞ before applying the softmax transform.

Anyway, back to the results: The heatmap in panel C appears to be solid black. However, you can see a thin vertical stripe of yellow to the right, because all softmax attention scores of the first token to itself are trivially 1.

Figure 6.28: Heatmaps showing the distributions shown in Figure 6.27 over all transformer layers.

The most noticeable changes over layers are the self-attention scores, where the mass of the softmax probabilities increase in early-to-middle layers. Still, the most prominent feature of the results is their sparseness: For all token pairs and all layers, most of the attention scores are close to zero while only a small number of token pairs have values high enough to make a large impact on the attention adjustments to the hidden-state vectors at the output of the transformer layer.

This final part of the project is both methodological and conceptual. Here is the question we will address: Do you really need to calculate QK^⊤ separately per-head, or can you calculate QK^⊤ once over the full Q and K matrices without splitting into heads?

Task

Using the Q and K matrices from one layer, calculate QK^⊤ twice: Once ignoring heads and the second time separately calculating for each head. In the first QK^⊤, scale the dot products by nhdhn_h \sqrt{d_h} where n_h is the number of heads and d_h is the head dimensionality. In the second QK^⊤, store the results in a heads × tokens × tokens tensor.

Show a scatter plot of the relationship between the ignoring-heads QK^⊤ and the average of the per-head QK^⊤, as in Figure 6.29A. Then show their differences as in Figure 6.29B.

You should find that the two variants of QK^⊤ have the following shapes.

Size of QKt all heads: [115, 115] Size of QKt per head: [16, 115, 115]

To create the scatter plots you’ll need to average the second tensor over heads, and then flatten the matrices.

Figure 6.29: Comparison of calculating QK^⊤ ignoring heads vs. separating by heads. In LLMs, the calculations are done per-head.

The scatter plot in panel A suggests that the two calculations are perfectly correlated, and the scatter plot of the differences in panel B show that the differences are very small (note the y-axis multiplicative factor) and attributable to precision errors.

Why are these two averaging approaches equivalent and does this mean you don’t need to separate into heads in analyses?

These two approaches are equivalent only because each head has the same number of dimensions, and because averaging is a linear operation. When subsets are balanced, the average of individual subset-averages equals the average of the entire set. In the online code file I show a small arithmetic demo of this equivalence.

Does this mean you don’t need to separate heads in analyses? Definitely not! There are three reasons why you should implement attention-related calculations per head. First, the raw attention scores are not directly used in LLM calculations, but instead are first softmax-transformed before multiplying V. That nonlinear transform breaks the averaging-equivalence that you observed in the raw scores. Second, even after the softmax transform, information across heads is combined using a weighted average (by the W_O matrix), which further breaks the averaging-equivalence. Third, each head learns to attend to different features of the text, and thus the heads are functionally separate systems.

The conclusion is that for both arithmetic and conceptual reasons, calculating attention scores to token positions should be done separately per head, even if the results are subsequently averaged across heads.

day-mode Bookmark

Characteristics of attention adjustment magnitudes

In Project 36, you will explore the attention adjustments — the context-rich outputs of the attention block that get added back onto the hidden-state vectors. Before getting to the specifics of the project, I’d like to provide some background on two technical topics that you’ll use: least-squares model-fitting (a statistical approach to regression) and vector magnitudes (a linear algebra approach to representing a vector using a scalar).

You learned about the concepts and implementions of least-squares regression in Project 21. Now I will introduce you to the math.

The goal of regression is to find the parameters that make a mathematical model of the data fit those data as closely as possible. The mathematical model of the data has the general form of

y^=β0+β1x1+β2x2+…+βkxk(6.12)\hat{y} = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \ldots + \beta_k x_k \tag{6.12}

The β values are the parameters, x are the independent variables, and y^\hat{y} (pronounced out loud as “why-hat”) is the model-estimated dependent variable. The β values are estimated by minimizing the following loss function.

arg⁡min⁡β∑i=1N(yi−y^i)2(6.13)\arg\min_\beta \sum_{i=1}^{N} (y_i - \hat{y}_i)^2 \tag{6.13}

In other words, find the parameters that minimize the squared differences between the model-predicted data and the observed data.

The solution to the objective function comes from the following equations, where the columns of matrix X contain the k independent variables.

Xβ=y(6.14)X\beta = y \tag{6.14} X⊤Xβ=X⊤y(6.15)X^\top X \beta = X^\top y \tag{6.15} (X⊤X)−1X⊤Xβ=(X⊤X)−1X⊤y(6.16)(X^\top X)^{-1} X^\top X \beta = (X^\top X)^{-1} X^\top y \tag{6.16} β=(X⊤X)−1X⊤y(6.17)\beta = (X^\top X)^{-1} X^\top y \tag{6.17}

Equation 6.17 is called the “least-squares solution” and is one of the most important equations in applied math and statistics.

The least-squares equation provides a one-shot (non-iterative) solution that is the best possible solution to the minimization objective. The proof that it’s the optimal solution comes from setting the derivative of the objective function to zero and showing that solving for β leads to Equation 6.17 (not shown here).

That’s the theory. In practice, the explicit matrix inverse can be numerically unstable, and therefore numerical algorithms apply other “tricks” like QR decomposition and Gaussian elimination instead of matrix inverses. The details of the numerical methods are beyond the scope of this book; fortunately, Python libraries like NumPy and statsmodels have highly accurate implementations of least-squares.

In Project 21 you used the statsmodels library and LinearRegression function to implement the least-squares regression; in this project (Parts 4 and 5) you’ll use NumPy’s linalg.lstsq method. It’s good to have many tools in your toolkit, and I’ll discuss when to use each approach at the end of the project.

Background: Attention adjustment magnitudes

Section titled “Background: Attention adjustment magnitudes”

As you know, the goal of the attention block is to calculate adjustments to the hidden-state vectors. Those adjustments are dense, high-dimensional, and difficult to interpret on their own. However, we can quantify the magnitude of each adjustment as the norm of the attention projection vector, which is the square root of the sum of squared vector elements:

∥v∥=∑i=1Nvi2(6.18)\|v\| = \sqrt{\sum_{i=1}^{N} v_i^2} \tag{6.18}

You can implement the equation manually, but it’s probably easier to use either np.linalg.norm or torch.norm. But be mindful that the input arguments differ slightly. You’ll use both libraries in this project.

Consider that if the hidden-state vector at some transformer layer already contains all relevant information, then no new context-based information needs to be added. In this case, the output of the attention block for that vector will be all zeros, and |0| = 0. Conversely, the more a hidden-state vector is modulated by its context, the larger the adjustment vector magnitude. We will focus on the norms of the attention projection vectors, which are the outputs of the attention block and are accessed in the model from attn.c_proj.

On a practical level, you can think of the adjustment vector magnitude as an interpretable dimension-reduced metric of the size of the attention adjustment, which can be visualized and analyzed across a large number of tokens, layers, and texts.

GPU There is only one forward pass in this project, but it’s a relatively large model with a relatively large batch. I chose not to use a GPU here, but the GPU will save you several minutes of computation time. On the other hand, this project does involve many calculations, so a high-RAM CPU will be helpful if available.

The end result of Part 1 will be tensors of attention adjustment vectors for a batch of 64 short text sequences of varying lengths, which you will use for analyses in the rest of the project.

Task

Import GPT-2-large and its tokenizer. Define a variable for the number of transformer layers.

Create and implant hook functions into all attn.c_proj layers that detaches the output of the attention block and stores it in a dictionary with keys indicating the layer from which the vectors were taken.

The online code file shows how to import the test set from the “Rotten Tomatoes” dataset via the Hugging Face function load_dataset. Explore the dataset by examining the number of samples it contains and by printing out an example text sample.

The test set contains 1066 samples, and each sample has two features: text and label. The text feature has brief movie reviews. The label feature is for categorizing each review as positive or negative — but we won’t use that information here.

Task

Create a batch of 64 text sequences. The movie reviews have varying lengths, which means you’ll need to use padding to create a batch. Remember that you need to define a pad token in the GPT-2 tokenizer object. Also remember that the shorter token sequences are padded to the length of the longest token sequence in the batch.

Because different sequences have different lengths, you will need a Boolean mask of size batch × tokens that contains True for valid tokens, and False for padding tokens. This is different from the attention_mask variable produced by the tokenizer, and will be used later in the project. Visualize the Boolean mask using plt.pcolor as in Figure 6.30A, and a histogram of sequence lengths as in Figure 6.30B.

The token mask I asked you to create may seem redundant with the tokens[’attention_mask’]. However, that attention mask is integers whereas the mask will need to be Boolean for later analyses. You can create the Boolean mask simply by converting the data type:

token_mask=tokens[’attention_mask’].to(torch.bool)

Figure 6.30A shows token position on the x-axis and the batch sequence on the y-axis. The image shows that the longest sequence comprises 59 tokens, and the shortest comprises 7 tokens.

Figure 6.30: Visualizations of token sequence lengths in this batch of 64 sequences. Panel A shows a heatmap in which rows (y-axis) are sequences and columns (x-axis) are token positions, white lines indicate the sequence lengths and black indicates the locations of padding tokens. Panel B shows the histogram of token counts.

Task

Run the tokens through the model to get the attention activations. Print out the names and shapes of the activations tensors.

This is the only forward pass in this project. It takes around a minute on Google Colab’s CPU, and around a second on a GPU. In my humble opinion, that waiting time is not worth the additional effort to implement the code to move matrices back and forth between the CPU and GPU, but that is just my personal preference.

I won’t print the full output, but it will look like this:

attn_L0 has shape [64, 59, 1280] attn_L1 has shape [64, 59, 1280] … attn_L35 has shape [64, 59, 1280]

Part 2: Laminar profile of attention adjustment magnitudes

Section titled “Part 2: Laminar profile of attention adjustment magnitudes”

The goal of Part 2 is to calculate and visualize the distribution of attention vector magnitudes over the transformer layers.

But first, a brief aside about indexing using masks in Python.

Task

To understand why I asked you to recreate the token mask as a Boolean matrix, check the sizes of the outputs of the following two lines of code: activations[’attn_L4’][tokens[’attention_mask’]] activations[’attn_L4’][token_mask] # Boolean mask

Also inspect the outcome of the first line and notice the redundancies.

Here are the sizes:

torch.Size([64,59,59,1280]) # from integer matrix
torch.Size([1691, 1280]) # from Boolean mask

The first line is not what we want: Python interprets the 0’s and 1’s in tokens[’attention_mask’] as indices, not as a matrix mask. That’s why, for example, the following line of code just repeats the same row of data 64 times. activations[’attn_L4’][tokens[’attention_mask’]][:,1,1,:]

The second line is what you want: it returns a matrix of attention projection vectors from all valid tokens.

Task

Loop over all transformer layers. For each attention block, extract the logarithm of the vector norms from valid tokens — excluding the first token in the sequence. Use NumPy functions for the calculations.

Make a histogram of the log-norms and visualize in line plots as in Figure 6.31A. Then calculate the average and standard deviation of the log-norms and show in a scatter plot with error bars as in Figure 6.31B.

When you input a matrix into NumPy’s norm function, it will by default calculate the matrix norm. However, we want the vector norm (Equation 6.18). You can calculate the vector norm by specifying a dimension along which to calculate the norm. In this case, the embeddings dimension is the final dimension, so you can use the following code to obtain a vector of norm values, one per token position.

acts = activations[f’attn_L{layeri}’][:,1:,:] att_projs = acts[token_mask[:,1:]] att_projs = att_projs.numpy() # using numpy here norms=np.log( np.linalg.norm(att_projs,axis=-1) )

These vector norms are strictly positive-valued, and tend to be long-tailed, and therefore taking the log helps to visually compare the distributions. I encourage you to check the results with and without the log transform.

To be clear: the adjustment vectors are not scaled by their log-magnitudes in LLMs during runtime, and larger vector magnitudes are meaningful because they produce a more significant change in the hidden-state vectors. However, log-transforming is useful here because it helps reveal differences across layers without the axis scaling being dominated by a small number of very large values.

Figure 6.31: Panel A shows distributions of the attention projection vector magnitudes, which indicate the “amount” of adjustment to the hidden-state vectors over all valid tokens (excluding the first), separated by layer. The line color corresponds to transformer layer from purple (earlier layers) to yellow (later layers); see also the color mapping and x-axis values in panel B. Panel B shows the mean and standard deviation of adjustments per layer. Data were log-transformed to facilitate visual interpretation by shrinking the large magnitudes.

The results show that the average token magnitudes generally increase as the hidden-state vectors traverse deeper into the model, with a striking increase towards the end.

You can also check out what happens when you include the first token (tip: take a screenshot or copy the code into a separate cell to facilitate visual comparison).

Part 3 is deceptively simple: Calculate the average attention adjustment vector norm per token position, and visualize as a heatmap. I write “deceptively” simple because you need to exclude the padding token vectors, which vary by sequence.

Task

In a for-loop over transformer layers, calculate the log-norms of all attention adjustments vectors, this time using PyTorch. Average together the log-norms, separately per token position — but only average the valid (non-padding) tokens. Then convert to NumPy such that the result is a NumPy array of size layer × token positions in which each element is the average attention adjustment magnitude (excluding pad tokens).

Show the results in a heatmap of token position (x-axis) by transformer layer (y-axis) as in Figure 6.32. The color limits correspond to the 5% and 95% of the log-norm distributions. Finally, make a scatter plot of the number of valid tokens per token position, as in Figure 6.33.

Averaging across the valid tokens can be accomplished by looping over each token position and slicing out one vector from the mask. Here’s how that would look using a for-loop:

all_norms=torch.norm(activations[’attn_L5],dim=-1)

for t in range(n_tokens):
this_pos_mask = token_mask[:,t]
valid_norms = all_norms[this_pos_mask,:]
ave_norms[t] = valid_norms.mean().item()

In the for-loop over layers, I condensed that for-loop into a list comprehension.

Figure 6.32: Heatmap showing the magnitudes of attention adjustment vectors across token positions and transformer layers.

The pattern in the heatmap across the y-axis is similar to the result from Part 2 (increasing adjustment norms with increasing layer index). What’s new here is the dynamics over token position (the x-axis). From visual inspection, it seems that vector magnitudes are small in the first few tokens, then increase in later tokens. That makes sense, considering that later tokens have more previous tokens from which to extract information and calculate adjustments.

But is that a statistically meaningful increase, or have I mistakenly over-interpreted the visual appearance of the heatmap? You will find out in Part 4!

Final comment for Part 3: The heatmap appears to get noisier after around 45 tokens. That’s attributable to the decreased sample sizes. That’s what Figure 6.33 shows: the number of data points contributing to the average decreases with longer sequences. This reflects the fact that fewer movie reviews are longer (at least in our batch of 64).

Figure 6.33: Scatter plot showing the decrease of sample size (y-axis) with increasing token position (x-axis). This graph has implications for the robustness of statistical modeling of token-sequence relationships based on token position, because smaller sample sizes lead to poorer estimates of statistical parameters like regression coefficients.

Part 4: Predicting adjustment norm from token position

Section titled “Part 4: Predicting adjustment norm from token position”

Now it is time for the least-squares analyses. You’ll use least-squares to test two hypotheses about attention adjustment magnitudes, one here and one in Part 5.

The idea here is to test my qualitative observation in Part 3, that the adjustment magnitudes increase with ordinal token position. In particular, you’ll test the following mathematical model:

ln⁡∣vt∣=β0+β1t+ϵt(6.19)\ln|v_t| = \beta_0 + \beta_1 t + \epsilon_t \tag{6.19}

The equation says that the log of the norm of the adjustment vector for token position t is a linearly weighted combination of an offset (β_0) and the token position (β_1). The 𝜖 captures the adjustments not explained by the token position, which we can expect to be large, considering that there is so much more to natural language processing than just token position. However, we’ll focus on the laminar profile of the β values here, not on the effect sizes or 𝜖 characteristics.

The goal is to find the β values that best fit the model, and visualize the laminar profile of those parameters.

Task

Create a design matrix that contains two columns: a column of all 1’s (the intercept term) and a column of integers from 0 to N-1, where N is the number of token positions to include in the analysis. As you know from Part 3, the sample size decreases with increasing position index; therefore, set N = 30 instead of 59 to avoid using very small sample sizes in the analysis.

In a for-loop over transformer layers, extract the average log-norm of the valid (non-pad) tokens for each position, just like in Part 3. That vector of average norms is the dependent variable. Use NumPy’s linalg.lstsq function to fit the layer-specific data to the design matrix. Exclude the first token in the sequence from the analysis.

Visualize the data as in Figure 6.34. Panel A shows the data (the dependent variable), panel B shows the β_0 (intercept) parameters, and panel C shows the β_1 (slope) parameters.

Figure 6.34: Results of the regression analysis. Panel A shows the average attention adjustment log-norm over token positions. Each color corresponds to a layer (see panels B and C for color-to-layer mapping). Panel B shows the fitted intercept terms, and panel C shows the fitted slope terms. A positive slope indicates that the attention adjustment vectors become larger in later transformer layers.

Panel A shows some nonlinear trends, with square-root-looking increases for some layers. However, the linear regression captures only the linear aspects of those relationships. The regression results show a consistent pattern of increases in attention vector magnitudes deeper into the model, until the final few layers.

The intercept terms in a simple regression provide similar information as the average offsets (average attention projection norms getting larger in the final few layers).

The slopes in panel C indicate the extent to which the adjustment magnitudes increase with token position. Thus, larger positive slopes indicate that larger adjustments occur later in the token sequences. That relationship occurs in the middle layers, but not in the first few, or last few, layers.

Keep in mind that this analysis is based on log-norms, not the “raw” vector norms. Given the overall increase in projection vector norms in later layers, the β_1 laminar profile is slightly different when running the analysis on the non-log-transformed data. I don’t show that here, but it’s easy to run in the code.

Let’s try a more granular investigation. Instead of quantifying a general trend over all tokens as in Part 4, here we will zoom in to each token and ask whether the attention adjustment to the current token can be predicted from the attention adjustments to the two preceding token positions.

Translated into an equation, we’ll test the following regression model.

ln⁡∣vt∣=β0+β1ln⁡∣vt−1∣+β2ln⁡∣vt−2∣+ϵt(6.20)\ln|v_t| = \beta_0 + \beta_1 \ln|v_{t-1}| + \beta_2 \ln|v_{t-2}| + \epsilon_t \tag{6.20}

Thus, each vector magnitude is modeled as a weighted combination of previous adjustment magnitudes plus token-unique variability. β_1 and β_2 are the impacts of the adjustments in the previous two token positions.

Task

Create a double for-loop over transformer layers and over the 64 sequences in the batch. Inside the inner for-loop, find all of the valid tokens in each sequence, and create a data matrix where each row is a triplet of log-norms of the current and previous two token positions.

After the inner for-loop to create the data matrix, create a design matrix where the the columns are: 1’s (the intercept or β_0 term); the log-norm adjustment from the prior token (the β_1 slope); the log-norm from two tokens prior (the β_2 term). The dependent variable y is the log-norm adjustment magnitude from the current token position.

Fit the regression model for each layer, and visualize the β_2 and β_1 terms as in Figure 6.35.

You can confirm that the shape of the data matrix for each layer is 1499 × 3. The 1499 comes from all valid triplets across the 64 sequences.

Figure 6.35: Visualizing the regression results for the previous two token position attention adjustments, over all transformer layers. The slopes (β_1 terms) indicate that both previous two token position vector norms predicted the current token position norm, with the previous (blue circles) having a larger impact than the position two tokens prior (green squares).

Interestingly, both previous tokens have a positive impact on the magnitude of the current token. In other words, if the attention block calculated a relatively large adjustment on a given token position, the adjustments on the next few positions are also likely to be large.

We haven’t done inferential statistics on each regression coefficients and the sample size is small, but the direction of the effects are consistently above zero for both β coefficients, suggesting that these results reflect meaningful dynamics in the attention block.

Thus far in this book, you have used three approaches for calculating regression models using least-squares. The list below indicates when each approach should be preferred.

  • Use statsmodels’s OLS when you want a detailed and nuanced statistical analysis with multiple goodness-of-fit metrics and statistical inferences such as p-values.
  • Use SciPy’s LinearRegression when you are performing a machine-learning analysis involving training a model on data to predict data values or categories in a test set.
  • Use NumPy’s linalg.lstsq if all you need are the β parameters. Of these three options, this one requires the least additional code, libraries, and dependencies, but also provides the least amount of supplemental information.

day-mode Bookmark

Token prediction and attention KL divergences

You learned in Chapter 4 that you can calculate the categorical accuracy of token prediction by checking whether the maximum final output logit from token position N − 1 matches the token index from token position N.

What differences in internal calculations predict whether the model correctly vs. incorrectly predicts the token? That’s what you will explore in this project.

The goal of this project is to extract attention adjustment vector norms for correct vs. incorrect token predictions, and compare their probability distributions using Kullback-Leibler (KL) divergence, which is a measure of the discrepancy between two probability distributions. I’ll provide some background about KL divergence before getting to the project.

KL divergence is a number that quantifies the dissimilarity between two probability distributions. For example, the two probability distributions in Figure 6.36A would have a KL divergence value close to zero because the two distributions are nearly identical, whereas the divergence value in panel B would be greater than zero.

Figure 6.36: Visual intuition of Kullback-Leibler (KL) divergence. The two probability distributions in panel A are similar, and thus their KL divergence score would be close to zero. The distributions in panel B, on the other hand, are less similar, and thus their KL score would be higher.

There are three important things to know about Kullback-Leibler divergence.

1: Terminology It’s called KL divergence or KL distance. You might also see it abbreviated as KL-div, KL value, or D_KL.

2: Formula The equation for KL divergence involves scaling a probability distribution by the log of the ratio of that distribution to a reference distribution.

DKL(P∥Q)=∑Pln⁡(PQ)(6.21)D_{KL}(P \| Q) = \sum P \ln\left(\frac{P}{Q}\right) \tag{6.21}

Where P and Q are probability functions (different log bases affect the units of the KL values but not their calculations or relative scores). You can see that when P = Q, the ratio is 1, the log of which is zero, thus giving a KL score of zero. A minor but important implementation detail: KL divergence is based on probabilities, not probability densities. The difference is that a density incorporates bin width, but that means that bin width will “leak” into the divergence value. In other words, when calculating KL divergence, we want ∑ p = 1, not ∑ pdx = 1. You’ll see how to incorporate that into code in Part 3.

3: Asymmetry KL divergence is asymmetric. That is,

DKL(P∣Q)≠DKL(Q∣P)(6.22)D_{KL}(P|Q) \neq D_{KL}(Q|P) \tag{6.22}

That asymmetry is fine if you have a specific hypothesis about which distribution is the reference and which is the target (e.g., a baseline vs. experimental condition; or healthy control subjects vs. patients). However, in many cases — including in this project — you simply want to compare two distributions without giving either one priority. The solution is to calculate the Jensen-Shannon divergence, which is essentially the average of two divergences from the average probability distribution. I’ll show the formula for that in Part 4.

Here is the upshot: KL divergence can be used as one number that characterizes the dissimilarity between two probability distributions. In this project, we will use KL divergence to quantify whether there are differences in attention adjustment magnitudes between correct and incorrect token predictions.

Part 1: Model, tokens, attention projections

Section titled “Part 1: Model, tokens, attention projections”

Before getting to the analyses, we need some data.

Task

Import GPT-2-large and its tokenizer. Write a hook function that detaches the attention projection vectors from the attn.c_proj module of each transformer, and stores them in a dictionary during a forward pass.

Import the text for Through the Looking Glass from gutenberg.org. Tokenize the text. Find the variable that lists the maximum sequence length of the LLM in model.config. Extract a tensor of maximum sequence length starting from the center of the book. Push the tokens through the model and confirm the keys and tensor sizes of all the attention projections that the hook function stored.

GPT-2 has a maximum sequence length of 1024. This means that it cannot process more than 1024 tokens at a time. That parameter is stored in the n_ctx and max_position_embeddings attributes of model.config. Be mindful that that information might be named differently in different LLMs.

With a maximum sequence length of 1024 and an embeddings dimensionality of 1280, the attention projection vectors will have size 1 × 1024 × 1280.

Now we’re ready for some analyses.

By the end of Part 2, you will have a dataset of correctly- and incorrectly-predicted tokens, with which you’ll calculate probability distributions and KL divergences in later parts.

Task

In a for-loop over the prompt tokens, calculate categorical accuracy of each token by testing whether the maximum output logit from each token matches the subsequent token. Store the results in a Boolean vector. Also calculate and store the number of characters in each token.

Calculate and report the count and percentage accuracy, and show the results in a scatter plot like Figure 6.37.

Show histograms of token lengths for incorrect and correct predictions, along with their average character lengths, as in Figure 6.38.

One tricky aspect of calculating sequence-dependent results like next-token accuracy is that an N-element sequence has only N − 1 predictions. A common solution is to omit the final data point, so the dataset would go from having 1024 tokens to only 1023.

However, in this case, the 1024 token were sliced out of a much longer token sequence, so we actually can label the final logit as being a correct or incorrect prediction. I implemented that in the code by setting the target token using the allTokens variable (the entire tokenized book) instead of the tokens variable (the token sequence given to the model).

You should find that the model correctly predicted 46.19% (473/1024) tokens. That may seem low, but remember that there are over 50,000 tokens in the dictionary, and remember that many of the categorically incorrect predictions might be semantically appropriate, as you learned in Chapter 4).

Figure 6.37: Prediction accuracy (y-axis) by token position (x-axis). Small y-axis jitters were added to facilitate visual inspection.

The purpose of visualizing the accuracy data is to see whether there are any noticeable systematic effects, for example if there were regions of, say, dozens of tokens where average accuracy was low. From visual appearance, it seems that accuracy is roughly evenly distributed.

Why are some tokens accurately predicted while others aren’t? Well, there are obviously many reasons, including local context, some tokens being harder to predict like proper nouns and formatting characters, and so on.

We collected data on token length, so let’s see whether there is a relationship between token length and prediction accuracy.

Figure 6.38: Two histograms to inspect whether incorrect predictions (red boxes) might be associated with longer tokens (measured in character count; x-axis) compared to correct predictions (green circles).

This is a small dataset and we haven’t done inferential statistics, but the token length analysis does suggest that shorter tokens are more likely to have accurate predictions compared to longer tokens. Please keep this observation in mind as you continue with the rest of the project. I’ll get back to it at the end of the project.

Part 3: Attention projection norms by accuracy (one layer)

Section titled “Part 3: Attention projection norms by accuracy (one layer)”

The goal of Part 3 is to write code that will extract and visualize histograms of attention adjustment vector norms. You’ll use that code for later analyses.

Task

Pick one layer to focus on; I used layer index 4. Extract the attention adjustment vector norms. Log-transform the norms and store the data in separate variables depending on the accuracy category.

Calculate the histograms of the two vector log-norm variables. Because KL divergence involves comparing probabilities point-by-point, the histogram bins need to be the same. Use 31 bins and extract the bin counts, not densities. Then, normalize to probability by dividing the counts by their sum. Visualize the distributions as in Figure 6.39.

The appropriate normalization here is as follows:

yC,_ = torch.histogram(C_norms,                bins=histbins,density=False) yC = yC/yC.sum()

density=False is actually the default parameter setting; I included it in the code for clarity. You can confirm that the sum over all yC values is 1. In my solution code, I report some calculations that demonstrate the differences. That code block produces the following.

Sum of counts: 473.0 # density=False Sum of density: 27.53 # density=True Sum of bin-normalized density: 1.00 Sum of count-scaled probability: 1.00

For KL divergence, the probability values must sum to 1. You can obtain that either by normalizing the densities by bin width, or by normalizing the counts. In my mind, the latter is cleaner because it involves only one normalization.

Why use 31 bins for the histogram? Why not 30 or 45 or 13 bins? The number of bins in a histogram is, in general, a somewhat arbitrary parameter that has implications for any analyses based on the histogram (including KL divergence). Leave it at 31 for now, and I’ll come back to this issue later.

Figure 6.39: Comparison of attention adjustment vector norms for incorrect predictions (orange line) vs. correct predictions (blue line).

Visually, it seems as if the correctly-predicted distribution is shifted to the right, which would indicate that the attention adjustment norms are slightly larger for correct compared to incorrect token predictions.

However, that is a qualitative visual assessment, and the difference is subtle at best. Part 4 involves quantifying those differences between the probability distributions, Part 5 involves statistically evaluating those differences, and Part 6 involves applying the statistical methods to the data from all layers.

Part 4: Asymmetric and symmetric KL divergence

Section titled “Part 4: Asymmetric and symmetric KL divergence”

Implementing KL divergence in Python by directly translating Equation 6.21 into code is not difficult. On the other hand, familiarity with PyTorch’s KL divergence function is useful if you plan on working with deep learning models (e.g., creating custom loss functions). Furthermore, there can be numerical instabilities in the KL calculations that PyTorch’s implementation handles internally.

The PyTorch function is F.kl_div. It takes two probability distributions P and Q, and returns the KL divergence between them. The function expects the first input to be log-probabilities and the second input to be non-log probabilities (though you can input log-probabilities with an optional input flag log_target).

However, as I wrote at the outset of this project, KL divergence is asymmetric, meaning the divergence value depends on which distribution is labeled P and which is labeled Q. That asymmetry makes sense in some situations, but there are other situations where we want to calculate the overall divergence between the two probability distributions without assigning one or the other to be the reference or the target.

Symmetric KL (Jensen-Shannon divergence) The JSD is simple: Calculate two KL divergences from each probability distribution to their average, and then average those two KL divergence scores. In particular, define the “target” distribution as M = (P + Q)∕2. Then calculate D_KL(P|M) and D_KL(Q|M), and average those two KL scores together. The JSD value is not calculated by PyTorch, so you will need to write code to implement this analysis.

Warning: Symmetric KL divergence is not calculated as the average of D_KL(P|Q) and D_KL(Q|P).

Task

Run the following line of code, and inspect the warning message (as of version 2.9.0) and the output. F.kl_div(torch.log(yC),yI)

Even if you don’t get a warning message, you’ll get a result of NaN. Figure out why that happens and how to resolve it.

Demonstrate the asymmetry in KL divergence by calling the kl_div function twice using different orders of input. Then write code to implement the JSD symmetric KL divergence, as I described above. Print that symmetric score, and also print the average of D_KL(P|Q) and D_KL(Q|P) (remember that that’s not the JSD score and is printed here only for comparison).

When you run the code printed in the task description, the result is tensor(nan). That happens because torch.log(yC) contains −∞ values, and that happens because there are histogram bins with zero observations (thus, p_i = 0).

Taking the log of p = 0 is a common issue in machine learning and optimization, and a typical solution is to add a small number to the probabilities to prevent absolute zeros. Thus, instead of torch.log(yC) you can use torch.log(yC+1e-15). In other words, add a tiny non-zero number, which will have negligible impact on non-zero probability values while guaranteeing that you don’t take the log of zero.

About the warning message: You may or may not see the warning about batchmean, depending on the version of PyTorch you’re using. Best practice is to specify the input argument reduction=’batchmean’ unless you have a reason to use any other method of averaging.

The asymmetry of KL divergence is easily demonstrated by swapping the orders of the “correct” and “incorrect” probably distributions. Here are my results:

Target is “incorrect”: 0.0092 Target is “correct”  : 0.0152

Which of those two results is correct? Well, they’re both correct, depending on whether you want to consider correct or incorrect predictions as the target (a.k.a. baseline or reference) distribution. A cleaner interpretation comes from using the symmetric version. Here you should find:

Average KLs : 0.0122 Symmetric KL: 0.0051

The JSD score will generally be lower than the asymmetric KL divergences, because the target distribution is the average, which is necessarily closer to each distribution than they are to each other.

The JSD score doesn’t require a lot of code, but you will calculate it many times, so it will be handy to have a helper function to make subsequent analysis code cleaner.

Task

Write a Python function called symmetric_KL that takes two PyTorch arrays as input (one for each variable, e.g., log-norms from correct vs. incorrect predictions), and an optional number of histogram bins that defaults to 31.

Inside the function, calculate probability distributions of the two input variables using the same histogram edges for both variables, and calculate and return the JSD score. Test the function by calculating the JSD score using the correct and incorrect prediction norms. Check that you get the same result regardless of the order in which the norms are inputted.

Finally, to demonstrate the impact of discretization on the JSD score, run an experiment where you call the symmetric KL function repeatedly using the same data but discretization bins from 10 to 50. Plot the JSD score by the number of bins as in Figure 6.40.

You can confirm the symmetry of the JSD score by examining the outputs of the following function calls:

symmetric_KL(C_norms,I_norms)
symmetric_KL(I_norms,C_norms)

You should get .0051 in both cases.

Figure 6.40: Empirical KL divergence involves discretizing (binning) the data. This plot shows that the number of histogram bins has some impact on KL divergence, especially when the bin count is relatively small.

The results show a trend towards decreasing KL divergence with increasing bin count. However, it is not a perfect monotonic function, and there are several data points that seem inconsistent with a trivial relationship between bin count and divergence.

There is no deep mathematical reason for the imperfections in the results. We are working with a limited amount of complicated data.

The conclusion is that choosing a discretization for histograms involves uncertainty that can impact the results. I cannot tell you the “correct” number of histogram bins to use, but I can advise you to pick one value and use it consistently across analyses, so that any biases introduced by the discretization are applied consistently to all results. For this reason, we will stick to 31 bins for the rest of this project.

The goal of Part 5 is to develop code to perform statistical evaluation of KL divergence using non-parametric permutation-based null-hypothesis testing. I will first introduce you to the theory, and then we’ll get to code.

Permutation testing involves randomly shuffling one aspect of the data while preserving the rest of the data characteristics. Each time you shuffle the data, you re-calculate the test statistic (in this case, the symmetric KL divergence value), and then compare the observed test statistic to the distribution of shuffled values.

The hypothesis is that the KL divergence is different between the distribution of attention adjustment norms for correct and incorrect token predictions. Therefore, the null hypothesis is that there is no difference, in which case the non-zero KL divergence is simply due to random sampling variability from a small sample size. And that in turn implies that the KL divergence would be of comparable size if we would randomly shuffle the labels so that any token could be labeled as “correct” or “incorrect.”

And that’s the key step to permutation testing here: Randomly reshuffle the vector of token prediction accuracy, calculate the KL divergence, and repeat the random reshuffling many times to get a distribution of shuffled KL scores. Finally, compare the observed KL score (without shuffling) to that shuffled distribution.

That comparison can be quantified as a p-value, calculated as the proportion of permuted KL values greater than the non-shuffled KL value. If the p-value is small (for example, <.05), then we consider the observed KL value to be statistically significant.

The number of permutations is a trade-off between statistical robustness (more shufflings gives a better estimate of the p-value) and computation time. For now, use 1000 random shuffles.

Task

Create a for-loop over 1000 permutation iterations. Generate a shuffled vector of prediction accuracies. Don’t define it as a random sequence of 0’s and 1’s, because that would give random category counts. Instead, randomly permute the prediction accuracy vector (make sure to store the permuted vector in a different variable name so you don’t overwrite the original variable). Use that shuffled accuracy vector to extract new variables of log-norm attention adjustment vectors from “correct” and “incorrect” predicted tokens. Calculate and store the JSD value.

After the for-loop finishes, calculate the p-value as the proportion of shuffled divergence values that exceed the non-shuffled value.

Visualize the test results as a histogram of the shuffled KL values with a vertical line corresponding to the non-shuffled KL value (Figure 6.41). Report the p-value in the title.

This analysis takes some time to run, perhaps 20-30 seconds. That’s fine for one analysis, but imagine that you’re repeating this analysis over many batches, layers, token types, etc. It can become prohibitively computationally expensive. Therefore, in practice, it’s common to reduce the number of permutations to a few hundred.

Figure 6.41: Illustration of statistical inferential evaluation of KL divergence using permutation testing. The bars depict the null hypothesis (a.k.a., shuffled, a.k.a., H_0) distribution, and the vertical black line depicts the observed KL value without shuffling. The p-value is less than .05, so KL values greater than the observed value are unlikely to be obtained if there were no effect.

Your figure won’t look exactly like mine because of the random shufflings, but it should look comparable in terms of the overall shape of the null-hypothesis distribution and the p-value.

In this case, the p-value is less than the typical statistical significance threshold, so we would consider the KL divergence value here to be statistically significant. In other words, there is a statistically significant difference between the probability distribution of attention adjustment magnitudes for correct vs. incorrect predicted tokens.

A caveat about the permutation testing: Permutation testing assumes exchangeability of the labels, but that assumption isn’t entirely met in our case: a given token does not generate a correct or incorrect prediction on its own; instead, it is the combined calculations in the entire sequence of tokens (prior to the current token) that provides the information that each token uses to generate a prediction.

On the other hand, context-relevant information from preceding tokens is already loaded onto the current hidden-state vector, and so each hidden-state vector does in fact retain context information. Thus, the exchangeability assumption is not fully violated, but it is also not fully met in token sequence data.

None of this invalidates the use of permutation testing for statistical evaluation, but it does mean that the significances might be somewhat inflated. The conclusion is that the p-values should be treated more as an indicator of robust patterns in the data rather than a theoretically exact measurement of a strict null hypothesis probability distribution.

Part 6: Laminar distribution of KL divergences

Section titled “Part 6: Laminar distribution of KL divergences”

You now have all the code, data, and knowledge to run the final analysis of this project: Evaluating the statistical significance of KL divergences across the transformer layers. The goal will be to see if token-prediction accuracy can be detected in attention adjustment magnitudes in different depths of the model.

The instructions below state to run 1000 iterations in the permutation test (per layer), but I recommend reducing this to, e.g., 50 iterations while working on the code.

Task

Create a for-loop over the transformer layers. Extract the attention adjustment vector log-norms for correct and incorrect token predictions, and visualize as in Figure 6.42A.

Create a null-hypothesis distribution to calculate a p-value using the code you developed in Part 5. Visualize the data as in Figure 6.42B. The thin vertical black lines show the range of the shuffled KL values, the black boxes show the average shuffled KL value, the large green hexagons show the non-shuffled KL value if p < .05, and the smaller red hexagons show the non-shuffled KL value if p > .05.

Finally, visualize the difference of the means as in Figure 6.42C, where the markers are larger and darker if significant, and smaller and lighter if non-significant.

Depending on your CPU capacity and number of permutations, this analysis can take between a few tens of seconds and many minutes. Thus, reduce the number of iterations and layers to have a fast code-iteration cycle, then increase the number of permutations when your code works and you’re ready for the real analysis.

Figure 6.42: Results of the statistical evaluation of the laminar sweep of KL divergence. Panel A shows the means of the log-norm attention adjustments per layer. Panel B shows the divergences. Hexagons show the observed KL values that were deemed statistically significant (larger green markers) or not significant (smaller red markers). The black squares are the means of the null-hypothesis distributions, and the vertical thin black lines depict the ranges of null distributions. Panel C shows the difference between the means of the log-norm adjustment vectors per layer, with larger and darker markers indicating significances.

Two final comments:

  1. I tested each layer using a threshold of p < .05 without correcting for multiple comparisons over the 36 layers. In a real analysis, it would be appropriate to correct for multiple comparisons, for example using the false discovery rate method. On the other hand, in real research, you would use a lot more data and the results would be more reliable.

  2. In Part 2, I asked you to think about the difference in token length for correct vs. incorrect token predictions. If you haven’t already taken the time to think about whether that might influence our analyses, then stop reading now and think about it!

Token length does present a potential confound, because it is possible that at least part of the differences in KL values between correct and incorrect token predictions are attributable to differences in token lengths. But that’s not the only additional variable to take into consideration: Factors like token frequency and part of speech also contribute to attention adjustment magnitudes and to token prediction accuracy. Natural language is indeed very complicated :)

day-mode Bookmark

Laminar profile of RSA and category selectivity

If you haven’t completed Projects 12 or 25, I recommend doing so before solving this one: Project 12 introduced the RSA technique, and Project 25 introduced the category selectivity with space, furniture, and fruit, which you’ll re-use in this project.

As a brief reminder, an RSA (representational similarity analysis) works by comparing cosine similarity matrices across different embeddings spaces (layers, blocks, models, etc.). The idea is that different embeddings spaces may have distinct coordinate systems and even different dimensionalities, but if their internal representations are similar, the relative similarities should be strongly correlated even if the vectors are distinct.

The goal of Project 38 is to compare how attention adjustments are represented in the Q, K, and V matrices. You will discover that the adjustment vectors are largely uncorrelated while their RSA scores are quite high. The results show that although individual attention matrices have idiosyncratic internal calculations, they interact in elegant ways to identify and amplify context-relevant cross-token relationships.

I decided to ignore the attention heads for this project. That’s partly because we’re not working with the QK^⊤ dot products, which is where the representations become head-specific, and partly in the interest of focusing on the mechanics and interpretations of RSA. An interesting extension of this project could involve running the analyses separately per-head, although that would create a dimensionality-explosion due to the number of heads and matrices that could be compared with RSA.

Part 1: Hook all layers and get activations

Section titled “Part 1: Hook all layers and get activations”

As is often the case with the first part of these projects, the goal here is to setup the model, tokens, and hook function so that you can apply ML analyses in the rest of the project.

Task

Import GPT-2-xl and its tokenizer, and switch it to eval mode. Define a variable that represents the number of transformer layers.

Implant a hook into the attn.c_attn block of all transformer layers. The output of c_attn is the Q, K, and V activations vectors you’ve worked with in earlier projects. Split that wide matrix into the three attention activations matrices, convert them into NumPy arrays, and store them in a dictionary with key names corresponding to the layer number and the matrix, for example attn_23_q.

The online code file contains a list of single-token words in three categories: space, furniture, and fruit. It’s the same words you used in Project 25 (Chapter 5). Create a column vector of word categories mapped as space = 1, furniture = 2, fruit = 3.

Create two Boolean category masks, one for all within-category pairs and one for all across-category pairs. This is different from the mask you created in Project 25. Start by creating a “same-category” mask as the element-wise comparison c == c^⊤ where c is a column vector of category labels (numbers 1, 2, and 3). (Note: This is not formal mathematical notation, but works in NumPy due to vector broadcasting.) Then define a within-category mask as the values that are above the diagonal and in the same category, and define an across-category mask as the values that are above the diagonal and not in the same category. Visualize the masks as in Figure 6.43.

Figure 6.43: Binary heatmaps showing the creation of matrix masks that identify within-category (panel C) and across-category (panel D) word-pairs, based on a symmetric same-category mask (panel A) in combination with an upper-triangular mask (panel B).

Panels C and D show the two masks that you will use for the rest of the project; panels A and B are merely steps to create the desired masks.

Compared to the mask approach used in Project 25, this approach is more elegant and scalable, but offers less flexibility because it lumps together all category pairs. That is, the mask in Project 25 allowed you to separately analyze, e.g., space-furniture vs. fruit-furniture pairs, whereas the mask here pools across all categories.

Task

Create a batch of tokens in which each row corresponds to one of the words, and the text before each word is The next word is . Run the tokens through the model and check the keys and shapes of the activations vectors that the hook function grabbed.

This task (and many others in this book) can be accomplished by copy-pasting code from previous projects. Copying code has advantages and disadvantages. The primary advantage is, of course, that it requires less cognitive effort (though there is still some effort to find the relevant code). The disadvantages include that there is less learning and opportunities for practice and problem-solving, and that the time it takes to find the appropriate code to copy and modify is not necessarily less than the time it takes to code it again. I personally enjoy coding and find it interesting to see how I solve the same problems in different ways, so I often prefer coding again from scratch even if it takes longer. All that said, you are the master of your self-directed education; I just want you to be intentional about deciding how and how much to code.

I won’t print all the dictionary keys, but they are the combinations of layer index and matrix letter, for example attn_0_q up to attn_47_v. The shape of each tensor is 34 × 5 × 1600, corresponding to 34 sequences (target words), 5 tokens per sequence, and 1600 dimensions in the embeddings.

Final note here: I carefully selected the words to be single-token encoded (with preceding space). That makes the batch-creation code bespoke but brittle. If you want to expand this code to a larger sample size that includes multi-token words, you may need to adapt the code.

Part 2: Correlating Q, K, and V activations

Section titled “Part 2: Correlating Q, K, and V activations”

The goal of Part 2 is to correlate the activations between pairs of attention activation matrices (e.g., Q and K vectors). Spoiler alert: The correlations will be close to zero. But you need to see how small these correlations are, in order to appreciate the insights gained from applying the RSA technique.

Task

Run the analysis in layer index 6. Extract the Q, K, and V vectors for the second token position from all sequences. Correlate all three pairs and show in a scatter plot as in Figure 6.44.

Each dot in the scatter plots reflects the activation value for one embeddings dimension for one token position.

Figure 6.44: Three example scatter plots showing weak to no correlations among the attention activations matrices.

The correlation between Q and K shows a weak negative correlation, while the other two pairs have correlations near zero. The negative correlation between Q and K stems from the shift towards negative values in QK^⊤, although this isn’t the most appropriate analysis to demonstrate that, because all heads are pooled together. But overall, it seems that the activations in one matrix are unrelated to the activations in the other matrices — even though the tokens and contexts are identical.

By the way, I asked you to extract the data from the second token instead of the final (target) token to demonstrate that the weak correlations are not trivially due to processing different tokens; these scatter plots reflect identical token sequences at this point. In fact, some of the correlations are even closer to zero when using the final token.

Task

Repeat the analysis over all transformer layers, but visualize the correlation coefficients (Figure 6.45) instead of the scatter plots of all activation values.

The results shown in Figure 6.44 are similar in all layers: Near-zero correlations for the pairs involving the V vectors, and weakly negative correlations between Q and K.

Figure 6.45: The three correlation analyses shown in Figure 6.44 for all layers.

The correlations between Q and K are weakly but consistently negative. That negative correlation is broadly consistent with the negative shift in the QK^⊤ dot products, but it doesn’t make sense in terms of token representations: the matrices are processing identical tokens with identical contexts, so why do their representations seem so unrelated? Think about an answer as you continue working through this project.

Part 3: Cosine similarities and RSA (one layer)

Section titled “Part 3: Cosine similarities and RSA (one layer)”

As the title suggests, you will now calculate the all-to-all cosine similarity matrices and perform an RSA on the activations from one layer.

Task

Use data from layer 6. Extract the Q, K, and V activations from the final token from all batch sequences, and calculate the token × token cosine similarity matrices within each attention matrix. Visualize those similarity matrices, with dashed lines indicating the category boundaries, as in Figure 6.46.

Calculate the pairwise RSA scores by correlating the non-redundant and non-trivial cosine similarity values across the pairs of attention matrices. Don’t separate into within- vs. across-category submatrices here; calculate the RSA score based on all words. Visualize as in Figure 6.47.

The cosine similarity matrices are interesting to look at: The within-category similarities (block-diagonals) are visually higher than the across-category off-diagonal elements, and the overall similarities are highest for K and weakest for V. You will quantify those category differences later in the project, but those differences are already visually apparent.

Figure 6.46: Cosine similarities across all pairs of words, separately for the three attention matrices. The within-category grouping is indicated by dashed white lines, but is easily visible in the diagonal-block structure.

After having seen the weak correlations of activation values across the attention matrices, the RSA is a remarkable and refreshing change.

Figure 6.47: Representational similarity analysis (RSA) for each pair of matrices. These robust correlations, in context of weak direct correlations across matrices, demonstrate that the representations of hidden-state adjustments are distinct across the attention matrices, but that the internal relational structures are highly preserved.

The correlations of the within-matrix cosine similarities are extremely high — even the “weakest” correlation is still around .85.

The interpretation of the results from Parts 2 and 3 is that the Q, K, and V matrices represent token updates in distinct (often orthogonal) ways, but the nature of how those adjustments relate to each other is comparable across the matrices. In other words, the internal representations are similar while the coordinate spaces are distinct.

That is no accident: If the three sets of attention vectors were already so closely correlated, then they would be redundant and the attention algorithm wouldn’t be terribly useful. Instead, each of the three matrices (especially V) is trained into orthogonal spaces so that their unique contributions to the hidden-state adjustments can be information-rich and context-selective.

Task

Repeat the RSA analysis from Part 3 in a for-loop over all transformer layers. Visualize the laminar profiles of the correlation coefficients as in Figure 6.48.

With exception of the first transformer layer, the RSA scores are all roughly equally strong, around .9, and not visually obviously changing with depth into the model.

Figure 6.48: RSA is high across all transformer layers.

Thus far we have ignored category membership. You’ll remember from Project 25 that we calculated a category selectivity index as the t-value from comparing within- to across-category similarity values (the t-value is the difference in the group means scaled by a sample-size-weighted combination of the standard deviations).

Here in Part 5 you will calculate the selectivity t-values and visualize the distributions for one layer, and then you’ll extend this to all the layers in the final part of the project.

Task

Continue working with data from layer 6. Calculate the cosine similarity matrices as you did for the RSA analysis, but extract all of the within-category vs. across-category cosine similarities using the category mask you created in Part 1. Calculate the t-value and show histograms of the two distributions for each attention matrix, as in Figure 6.49.

There are two noteworthy features of these histogram plots.

Figure 6.49: Distributions of cosine similarity values (x-axis) for within- vs. across-category word pairs in one layer.

The first is the separability between the within- and across-category similarity values. It’s no surprise that the t-values are above 25.

The second is the differences in overall cosine similarity values between the three matrices, which you also observed in Part 3. Check the x-axis ranges in each of the subplots (and also the x- and y-axis ranges in Figure 6.47), and notice that the within-matrix similarity values range from .2 to .9 for different distributions. Nonetheless, the RSA score is calculated using the correlation coefficient not cosine similarity, which means these global offsets are not taken into consideration.

Let’s now explore category selectivity values across the layers. That will reveal whether category selectivity evolves throughout the transformer stack, or whether it’s already inherited from the embeddings layer. Furthermore, we will identify a potential confound of variance suppression that will be resolved in Part 7.

Task

Create a for-loop over transformer layers. Within each layer, calculate the token cosine similarity matrices and extract the within- and across-category similarity values. Quantify and store three metrics: The difference between the within-category and the across-category similarity averages; the average of the within-category and across-category similarities; and the t-value as you’ve done before.

Visualize the average differences and t-values across all layers, as in Figure 6.50. The averages across all categories will be used later.

The striking finding is the comparison of the differences (panel A) vs. the t-values (panel B). In particular, the t-values are roughly comparable for all three matrices whereas the mean differences show a remarkable (up to four-fold) difference between, e.g., K and V.

That may seem like a confusing set of results, considering that the mean differences in panel A are literally the numerator of the t-values in panel B.

Figure 6.50: Laminar profile of differences in mean similarity values (panel A) and a t-test comparison (panel B) between within- and across-category word pairs.

How can you explain that seeming discrepancy? Here’s a hint: Look back at the ranges of cosine similarity values of the different matrices in Figure 6.49 before continuing with the next task.

Task

Make scatter plots of the average cosine similarity by their differences (Figure 6.51A) and the average similarity by their t-values (Figure 6.51B). Optionally use a different color or marker for each layer.

Here’s the situation: Cosine similarity values are bound by 1, and so as a collection of similarity values approach 1, the variability gets compressed. This means that category differences are necessarily numerically smaller as the similarities increase.

Figure 6.51: Relationships between average and difference cosine similarity values (panel A), and between t-values and averages (panel B). The strict upper bound of 1 collapses the variability, which means that differences are trivially related to averages towards the bounds. T-values do not have this trivial relationship because of the normalization term in the denominator.

On the other hand, the t-value is the difference of the means scaled by the standard deviations. Thus, two distributions can be extremely close to each other in terms of averages, but they can still have a very large t-value if their variabilities are small.

That’s what you see in Panel A: The average category differences become vanishingly small as the cosine similarity values approach their maximum value. The t-values, in contrast, do not show this trivial relationship.

It turns out that there is a way to remove the trivial compression. Segue to Part 7…

The Fisher-z transform is a way to stretch out a uniform distribution into a normal distribution. It is defined by the following formula.

zr=12ln⁡(1+r1−r)(6.23)z_r = \frac{1}{2} \ln\left(\frac{1+r}{1-r}\right) \tag{6.23}

where r is the correlation coefficient or cosine similarity value. It turns out that this equation also equals the trigonometric transformation inverse arc-tangent, which you can implement using np.arctanh.

The goal of Part 7 is to repeat the analysis from Part 6 after applying the Fisher-z transform. But before getting to the real data, you’ll build intuition for the Fisher-z transform by applying it to uniform-distributed data.

Task

Simulate 10,000 cosine similarity values between -1 and +1, and apply the Fisher-z transformation. Visualize the transformation as in Figure 6.52A (x-axis is cosine similarity, y-axis is their Fisher-z transform, dashed line is the line of unity indicating no impact of the transform), and show their histograms as in Figure 6.52B.

To simulate the data, you can generate uniformly distributed numbers and then apply the transform.

r = np.random.uniform(-1,1,size=10_000) fz_r = np.arctanh(r)

Figure 6.52: Impact of the Fisher-z transform on uniformly distributed numbers between -1 and +1 (simulating cosine similarity values). Panel A shows the nonlinear stretching towards the bounds (dashed line is of unity), and panel B shows that the distribution goes from uniform to normal.

The Fisher-z transform has little impact on values near zero, as evidenced by the dots falling close to the line of unity for values less than around |.7| (you can create that line using the function axline with a slope of 1). On the other hand, the transform stretches the values as they approach ±1.

Task

Rerun the code for Part 6 but apply the Fisher-z transform to the cosine similarity values. It’s a minor change to the code, so you don’t need to copy/paste all the code; just save screenshots of the results so you can qualitatively compare the results with vs. without the Fisher-z transform. My results for re-analyzing Figure 6.51 are shown in Figure 6.53.

There are two changes to the code. The first is to modify the analysis by replacing the first line below with the second:

w = cs_actsQ[within_mask].flatten() w = np.arctanh(cs_actsQ[within_mask].flatten())

And of course, apply that to all six cosine similarity variables (within- and across-category for Q, K, and V).

The second change is to update the figure axis labels to avoid confusion. “Raw” and Fisher-z-transformed cosine similarity are, of course, closely related, but without properly labeling the axes, people might be understandably concerned about cosine similarity values being larger than 1.

Anyway, the important result here is that the trivial relationship between average vs. difference similarity values is completely untethered.

Figure 6.53: Same as Figure 6.51 but after applying the Fisher-z transform to the cosine similarity values.

Do you need to apply the Fisher-z transform every time you analyze correlation coefficients or cosine similarity values? As a general rule, no, you don’t need to: Correlation and similarity values are intrinsically interpretable and meaningful. Furthermore, the transform has a negligible impact on values smaller than around ±.7.

Applying the Fisher-z transform should be done when applying statistical analyses to the coefficients that assume normal distributions or would otherwise provide trivial results due to coefficient compression near the bounds of ±1.

day-mode Bookmark

Token frequency, attention adjustments, QK^⊤

The overall goal of this project is to determine whether the attention adjustments and QK^⊤ dot products are related to token frequencies, where “token frequency” refers to how often particular tokens appear in text.

The idea is to examine whether attention adjustments are larger for tokens that are more commonly used in text.

In theory, we would like to have a vector of token frequencies in the entire training corpus, but in lieu of that, we will estimate token frequencies using one million tokens from Wikitext.

GPU and system resources There is only one forward pass in this project. It is a large batch, and can take several minutes on a CPU vs. seconds on a GPU. Additionally, this project does require more RAM than most other projects. From checking the resources manager in Google Colab, I used up to 8 GB of RAM and 70 GB of disk space for the model and dataset.

Part 1: Tokenize Wikipedia data and count token frequencies

Section titled “Part 1: Tokenize Wikipedia data and count token frequencies”

The primary goal of Part 1 is to create a vector of token proportions in a large text.

Ideally, we’d like to have token probabilities in the LLM’s full training set. However, that is a very large dataset, and so in the interest of expediency, we’ll sample only 1M tokens. This isn’t a fully representative sample because all of our data come from one Wikitext dataset whereas BERT was trained on a much more diverse dataset. But it’s still a decent approximation and a fantastic learning opportunity.

Task

Import the BERT large model and its tokenizer.

The online code file shows how to import a small amount of Wikipedia text that is used to train LLMs. I recommend copying that code exactly to be able to reproduce my results in the rest of the project.

Be mindful that even just 1% of the test set can take around six minutes to download on Google Colab. Once it loads, take a moment to explore the dataset.

The dataset contains 64,078 samples of text data, each of which is a Dataset dictionary with keys id, url, title, and text. The first three fields are relevant for sourcing and identifying the text; in this project we need only the text field, which contains the article texts.

The next goal is to estimate token frequency by counting occurrences in one million tokens.

Task

Continue tokenizing the Wikitext entries (exclude the BERT special tokens) until you have over one million tokens. Calculate the number of times each token appears. The result will be a vector of size 30,522 (the vocab size) where each element contains the number of times that that token index appears in the data.

Report the 20 most frequent tokens. Convert the token counts to proportion, and visualize the log-proportions as in Figure 6.54.

To get 1M tokens, I setup a while-loop that continues importing each row of data until the total token count exceeds 1M. Inside that while-loop, elements in the token-frequency vector increment by one when their index appears in the text. In the loop, I printed the following information:

 86,693 tokens after 10 rows. 138,740 tokens after 20 rows. … 950,937 tokens after 140 rows.

Final count: 1,009,254 tokens after 145 rows.

The most frequent tokens include the following:

Most frequent tokens:

55174 occurrences of "the"
51063 occurrences of ","
38123 occurrences of "."
28938 occurrences of "of"
23954 occurrences of "and"

You can divide the vector of token counts by the sum of the vector to obtain proportion values. Figure 6.54 below shows the log of those proportions.

Figure 6.54: Scatter plot showing the empirical proportion of tokens appearing in 1M Wikipedia tokens.

Many tokens never appeared in the sample, meaning they have a count of zero. The log of zero is undefined, and thus, you should add a tiny number (e.g., 1e-15) before taking the log.

The goal is to have a 64 × 512 PyTorch tensor of tokens, with the following constraints:

  1. Each sequence in the batch corresponds to the first 512 tokens of a row of text data (excluding special tokens).

  2. There is no padding, thus each token in the batch is a valid token from the text. This means that text samples with less than 512 token are excluded.

Task

Create the batch described above. I recommend implementing this in a while-loop so you can tokenize each Wikitext sample, count its tokens, and skip to the next sample if there are too few.

Confirm that the resulting batch has shape 64 × 512. Make an image of the batch as in Figure 6.55.

There are several correct ways to implement this task. I initialized the batch as an empty list, then appended a 512-token sequence to that list only if there were at least 512 tokens, and finally converted the list of lists to a PyTorch tensor.

Figure 6.55: Heatmap showing the batch of token indices, with token position on the x-axis and sequence index on the y-axis.

We don’t expect any meaningful structure in the image of the batch, which is why inspecting it is important: Visible sections or rows with a flat color would indicate systematic gaps or repetitions. In other words, if this image did not look like unstructured noise, then there’s probably a mistake in the code.

Part 3: Hook attention QK^⊤ and adjustments

Section titled “Part 3: Hook attention QK^⊤ and adjustments”

Now to hook the transformers to get the attention adjustments magnitudes and the QK^⊤ dot products. A few warnings before starting:

  1. The QK^⊤ dot products matrices are batches × tokens × tokens per layer. Those matrices can become extremely large. Normally during runtime, the matrices are created and destroyed on the fly; here you will store them for subsequent analysis. If you run into out-of-memory problems, try reducing the batch size, e.g., from 64 to 32.

  2. Although the math of the attention algorithm is the same in BERT-style and GPT-style models, the organization of the matrices in the model is different. Do not create the hooks for this project by mindlessly copying from a GPT hook. Instead, follow my instructions and focus on the concepts rather than on the GPT nomenclature.

For reference, the BERT attention layer looks like this:

(attention): BertAttention(

(self): BertSdpaSelfAttention(
(query): Linear(in_features=1024, out_features=1024)
(key): Linear(in_features=1024, out_features=1024)
(value): Linear(in_features=1024, out_features=1024)
(dropout): Dropout(p=0.1, inplace=False)
)
(output): BertSelfOutput(
(dense): Linear(in_features=1024, out_features=1024)
(LayerNorm): LayerNorm((1024,), eps=1e-12)
(dropout): Dropout(p=0.1, inplace=False)
)
)

Notice that BERT stores the W_Q, W_K, and W_V matrices separately (cf. one wide matrix in GPT). Furthermore, the output layer includes a layerNorm, which means it produces the addition of the attention adjustment onto the hidden-state vectors. That is not the attention adjustment (projection) vectors that we want to analyze. Instead, you need to grab the dense vectors — that’s the closest equivalent to the attn.c_proj layer in GPT-2 models.

Task

Implant two hooks into all transformer layers, one to get the QK^⊤ dot products and the second to get the attention adjustment vector norms.

The first hook goes into attention.self. Obtain the Q activation vectors by passing the first element of the input tuple through the module.query object. Same for the K vectors. Then calculate the QK^⊤ dot products. You’ll need to reshape the Q and K matrices to have a head dimension, then calculate QK^⊤ per head, then average over the heads dimension (see Project 35 Part 9). Store the head-averaged QK^⊤ matrix in a dictionary for subsequent analysis and confirm that the size of the result is batch × tokens × tokens.

The second hook goes into the attention.output.dense layer. Here you detach the output tensor, which corresponds to the token embeddings adjustments that the attention algorithm calculated. Calculate the logarithm of the vector norms as you’ve done in previous projects, and store those norms in the dictionary for subsequent analysis.

Run a forward pass on the token batch you created in Part 2 (note: this takes 5-10 minutes on a standard CPU), and print the dictionary keys and tensor shapes.

Reducing the batch size isn’t only about saving memory; it’s also about saving time so you can iterate faster when writing code. Thus, you can start with a batch size of four while working on the code, then increase the batch size to 64 when you’re ready to create the data matrices for the rest of the project.

Regarding the first hook function: as you learned in Project 35, the head-averaged raw attention scores can be calculated without separating the matrices per head. That means that you could write the hook function like this:

def hook_qkt(module,input,output):
Q = module.query(input[0]).detach()
K = module.key(input[0]).detach()
qkt_acts[f’L{layer}’] = Q@K.transpose(-2,-1)

However, I still recommend reshaping the matrices to calculate QK^⊤ over each head, then averaging those raw attention scores across heads. That is conceptually cleaner and would be necessary if you want to adapt the code, e.g., to examine the softmax attention scores or run per-head analyses. The online code solution implements the per-head calculations.

Note that the syntax for getting the Q and K vectors is different in BERT vs. GPT, although the calculation of the dot products is the same. In BERT models, the variable input is the input into this layer, which are the layerNorm’ed hidden-state vectors. At this point, the data have not yet been multiplied by W_Q and W_K. Because those weights matrices are stored as PyTorch objects, you can implement the multiplication by passing the hidden-state vectors into the query object.

The second hook function is less complicated:

def hook_adj(module,input,output):
O = output.detach()
norms = torch.norm(O,dim=-1)
adj_norms[f’L{layer}’] = torch.log(norms)

After the forward pass, you should get one key-value pair per layer in each of the hooked dictionaries. The QK^⊤ tensor is of size 64 × 512 × 512, corresponding to 64 sequences in the batch and 512 tokens per batch. The attention adjustment vector norms is of size 64 × 512, corresponding to 64 sequences and 512 tokens per sequence.

Part 4: Adjustment norms by token frequencies

Section titled “Part 4: Adjustment norms by token frequencies”

The question we will address here is this: Is there a systematic relationship between token frequency (the proportion of times each token appears in the 1M token dataset) and the magnitude of the attention adjustment vector?

Task

This analysis will focus on three transformer layers: the first, the middle, and the last. For each of those layers, extract the log of the token proportions, and the attention adjustment log-norms that you calculated in the second hook function. Separate the analysis for the first token in the sequence vs. the rest of the tokens.

Make scatter plots of those relationships as in Figure 6.56. Each marker in those plots is from one token; the x-axis shows the log-proportion of times that marker appeared in the 1M-token dataset, and the y-axis shows the log-norm of adjustment vectors from the same tokens. The red x’s are the first token in each sequence, and the black dots are the rest of the tokens.

The three scatter plots reveal several interesting observations. First, they show yet another demonstration that the first token in the sequence exhibits different patterns than the rest of the tokens — though the extent to which they are outliers depends on the layer.

Figure 6.56: Scatter plots showing the relationship between attention adjustment vector norms with token proportion (both log-scaled), for three transformer layers. The red x’s indicate the first token in each sequence.

A second observation is the lack of visually obvious relationship between adjustment vector norm and token frequency. The non-zero correlation coefficients hint at some linear relationships for some layers, which we can continue to investigate.

Task

Repeat the correlation analysis over all layers, but just store and plot the correlation coefficient as in Figure 6.57, instead of the scatter plot for each layer.

Despite the lack of obvious relationship in Figure 6.56, the scatter plot of correlation coefficients over layers in Figure 6.57 does suggest some consistency in the relationship, with negative correlations in earlier layers and positive correlations in middle layers.

Figure 6.57: The correlation coefficients (y-axis) for the analysis show in Figure 6.56, for each transformer layer (x-axis).

Part 5: QK^⊤ by proportion product (one layer)

Section titled “Part 5: QK^⊤ by proportion product (one layer)”

The previous analysis was focused on the output of the attention algorithm; now we will go back to earlier attention calculations and explore whether there is a relationship between raw attention scores and token frequency.

Correlating QK^⊤ with token frequency is trickier, though, because QK^⊤ reflects interactions between pairs of tokens, not just individual tokens. Therefore, we will correlate QK^⊤ with the product of token proportions.

On the other hand, many tokens have very small probabilities, and multiplying two tiny numbers risks numerical issues. Therefore, we will work with log-probabilities and leverage the product rule of logarithms. The product rule of logarithms states that the log of a product equals the sum of logs: ln(a × b) = ln(a) + ln(b).

If p is a column vector containing token proportions, then P is a matrix of pairwise log-proportion products.

P=ln⁡(p⋅p⊤)(6.24)P = \ln(p \cdot p^\top) \tag{6.24} =ln⁡(p)+ln⁡(p⊤)(6.25)= \ln(p) + \ln(p^\top) \tag{6.25}

I must apologize for Equation 6.25: It is an abuse of math terminology. Linear algebra does not allow summing a column vector and a row vector. However, in numerical programs like NumPy, notation like this implements a broadcast sum between the two vectors. So Equation 6.25 is equivalent to the log of the outer product of p with itself, and if you implement that in NumPy (using dimension-endowed arrays), you’ll get a matrix P in which each element is the log of the product of two probabilities for each pair of tokens.

For each sequence in the batch, matrix P is the same size as QK^⊤, which means they can be vectorized and correlated.

One caveat before getting started: The P matrix contains marginal token frequencies (how often each token appears individually), not actual co-occurrence frequencies (how often token pairs appear together). The product of marginals equals the joint probability only if tokens are independent, which is obviously not the case in natural language. That doesn’t invalidate the analysis or the results, but it does mean that we’re ignoring some meaningful structure in the data in the interest of simplicity. On the other hand, each hidden-state vector absorbs information from previous tokens, so in some sense, the simple marginal product does incorporate some dependencies.

Task

For the first sequence of the batch, implement Equation 6.25 and visualize the matrix as in Figure 6.58.

Loop over the 64 batch sequences, calculate P, extract QK^⊤ from the corresponding sequence from layer 5, and visualize in a scatter plot as in Figure 6.59. There are many points to show, so I plotted only every 500^th point.

Figure 6.58: Heatmap illustrating the product of probabilities, implemented as the sum of log-probabilities, for all pairs of tokens in one token sequence.

As a sanity-check, you can confirm that P −P^⊤ is the zeros matrix. That is easily proven in linear algebra (transpose pp^⊤ to find that it equals itself). In other words, the marginal probability of token A with token B is the same as the probability of token B with token A.

Figure 6.59: The “mitten plot,” showing the relationship between the QK^⊤ dot product (y-axis) and joint probability (x-axis) for each token pair.

From this figure, there appears to be a positive relationship between the raw attention scores and the joint token probabilities. The rest of Part 5 is focused on quantifying that relationship. The approach will be to discretize the joint probability values (the x-axis) and measure the mean and standard deviation of the QK^⊤ values (the y-axis) in each of the bins.

Task

Use data from layer 7. Create a for-loop over sequences in the batch. Within each sequence, calculate P as described above, and flatten the matrix. Use np.percentile to split the data into 40 bins (note: that requires 41 boundary values) of equal sample size (as opposed to equal x-axis grid spacing, which you’d get from using np.linspace).

Extract the raw attention scores from the same batch sequence, and use the binned_statistic function from the scipy.stats library to extract the mean and standard deviation of the QK^⊤ values within each bin defined from P. Calculate bin centers from the boundary edges, and visualize as a scatter plot as in Figure 6.60 (each color corresponds to a different sequence in the batch. Finally, calculate and store the correlation coefficients between the bin centers and descriptive statistics, and plot those coefficients per sequence in a separate plot as in Figure 6.61.

The online code produces a figure illustrating the distinction between discretizing to preserve equal data counts (using np.percentile) vs. equal axis spacing (using np.linspace). Equal axis spacing is more appropriate for histograms; in this case, the equal data-count spacing is more appropriate because the accuracy of estimates of the mean and standard deviation depend on sample size, which is now balanced across bins. With equal axis spacing, it is possible that we would be comparing standard deviations between, e.g., samples of 2 vs. samples of 200. Furthermore, equal axis spacing can lead to empty bins, which in turn will lead to numerical issues like division-by-zero.

The discretizations reveal interesting patterns of increasing QK^⊤ for increasing probability-product token pairs. In other words, the more common the token pairs, the larger their attention updates.

Figure 6.60: The average (panel A) and standard deviation (panel B) QK^⊤ dot products are related to the token pair proportions.

That seems intuitive in the context of language comprehension: If a word has exactly one interpretation in every possible context, then an LLM would simply need to look up its meaning without cross-referencing the rest of the text. On the other hand, words that appear more often and in more contexts can take on more interpretations and nuances; and thus, an LLM would need more information from surrounding context to assign meaning to that word.

The scatter plots suggest that the relationships are not perfectly linear, but there clearly is a linear component, and that’s what the correlation coefficient captures. Visualizing the correlations for each sequence would identify if the relationship is consistent, or whether it’s driven by a quirk in only one or a few sequences.

Figure 6.61: Correlations from Figure 6.60 shown separately for each sequence in the batch.

There is, of course, some variability across sequences, but all sequences show a robust correlation.

That’s for one layer. I think you can imagine what will happen in the finale to this project :)

Part 6: Laminar profiles of QK^⊤ by proportion

Section titled “Part 6: Laminar profiles of QK^⊤ by proportion”

Now to wrap up this project by exploring whether the findings from layer 7 are observed in other layers.

Task

In a for-loop over the transformer layers, run the calculations you wrote in Part 5. But instead of making scatter plots per layer, store the bin centers, the means, and the standard deviations in a data matrix of size layers × 40 (bins) × 3 (means, standard deviations, and bin centers). Remember to average over all sequences.

Visualize the results as in Figure 6.62. In the top row, each line corresponds to a layer. In the bottom row, layer is on the x-axis and correlation coefficients are on the y-axis. All colors in the plot map onto the same transformer layer.

Figure 6.62: Relationships between QK^⊤ dot product characteristics (average in panels A and C, standard deviation in panels B and D) across all layers. Line colors in panels A and B indicate transformer layer (see colorbars and marker colors in panels C and D).

Other than the initial transformer layer, the trend is clear: The more often the two token pairs appear in the 1M-token sample, the larger the raw attention score of those token pairs. The standard deviations show a different pattern, with the variability increasing in early to middle layers, then collapsing with increasing probability in later layers.

Keep in mind that the single-layer scatter plots suggested a nonlinear relationship; the correlations capture only the linear trends embedded in the nonlinearities. That said, most of the data are clustered in the linear regime; there are relatively few data points in the largest token-pair probability values of Figure 6.60.

day-mode Bookmark

Downstream impacts of head silencing

In Chapter 5 you learned how to interfere with PyTorch models during runtime through outputs of hook functions. And now in this chapter, you’ve learned about the attention block of the transformer, but thus far only through observational mechanisms. The general goal of this and the next project is to show how to manipulate the attention calculations to run causal experiments that elucidate the role of attention heads in LLMs.

This project is a data-driven exploration of the downstream impact of head silencing. Basically, you will switch off one head at a time, and measure the impact on the hidden-state vectors as they pass through the transformers, and on the final output logits.

GPU This project involves a lot of forward passes (e.g., one forward pass per attention head and per layer in Part 5). I recommend running this project on a GPU if available. I will also show a demo in Part 4 that illustrates several ways of moving tensors from the GPU to the CPU — and errors that you might encounter.

Part 1: Hook all layers and get activations

Section titled “Part 1: Hook all layers and get activations”

The goals of Part 1 are to implant hook functions to silence one attention head in one layer, tokenize some text, and push the tokens through the model — without manipulations — in order to get a “clean” set of hidden-state activations and output logits as a baseline comparison for the causal experiment in later parts.

You will install two sets of hook functions into this model. The first will silence (replace activations with zeros) one head in one layer. Unlike previous hooks in this book, this one gets implanted using the method register_forward_pre_hook — notice the additional pre in the method call, which allows us to manipulate the activations before the module is run. In other words, you will manipulate the input of the layer instead of the output. That’s necessary for this project, because the attention activations are still segmented by heads at the input to attn.c_proj, but they are linearly combined (and thus, no longer separable into heads) by the W_O mixing matrix at the output of attn.c_proj.

The second hook will store (without manipulating) the outputs of the transformer layers. As you know, this is the same as the hidden-state tensors that the model call can optionally output, except here we don’t need the initial embeddings layer, and we want the final transformer outputs without the additional layerNorm.

Task

Import GPT-2-medium, switch it to eval mode, and move it to the GPU. Define variables for the number of heads, the number of layers, the embeddings dimensionality, and the head dimensionality.

Create a hook function to manipulate attention heads, which you’ll implant into attn.c_proj. As you’ve previously done with single-layer manipulations, define an embedded hook function to specify the layer to manipulate. Inside the hook function: (1) reshape the first element of the input tuple into a tensor of size batches × tokens × heads × head dimensionality; (2) silence only one head corresponding to a variable head2silence by replacing the activation values for all token positions with zeros; (3) reshape the tensor back to batches × tokens × embeddings dimension; (4) repackage the modified input into its original tuple; and (5) return that variable input as the output of the hook function.

The second hook function is implanted into the main transformer layer, and simply detaches the transformer output to be stored in a dictionary with a layer-specific key name. Store the transformer outputs on the CPU and in NumPy format. Implant using the function register_forward_hook because we want to access the output of the module.

By the way, it is not strictly necessary to reshape the tensor twice. You could alternatively calculate the indices of the desired head and zero it out without reshaping. However, reshaping helps build intuition for how the heads are organized and stored in tensors.

Task

Tokenize the following text (excluding the final period): Look for the music on all things, and life will be a symphony of joy. My music is best understood by children and. It’s a quote from the genius composer and philosopher Igor Stravinsky. The quote ends with the word “animals,” but leave that final word out, so we can see what the model predicts. Print out a table of the tokens and their indices.

Run a forward pass with no manipulations. Make copies of the transformer outputs and the final output logits, and include clean in the variable names for later comparisons. Print the keys in the hidden-state dictionary, the shape of the hidden-state activations, and the shape of the output logits tensors.

Here are the first few tokens:

There are 26 tokens:

8567 is "Look"
329 is " for"
262 is " the"
2647 is " music"

To get a clean version of the model, simply set variable layer2silence to a number that does not equal a layer index, such as a negative number or 1000 or 1.23.

Remember from Project 26 (part 5) that the dictionary collecting the hooked activations is overwritten at every forward pass. That’s why you need to make a copy of the clean-run dictionary to preserve the transformer outputs for comparison with the manipulated models later in the project.

Each transformer output tensor is of size 1 × 26 × 1024, corresponding to one batch of 26 tokens, and an embeddings dimensionality of 1024. The output logits are of size 1 × 26 × 50257, with the third dimension corresponding to the vocab size.

Part 2: Cosine similarity in the “clean” model

Section titled “Part 2: Cosine similarity in the “clean” model”

Let’s have a look at the hidden-state vectors before testing the impact of head silencing. The goal of Part 2 is to visualize cosine similarity values across all token pairs for each layer.

Task

Determine the number of non-redundant and non-trivial elements in a symmetric (N−1)×(N−1) tokens cosine similarity matrix (N tokens excluding the first). Initialize a matrix of size layers × non-redundant similarity values.

Loop over all the transformer layers, calculate the cosine similarity matrix between all pairs of hidden-state vectors except the first token position, and extract and store the non-redundant values.

A symmetric matrix of size M × M contains M^2 total elements and M(M − 1)∕2 elements above the diagonal. In our case, excluding the diagonal and the first token leads to the expression (N − 1)(N − 2)∕2 non-redundant elements for N tokens.

Task

Write code to generate Figure 6.63. This figure shows the transformer layers on the x-axis, cosine similarity on the y-axis, and histogram count on the color axis. In other words, each vertical slice of the image shows the histogram of inter-token cosine similarity values from that layer. Use the same bin boundaries for all layers (I used 31 bins between .6 and 1). The light blue hexagons indicate the average cosine similarity value at each layer. Use the Matplotlib function pcolor instead of imshow, and the color map afmhot_r.

Figure 6.63: This heatmap shows the distributions of cosine similarity values across hidden-state vectors for each transformer layer. Columns (x-axis) correspond to transformer layers, rows (y-axis) correspond to cosine similarity bins (from a histogram), the color indicates the counts per bin, and the light blue hexagons indicate the average similarity value per layer.

One of my general goals in this book is to introduce you to multiple ways of visualizing data, in this case histogram distributions. Just showing one marker corresponding to the average value is appropriate in many situations, but there are other cases where showing the distributions can reveal additional insights — or at least be more eye-catching :)

These results will provide a baseline level of cosine similarity, and the goals of the next two parts of this project are to determine whether and how single-head silencing modifies the way that hidden-state vectors relate to each other.

Part 3: Downstream impact of silencing one head

Section titled “Part 3: Downstream impact of silencing one head”

One attention head in one layer provides just a tiny sliver of the computations across the transformer stack. Can silencing only 1/384 heads (16 heads in each of 24 layers) have a measurable impact on hidden-state cosine similarities?

Let’s find out :)

Task

Set the hook function parameters to silence head #1 in layer 4. Run the tokens through the model and store copies of the hooked hidden-state vectors and output logits in variables with silence in the name. You’ll use the output logits in Part 4.

In a for-loop over transformer layers, calculate the cosine similarity matrix of the hidden-state vectors for the silenced model, as you did in Part 2. Subtract the “silenced” similarities from the “clean” similarities. Visualize histograms of those differences for each layer as in Figure 6.64A, but show the histograms only starting from the manipulated layer, because the differences from earlier layers are trivially all zero. Then plot the average similarity differences as in Figure 6.64B.

Figure 6.64: Impact of single-head silencing on cosine similarities of hidden-state vectors. The distributions in panel A show all similarity differences, with positive numbers indicating stronger similarity in the “clean” compared to the manipulated model. The scatter plot in panel B shows the average difference per layer. The dashed vertical line at layer 4 indicates the layer at which the manipulation was made.

The effect is quite weak — around a .001 decrease in average cosine similarity. Certainly nothing to contact the Nobel prize committee about. But on the other hand, I find it remarkable that such a tiny manipulation to the model has a measurable impact that propagates throughout the entire model, nearly 20 layers deeper than the manipulation.

Interlude: Copying data from the GPU to the CPU

Section titled “Interlude: Copying data from the GPU to the CPU”

Before proceeding to the rest of the project, I want to take a small tangent to show several ways of getting data from the GPU back onto the CPU. You’re already familiar with the .cpu() method on a PyTorch tensor, which creates a copy of that tensor on the CPU (the original tensor remains on the GPU).

The online code file has a block of commented code that performs some simple analyses on the GPU before moving the result back to the CPU. The point is to show that (1) many PyTorch functions can be run on the GPU (that’s not the case for NumPy, SciPy, Matplotlib, and many other libraries, which are executable only on the CPU); (2) there are several ways to copy data to the CPU; and (3) some methods of data transfer depend on the data type and tensor size.

Before reading my explanations below, uncomment and run each line in the code block at a time. When you see errors, try to understand why you get those errors.

First code demo:

L = out_clean.logits[0,-1,:] next_tok = torch.argmax(L) print(next_tok.device)

If you’re using a GPU for this project, then the variable out_clean is on the GPU. The first line shows that you can call PyTorch functions on PyTorch variables on the GPU. The second line confirms that the result remains on the GPU.

Second code demo:

next_tok = torch.argmax(L).cpu() print(next_tok.device)

This code runs an analysis on the GPU and then copies the result to the CPU via the .cpu() method that you’re already familiar with.

Third code demo:

next_tok = torch.argmax(L).item()

print(next_tok.device)
print(torch.tensor(next_tok).device)

The first line applies the method .item() on the output, which copies it to the CPU. The second line, however, throws an error: ’int’ object has no attribute ’device’. You can check the device by transforming the result back into a PyTorch tensor using the third code line, and that result will tell you that the variable is on the CPU.

Fourth code demo:

lsm_logits = F.log_softmax(L,dim=-1).item()

Here you also get an error: Tensor cannot be converted to Scalar.

What have we learned from these demos?

  • Calling the method .cpu() on a PyTorch variable copies it back to the CPU and leaves it as a PyTorch variable.
  • Calling the method .item() on a PyTorch scalar (a 0-dimensional tensor) copies it to the CPU — and converts it to a Python int or float, i.e., no longer a PyTorch variable.

You’ve explored the impact of single-head silencing on the hidden-state vectors; now we’ll switch to exploring the impact on output logits and next-token prediction.

Task

Calculate the predicted new token by finding the maximum logit from the “clean” logits. Transform the logits to log-softmax to store the log-probability of the maximum logit.

Calculate the predicted next token and its log-softmax probability from the “silenced” model you calculated in Part 3. Print the original text, the predicted next tokens, and the probability in percent, from both models.

Print out the tokens with the 10 highest logits from both models.

Here are my results:

   CLEAN: Next token is ” adults” with 25.996% SILENCED: Next token is ” adults” with 27.219%

Although the original quote ends with “animals,” “adults” is certainly an appropriate prediction given the context. Interestingly, the silenced model was more confident about selecting that token compared to the clean model.

Remember from Chapter 4 that models don’t always pick the maximum-logit token; they randomly choose from a sample of the largest logits. Here are the top-10 logits for both models.

Top 10 logits from CLEAN model: ” adults”, ” young”, ” grown”, ” the”, ” their”, ” by”, ” youth”, ” grandchildren”, ” teenagers”, ” children”,

Top 10 logits from SILENCED model: ” adults”, ” young”, ” grown”, ” their”, ” the”, ” by”, “grandchildren”, ” youth”, ” teenagers”, ” parents”,

Although the two lists are largely overlapping, they are not identical. Thus, although the impact of silencing one head in one layer may be small, seemingly insignificant differences can lead models down very different paths after multiple iterations of token selection, analogous to the flap of a butterfly’s wings catalyzing a cascade of wind changes that ultimately produces a hurricane.

Task

In a for-loop over all transformer layers, silence head #1 in each layer while running a forward pass, and extract the predicted next token and its log-softmax probability. To be clear: Only one head is silenced in each forward pass in each iteration, and each iteration involves silencing head index #1 for one layer. Print the predicted next token and its log-softmax, and show the max-logit value in a scatter plot as in Figure 6.65.

The model predicts the new token “adults” after manipulating all layers except for layer 6:

Next token: ” adults” with 26.23% (silenced L0:H1) Next token: ” adults” with 28.58% (silenced L1:H1) … Next token: ” the” with 6.104% (silenced L6:H1) …

Figure 6.65: Impact of single-head silencing on the maximum output logit (log-softmax probability). The dashed gray line is the maximum log-softmax value from the clean model.

The differences in logits relative to the clean version are small but measurable.

Now to silence each head in each layer. As in Part 4, only one head will be silenced at a time, but each of 384 heads will be silenced in 384 forward passes.

Task

Silence each of the 384 attention heads in the model using a double for-loop over all layers and all heads. After each forward pass, transform the output logits to log-softmax, and calculate and store (1) the maximum logit and (2) the logit corresponding to the predicted token from the clean model (the target token “ adults”).

Visualize the results using heatmaps of the differences between the silenced models and the clean model (use the function pcolor) as in Figure 6.66. The color limits are defined as twice the L_1 average (remember that the L_1 mean is the average of the absolute values), and the color map is RdBu_r.

Calculate the marginal layer impact by averaging the logits across all heads, and visualize the difference from the clean logits, and their standard deviation, as in Figure 6.67.

Of course, the target logit and maximum logit are the same value when the silenced model’s max-token is the same as that of the clean model.

Figure 6.66: Impact of silencing each head individually on the target log-softmax value (panel A) and maximum log-softmax value (panel B). x-axis corresponds to the transformer layer, y-axis corresponds to attention head index, and the color corresponds to the change in log-softmax probability relative to the clean model (blue colors indicate larger logits in the clean model).

The most noteworthy observation from this result is that there is no consistent pattern of a positive or negative impact. There are downstream consequences of silencing each head, as evidenced by the non-zero differences from the clean model, but some heads increase the target logit while other heads decrease the target logit. It seems that single-head silencing is adding non-systematic noise to the model, although it is possible that a full experiment with careful controls and a large sample size would reveal more interpretable patterns.

Figure 6.67: Summary statistics of the manipulations across all attention heads per layer. The markers indicate the means, the lines indicate one standard deviation on either side of the mean, and small x-axis offsets were included for visibility.

This interpretation is confirmed by the marginal layer impact, shown in Figure 6.67. Furthermore, the overlap between the target and maximum logits for all layers except for layer 6 is due to the silenced models predicting the same token as the clean model.

Final thought for this project: Is it appropriate to zero-out an attention head? It’s an unnatural manipulation, because entire heads never equal zero during real forward passes. Here are several alternative manipulation approaches:

  1. Replace each head with its mean, which preserves the average value while suppressing variability.

  2. Replace the head with random noise that preserves the mean and standard deviation.

  3. Randomly permute the activation values so that all the numbers in the head are the same (and thus the global statistics are preserved), but the patterns (and, thus, the information content) are destroyed. You’ll implement this approach in the next project.

  4. Replace the activations with those calculated in a “donor” model that was given different tokens. That’s called “patching”; you’ve done it in Project 32 using hidden-state vectors, and you’ll do it with attention heads in the next project.

day-mode Bookmark

Patching heads in IOI

This project combines what you learned about the indirect object identification (IOI) task in Project 32, with manipulating attention heads from Project 40. I recommend completing those two projects before starting this one.

You will run two experiments in this project. The first (Part 2) measures the impact of randomly permuting head activations on IOI scores, and the second (Part 4) measures the impact of patching heads on IOI scores.

GPU This is one of the few projects where you really need a GPU. Per experiment, it takes around around 10 seconds on a GPU vs. around 20 minutes on a standard CPU. In other words, running the completed project code on a regular CPU might take 45-60 minutes. If you do not have access to a GPU, then use GPT-2-small instead of GPT-2-large, and consider manipulating only, e.g., one-half of the heads instead of all of them.

Part 1 simply involves copying code from Project 32 to setup the rest of this project.

Task

Import GPT-2-large and move it to the GPU. Copy and tokenize the two sample texts, and move the tokens to the GPU. Define variables for the targets “ Mike” and “ Emma”. Run forward passes to get the output logits. Calculate baseline IOI scores for later comparison. You don’t need the hidden-state vectors for this project.

Define variables for the number of heads, the number of transformer layers, the embeddings dimension, and the head dimensionality. You’ll use these variables later in the project.

The end result of Part 1 will be the two IOI scores:

IOI score for text “ME”: -3.047 IOI score for text “EM”:  3.530

The online code has some additional visualizations to remind you of the IOI task and key results, but I won’t show them here because they were already discussed in Project 32.

Part 2: Impact of single-head permutation on IOI

Section titled “Part 2: Impact of single-head permutation on IOI”

One of the key findings from Project 40 was that silencing individual heads modulates output logits but not in any systematic direction; in other words, it added noise and instability.

The goal of Part 2 of this project is to examine whether randomly permuting the activations from a single head can impact IOI scores, and whether that impact is consistently negative or positive relative to a clean IOI score. We won’t actually change any of the activation values in the model; just randomly rearrange them.

To make sure you understand what you’ll manipulate: Each head that you access via the input into c_proj using the .register_forward_pre_hook method is the following equation (repeated from the beginning of this chapter).

Ah=σ(QhKh⊤dh+M)Vh(6.5)A_h = \sigma\left(\frac{Q_h K_h^\top}{\sqrt{d_h}} + M\right) V_h \tag{6.5}

Thus, we’ll manipulate the end-result of the per-head attention calculations, not the individual Q, K, or V activations.

In contrast, the output of c_proj that you access using the .register_forward_hook method is the concatenation of all individual heads, mixed together by the output mixing matrix.

A=[A1∥A2∥…∥Ah]WO(6.6)A = [A_1 \| A_2 \| \ldots \| A_h] W_O \tag{6.6}

Those are the final output projection vectors of the attention block, where there are no more heads to separate.

Before starting with the LLM data, you’ll write code using a small matrix to illustrate how to randomly permute the elements in a matrix.

Task

Write code to randomly permute a matrix, using the following steps with PyTorch functions: (1) Create a 3 × 4 matrix comprising the integers 0 through 11; (2) Vectorize (a.k.a. flatten) the matrix; (3) Use torch.randperm to randomly permute the matrix elements; (4) Reshape back to 3 × 4. Print the original and randomly shuffled matrix, and rerun the code block several times to see how the numbers randomly differ each time.

Here is an example result:

Original:

tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

Randomized:

tensor([[ 8, 6, 5, 10],
[ 4, 3, 11, 1],
[ 9, 7, 2, 0]])

Of course, your randomized matrix will differ from mine (and be different each time you run the code), but the important things are (1) the randomized matrix is the same size as the original; and (2) the numbers in both matrices are identical, but any patterns embedded in the positions of the numbers has been destroyed.

It’s also possible to combine the steps into one line of code. Either way, you now have code that randomly permutes activation values in individual attention heads.

Task

Define variables for the number of heads, the number of transformer layers, the embeddings dimension, and the head dimensionality.

Write a double for-loop over all layers and all heads within each layer. The rest of this Task Box describes what happens inside each iteration of the loops.

Create a hook function that is implanted into the attn.c_proj layer using the register_forward_pre_hook method. Implement the following calculations in the hook function: (1) Reshape the first element of the input tuple into shape batches × tokens × heads × head-dimension; (2) Randomly permute the activations in one head corresponding to the current iteration in the head for-loop using code you developed in Part 1; (3) Reshape and repackage the input tensor; (4) Calculate and store the matrix norm of the head you just permuted in a NumPy array of size layers × heads. Steps 1-3 should be done using PyTorch functions on the GPU, and Step 4 should be done using NumPy on the CPU.

Run a forward pass using the “EM” tokens (Emma gave a coffee to), and remove the hook function. Then calculate and store the IOI score as the difference in output logits for the token “ Mike” vs. the token “ Emma”.

While developing your code, I recommend running the loops only over the first few layers and heads. That will allow you to have a rapid iteration cycle.

A few warnings in case you run into trouble when coding the hook function:

  • Print shapes of tensors inside hook function. (Best to comment out those lines after you’re sure the functions work.)
  • If you change the hook function but get the same error messages, you might have multiple hooks implanted. Try re-importing the model to have a clean slate.
  • Set the for-loops to run only one layer and one head so you can rapidly iterate and test changes to the function.

Task

Visualize the impact of activation-permuting in three ways. First, calculate a matrix of ΔIOI values, defined as the IOI scores from the permuted manipulations minus the IOI score calculated from the clean model. Show the results as a heatmap (Figure 6.68A).

Second, make a scatter plot of the average over heads per layer to determine whether there is consistent direction of the manipulation on increasing or decreasing IOI scores (Figure 6.68B). The vertical error bars show one standard deviation above and below the head-average.

Third, make a scatter plot of the head matrix norm by the ΔIOI (panel C), using the same color scaling as in panel A.

Figure 6.68: Impact of single-head random permuting on the IOI score. Panel A shows a heatmap of all heads in all layers, with the color of each head indicating the change in IOI relative to the clean model run. Panel B shows the marginal impact, assessed as the average and standard deviation across the heads from panel A. Panel C shows that heads with larger attention adjustment norms had a larger overall impact on the IOI. Each marker corresponds to a head. The color maps onto the y-axis values.

There is clearly a numerical impact of the single-head permutation on the IOI score, but the effect is not systematically in any particular direction. In other words, it appears that randomly reordering activation values made the model non-systematically noisier, at least for this one text sample.

Panel C shows an outward-fan effect, such that the impact of permuting heads on IOI increases with increasing head norm. That should make sense intuitively: Heads with norms close to zero make minimal contribution to the attention adjustments, and thus, manipulating them has minimal impact. You can better visualize the fanning effect by plotting the absolute value of the ΔIOI.

Section titled “Part 3: Get all ME-related attention activations”

We will now work towards the patching experiment, in which single-head activations from a “donor” model will be transplanted into a recipient model. To do that, we need a set of clean activations. The purpose of Part 3 is to hook a model to get those activations.

Task

Create and implant hooks into all layers to get the attention head activations. There is no manipulation; just detach the tensor from the computational graph, reshape it to have a dimension for head index, and store the tensor in a dictionary with a key for each layer.

Run a forward pass on the model using the “ME” tokens (Mike gave the coffee to), and remove all the hooks. Print the shapes of all hooked tensors.

Here are the tensors from the first two layers:

MEattn[’L0’] has shape [1, 14, 20, 64] MEattn[’L1’] has shape [1, 14, 20, 64]

The sizes correspond to one sequence of 14 tokens, 20 heads, and 64 dimensions per head.

In the experiment, you will run a forward pass using the “EM” tokens, and replace individual heads’ activations with these vectors (patching). But first, let’s explore the head-specific activations.

Task

Visualize the attention heads in two ways. First, create a sequence of heatmaps of each head from layer 4 as in Figure 6.69. Second, calculate the average of the vector norms of all attention heads per layer per token, and visualize that heatmap as in Figure 6.70.

The attention heads, like most of the direct visualizations in LLMs, do not have any obvious human-interpretable patterns that can be detected just from using your eyeballs. Perhaps for that reason, I find them fascinating to look at. They’re also good sanity-checks, because if these heatmaps were, for example, all flat, then you would know that there is something wrong with your code.

Figure 6.69: Heatmaps showing the activations of all heads from one layer for each token. I transposed the matrices to visualize them as tall instead of wide maps. There is no deep theoretical reason for this; tall matrices just looked nicer in the figure.

Figure 6.70 reveals several interesting internal dynamics, for example that the first two tokens have larger adjustment norms in earlier layers whereas other tokens have larger adjustment norms in later layers (e.g., “,” “gave” and “to”). During the first few tokens, the model has not yet acquired enough information to process higher-level context features.

Figure 6.70: This heatmap shows the average attention adjustment vector norms across all heads, separately for each token (x-axis) and transformer layer (y-axis).

Anyway, in the context of the key IOI experiment of this project, we now have the “donor” attention activations from a clean model processing the “ME” tokens, which we can use to replace the activations in a model processing the “EM” tokens.

I find visualizations like the ones in Part 3 to be tantalizing, mysterious, and wondrously uninterpretable. They represent one sliver of the highly nonlinear representations that LLMs develop of human language.

In particular, I found it interesting that the two “Mike”s have different activation patterns — identical tokens, identical heads, but different contexts. In the interest of curiosity-driven knowledge exploration, I decided to include an interlude here to continue exploring the difference between the activations to the two “Mike” tokens. The goal will be to visualize and quantify how the two token representations become increasingly differentiated by a small number of heads.

Task

In a for-loop over transformer layers, extract the head × head-dimension matrix for the first and second “Mike” token, and visualize their difference as a heatmap (Figure 6.71). Use the same color scaling of -.4 to .4 for all maps. Show only every 3^rd layer to facilitate visual inspection.

Figure 6.71: Each heatmap shows the difference between the first and the second appearance of the token for “Mike” in the sentence. Deeper layers have sparser differentiation between the two positions, reflecting head-specific context updates.

Notice the vertical stripes in the maps that appear to become more prominent in later layers. That suggests that the heads begin to specialize for the distinct grammatical and semantic meanings of the two “Mike”s. In other words, the heads become increasingly sparse, with the activations in many heads compressing towards zero while a small number of heads have larger-magnitude activations.

The next part of this interlude is to quantify that sparseness.

Task

In a for-loop over transformer layers, extract and subtract the heads × head-dimension maps as for the previous figure, but now calculate the L_1 mean of each head (across head-dimension). Plot the ratio of the average of the two largest L_1 means, to the average of the two smallest L_1 means. See Figure 6.72.

I introduced the L_1 mean in Project 34; as a reminder, it’s the average of the absolute values of the vector. In Figure 6.72, higher numbers indicate a greater separation between the high-activation vs. low-activation heads.

Figure 6.72: The ratio of the largest two to the smallest two average differences indicates the “head selectivity” for differential processing of the two “Mike” tokens.

The results show an increasingly sparse differentiation in middle to later layers of the model.

I hope you enjoyed this little interlude, and I hope you take inspiration not just about this particular analysis and visualization, but about the general openness and curiosity to explore model internal activations.

Anyway, let’s get back to the main thread of this project. The goal of Part 5 is to perform the patching experiment. The idea is conceptually identical to the patching experiment in Project 32: Replace activations while processing the EM tokens from a clean model that processed the ME tokens. The only difference here is that you’ll patch individual heads instead of patching hidden states.

Task

Create a double for-loop over all layers and heads. Inside the inner (head) loop, create a hook function that is similar to the hook function in Part 2, except instead of scrambling the head activations, replace them with the activations you extracted in Part 3. Make sure the layer and head indices match. You don’t need to extract or store any data from this head.

Run a forward pass for each layer-head combination, and make sure to remove the implanted hook after each forward pass. Calculate the IOI score as before.

Visualize the ΔIOI scores similar to the visualization in Part 2 (Figure 6.73). Unlike in Part 2, panel C here shows the standard deviation over the heads per layer.

Figure 6.73: The change in IOI scores from the patched models compared to those in the clean run.

The direction of the effect (panel A) is not consistent as it was when manipulating the transformer outputs in Project 32. The head-averaged and standard deviation plots in panel B also suggest that the direction of the effect differs for different heads.

On the other hand, the overall impact on ΔIOI, as reflected in the standard deviation, increases starting in middle layers, consistent with the manipulation impact when patching the transformer outputs.