Skip to content
ImagineWorld

Transformer Outputs

node_idnode-book_50-ml-projects-to-understand-llms_chapter-05-transformer-outputs
node_typechapter_node
schema_profileworld.chapter_node.v1
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
statusactive
chapter_num5
chapter_titleTransformer Outputs
sections5.24 Project 24: Cosine similarities within and across layers, 5.25 Project 25: Category selectivity via cosine similarity, 5.26 Project 26: Current layer = previous layer + adjustments, 5.27 Project 27: Impact of layer-specific noise and scaling, 5.28 Project 28: Effective dimensionality of hidden layers, 5.29 Project 29: Hidden state dimensionality reduction, 5.30 Project 30: Sentiment analysis with decision trees, 5.31 Project 31: Logit lens, 5.32 Project 32: Patching hidden states in indirect object identification
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

The transformer is the heart and soul of an LLM. Its goal is to transform embeddings vectors as they pass through the model.

Inside each transformer are two blocks that calculate adjustments to add back onto the embeddings vectors: the attention block (Chapter 6) and the MLP (multi-layer perceptron) block (Chapter 7). See Figure 5.1. The goal of these blocks is to incorporate information from context (other tokens in the sequence) and world knowledge (acquired during training) to modify the embeddings vectors. These are the adjustments that transform the embeddings vector from representing the current token into a prediction about the next token.

In this chapter, you will work with the outputs of the transformers (the top arrow in Figure 5.1B).

Figure 5.1: Overviews of an LLM (panel A) and the transformer layer (panel B).

The transformer layer is powerful, but the richness and complexities of natural language are too complex for one transformer. Therefore, many transformers are stacked, such that the output of transformer L is the input into transformer L + 1, and so on. GPT-2-small has 12 transformers, GPT-2-xl has 48 transformers, and GPT-5 has many dozens of transformers.

Each transformer layer implements the exact same calculations, but the weights matrices differ, leading to distinct transformations in each layer. You’ll explore the weights matrices more in the next two chapters.

Terminology: embeddings vectors, transformer outputs, hidden states

Section titled “Terminology: embeddings vectors, transformer outputs, hidden states”

These three terms can be confusing, because they are closely related and sometimes overlap.

  • Embeddings vectors. These are the dense, high-dimensional representations of tokens that you learned about in Chapter 3. They change as they pass through the model, as each transformer layer calculates and adds adjustments to the embeddings vectors. That said, the term “embeddings vectors” is usually used to describe the pre-transformed vectors in the embeddings layer.
  • Transformer outputs. These are the embeddings vectors at the output of each transformer layer. In other words, transformer outputs are embeddings vectors, but using the term “transformer outputs” helps to disambiguate from the initial token and positional embeddings.
  • Hidden states. The hidden states in Hugging Face models are largely overlapping with transformer outputs, but differ in two ways: (1) A model with L transformer layers has L + 1 hidden states. The first hidden state is the output of the embeddings layer (the token plus positional embeddings), while hidden states #2 through the end (corresponding to Python index 1 through L) are the transformer outputs. (2) The final hidden state includes a normalization (layerNorm) that is applied during the forward pass but after the transformer output. You will confirm this in Project 26. Hidden-state vectors are also sometimes called “residual stream” vectors. But the terminology of LLM components is already confusing enough, so I’ll avoid using the term “residual stream.”

There are several practical implications of the distinction between hidden states and transformer outputs: (1) Be careful when indexing, e.g., the first transformer layer is hidden state index 1 instead of index 0; (2) Analyses using the first and final hidden states may show qualitatively distinct patterns of results compared to the layers in between; (3) L− 2 hidden states are identical to L− 1 transformer outputs. In models provided by Hugging Face, the hidden states are easier to extract from the model compared to the transformer outputs, because the latter requires special hook functions, which you’ll learn about in Project 26 and then use throughout the rest of the book.

One final comment on terminology before starting the projects: There is a one-to-one mapping between a token string, its token index, and its embeddings vector. However, that breaks down in the transformers. That is, an embeddings vector begins its journey from a specific token, but the transformer layers mutate that vector into another vector that no longer points towards its original token.

For this reason, the hidden-state vectors do not directly correspond to tokens, and it is more accurate to describe a hidden-state vector in terms of its ordinal position in the sequence. That is, you can talk about the embeddings vector for the token “ grapefruit” but the hidden-state vector no longer directly maps onto the token “ grapefruit”; instead, that hidden-state vector is best described as, for example, the second hidden-state vector in the sequence (assuming “ grapefruit” is in the second token position).

That said, for convenience, hidden-state vectors can be identified using the token in the sentence from which they originated. That’s particularly useful when the ordinal token position changes in different sequences (e.g., if “ grapefruit” is the 2^nd token in one sentence and the 14^th token in a different sentence).

day-mode Bookmark

Cosine similarities within and across layers

We begin our explorations of transformer outputs by calculating and visualizing descriptive statistics including arithmetic and L_1 means, variances, and cosine similarities. Along the way, you’ll learn how to extract and visualize hidden states, and you’ll learn more about working with tokenizer outputs.

Task

Import GPT-2-medium and switch it to eval mode. Inspect the model.config to find the attribute that encodes the number of transformers layers.

Tokenize the sentence A wise man once said: Penguins are cute. (including the period.) Input the text directly into the tokenizer variable instead of using the encode method. Inspect the output of the tokenizer.

Run a forward pass with the tokens. Use the output_hidden_states optional input argument to get the hidden states in the model output.

The model output is a dictionary. Print the keys in that dictionary, the size of the output logits, the number of hidden states, and the size of each hidden state (all hidden states have the same size).

In model.config, the number of transformer layers is called n_layer, and equals 24 for GPT-2-medium (c.f. 12 for GPT-2-small and 48 for GPT-2-large).

As you learned in Project 22, when you input text directly into a tokenizer instead of using the encode method, the output is a tokenizer-type dictionary (not a regular Python dictionary). It contains the following information:

“input_ids” contains:

tensor([[ 32, 10787, 582, 1752, 531, 25, 29755,
389, 13779, 13 ]])

“attention_mask” contains:   tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

The input_ids field contains the token indices as a PyTorch tensor, and the attention_mask is a vector of all 1’s. This is, I must say, confusingly named, because it has nothing to do with the famous “attention” algorithm that is inside the transformer layer, and is the topic of Chapter 6. Instead, this attention mask is a Boolean vector that indicates which tokens are from the text and which are padding tokens (used for different-length sequences in a batch).

To get the hidden states vectors from the forward pass, use the following code.

outputs = model(**tokens,output_hidden_states=True)

The information below is from the output of the model call.

Keys in “outputs”:

odict_keys([’logits’, ’past_key_values’,
’hidden_states’])

Size of outputs.logits:    torch.Size([1, 10, 50257])

Number of hidden states:    25

Size of each hidden state:    torch.Size([1, 10, 1024])

Why are there 25 hidden states but only 24 transformer layers?

Well, if you read the opening part of this chapter, then you know that the first hidden state is the output of the embeddings matrices (the token plus the positional embeddings vectors). Thus, the first transformer output is actually the second hidden state. This is a source of confusion; be mindful of +1 indexing when accessing transformer outputs.

The goal here is to visualize some features of the hidden-state activations.

Task

In a for-loop over all hidden layers, extract the vectors for one token position from the text (you can use token #8 to reproduce my results). Plot all elements of the vector as in Figure 5.2A, the average of the vector from each layer as in Figure 5.2B, and the variance of the vector from each layer as in Figure 5.2C.

In the same loop, extract the standard deviations for each token position and store in a layers × tokens matrix to visualize as in Figure 5.3.

The spread of the activations grows considerably with depth into the model — that’s visible in the raw-data scatter plot and in the variance plot. Visually, the means appear to increase with model depth, but notice that the y-axis scaling is multiple orders of magnitude smaller than the shift in variance. In other words, the vector means remain fairly close to zero while their spread increases.

Figure 5.2: Descriptive statistics of one token position across the hidden-state layers in GPT-2-medium. In Panel A, each dot is the value of each dimension in the hidden-state vector; in Panel B, each dot is the average over all vector elements; in Panel C, each dot is the variance across all vector elements.

Another interesting observation in Figure 5.2 is that the variance increases sharply, only to plummet at the final hidden-state layer. That final layer is distinct both because it’s the last stage of processing before the model selects a token, and because the final hidden-state output includes a normalization that is not present in earlier layers.

Those results are for one token position. We can visualize the characteristics over all positions using a heatmap as in Figure 5.3.

Figure 5.3: Heatmap showing the standard deviations of the hidden-state vectors for each token position (x-axis) and each layer (y-axis).

There are several striking results from this figure.

  • The first token position has a large standard deviation across nearly all transformer layers. The first token (BOS) in a sequence often produces extreme results, which are outliers for statistical analyses. The reason is that causal autoregressive models predict upcoming tokens based on past tokens. The first token in a sequence has no past and therefore the model has difficulties making any plausible predictions. Consider this example: If I give you the word “A”, you have no idea what the next word should be. On the other hand, once you know “A wise” then you still don’t know exactly what word comes next, but you can at least start making some reasonable predictions.
  • The standard deviations appear to be zero for the embeddings layer (note the all black rectangles at the bottom of the heatmap). The standard deviations are not zero, but are an order of magnitude smaller than in the other layers.
  • The standard deviations generally increase towards later layers, although some tokens (e.g., “Penguins”) have higher standard deviations than others (e.g., “are”).
  • The standard deviation plummets at the final layer for all token positions; the result in Figure 5.2 wasn’t just a quirk of that one example.

Are you confused about why I instructed to show the variance for one token (Figure 5.2) but the standard deviation for all tokens (Figure 5.3)? Because variance is the squared standard deviation, it is useful for highlighting larger changes in variability; in contrast, standard deviation is more useful for visualizing heatmaps to prevent a small number of data values from dominating the color scaling and thus obscuring more subtle effects.

As the hidden-state vectors pass through the transformer layers, they are rotated and scaled from pointing towards the token they initially represented, into a prediction about the token that should come next.

One way to quantify the change in the vectors is by calculating cosine similarity across layer pairs. For example, imagine that the cosine similarity between layers 5 and 6 for one hidden-state vector is exactly 1; this would indicate that transformer layer 5 made no modifications to the vector. In contrast, a cross-layer cosine similarity closer to zero would indicate that the transformer layer had a massive qualitative impact on the vector.

Task

Identify the four token positions that are evenly spaced between the first and the last. For each token position, extract the hidden-state vectors across all layers. Calculate all pairwise (that is, each pair of layers) cosine similarities for each of the four token positions, and visualize as heatmaps as in Figure 5.4.

The x- and y-axes in these plots both show the hidden-state layers, and the colors show the cosine similarity between each pair of layers. Higher similarities indicate that the transformer made relatively minor adjustments to the vector.

Figure 5.4: Heatmaps depicting pairwise layer cosine similarities for four tokens. All four plots have the same color scaling.

The similarities matrix for the first token is qualitatively different from those of the other tokens. As I wrote earlier, the first token in a sequence has no context with which to predict the next token, and therefore has little opportunity for calculating context-relevant adjustments.

The results for the other tokens look overall similar, with cosine similarity decreasing further from the diagonal. Thus, cosine similarity generally decreases as a function of inter-layer distance. That should make sense: Each layer adds a small adjustment to the hidden-state vectors, and thus the vectors become less similar the more adjustments are added.

Another striking result is that the similarities with the first and final hidden state layers are lower than the layers in between. The first hidden state is the token embeddings; at this point, there is no context or world knowledge that is loaded onto the vectors. The final hidden state is the model’s final opportunity for adjustments before token selection, and also includes the additional layerNorm.

By the way, lest you think that these cosine similarities are low because of the color scaling: Notice that the lowest value on the colorbar is .8. Thus, the similarities are quite strong across all layer pairs.

Task

Create a matrix that encodes inter-layer distances. For example, layers 4 and 7 are three index-units apart. Visualize that matrix as in Figure 5.5.

Make four scatter plots of distance by similarity as in Figure 5.6. For an additional challenge, use a different color for markers from each column to visualize the layer the data values come from.

You can calculate the distance matrix by creating a 1 × 25 row vector of the numbers 0 through 24, then broadcast-subtracting that matrix from its transpose.

Figure 5.5: A matrix of inter-layer distances.

Because the cosine similarity and inter-layer distance matrices are symmetric — and because the diagonal elements of the similarity matrix are trivially 1 and therefore not useful here — you should extract only the upper-triangular elements of these matrices for the scatter plots in Figure 5.6.

Figure 5.6: Scatter plots showing the relationships between inter-layer distances and cosine similarities for four token positions. Each color corresponds to a different layer.

These results reveal that similarities wane with distance, and how different the calculations in the initial embeddings and final hidden states are.

A conclusion from Part 3 is that each transformer layer makes only minor adjustments to the embeddings vectors, which is why highly capable LLMs have dozens of transformer layers.

This is similar to Part 3 except here the similarities are calculated across token positions within each layer.

Task

Identify four linearly spaced layers between the first and the final, and calculate the cosine similarities across all pairs of hidden-state vectors within each of those layers. Visualize the results as in Figure 5.7.

The diagonals of these matrices — like the diagonals of all pairwise similarity matrices — are trivially 1.

Figure 5.7: Cosine similarities across all pairs of hidden-state vectors for four hidden layers. All four heatmaps use the same color scaling.

Unlike in Part 3 where the heatmaps looked similar to each other, these similarity matrices are more distinct, because the ways that the embeddings vectors relate to each other changes as those vectors go deeper into the model.

Also striking is the low similarities for the first token “A” — yet another demonstration of why the first token in a sequence should be excluded from analyses. Within the other token pairs, the similarity between “penguins” and “wise” appears to be relatively weak. I’ll leave the interpretation of that observation as an exercise to the reader.

The similarities are considerably lower for layer 0 (the embeddings layer), which makes sense: Before the first transformer, no information is shared across tokens. Are there other, perhaps more subtle, differences in inter-token similarity values across layers? That’s what you’ll investigate next.

Task

Repeat the inter-token similarity analysis but for all layers. Extract the non-redundant elements of the cosine similarity matrix, and visualize as a scatter plot with similarities on the y-axis and hidden layer index on the x-axis (Figure 5.8). Exclude the first token from the analysis.

When you have the code to reproduce Figure 5.8, try it again with the first token vector included.

Figure 5.8: Each marker depicts a cosine similarity value between a pair of hidden-state vectors (excluding the BOS token), for each layer. Small x-axis jitters were added to facilitate visualization, and the color of the dots is based on the layer index.

Overall, the results show a steep increase in similarity from the embeddings to the first transformer layer, because that’s the first stage in the model where contextual information is incorporated. Some of that context information is token-specific, but a lot of context is applied to all tokens in this short sequence, which globally increases the similarity values across the entire transformer stack.

Final observation for Part 4: the cosine similarities are all positive. In fact, most hidden-state vectors in GPT-style LLMs have positive cosine similarities, in part because the embeddings vectors are clustered into a hyper-conoid instead of being uniformly distributed in the embeddings space, and in part because shared context is added to all hidden-state vectors.

In theory, cosine similarity values can become positive if there are offsets in the vectors in absence of strong correlations (as shown in Project 8). However, the results from Part 2 of this project showed only minimal mean offsets compared to the vector values themselves.

The goal here is to follow-up on the descriptive analysis from Part 2, but in a larger dataset. Of course, “large” is a relative term — modern LLMs are trained are trillions of tokens — but here we’ll inspect hidden-state characteristics in around 2000 tokens from the book The Great Gatsby, which is at least slightly more representative than a bizarre short sentence about penguins.

Task

Import and tokenize the text of The Great Gatsby (see code from Chapter 2). Extract two non-overlapping segments of 1024 tokens. Push both sets of tokens through the model.

In a for-loop over hidden-state layers, extract the arithmetic and L_1 means, and standard deviations, of the embeddings vectors (reminder that the L_1 mean is ∑ |x|∕N whereas the arithmetic mean is ∑ x∕N). Visualize them in separate subplots, and against each other in a scatter plot, as in Figure 5.9. Exclude the first token in each sequence from the analysis.

Think about the possible implications of the mean offsets for inter-token cosine similarity analyses.

I find these plots very nice to look at, and I hope you agree.

Figure 5.9: Descriptive statistics of hidden-state vectors in a text snippet from The Great Gatsby. Each dot represents one token position’s hidden-state vector.

Here are several observations about these results:

  1. The initial embeddings vectors (hidden layer “0”) are small, in that their means and standard deviations are close to zero. Geometrically, the vectors are very close to the origin of the embeddings space.

  2. As the vectors pass through the transformer layers, their means and standard deviations increase. That is not trivial. While it is the case that each transformer layer adjusts the vectors, it is not trivial that the vectors spread out or stray further from the origin.

  3. The final hidden layer is very different from the others. As you know, this is partly because it’s the model’s last chance to adjust the vector before token selection, and partly because of the additional layerNorm.

  4. The mean offsets generally increase deeper into the model, although not for all tokens and the offsets are an order of magnitude smaller than the L_1 mean (that is, the magnitudes of the vector elements).

That final observation has implications for interpreting cosine similarity: The similarity between two vectors can be inflated if both vectors have large mean offsets, even in absence of a strong correlation. The relatively small mean offsets suggest that hidden-state vectors similarities reflect linear relationships with little specious inflation from global mean offsets.

day-mode Bookmark

Category selectivity via cosine similarity

In Chapter 3, you learned that cosine similarity of token embeddings can group semantically similar words. But the embeddings vectors change as they pass through the transformer blocks, leading to the question: Does cosine similarity continue to reflect semantic relations in hidden states? That’s what we’ll explore in this project.

The end result of Part 1 will be tensors of hidden-state vectors to analyze in Parts 2 and 3.

Task

Import GPT-2-small and its tokenizer. When importing the model, toggle the optional input argument output_hidden_states to be True. Switch the model to evaluation mode.

The online code file has a variable words that contains 34 words in three semantic categories (space, furniture, fruit). Confirm that the words are each encoded using only one token when they include a preceding space.

The code below shows how to import the model such that the hidden-state vectors are outputted by default:

model = AutoModelForCausalLM.from_pretrained(
’gpt2’,output_hidden_states=True)

To confirm that the words are encoded as single tokens, you can tokenize and print a list like the following (remember to tokenize using a preceding space).

galaxy is token [16161]
asteroid is token [27460]
comet is token [31733]

Now we need data. 34 words is small enough to run in one batch. But here’s the thing: LLMs aren’t optimized to process sequences with only one token, and it doesn’t make sense to process all tokens in one sequence (e.g., “galaxy asteroid comet cosmos…”). So instead, you can create short text sequences that are identical except for the final word.

Task

Create a batch of size 34 × 5 tokens, comprising 34 sequences of five tokens each. Each sequence is the sentence “The next word is X” where you replace “X” with each of the 34 words.

Push the tokens through the model. Use the code model(batch) without calling any additional input arguments. Confirm that the output of that model call still contains a hidden_states variable where each element in that variable is a tensor of size 34 × 5 × 768.

To confirm that all sequences are identical up to the final token, calculate and plot the variance across sequences for each token, as in Figure 5.10. The resulting scatter plot of token position (x-axis) by variance (y-axis) should be all zeros for the first four tokens, showing that all hidden states are indeed identical.

If you encounter errors when pushing the batched tokens through the model, remember that the data type must be PyTorch tensor of integers, which PyTorch calls torch.long.

Figure 5.10: Variances of hidden-state vectors across the 34 sequences for each token position. This visualization is used to sanity-check the code, because all hidden-state vectors should be identical until the 5^th token.

You didn’t need to include the output_hidden_states argument in the model call to get the hidden state vectors in the model output, because you toggled that option on when importing the model. Whether to switch the default behavior or add the additional input argument when running the model depends on personal preferences and on how often you need the hidden states exported.

The goal of Part 2 is to determine whether there are differences in cosine similarities within- vs. across-categories. Let’s begin by creating a matrix that labels each word-pair according to co-category membership.

Task

Extract the category labels in the words variable into a NumPy array. Make sure the array is a 34 × 1 column vector (not a dimensionless array). Create a “category matrix mask” as the upper-triangle of an outer product of the labels vector with itself (the outer product is a linear algebra operation that creates a matrix from a vector as vv^⊤). Visualize that matrix as in Figure 5.11.

Figure 5.11: The outer product of a category labels vector with itself forms a mask, with which you can identify which word pairs correspond to which category pairs.

That mask-matrix contains the products of word-pair labels, meaning that matrix elements with values 1, 4, and 9 are the within-category pairs (1^2 = 1, 2^2 = 4, 3^2 = 9), while elements with values 2, 3, and 6 are the cross-category pairs.

Warning: This approach to creating a within- and across-category mask-matrix works only for a small number of categories. For example, if you have four categories, then 2 × 2 = 4 × 1. In other words, after three categories, the label products are no longer unique and you’d need a different solution. I’ll introduce a different masking approach that can be extended to more categories (but doesn’t allow for specific category pairs) in Project 38.

Task

Choose one hidden-state layer (I used layer index 4). Extract the hidden states for the final token, normalize the vectors, and calculate the cosine similarity matrix as HH^⊤ as you learned in Chapter 3. Visualize that matrix as in Figure 5.12A and look for a block-diagonal structure that would indicate differences between within- vs. across-category similarities.

Extract all the within-category similarities into one vector, and all the across-category similarities into another vector. Then show histograms of those two groups as in Figure 5.12B, perform a two-samples t-test to compare the distributions, and calculate a Δ term as the difference between the means of the within- (w) and across-category (a) similarities (Δ = w −a).

Cosine similarity matrices are symmetric and their diagonals are trivially 1; the zeros on and below the diagonal of the mask-matrix ensure that only the non-redundant and non-trivial similarity values are included in the histograms.

Figure 5.12: Cosine similarities of hidden-state vectors across pairs of words. Because the words are sorted into categories, within-group similarities are visible as a block-diagonal structure in the matrix in Panel A. The mask-matrix was used to separate within- vs. across-category pairs to visualize their histograms in panel B.

The block-diagonal structure is visible in the cosine similarity matrix, although it’s less robust than the result you’ll find in Part 5. The histograms show that although there is some overlap in the similarity values, there is a non-zero Δ and a large t-value.

Also note that because of the differences in data sample counts, you need to extract the probability density estimates for the histograms, not the raw counts.

Final comment about the Δ term and its relation to the t-statistic: Δ is the numerator of the t-value, but that t-value is normalized by the pooled standard deviations and sample sizes. I’d like you to think about the impact of that normalization and when you might see a divergence between Δ and the t-statistic. I’ll write my interpretation at the end of the next part, and we’ll come back to this issue in Project 38.

The goal here is to explore how the results from Part 2 change over the hidden-state layers.

Task

In a for-loop over the hidden layers, repeat the analysis you developed in Part 2, and store the Δ and t-values for each layer in a NumPy array. Visualize the results as in Figure 5.13.

Figure 5.13: Category selectivity analysis over all hidden-state layers. Panel A shows the similarity averages, panel B shows their differences (the lengths of the vertical gray lines in panel A), panel C shows the t-values, and panel D shows the Δ-t relationship (each marker is a layer). The colors of the markers in Panels B-D indicate layer number, with purple indicating earlier layers and yellow indicating later layers.

The results in panel A show that cosine similarities drop slightly, then increase in deeper layers. The difference between the within- and across-category averages (the gray vertical dashed lines) is the Δ, which is larger in the earlier transformer layers.

On the other hand, the Δ and t-values are not completely redundant, as Panel D shows. What explains the difference?

The difference is that the normalization in the denominator of the t-value accounts for the widths of the distributions. In general, mean differences (the Δ term) are not statistically insightful without knowing the corresponding standard deviations. That is clearly the case in the final hidden layer, where the similarities are all extremely close to one, causing Δ to go towards zero. On the other hand, the t-value is still around 5, which is highly statistically significant (p < 10^(−7)), because the distributions are so narrow (not shown here but you can rerun Part 2 using the final layer).

The point is that non-normalized differences of distribution means can be difficult to interpret without normalizing the Δ by the standard deviations.

But why are all the cosine similarities so high — approaching 1 towards the end of the model?

Task

For each text sequence in the batch, find the maximum output logit of the final token, build a text sequence from the input tokens plus the max-logit token as the newly generated token, and print the texts.

Here are a few of the results:

The next word is galaxy. The next word is asteroid. The next word is comet.

Thus, with a few exceptions (e.g., “lamp” became “lampoon”; “bed” became “bedtime”), the model transformed those distinct words into a period, and that’s why the cosine similarities approached 1. On the other hand, the category selectivity remained statistically robust, so although the model consistently considered the period to be the most likely next token, it retained token-unique information, which would be used to guide subsequent token selections.

So far in this project, you’ve analyzed different words in an identical context. The rest of this project will involve the complement: identical words in different contexts.

The goal of Part 4 is to create a batch of token sequences where the final token is the same while the preceding tokens are different. You’ll use those data to continue exploring how embeddings vectors change as they pass through the transformers.

Task

Import and tokenize the text of The Great Gatsby. Find all instances of the tokens “ years”, “ garage”, and “ lawn” (note the leading spaces). Confirm that those are single-token words that appear 35, 24, and 27 times in the text. Create an 86×2 NumPy array containing the indices of the target words in the full book token sequence, and an integer label (“1” for years, “2” for garage, and “3” for lawn).

Create a batch of tokens that is 86×51, corresponding to 86 sequences, each comprising one of the three target tokens and their 50 preceding tokens. You can print out some of the token sequences to confirm that they have the same final words but different contexts.

You should find 89,268 tokens in the text, 8,150 of which are unique. The output below confirms the token indices and counts of the three targets.

 years is token [812] and appears 35 times. garage is token [15591] and appears 24 times.   lawn is token [21133] and appears 27 times.

When creating the batch, remember that it must be a PyTorch tensor of integers (torch.long).

In my code solutions file, I print out the final five tokens of each sequence. Here is a sample of them:

younger and more vulnerable years
since his New Haven years

’s three years …

this shadow of a garage
impatiently around the garage
so remarkable in the garage

…

a country of wide lawn
than forty acres of lawn
neighbour’s lawn

Thus, identical tokens with different local contexts (the macrocontext is the same for all tokens because they come from the same book).

Also notice that “garage” and “lawn” are semantically similar to each other, and are dissimilar to “years.”

Part 5: Within- and across-word similarities in one layer

Section titled “Part 5: Within- and across-word similarities in one layer”

Much of Part 5 is focused on reproducing analyses from earlier in this project, but be mindful that copy/pasted code might require adjustments.

Task

Run a forward pass on the batch of tokens. Confirm that the hidden states tensor for each layer is size 86 × 51 × 768.

Create a category mask-matrix as you did in Part 2. Then reproduce the cosine similarity matrix and distributions as you did in Part 2 (using data from layer 4), except here you create three groups: the within-word similarities, the across-word similarities involving years, and the across-word similarities for garage and lawn. Show the results as in Figure 5.14.

The online code file additionally visualizes the matrix-mask similar to Figure 5.11, although I don’t show the figure here.

The different categories have different sample sizes, so the histograms need to be calculated using densities instead of counts.

Figure 5.14: Similar to Figure 5.12 but using data from The Great Gatsby.

The block-diagonal clustering is visually much stronger here compared to the previous dataset. That’s not surprising considering the words are the same.

On the other hand, the similarities are clearly not all 1’s, so the vectors changed as they passed through the transformers. Visualizing that change is the main goal of Part 6.

Part 6: Laminar profiles of similarity distributions

Section titled “Part 6: Laminar profiles of similarity distributions”

Visualizing histograms is great for one layer, but presents a challenge for 12 layers and three distributions per layer. The solution here will be to create “tornado plots” (“tornado plot” is not an official data-visualization method, but I think you’ll agree with my nomenclature after seeing the results).

Task

In a for-loop over the hidden layers, repeat the analysis from Part 5, but use the same bin boundaries of .4 to 1 in 35 steps. The outputs of torch.histogram with density=True is normalized to bin width, but you should re-normalize it to probability by multiplying the density values by dx, which is the width of the bins.

Show the results in three heatmaps, one per category, as in Figure 5.15.

In these heatmaps, the rows (y-axis) correspond to hidden layers and the columns (x-axis) correspond to cosine similarity bins. Thus, the x-axis is the same as in Figure 5.14, and the color in Figure 5.15 corresponds to the heights in Figure 5.14.

Figure 5.15: Histograms of cosine similarities over hidden-state layers, separated by target word grouping.

These results show that the similarities are tightly clustered early in the model and then widen as the vectors pass deeper into the model. In other words, with each transformer layer, the vectors get pushed further away from their initial embeddings state. That’s particularly striking for the “within” category, where the words are all the same (the similarities are all exactly 1 in the embeddings layer).

Task

Your task here is simple: Rerun the notebook file using a larger variant of GPT-2 (large or xl).

There are three goals of Part 7:

  1. Make sure the code still works, e.g., if there are parameters or settings that you hard-coded for GPT-2-small that create errors or warning messages with the larger models. Hint: Pay attention to the rows of the “tornado plots” to check whether the bin boundaries are still appropriate.

  2. Check whether the visualization code that you wrote for GPT-2-small is still appropriate for the larger variants. In particular, consider the aesthetics choices like color limits, marker sizes, and axis tick labels.

  3. Observe whether the qualitative patterns of results are the same or different. For this purpose, it’s useful to take screenshots of the figures for side-by-side comparison.

Keep in mind that different models might use different variable naming conventions and data structures, have different weights and might show different results, etc. It is unreasonable to expect that any given code file must work for every LLM, although it seems reasonable to expect some code to work for different variants of the same model.

A more important point here is that understanding your code allows you to adapt it to new analyses, new datasets, and new models. The risk of running code you don’t understand (e.g., because it was copied from genAI, StackExchange, or GitHub) is that your knowledge is brittle and your code is not robust to changes. To be clear: I am not suggesting that you shouldn’t use code written by other humans or non-humans; instead, I encourage you to invest the time to understand the code regardless of who (or what) wrote it.

day-mode Bookmark

# 5.26 Project 26:
Current layer = previous layer + adjustments

I’ve mentioned several times that the transformer layer takes in a set of embeddings vectors, calculates adjustments to those vectors, and sends them onto the next transformer.

In this project, you’ll demonstrate that concept. And you’ll learn about hook functions — special methods on PyTorch models that allow you to measure and manipulate internal dynamics during the forward pass. (It’s also possible to manipulate the model dynamics during back-propagation, although I won’t discuss that in this book.)

A hook function is a regular Python function that gets “attached” to a specific component of a model. The declaration of the function looks like this:

def hook(module,input,output):
# code here...
return output
  • hook: This is the name of the function. It’s a good idea to give your hook functions meaningful names, especially when creating multiple hook functions.
  • module: This is a reference to the layer the hook is attached to. You’ll need this if you want to run downstream calculations from inside the hook function.
  • input: This is the input into the layer (module) the hook is attached to. You would use this variable, for example to access the hidden-state vectors before the current-layer transformations are applied.
  • output: This is the output of the layer. Most of the projects in this book involve accessing this variable for storage or manipulation. Warning: The input and output variables are sometimes PyTorch tensors and sometimes tuples, depending on the layer they are attached to. Check the variable type and size when writing your hook functions.
  • # code here: Hook function are special because they allow you to interact with the internal dynamics of the models, but they are not special in the sense that they are just regular Python functions. You can put any code you want in these functions! You’ll see lots of options in the rest of this book. Just keep in mind that the computation time of the hook function adds to the computation time of the model forward pass.
  • return: It is not necessary to return outputs. When using hook functions only to grab and store internal activations, you won’t need a return line. If you want to manipulate internal activations, you return the output variable. Internally, PyTorch will replace the layer’s calculated output with the returned variable. That’s how you causally manipulate internal calculations when running experiments. It’s also possible to manipulate the input into the layer, depending on details of how the hook is implanted; you’ll see this in later projects.

I realize that’s a lot of information for just a few lines of code, but hook functions are the key to unlocking LLM mysteries, and can be confusing at first.

Here’s the first hook function we’ll use in this project:

transf_out = {}

def hook(module,input,output):
transf_out[’data’] = output[0].detach()
# implant the hook

module_name = model.transformer.h[5] handle = module_name.register_forward_hook(hook)

The dictionary transf_out is initialized outside the hook function, and then populated inside the function. When that function is called, it will simply copy the output of the module (in this case, the transformer outputs) into the dictionary. The .detach method on a PyTorch tensor removes an object from the model’s computational graph. It’s a way of cleanly storing the numerical values without the links to the rest of the model that are used for gradient descent calculations.

That hook function has no return statement, so it’s only grabbing data without altering any calculations.

I then use the register_forward_hook method to implant that hook function into the 6^th transformer layer. The handle variable is a reference to the hook function, and you can run handle.remove() to remove the hook. You would remove hooks (1) while developing your code and you need to change the hook function, or (2) when running experiments and you want to add and remove hooks to access different parts of the model.

Because this hook function grabs the output of a transformer layer, you might think that it is redundant with the hidden-state vectors that you access using the output_hidden_states argument. Those two sets of results are only partially overlapping, as I explained at the beginning of this chapter and as you will empirically demonstrate.

A reminder of terminology from the beginning of this chapter: I’ll refer to the activations returned by this hook function as “transformer outputs” and the output of the model call in out.hidden_states as the “hidden states.”

Task

Import GPT-2-small, implant the hook function shown above into transformer layer 5, and tokenize the following text (it’s also printed in the online code file): Plants make fantastic pets because they don’t leave a mess after you feed them.

Call a forward pass and remove the hook.

Check that the shape of the tensor stored in the transf_out dictionary matches that of the output of the hidden states. Pick one embeddings dimension and make a scatter plot of the value in that dimension for both the hidden state and the transformer output (Figure 5.16). The data points should overlap because they both access the same data.

After the visual confirmation for one embeddings dimension, subtract the hidden-state tensor from the transformer output tensor, and confirm that the difference matrix is all zeros.

I know I’ve mentioned this several times already, but it’s important: The hidden states provided by the model’s output variable has 13 tensors (for GPT-2-small) while the hook function implanted into all the transformer layers provides 12 tensors. The discrepancy comes from the embeddings matrix, which is the first output of the model’s hidden states but is not a transformer layer.

Therefore, if you don’t get an exact match in Figure 5.16, check for indexing mismatches.

Figure 5.16: Visualization of the internal activations from one embeddings dimension across all tensors. The blue circles and red plus-signs overlap because — for this layer — the hidden states and transformer outputs are identical.

You can use the following code to confirm their identity: outputs.hidden_states[layi+1] - transf_out[’data’] That matrix should be all zeros.

Now you know how to implant a hook into one layer. But what if you want to hook multiple layers? Here’s how you do it:

def outerHook(layi):
def hook(module, input, output):
transf_out[f’layer_{layi}’]=output[0].detach()
return hook

handles = []

for layi in range(model.config.n_layer):
modname = model.transformer.h[layi]
h=modname.register_forward_hook(outerHook(layi))
handles.append(h)

The hook function is now embedded inside another “helper” function, which allows us to send a looping-index variable into the hook function. Notice that the return hook line is part of the outerHook function, not the hook function itself. In other words, the outerHook function creates and returns a hook function.

The for-loop implants the same hook function into each layer, while changing the value of layeri. The upshot of that code is one hook function per transformer layer that will save a layer-specific key into the transf_out dictionary.

Task

Run the hook-generating code block and call the model forward pass again. Then remove all the hooks. Check the keys of the transf_out dictionary, and the size of the data stored in one of the items.

In a for-loop over all layers, subtract the hooked transformer outputs from the corresponding hidden-state tensor, and store the norm of that difference matrix. Show the results in a scatter plot as in Figure 5.17. Matrix difference norms of zero indicate that the hidden states and hooked transformer outputs are identical.

Find the final layerNorm layer in the transformer module (hint: “layerNorm final” is abbreviated to ln_f) and apply that transformation to the final hooked transformer output. Then subtract that result from the final hidden states tensor and confirm that their difference matrix is all zeros.

After running the forward pass, you should get the following keys in variable transf_out, with the size of one layer.

dict_keys([’layer_0’, ’layer_1’, ’layer_2’,
’layer_3’, ’layer_4’, ’layer_5’,
’layer_6’, ’layer_7’, ’layer_8’,
’layer_9’, ’layer_10’, ’layer_11’])

transf_out[’layer_3’] has size:   torch.Size([1, 17, 768])

The size of the transformer output corresponds to one sequence of 17 tokens, and an embeddings dimensionality of 768.

Figure 5.17: Matrix norms of the difference matrices between the hidden states and the transformer outputs. All but one of the norms are zero because the second through penultimate hidden states are the same as the hooked transformer outputs.

The scatter plot of difference matrix norms is all zeros except for the last hidden layer, which has a norm of just under 1500. The following code will produce the zeros matrix:

pre_ln = transf_out[’layer_11’] ln_final = model.transformer.ln_f(pre_ln) outputs.hidden_states[12] - ln_final

The important take-home here is the demonstration of a nuance I’ve mentioned a few times so far: the hidden_states variable that is provided by the model output is the output of each transformer layer — except for the final layer, which is the hidden state normalized by the final layerNorm.

Part 3: Hooking attention and MLP adjustments

Section titled “Part 3: Hooking attention and MLP adjustments”

Hook functions can be implanted into any module in the model, including inside the transformer layer. You’ll learn more about the mechanisms and algorithms inside the attention and MLP blocks in the next two chapters; for this project, it is sufficient to know that these two blocks calculate the context- and world-knowledge-based adjustments that modify the hidden-state vectors.

The goal of Part 3 is to hook those two blocks and see how they relate to each other. That will also provide the data you’ll need to demonstrate that the output of transformer L equals the output of transformer L − 1 plus the adjustments.

Task

Write two hook functions to grab the projections from the attention and MLP blocks. Pick one layer to implant into (I used transformer layer 10). There are several modules within the attention block; implant the hooks into the output projections attn.c_proj and mlp.c_proj. These are the “projections” (the adjustments to the hidden-state vectors) after the internal calculations have been completed.

Do not assign an output to the register_forward_hook function. That has no implications for the functioning of the hook, but it prevents you from being able to remove the hook once it’s attached. This will be relevant later in the project.

Run a forward pass to trigger the two hook functions and check the sizes of the activations matrices.

Because this task involves implanting two separate hooks in the model, it’s a good idea to give the hook functions different names. For example, here’s my attention hook function:

def hook_att(module,input,output):
activations[’attn’] = output.detach()

Notice the difference in how I captured the output variable: The hook into the transformer layer used output[0] while the hook into the attention block used output. The transformer layer output is a tuple whereas the attention and MLP outputs are tensors. Same variable name and positional argument, but different variable type. I know it’s confusing, but you’ll get the hang of it with practice.

The code output below shows the sizes of the matrices, which are the same as the sizes of the hidden states (batch × tokens × embeddings-dimension). That’s not surprising: these attention and MLP vectors are adjustments to the hidden-state vectors, so the shapes need to match.

Here are the keys in “activations”:   dict_keys([’attn’, ’mlp’])

activations[’attn’] has size:   torch.Size([1, 17, 768])

activations[’mlp’] has size:   torch.Size([1, 17, 768])

Are the attention and MLP adjustments related to each other? We can explore this by visualizing and correlating.

Task

In a for-loop over the tokens in the sequence, calculate the correlation coefficient between the attention and MLP adjustment vectors. Calculate the correlation twice: using the Pearson correlation and using the Spearman correlation. You can get those two correlation functions from the scipy.stats library.

Show the resulting token sequence of correlation coefficients in a scatter plot as in Figure 5.18A. Then show a scatter plot of those adjustments for one token as in Figure 5.18B (I plotted the final token).

You can see from the scatter plot in panel B that the attention and MLP adjustments are sparse in that most values are close to zero while a small number of values are relatively large. That’s an important feature for LLM mechanisms, but it presents challenges for statistical analyses, because a small number of extreme values (a.k.a. outliers) can skew the results.

Figure 5.18: Relationships between the attention and MLP adjustments from one transformer layer, for each token in the sequence.

The Spearman correlation is calculated by applying the Pearson correlation to rank-transformed data, and the rank-transform removes outliers. When the data are roughly normally distributed and without outliers, then the Pearson and Spearman correlations are nearly identical. In contrast, differences between the two analyses indicate the presence of outliers or non-normal distributions.

Overall, these results indicate a weak relationship between attention and MLP adjustments. This figure shows results only from a small set of tokens, but it is a generalizable observation.

Part 4: Reconstructing hidden state L from L-1

Section titled “Part 4: Reconstructing hidden state L from L-1”

And now to demonstrate that the output of transformer layer L is the output from layer L − 1 plus the attention and MLP adjustments.

Task

Using the hidden states and hooked attention and MLP activations that you obtained in Part 3, reconstruct the hidden-state vectors from one layer based on vectors from the previous layer plus the adjustments, by translating the following equation into code:

HSL=HSL−1+attnL+MLPL(5.1)HS_L = HS_{L-1} + \text{attn}_L + \text{MLP}_L \tag{5.1}

Demonstrate the reconstruction accuracy by subtracting the variables for the two sides of the equation, and evaluating whether the norm of the difference vector is zero (within precision-error tolerance).

Then visualize the results as in Figure 5.19.

Note: This equation is accurate in terms of code implementation but oversimplifies the actual calculations. I’ll get back to this after discussing the results.

I started this code solution by confirming that the sizes of all the tensors match:

Attention size: torch.Size([1, 17, 768])
MLP size: torch.Size([1, 17, 768])

Hidden state pre: torch.Size([1, 17, 768]) Hidden state pst: torch.Size([1, 17, 768])

Demonstrating the reconstruction involves creating variables for the two sides of the equation:

hs_pre = outputs.hidden_states[layer2hook] hs_pst = outputs.hidden_states[layer2hook+1] adj = activations[’attn’] + activations[’mlp’] recon = hs_pre + adj

You can then subtract hs_pst from recon to find that the difference vector is all zeros.

Figure 5.19: Scatter plots showing the relationship between hidden state vectors from two sequential layers (panel A), the attention and MLP adjustments (panel B), and that the previous hidden-state vectors plus their transformer-calculated adjustments equals the current hidden-state vectors (panel C).

These results confirm that the hidden-state vectors pass through the model and pick up adjustments at each transformer. The adjustments calculated by each transformer are often relatively small (note the strong correlation in panel A), which is why dozens of transformers are needed to endow LLMs with such impressive linguistic capabilities.

Also note that the reconstruction would fail for the final hidden state because, as you learned in Part 2, that last hidden state also contains a layerNorm.

Theory vs. implementation. The simple equation that you demonstrated in the code (Equation 5.1) is slightly more nuanced in theory. In fact, the full equation would be as follows.

HSL=HSL−1+MLPL(LN2L(HSL−1+attnL(LN1L(HSL−1))))(5.2)HS_L = HS_{L-1} + \text{MLP}_L(\text{LN}_2^L(HS_{L-1} + \text{attn}_L(\text{LN}_1^L(HS_{L-1})))) \tag{5.2}

where LN_L1 refers to the first (pre-attention) layerNorm of transformer layer L. In other words, the hidden-state (HS_(L−1)) vectors are normalized, attention adjustments are added on, normalized again, and finally the MLP adjustments are added on. That’s the math of how you get to transformer layer L from transformer layer L − 1.

But why did you still get perfect reconstruction of layer L + 1 with the simpler Equation 5.1? The reason is that the layerNorms and adjustments are already incorporated into the outputs of the attention and MLP blocks. In other words, Equation 5.2 captures the flow of information in the model in terms of the math, while Equation 5.1 captures the flow of information in terms of the PyTorch code implementation.

The last part of this project is designed to teach you more about creating, working with, and removing hook functions.

Task

Confirm that the current value of activations[’attn’] has size 1×17×768. Run a different token sequence through the model (e.g., the sentence “I like corn.”) and check the size of the activations dictionary again. What happened to the initial activations?

The activations were overwritten. That means that each time you call the model, the hook function activates and the data are overwritten. In some situations, that is desirable behavior. But there will be other situations where you want to store activations across multiple model calls without losing data.

I’ll teach you how to do that, but first remove the hook function… oh wait — I specifically told you not to store a handle variable, which means it’s no longer possible to access and remove that hook via its handle. Technically, it is still possible to find and remove the hook by iteratively searching each component of the model for ._forward_hooks methods, but that doesn’t work for all types of hooks — and it’s just an ugly solution.

In this case, the easiest solution is to re-import the GPT-2 model. Fortunately, the model has already been downloaded (either locally or to your Google-Colab runtime disk), so re-importing it into Python is quick.

Needless to say, re-importing an LLM each time you want to modify or remove a hook function is not exactly elegant coding. This is why storing the handles to the hook functions is always good idea, especially when developing and debugging your code.

Task

Re-import the GPT-2 model. Then create a new hook function into the MLP projection of one transformer (with a handle variable). Initialize the activations variable as a list (not as a dictionary) and use the append method on that list to store new activations inside the hook function.

Test your new hook by calling the model multiple times using different text sequences of different lengths. Confirm that the variable activations is a list of tensors, not a dictionary, and that the list grows by one tensor each time the model is called.

I called the model four times with different token sequences, and printed out the following results:

“activations” is a <class ’list’>     that contains 4 elements

Element 0 has shape torch.Size([1, 4, 768]) Element 1 has shape torch.Size([1, 5, 768]) Element 2 has shape torch.Size([1, 14, 768]) Element 3 has shape torch.Size([1, 7, 768])

The upshot is this: hook functions are extremely powerful and versatile tools for exploring LLM internal dynamics. They can be confusing to code and tricky to debug, but you’ll develop mastery of hook functions over the next several chapters.

day-mode Bookmark

Impact of layer-specific noise and scaling

How robust are the transformer outputs to noise and scaling? That’s what you’ll explore in this project.

You will manipulate the transformer outputs, either by adding noise or by scaling down, and you will measure the impact of those manipulations on output logits and next-token selection.

In the previous project you learned how to use hooks to measure internal activations, and here you’ll learn how to use the same functions to manipulate activations.

GPU This project can be done on a CPU, but I recommend using a GPU if you have one available. If you’re running the project on a CPU, consider using a smaller variant of GPT-2.

Part 1: Model, tokens, and clean activations

Section titled “Part 1: Model, tokens, and clean activations”

Task

Import GPT-2-large and its tokenizer, and set the flag for outputting hidden states to True. Switch the model to eval mode and optionally move it to the GPU. Report the number of transformer layers based on information available in model.config.

Tokenize the sentence “Pay no attention to that man behind the”. Do you know what word should come next?

It’s “curtain.” Find the token index for the word “ curtain” (with leading space), and print out the tokenization.

Here’s the tokenization:

Token 19197 is “Pay” Token   645 is ” no” Token  3241 is ” attention” Token   284 is ” to” Token   326 is ” that” Token   582 is ” man” Token  2157 is ” behind” Token   262 is ” the”

This is, of course, a famous quote from the movie Wizard of Oz. Later in the project, you will determine whether adding noise to the hidden states interferes with the model’s ability to identify “curtain” as the next token.

Task

Run a forward pass to get model outputs. Name the output variable outputs_clean. These data will be used as a “clean” baseline reference against which to compare the impact of the manipulations.

Find and print the token with the largest output logit, and store the log-softmax probability of the logit for “ curtain”.

Show all logits in a scatter plot, and indicate the maximum using dashed lines, as in Figure 5.20.

As expected, the max-logit index from the final sequence position corresponds to the token “ curtain” and its softmax probability is 38.84%. Remember that the probability of the log-softmax is obtained by undoing the logarithm through the natural exponential.

Figure 5.20: Log softmax probabilities for the final token in the sequence. The maximum value corresponds to the word “curtain.”

The figure shows that there are several other tokens with high probabilities. If you are curious, you can additionally explore those using the PyTorch function topk as you learned in Chapter 4.

Creating a hook function to interfere with internal activations is straightforward: implement the interference and return the output.

An example interference-hook function looks like this:

def hook(module,input,output):
# unpack tuple
hidden, *rest = output
# change the hidden states
hidden += 1.
# reconstruct output
output = tuple([hidden]+rest)
return output

baselayer = model.transformer.h[10] h = baselayer.register_forward_hook(hook)

That hook function adds the number 1 to all hidden state elements in layer 10. Of course, in practice you’d apply a more interesting manipulation than shift-by-1.

That example hard-coded the manipulation to layer 10. A better approach is to use the embedded-function setup you learned about in Part 2 of Project 26, and additionally include an if-statement so that the actual manipulation happens only if the current layer equals a target layer that you can specify with a variable.

def implant_hook(layer_number):
def hook(module,input,output):
# only change one layer
if layer_number == layer2change:
# code here
return output
return hook

Now the manipulation is applied only when the current layer equals layer2change. That’s a variable you can specify, e.g., before calling the model inside a for-loop over the transformer layers. When that conditional is false, no manipulations are applied.

An alternative approach is to implant a hook function only into the layer you want to manipulate, removing and re-implanting hooks at each iteration inside a for-loop over the layers. You’ll learn that approach in later projects.

Task

Write a hook function that adds noise to the transformer output vectors. Give the hook functions interpretable names, like implant_noise_hook and noise_hook. The noise should be normally distributed random numbers with a standard deviation equal to half that of the layer-specific hidden-state vectors. Implant the hook into all transformer layers while allowing only one layer at a time to be manipulated.

Run the tokens through the model while adding noise only to layer 15. Name the output variable outputs_noise to differentiate it from the “clean” model you ran in Part 1.

In a for-loop over the hidden-state layers, calculate and visualize the matrix norm of the difference of the hidden-state activations between the two versions of the model. Include a vertical dashed line to indicate the manipulated layer. See Figure 5.21.

Finally, calculate and print the predicted new token. Use deterministic token selection.

To calculate the standard deviation of the added noise, you need to determine the standard deviation of the hidden-state vectors.

h_std = hidden.std() / 2 noise = torch.randn_like(hidden)*h_std

Thus, the noise level (standard deviation) is unique to each layer, as determined by the statistical characteristics in that layer.

Once you’ve implanted the hook, manipulating one layer works like this:

layer2noise = 15

with torch.no_grad():
outputs_noise = model(tokens.to(device))

By the way, it wasn’t actually necessary to get the clean outputs from a model with no hook functions. You could set the layer2noise variable to be any number other than a valid layer index to get non-manipulated outputs, e.g., layer2noise=4000.

The plot of the manipulated vs. clean hidden-state norms shows zeros before the manipulated layer — as expected. And it shows non-zero differences at and after the manipulated layer — also as expected. Visualizations like this are good manipulation checks that the code works correctly.

Figure 5.21: Visualizing a manipulation check: The hidden-state activations prior to the manipulated layer (indicated with a vertical dashed line) are the same as a non-manipulated version of the model. Introducing noise in layer 16 propagates forward to subsequent layers.

Curiously, the layers after the manipulated layer continue to show differences. Why does that happen?

Each transformer layer takes the hidden-state vectors from the previous layer, so manipulating one layer impacts all the downstream layers. On the other hand, information only flows forward during inference, so the clean and noised models are identical before the manipulated layer.

If you see a misalignment between the vertical dashed line (the manipulated layer) and the first non-zero difference norm, check the indexing of the hidden-state layers, recalling that the first transformer block is the second hidden layer.

Injecting noise into one transformer output impacted more than just the numerical matrix difference norm; the noise propagated forwards until the output logits, and caused a measurable impact on token selection:

 Clean model: next token: ” curtain” with p = 38.84%. Noised model: next token: ” x” with p = 4.56%.

Due to the random nature of the noise, you will likely get a different next token. You can run the code a few times to get a feel for the variability.

The goal here is to repeat and extend the analysis, and to examine the impact of interfering with each layer.

Task

In a for-loop over all transformer layers, run the same tokens through the model but change the value of the layer2noise variable at each iteration. To be clear: Each iteration in the for-loop involves directly manipulating only one layer, and all layers have their activations manipulated in different loop iterations. Calculate the log-softmax probability of the final token, and store the log-softmax of the target token (“ curtain”) and of the token with the largest logit.

Visualize the results as in Figure 5.22 (note the matching y-axis limits). Print out the predicted text after noisifiying each layer, e.g., L27: Pay no attention to that man behind the“ next”

Finally, remove all the hooks from the model. If you installed the hooks without saving the handles, you’ll need to re-import the model for Part 4.

There are 36 outputs corresponding to manipulating 36 transformer layers. Below are a few of the results, with the initial number indicating the layer.

 0 Pay no attention to that man behind the curtain 10 Pay no attention to that man behind the I 20 Pay no attention to that man behind the others 30 Pay no attention to that man behind the sign 35 Pay no attention to that man behind the desk

Run the for-loop a few times to observe how the results change. The random noise leads to different tokens being more strongly activated on each run.

Figure 5.22 below shows the impact of the layer-specific noise.

Figure 5.22: Visualizing the impact of adding noise into each layer (x-axis; only one layer is manipulated per run) on the final model outputs (y-axis; green dashed line is the log-softmax value from the clean model). Panel A shows the log-softmax probability for the target token, and panel B shows the maximum log-softmax probability.

Again, your results will look slightly different due to random number generation, but the overall pattern should be the same: minimal impact when noise is applied early or late in the model. When the noise is added early, the model has many more transformer layers to compensate and realign; and when the noise is added towards the end, the transformations are mostly finalized, and thus added noise has less impact on next-token selection.

Part 4 is similar to Part 3, except that instead of adding noise, you will dampen the activations by scalar-multiplying. Use the in-place method hidden.mul_(.5) to multiply all elements in the PyTorch tensor hidden by .5.

Task

Create and implant a new hook function into all layers. It should be nearly the same as in Part 3 but scale the transformer outputs down by a factor of 2 instead of adding noise. Use the variable name layer2scale to select which layer is manipulated.

Test the model by scaling down layer 15 and visualizing the norm of the hidden-state difference matrices as in Figure 5.23.

Then, repeat the for-loop, analyses, and visualizations from Part 3 (Figure 5.24). Be mindful of variables that were overwritten or given different names.

Figure 5.23: Manipulation check: The y-axis is the norm of the difference between the manipulated model and the “clean” model, the x-axis is the hidden-state layer, and the vertical dashed line indicates the layer that was scaled down.

Sanity-checking your code by visualizations like Figure 5.23 (that is, changes where you expect them and no changes where you don’t) are very useful when developing and debugging your code.

Scaling down the transformer outputs does impact the final output logits, but to a lesser extent compared to adding noise. For example, compare the y-axis limits of Figures 5.22 and 5.24.

Figure 5.24: Impact of global down-scaling of hidden-state vectors on final logits.

In fact, you can set the y-axis limit here to match that of Figure 5.22 from Part 3, and you’ll see that dampening had almost a negligible impact. Indeed, all of the max-logit tokens were either “curtain” or “counter.”

On the other hand, a magnitude of .5 global scaling is not directly comparable to adding .5 standard deviations of noise. I don’t want you to conclude from this project that adding noise is impactful and global down-scaling is not; instead, the conclusions are that (1) subtle manipulations can have cumulative downstream impacts, and (2) hook functions are a powerful and versatile way both to measure and to manipulate LLMs.

day-mode Bookmark

Effective dimensionality of hidden layers

Consider a flat sheet of paper. It is technically three-dimensional, but it has only two effective dimensions: height and width. The thickness of the paper is multiple orders of magnitude smaller than the other two dimensions, and carries no information.

Thus, we can consider the 3D paper to have an effective dimensionality of 2D.

Figure 5.25 illustrates this idea geometrically. Panel A shows dots that all lie exactly on a line in a 2D graph (in linear algebra terminology, the data are in a 1-dimensional subspace embedded in R^2).

Figure 5.25: Conceptual illustration of effective dimensionality. The dots in panel A are exactly in a 1D subspace (a straight line). The dots in panel B deviate from that subspace by a small amount. If we assume that those deviations are meaningless noise, then we can consider the dataset’s effective dimensionality to be 1.

Panel B is more interesting — and more ambiguous. The dots do not lie exactly on the line. What is the effective dimensionality of that dataset?

The answer depends on our assumptions. If we assume that the minor divergences off the line are pure noise — for example, tiny random measurement error from imperfect sensors — then we can consider the effective dimensionality to be 1. On the other hand, if we assume that the small divergences are meaningful, then the effective dimensionality is 2.

In practical data analyses, we choose some threshold to consider fluctuations negligible. For example, we might say that a dimension in the data space needs to account for at least 1% of the total variability in the data to be an “effective” dimension. Going back to the analogy of the piece of paper: We exclude the thickness from our dimensionality count because it accounts for less than 1% of the volume.

The singular value decomposition (SVD) (and its close cousin, the eigendecomposition) is one of the most important operations in applied mathematics with applications in statistics (e.g., principal components analysis), classifiers, image compression, signal processing, computational sciences, and economics.

The SVD represents a data matrix as the product of three other matrices that reveal important yet hidden patterns in the data matrix. A full explanation of the mechanics, interpretations, numerical methods, and applications of the SVD is outside the scope of this book, but I’ll provide brief explanations of the SVD here and in the next project.

For this project, we are concerned with the singular values of the matrix, which are indicated using σ (Greek letter “sigma”). An M × N sized matrix has min(M,N) singular values, and they encode the “importance” or the “thickness” of each dimension in the data space. The sum of all squared singular values is the total variability in the data.

Back to the paper analogy: the SVD of a US-standard piece of paper would have singular values of [11, 8, .005] corresponding to its physical dimensions in inches. To calculate the percent “variance” of each dimension, divide by the sum of all squared singular values:

σ~i2=100σi2∑σ2(5.3)\tilde{\sigma}_i^2 = 100 \frac{\sigma_i^2}{\sum \sigma^2} \tag{5.3}

That works out to 65.4%, 34.59%, and 0.0000135%. Hence, the paper is 3D in a strict mathematical sense but we can consider its effective dimensionality to be 2D.

In this project, you will extract the singular values of the hidden states, convert to percent variability explained, and count the number of components it takes to explain 95% of the variability.

(There is a related measure of effective dimensionality called the “participation ratio,” which you’ll learn about in Project 43.)

GPU You can run this project on a CPU, but a GPU will cut the calculation time down from minutes to seconds. The GPU will be particularly helpful in Part 4.

Part 1: Logits from real and shuffled token sequences

Section titled “Part 1: Logits from real and shuffled token sequences”

The goal of Part 1 is create a dataset that you can analyze.

This project involves using GPT-2-xl. However, if you find yourself spending a lot of time waiting for calculations to finish, you might want to use GPT-2-small to develop and debug the code, then switch to GPT-2-xl.

Task

Import GPT-2-xl and its tokenizer. Toggle the model into eval mode and move it to the GPU. Define a variable that encodes the maximum context window size, which is the maximum number of tokens the model can process at once. Hint: check model.config.

Import and tokenize the text for Through the Looking Glass from gutenberg.org (see Chapter 2). Extract a max-token-sequence-length vector of tokens starting in the middle of the book. Print out the tokens and enjoy reading a snippet of Alice’s adventures :)

Create a copy of the token sequence variable with randomly shuffled tokens. Thus, you should now have two PyTorch tensors of tokens to push through the model: One tensor is real tokens from the text, and the other is the same tokens but in a randomly shuffled order. Print those tokens.

The intact token sequence begins with Carroll’s trademark absurdity:

they lived at the bottom of a well-”

“What did they live on?” said Alice, who always took a great interest in questions of eating and drinking.

“They lived on treacle,” said the Dormouse, after thinking a minute or two.

There are 1024 tokens in the sequence, corresponding to the maximum sequence length of GPT-2.

The shuffled tokens will be different each time you run the code, but will look something like this:

as fancy; that nott a.

she wellAlice and be cup nothing_ Alice?
draw Hare, what well Alice to" these about ill

You might see a question-mark-in-a-diamond character. That corresponds to formatting characters that span multiple tokens, and thus randomizing the tokens makes them render incorrectly.

The shuffled tokens will serve as a baseline reference for the analyses, to evaluate whether the dimensionality findings are the result of tokens per se, or their temporal sequence patterns.

Task

Push both tensors of tokens through the model in separate runs to create separate output variables for the real and shuffled tokens. Export the hidden-state vectors, and check the sizes of the hidden-state activations. Determine the number of singular values in each hidden-state activations matrix based on my description of the SVD at the outset of this project.

Transform the output logits to log-softmax. Thus far in the book, I’ve been using the PyTorch function log_softmax. Here, use the method .log_softmax.

Find and store the maximum log-softmax value for each of 1024 tokens, separately for the real and shuffled token sequences. Then visualize the histograms of those max-log-softmax values as in Figure 5.26.

Each hidden-state tensor has size 1 × 1024 × 1600, corresponding to 1 sequence, 1024 tokens, and 1600 embeddings dimensions. You need to squeeze out the first (batch) dimension because the SVD is defined only for matrices. The number of singular values is the smaller of the two dimensions, meaning there are 1024 σ values for each hidden-state matrix. The question we’ll answer later in this project is how many of those are above an “effective” threshold.

Figure 5.26: Distributions of the largest log-softmax values.

Figure 5.26 shows the distributions of maximal log-softmax values. Even though the tokens are identical in both cases, the model was clearly more “confident” (higher concentration of larger probabilities) for the real compared to shuffled tokens. That’s neat to demonstrate, though not very surprising: LLMs are autoregressive prediction engines that learn patterns in token sequences. When you randomize the token sequences, the statistical patterns are destroyed, and thus the model has difficulties generating next-token predictions.

By the way, it is also possible to do one forward pass with both sequences in a single batch. When developing this project, I found it easier to have separate variable names to minimize risk of confusion, but that’s a matter of personal preference.

Part 2: Effective dimensionality in one layer (NumPy)

Section titled “Part 2: Effective dimensionality in one layer (NumPy)”

The goal of Part 2 is to write code to calculate the effective dimensionality of the hidden-state vectors for one layer. You’ll then expand that to all hidden layers in the next part.

Use NumPy (not PyTorch) for this part.

Task

Choose one hidden layer to focus on (I used layer 10). Extract the activations from that layer, and convert the PyTorch tensor into a 2D NumPy array. NumPy isn’t designed to operate on GPUs, so you need to transfer the hidden-state tensors to the CPU. You can focus only on the real-ordered tokens here; we’ll use the shuffled tokens later.

Mean-center the data token-wise, such that the mean of each hidden-state vector is zero. Calculate the SVD to get a vector of singular values. Transform the raw singular values to percent variance explained using Equation 5.3 (the singular values squared, divided by the sum of the squared singular values), and then to cumulative percent explained.

Visualize the percent variance explained and cumulative variance explained as in Figure 5.27. The dashed gray lines indicate the total variance explained by the first 50 components.

The reason for doing these analyses in NumPy is to compare against the PyTorch syntax in the next part. Some functions are nearly identical in PyTorch and NumPy, while others have different names or input formatting; being able to translate across the two libraries is a good skill.

The reason for mean-centering is that the first principal component of a dataset points towards the mean offset rather than meaningful covariance in the data. Mean-centering focuses the analysis on the patterns in the data, rather than on the global shifts. I’ll have more to say about that in the next project.

Figure 5.27: Singular value spectrum of hidden-state vectors. Panel A shows the spectrum normalized to percent variance explained, and panel B shows the cumulative percent variance explained. The first 50 components explains around 88% of the variance. There are 1024 components in total; I’ve clipped the x-axis to highlight the first 60.

The figure shows a typical pattern of singular values: steep drop in the first few components, and then flattening towards zero.

By the way, it is no accident that the largest components are on the left side of the plot: Numerical software programs including NumPy (and MATLAB, C, Julia, R, etc.) will return singular values sorted descending. This is not always the case for other decompositions such as eigendecomposition or independent components analysis.

Terminology: In statistics, the singular value spectrum (that is, the scatter plot of sorted singular values) is also called a “scree plot,” named after the rubble at the bottom of a cliff.

Task

Calculate the “effective dimensionality” as the number of components it takes to account for 95% of the total variability.

Why a threshold of 95%? Why not 99% or 97.231%? Thresholds in data science are often somewhat arbitrary. A related source of ambiguity is whether to consider the “number of components” to be the count closest to but not exceeding the threshold, or the number of components that first exceeds the threshold. Depending on that choice, you’ll get either 149 components (94.97% variance) or 150 components (95.01% variance). That said, taking the first component that exceeds the threshold is better to avoid errors if the first component already exceeds the threshold.

When thresholds are arbitrary, best practice is to be clear and consistent. It’s also a good idea to check the results using several thresholds to determine whether the overall pattern of results is robust to the exact choice of threshold.

Part 3: Laminar profile of effective dimensionality (PyTorch)

Section titled “Part 3: Laminar profile of effective dimensionality (PyTorch)”

Why bother measuring effective dimensionality? What does it mean and what implications does it have for understanding LLMs?

One way to interpret the singular value spectrum is as an indicator of the “spaciousness” of calculations and representations: A simple system has few “moving parts” and therefore most of its variance is captured by a small number of components. In contrast, a complex system has more distinct moving parts and subsystems, and therefore its variance is distributed over multiple separate components. This is diagrammed in Figure 5.28.

Figure 5.28: Diagrams of scree plots of simple and complex systems. A simple system is dominated by one pattern, which manifests in an SVD as one large component with the rest of the spectrum being small and indistinguishable. In contrast, a complex system has many patterns, thus producing a singular value spectrum with multiple differentiable components.

In the figure, I use the terms “simple” and “complex” in apology quotes, because an SVD alone should not be used to categorize systems as simple or complex. On the other hand, it is the case that complex systems with multiple dynamical and independent subsystems will have a singular value spectrum that decays more gradually.

In the context of LLM interpretability, the effective dimensionality provides insights into the richness of the representations of the text. As you’ll soon observe, the effective dimensionalities of the hidden-state vectors change throughout the transformer stack, which reflect their modifications due to additional information about context and learned world knowledge.

The two goals of Part 3 are to translate the NumPy analysis into PyTorch including running the analysis on the GPU, and examining effective dimensionality as a function of depth into the model.

Task

In a for-loop over the 49 hidden-state layers, calculate the effective dimensionality as you did in Part 2, except modify the code to use PyTorch instead of NumPy. Also calculate and store the matrix rank of each hidden-states matrix (the “rank” of a matrix is the number of linearly independent columns in the matrix). Leave the data on the GPU except for the final results for visualization (Matplotlib needs the data on the CPU).

Repeat the analysis for the shuffled tokens. You can store these results in a 49 × 2 PyTorch tensor of integers containing the number of components to account for 95% variability in each hidden layer.

Visualize the matrix ranks as in Figure 5.29.

Calculate the percent of maximum possible dimensionality as the effective dimensionality count divided by the matrix rank for each hidden-state layer. Visualize the results as in Figure 5.30. Note the two y-axis labels: the left axis and the markers shows effective dimensionality as counts, while the right axis and the lines shows effective dimensionality as percent of maximum dimensionality (rank).

Note that by “maximum possible dimensionality,” I am here referring to the constraint provided by the data as measured by the observed matrix rank, not the theoretical maximum dimensionality in a matrix (which is the smaller of M or N).

The matrix ranks of most layers is 1023 — mean-centering removes one rank point. The first three transformer layers have slightly lower ranks.

Figure 5.29: Ranks of hidden-state matrices.

A hint for accessing the right axis in Figure 5.30: Use the .twinx() method on the axis object.

Figure 5.30: Effective dimensionality analysis for real and shuffled tokens. The left axis and markers show the raw dimension count (number of dimensions to explain 95% variability), while the right axis and lines converts the dimensionality to percent of maximum possible dimensionality.

Here are some discussion points:

  • The raw number of components is difficult to interpret on its own. For example, a result of “200” is large if the maximum possible dimensionality is 201, but is small if the maximum possible dimensionality is 20,000.
  • Maximum possible dimensionality is itself tricky to calculate. Indeed, the matrix rank is calculated in literally the same way as effective dimensionality except the threshold is much lower. That is, the rank of a matrix is calculated as the number of singular values that exceeds some threshold, where the threshold is defined as some small fraction of the matrix norm.
  • For these reasons, scaling the effective dimensionality count by the matrix rank (instead of the maximum possible rank) is also difficult to interpret: It filters out the completely empty dimensions (with zero-valued singular values) and thus reflects the number of dimensions that have small-but-nonzero volume. In general, it’s best to report effective dimensionality as raw count or scaled by the maximum possible rank, but it’s also important to understand the differences among maximum possible rank, estimated rank, and effective dimensionality.

Because of the differences in matrix ranks, the lines and markers in Figure 5.30 may not perfectly coincide. However, with this LLM and this dataset, that difference is very small and limited to the first few hidden-state layers. You’ll see qualitative divergences in the next two parts.

Task

Rerun the analysis using different thresholds, e.g., 90% and 99%. Save screenshots of the figures for visual comparison. Of course, changing the threshold will change the results numerically; the question is whether the qualitative patterns remain.

You’ll find that some features are consistent (e.g., the increase in dimensionality in later layers) while others are less well-preserved (e.g., whether the shuffled or real tokens have higher dimensionality).

The rest of this project addresses universality in LLMs: Whether a characteristic of an LLM is unique to a particular architecture, model, or even training set; versus whether there are “genes” of LLMs that underpin general mechanisms and thus are present in all LLMs.

Establishing universality is quite difficult both conceptually and analytically, but it’s relevant for interpretability, complex systems analysis, and AI safety (e.g., whether technical safety solutions that are effective in one model can be effective in all models).

Task

Rerun the entire code file with one change: Use the Pythia-2.8b LLM instead of GPT-2-xl. You can access the model via Hugging Face using EleutherAI/pythia-2.8b. Before rerunning the code, save screenshots of the GPT-2 results for visual comparison.

Determine whether any of the code or visualization settings need to be modified for the different model.

Compared to GPT-2-xl, Pythia-2.3b has fewer transformer layers (32 vs. 48) but has a higher embeddings dimensionality (2560 vs. 1600).

If you encounter an out-of-memory error, it’s possible that both GPT-2 and Pythia don’t fit on the GPU, or even in the RAM. You can restart the Python session and comment out the code to load in GPT-2. Also consider switching the Colab runtime environment to High-RAM (if available).

Many of the results are qualitatively similar, although you may see some differences in the effective dimensionality plots due to differences in the first hidden-state rank.

The goal here is similar to the goal of Part 4, except the focus is on a different text (html code) rather than a different model. You can continue working with Pythia or go back to GPT-2-xl.

Task

Rerun the code file, but instead of importing a book text from gutenberg.org, import the website itself. That is, import http://www.gutenberg.org.

There is very little coding to do here. In fact, the only change to the code file is replacing the previous text-import with the following line: text = requests.get(’https://www.gutenberg.org/’).text

Printing the text data shows that it’s mostly html and css code.

I won’t spoil the fun of you discovering the results, but the patterns are noticeably different compared to those of Through the Looking Glass. Keep in mind that GPT-2 was trained on relatively little code compared to text.

One of the most prominent findings is the dimensionality-expansion around middle-to-late transformer layers. One interpretation is that the earlier layers extract core semantic features (compression phase), which later layers “unfold” into rich, context-specific representations. The results from the shuffled tokens suggests that this expansion relies on meaningful linguistic structure: the text is less compressible by earlier layers while having less context to add in later layers.

As always in this book, a more precise interpretation would require additional tests to ensure the results are robust to different sources of text (e.g., Wikitext, news articles, more books). But the code and analysis methods can be extended to more complete investigations.

More generally, these findings demonstrate that LLMs build rich, dynamic, and high-dimensional representations of token sequences. This has implications for dimensionality reduction, which is the main topic of the next project.

day-mode Bookmark

Hidden state dimensionality reduction

More background on SVD The SVD decomposes an M × N matrix A into the product of three other matrices:

A=UΣV⊤(5.4)A = U \Sigma V^\top \tag{5.4}

U is called the “left singular vectors,” V is called the “right singular vectors,” and Σ is called the “singular values.” The singular vectors reflect patterns (a.k.a., structure) in the matrix while the singular values encode how important each pattern is (that is, how much each pattern contributes to the matrix). You used the singular values in the previous project to measure effective dimensionality. The matrix Σ is the same size as the matrix A, and is all zeros except for the diagonal elements, which contain the singular values. It can also be trimmed to a square matrix of size k × k, where k is the number of singular values and corresponds to the smaller of M and N.

Each singular value is linked with a pair of vectors, such that:

A=∑i=1kuiσivi⊤(5.5)A = \sum_{i=1}^{k} u_i \sigma_i v_i^\top \tag{5.5}

where k is the smaller of M and N, u_i is the i^th row of U and σ_i is the i^th diagonal of Σ. Matrices can be reconstructed with a smaller number of dimensions by omitting some smaller components.

Ar=∑i=1r<kuiσivi⊤(5.6)A_r = \sum_{i=1}^{r<k} u_i \sigma_i v_i^\top \tag{5.6}

Matrix A_r is a rank-r dimension-reduced version of A. They have the same size (both M × N), but A_r has fewer patterns.

In this project you will reduce the dimensionality of transformer outputs to determine the impact on downstream calculations in the LLM. But first, Part 1 is focused on making the abstract equations above concrete by implementing and visualizing them in Python using a photograph of the Stedelijk Museum in Amsterdam (Figure 5.31).

Figure 5.31: A picture of a modern art museum in Amsterdam, which looks a bit like a giant bathtub from outer space. The picture is from Wikipedia; link and credits in the online code file.

GPU You can solve this project on a CPU, but a GPU will be convenient for the experiment in Part 4 that involves doing 24 forward passes to manipulate each hidden layer.

Part 1: Reducing dimensions while preserving shape

Section titled “Part 1: Reducing dimensions while preserving shape”

Before getting to the LLM data, I want to help you build visual intuition, and code, for dimension reduction.

Task

Use the online code to import the picture of the Stedelijk Museum in Amsterdam and convert it to grayscale.

Calculate the SVD and visualize the three matrices and the scree plot (scatter plot of sorted singular values) as shown in Figure 5.32.

Figure 5.32: Images of the SVD of the “giant bathtub from outer space museum” picture. Top row shows the three matrices as heatmaps; bottom row shows the singular values (diagonals of Σ).

Notice that the earlier columns in U, and the earlier rows of V^⊤, appear smoother; larger components in images tend to reflect lower spatial-frequency information, while later components tend to reflect higher spatial frequencies. The scree plot indicates one very large component followed by considerably smaller components, although part of that first component reflects a mean offset (average pixel values are above zero) that we will remove in the LLM data.

Now for the low-rank reconstruction. Here’s the math:

Ar=UΣ~rV⊤(5.7)A_r = U \tilde{\Sigma}_r V^\top \tag{5.7}

A_r is the rank-r reconstruction of the image, and Σ~\tilde{\Sigma}_r is the matrix of only the first r singular values; the rest of the matrix contains zeros. It can be implemented in code like this:

S = np.zeros_like(img)

for i in range(r):
S[i,i] = s[i]

How does one choose a value of r?

There are two approaches: You can set r to be the number of components to account for p% variance explained (e.g., 95%); or you can set r to some predefined number of components, e.g., r = 50. Let’s try both approaches.

Task

Transform the singular values to percent variance explained (as a reminder: pct_i = 100σ_i^2∕∑ σ^2). Create a low-rank reconstruction of the image by applying Equation 5.7 with r = 50. Calculate the percent variance explained using those 50 components, and visualize the original and reconstructed images as in Figure 5.33.

Figure 5.33: Visual impact of reducing the dimensionality of an image from 838 to 50.

The low-rank reconstructed image is clearly recognizable, and also clearly reduced in quality. Importantly, it has the same pixel width and height as the original image.

Task

Repeat the reconstruction, but now choose r as the number of components that explains 98% of the image variance. If you used my for-loop code to create the Σ matrix, then try to solve it this time without a for-loop (hint: use slicing to copy a square diagonal matrix into part of a non-square zeros matrix).

Calculate and report the ranks of the original and two reconstructed matrices.

Overall, the result is the same: a reduced-rank matrix of the same size as the original, that is clearly recognizable but degraded in quality.

You should find that 17 components accounts for 98.04% of the variability. It is quite striking that the next 33 components accounts for only an additional .9% of the variability.

You can confirm the ranks using the matrix_rank function in NumPy’s linalg module.

Rank of original matrix: 838

Rank of r = 50 matrix : 50
Rank of p = 98% matrix : 17

That’s for the visual intuition and code. Now let’s apply the theory and methods to LLM data.

The rest of this project involves reducing the dimensionality of the hidden-state vectors in one layer and calculating its impact on logits and loss.

The specific goals of Part 2 are to import a model and calculate the SVD of one transformer layer.

Task

Import the Eleuther GPT-neo-1.3b LLM and its tokenizer (available from Hugging Face with EleutherAI/gpt-neo-1.3b). Move it to the GPU if you have one available.

The online code file contains some text about the Stedelijk Museum copied from its Wikipedia page. Run the tokens through the model and collect the hidden-state vectors. Name the model output variable outs_clean for comparison with the manipulated model in the next part.

Extract the hidden-state vectors from one layer (I used layer 4). Calculate a vector of the column means, a vector of the row means, and a scalar of the global mean (across all matrix elements). Broadcast-subtract both the column and row means vectors, and then add back the global matrix mean. Show the SVD matrices and scree plot as in Figure 5.34.

I have two comments about the mean-centering. First, the mathematical comment: subtracting the column means and the row means is a double-subtraction, which will impose a global mean shift away from zero (the opposite of the intended effect). Adding back the global mean accounts for that undesired double-shift.

Next, the practical (coding) comment: If you’re encountering errors with the mean-centering, keep in mind that the vectors need to be multi-dimensional arrays or tensors for broadcasting to work properly. Thus, use the optional input argument keepdims=True when calculating the means.

The figure looks overall similar to the SVD of the museum picture. In fact, it’s nearly impossible to make inferences about a matrix based on visualizing its composite SVD matrices. Nonetheless, visualizing the decomposition — especially the scree plot — is informative and useful when crafting or debugging code.

Figure 5.34: Visualization of the SVD matrices for hidden-state vectors from layer 4.

You’ve now seen three different mean-centering options: In Project 28 you mean-centered the features; in Part 1 of this project you didn’t mean-center; and now you mean-centered both the features (embeddings) and the observations (tokens). Which one is correct?

It turns out that all options are correct, but they focus the SVD on slightly different patterns. Without mean-centering, the top SVD component captures the mean offset. For images, that can be appropriate; for datasets, that’s usually a confound to avoid.

For data-related applications of SVD including principal components analysis, mean-centering the features is generally sufficient. Mean-centering both the features and the observations removes all global offsets and forces the SVD to capture relational patterns that are distributed across the embeddings. That makes sense for data in a transformer, because the samples (token embeddings vectors) are not independent observations. Indeed, the entire purpose of the transformer layer is to add context-rich inter-token dependencies onto each hidden-state vector.

On the other hand, those mean offsets are meaningful, and we want to preserve them. Therefore, the means along each dimension need to be stored in a variable and added back onto the reconstruction.

Task

Reduce the dimensionality of the hidden state matrix to r dimensions, where r is the number of components to explain 95% of the variance. You can copy the reconstruction code from the image demo in Part 1, but (1) translate the NumPy functions to PyTorch and (2) add both dimensional means back onto the reconstructed hidden-state vectors, and subtract the global mean. Confirm that the shapes of the original and reconstructed hidden states match.

Visualize both hidden-state matrices, their difference, and their correlation as in Figure 5.35. Use the same color limits for all three heatmaps. Calculate and report the ranks of the original and reconstructed matrices.

Heatmaps of hidden-state vectors are not visually interpretable like pictures of a bathtub-shaped museum. Nonetheless, they do appear similar, and the difference map has values close to zero. Indeed, the scatter plot and “modest” correlation of r = .99939 reveal that the reconstruction is nearly perfect, despite the rank being reduced from 166 to 65.

Figure 5.35: Comparison of the original and rank-reduced hidden-state matrices.

Rank of original hidden-state matrix: 166 Rank of reduced hidden-state matrix :  65

The very high correlation despite the 100-point loss in rank tells us that most of information in the hidden-state matrix is stored in a small number of patterns.

Having the knowledge and code to decompose a hidden-state matrix and then create a low-rank reconstruction is an important step towards the main goal of this project; the next step is to put that code into a hook function so you can replace the real hidden-state activations with a low-rank ersatz during a forward pass.

Part 3: A hook to reduce hidden state dimensionality

Section titled “Part 3: A hook to reduce hidden state dimensionality”

Task

Create and implant a hook function into all transformer layers. The goal of the hook function is to replace the hidden states of one layer with an SVD-reduced version of the hidden states. Choose the rank r that explains 99% of the variance. (Hint: integrate code from Project 27 with code from Part 2 in this project.)

Also store the number of components it takes to capture 99% of the variance. Have the hook function print a summary like this: Changed layer 4 with 99.03% variance (106/167 comps) for each layer.

Test the hook function by reducing one layer during a forward pass with the same tokens you used earlier in this project. Compare the matrix norm of the hidden-state differences between the reconstructed and “clean” versions, and show in a scatter plot as in Figure 5.36.

These are the only hooks you’ll implant in this project, so technically you don’t need to save the handles. However, it’s likely that you will need to test, adapt, and debug your hook code, so saving the handles is still a good idea. Keep in mind that the hook functions remain in the model until they are removed, so modifying the function and re-implanting the hook will not overwrite the previously-implanted hook. In other words, you need to remove the hook functions before modifying and re-implanting them.

When calculating the difference matrices, remember to index with +1 because the first hidden state is the embeddings layer whereas the first hook is implanted into the first transformer.

Figure 5.36: Impact of dimension-reducing one layer on subsequent hidden-state activations.

The figure shows a change in the hidden states starting at layer 4. Those differences continue to grow as the compressed information continues to corrupt the subsequent layers. I find it quite remarkable that the impact continues and even intensifies, considering how close the original and reconstructed hidden states are.

Before moving on to Part 4, I want to explain a bit more about manipulating tensors inside a computational graph. PyTorch variables inside models are not simply collections of numbers; they are objects with links to other parts of the model, and to the optimizer (if the model is being trained). If you detach a tensor from the computational graph using the method .detach(), you get the numbers but lose the links back to the model. If you’re only doing a forward pass, then that’s fine because you don’t need the gradient information. But if you are running experiments where you manipulate the internal workings during training, then detaching a tensor will produce unwanted behaviors and might break the model. The solution is to make a copy of the tensor rather than modifying a detached version. I show this in the online code file for this project. Again, the extra code to make clones instead of directly manipulating the tensors is only necessary if you need to calculate gradient information in the model.

Part 4: Laminar-sweep reduction experiment

Section titled “Part 4: Laminar-sweep reduction experiment”

The goal here is to examine the impact of dimension-reducing the layer-specific hidden states on output logits and negative log-likelihood loss.

Task

Create a for-loop over transformer layers. Inside the loop, run the tokens through the model while reducing dimensionality of the hidden states for that layer, down to 95% of the original variability. Then calculate and store the following: (1) the norm of the difference matrix between the cleaned and reconstructed hidden states of that for-loop layer; (2) the vector norms of the same clean−reduced hidden state vectors (the difference with the previous analysis is that this one gives a vector norm for each of 167 tokens); (3) the norm of the difference between the output logits for the clean and reduced models, (4) the losses (use the labels= optional input argument when calling the model).

Show the results in a series of plots as in Figure 5.37. I max-value normalized the norms so that their shapes are directly comparable.

Finally, visualize a heatmap of the per-token hidden-state vector differences norms as in Figure 5.38.

The U-shaped plot of the number of components, and the inverted-U-shaped plot of the impact of dimension-reduction on loss, provide more demonstrations that the middle layers of LLMs learn to compress text representations before expanding them out to incorporate additional world knowledge.

Figure 5.37: Results of the experiment. The layer on the x-axis refers to the layer in which the manipulation was performed.

The heatmap of layer- and token-specific differences (Figure 5.38) would reveal any systematic impact on earlier vs. later tokens. At least in this sample dataset, that is not the case.

Figure 5.38: Heatmap showing the impact of layer-specific dimension-reduction on hidden-state vector norms. This image would reveal any temporal impacts, e.g., if the dimension-reduction differentially affected earlier vs. later tokens in the sequence.

Final comments: If you run the code for this analysis again using 99% instead of 95%, the results will be overall comparable but the the effects will be smaller. That indicates that the findings reflect meaningful patterns that get smaller as the amount of reduction decreases.

As in the previous project, the hook function was implanted into all layers and then activated one layer at a time. In Project 32 I will introduce an alternative approach, which is to implant the hook function into only one layer at a time in a for-loop over layers, and then immediately remove the hook.

And lastly, hook functions are limited only by your imagination and your coding skills. For example, instead of reducing the dimensionality of the entire hidden-state matrix, you could apply the technique to only the first half of the tokens. Or only to the nouns. Or only to the tokens corresponding to 4-letter words. Of course, in practice the manipulations should be guided by hypotheses about what those targeted manipulations might reveal.

day-mode Bookmark

Sentiment analysis with decision trees

The goal of Project 30 is to train a decision-tree classifier on the hidden-state vector for the [CLS] token in a BERT LLM. Each part of the project builds up one piece of the analysis, from creating batches to extracting hidden-state vectors to working with randomization in decision-tree analyses. The final result will be a visualization of classification accuracy in each hidden layer.

Before getting to the project, I’ll provide some background about decision trees and the [CLS] token.

Decision-tree analysis This is a hierarchical method used for classification that recursively splits the data in order to maximally separate two categories. At each step, the data are split by thresholding one feature. Each split is simple and univariate, but the whole analysis is nonlinear and multivariate because each split can be made from different features with different thresholds. I’ll use code to introduce the concept of a decision-tree analysis. Imagine you’re deciding whether to cook dinner or order delivery. Cooking is cheaper but takes more effort, so whether to cook or order depends on your budget and on your laziness.

if bankaccount < threshold:  # currently poor

if laziness < 8: # not too lazy
dinner = "cook"
else: # poor but very lazy
dinner = "order"
elif bankaccount > threshold: # currently rich
if laziness < 3: # different laziness threshold
dinner = "cook"
else:
dinner = "order"

Notice that the laziness threshold depends on the split of bankaccount. This feature of decision-trees makes the model complicated and nonlinear, even though each individual step is quite simple.

How are decision trees built in practice? Briefly, the analysis recursively evaluates the feature and threshold that best separates the categories. The split is evaluated using the Gini coefficient, which is a measure of the proportion of two categories in a dataset. A Gini coefficient closer to zero indicates that the split (called a leaf) is dominated by one category, while a coefficient closer to .5 indicates a balance of categories. Thus, the goal of splitting at each node is based on minimizing the Gini coefficient. Splitting continues until a stopping criteria is reached, such as a maximum number of splits (called the “tree depth”).

Decision-tree analysis has many applications and developments in ML. There are several parameters and extensions that you can explore (e.g., a random forest, in which multiple trees are built and aggregated), but I’ll keep things simple in this project.

BERT [CLS] token In previous projects with the BERT tokenizer, I specifically instructed you to ignore the [CLS] token, either by deactivating the special tokens during tokenization or by slicing it out. However, this token is not useless; the BERT LLM is trained to use the [CLS] token as a low-dimensional summary of the text. In other words, as the [CLS] embeddings vector passes deeper into the model, it becomes a fixed-length (768 dimensions for BERT-base) representation of the text, regardless of sequence length. Remember that BERT is not a causal autoregressive model like GPT, so BERT can use future tokens to adjust prior tokens. We will use the [CLS] hidden-state vector for sentiment classification.

GPU A GPU is definitely useful for this project; it will be the difference between waiting tens of minutes vs. tens of seconds. If you don’t have a GPU available, I recommend having a book or doom-scrollable social media app handy.

Task

Import BERT-large and engage the output_hidden_states setting. Move the model to the GPU if available. Import a piece of the “SST2” dataset using the following code: load_dataset(’glue’,’sst2’,split=’train[:5%]’)

Inspect the dataset to understand its organization. Create a list variable that contains the data labels, and report the number and percent of occurrences of each label type.

If you’re using a CPU for this project, you might want to write the code using the smaller version of BERT, then switch to the larger version when you have a working solution.

SST stands for Stanford Sentiment Treebank, and is a commonly used dataset in natural language processing for binary categorization of short text pieces (e.g., public movie reviews) into “positive” vs. “negative.”

The dataset contains the following information:

Dataset({
features: [’sentence’, ’label’, ’idx’],
num_rows: 3367

})

One of those 3367 elements looks like this:

{’sentence’: ’proves a lovely trifle that ,

unfortunately , is a little too in
love with its own cuteness . ’,
’label’: 0,
’idx’: 123}

Looking ahead, the ’sentence’ key will be tokenized and presented to BERT, and the goal will be to train a decision-tree classifier to predict the label “0” or “1” based on the hidden-state activations. Note that we’re not training (fine-tuning) the BERT LLM — the weights of that model stay fixed. Instead, the goal is to determine whether there is information embedded in the [CLS] token that distinguishes negative from positive reviews.

This slice of the dataset is not perfectly balanced:

“0” appeared 1514 times (45.0%). “1” appeared 1853 times (55.0%).

Perfectly balanced data is ideal, although a 45/55 split isn’t so bad. It’s the extreme imbalances that you need to worry about, e.g., 99% vs. 1% in the two categories. Extreme unbalanced designs happen with, for example, credit card fraud, weapons detection in airport x-ray scans, and medical disease diagnoses.

Anyway, we have enough samples here to create a perfect balance by subsampling, which we will do by stratifying the train/test split. More on this point in Part 4.

The goal here is to create two Python lists, one containing batches of tokens and one containing corresponding category labels.

Task

Given a batch size of 32 and a sample size of 3367 (this is the number of data samples, not the number of tokens), calculate how many batches can be created, and how many total samples will be contained across all batches.

The number of batches is the floor-division of the number of samples by the batch size. In this case, that’s 3367//32 = 105 batches leading to 3360 samples. The additional 7 samples that don’t fit into a full batch are dropped.

In general, how to deal with partial-batches depends on the application. If you have a large sample size, partial-batches can simply be dropped. If you have a limited sample size and cannot afford to throw away data, you can have one smaller batch and be mindful of batch-based averaging and indexing.

Because this project is more focused on education and analysis methods, I’ve decided to drop the extra batch in the interest of simplicity.

Task

Initialize two empty Python lists, one for the batches and one for the labels. Then create a for-loop over the number of batches.

Find the start and end indices into the dataset for each batch. Initialize temporary lists for the texts (sentence key) and labels. Append 32 sequential text samples. Tokenize that list of texts and store as a new element in the all-batches list. The sentences have differing lengths, so make sure to tokenize with padding.

After creating the two lists, confirm the following sizes: the all-labels and all-batches lists each contain 105 elements; each labels element contains 32 numbers; each all-batches element should be a tokenizer dictionary containing token IDs and the attention mask. The sizes of the batches will vary depending on the sentences therein, so you can extract the number of sequences, and the sequence length, for each of 105 batches and visualize as in Figure 5.39.

Finally, run one batch through the LLM to check the sizes of the hidden-state tensors. For example, batch 10 should produce hidden-state vectors of size 32 × 38 × 1024.

The number of sequences per batch is 32 by definition. Plotting it is redundant but is a good confirmation of the accuracy of the batch-creation code.

Figure 5.39: Counts of sequences and tokens-per-sequence for each batch.

The batch sequence length, on the other hand, is not trivial, and instead is determined by the longest sequence in each batch. Shorter sequences within each batch are padded up to the length of the longest sequence in that batch. Thus, each batch needs to have the same number of columns in each row (that is, all sequences must have the same number of tokens), but different batches do not need to be the same size.

Remember that you need the [CLS] token here for the decision-tree classification, so do not remove the special tokens when tokenizing the texts.

Part 3: Get the [CLS] hidden state activations from one layer

Section titled “Part 3: Get the [CLS] hidden state activations from one layer”

The final part of this project will be to train and test a classifier on each of the hidden layers, but first we will focus on only layer to develop an analysis pipeline.

Task

In a for-loop over the batches, run a forward pass on each batch. Extract the hidden states from the first token in the final hidden layer, bring it back to the CPU and convert it to a NumPy array. Combine all the activations into a 3360 × 1024 matrix, and all the labels into a 3360 dimensionless array.

The activations matrix size 3360 × 1024 corresponds to 3360 data samples and an embeddings dimensionality of 1024 (768 if you’re using BERT-base). The labels should contain 3360 elements.

Task

Examine whether the vector average differentiates the two categories, by averaging the hidden-state vectors to get one number per sample. Perform an independent-samples t-test to determine whether the vector average predicts category label, using the SciPy function ttest_ind. Visualize the data and t-test result using violin plots as in Figure 5.40.

The two distributions overlap and the t-value is far from significant.

Figure 5.40: Violin plots showing distributions of vector averages. Each dot is the vector average for the [CLS] token of each sample.

This demonstrates that the average [CLS] vector does not differentiate the categories. That’s not very surprising: You’ve seen many times in previous projects that the hidden-state vectors have means around zero. The decision-tree classifier is not based on the average, but instead is based on multiple hierarchical splits across the embeddings dimensions.

More generally, preliminary analyses like t-tests on averages are an important start to rigorous investigations. Just keep in mind that such simplistic approaches lack the nuance of more sensitive and multivariate techniques like decision-trees.

Part 4: Single-layer decision-tree classifier

Section titled “Part 4: Single-layer decision-tree classifier”

The goal of Part 4 is to develop analysis code to classify the activations from one layer, which you will then expand to all hidden layers.

But there are a few issues we need to deal with: First, very high dimensionality data can lead to numerical problems and overfitting in decision-tree analyses. Second, a decision-tree classifier should have a high ratio of observations to features — ideally over 50:1, but at least 10:1. Our dataset here has a ratio of around 3:1 (3360 observations and 1024 features). The risk of overfitting is very high. To address both of these issues, we will reduce the dimensionality of the data before fitting a decision-tree model.

In Project 29 you learned how to perform a PCA using an SVD on the data matrix. In this project we’ll implement a similar procedure but using the PCA function in sklearn.decomposition. The idea is that each principal component is a linear weighted combination of all embeddings dimensions, and the decision-tree classifier will be trained on a small number of components instead of a large number of hidden-state values.

Note: PCA is not always a good data transformation for a decision-tree analysis, though it is useful here. I’ll discuss this more at the end of the project.

Task

Fit a PCA on the CLS activations matrix. Keep the number of components that accounts for 80% of the total variance. Obtain the PCA scores for those components via the fit_transform method. Print the number of components and variance explained, and the ratio of observations to features.

Use the scikit-learn function train_test_split to separate the data into train (80%) and test (20%) sets. Use the stratify input argument to ensure that the train and test splits have the same ratio of categories.

Train a decision-tree classifier using the function DecisionTreeClassifier. Set the max_depth parameter to 4. Fit the model on the training data, and calculate both train and test accuracy.

The PCA code block should print the following results:

Kept 159 components explaining 80.01% variance.

Original data size is (3360, 1024)  Reduced data size is (3360, 159)

Observations:features ratio is 3360:159 = 21.1

In other words, the data used for classification will comprise 159 features, corresponding to the top 159 principal components. That gives a ratio of just over 20, which is much better than a ratio of 3.

The max_depth parameter constrains the complexity of the analysis. If it’s too high, the tree-model is likely to overfit the training data, especially with a high-dimensionality dataset. In real analyses, the value of that parameter is often selected using cross-validation; here you can assume that 4 is a reasonable value. (You can try leaving that parameter unset; you’ll probably get perfect accuracy on the training set, indicating overfitting.)

I got the following results from the decision-tree classifier:

Accuracies: Train 75.37%, Test: 69.49%

Did you get the exact same results that I did? I’m sure you didn’t. The train/test split is random, which means the trained tree-model weights will be somewhat different each time its run, which means accuracy will be somewhat different.

Explore this by rerunning that code block a few times.

Task

Write a for-loop over 20 repetitions. In each repetition, repeat the train/test split, classifier fitting, and train and test accuracy calculations. In other words, the data and the code remain the same; only the train/test split is randomized.

Show the results in a scatter plot as in Figure 5.41.

For the final run, calculate and visualize the feature importances. You can use the method .feature_importances_, and create a bar plot of the sorted importances as in Figure 5.42.

The scatter plot shows that the accuracies do fluctuate a bit, but not so wildly that it would be a major concern. That is, the accuracies don’t vary between, e.g., 50% and 95%. With more data, this variability would decrease, but you can also get a more stable estimate of performance by averaging across a few random re-splits.

Figure 5.41: Because the train/test split is random, the classification accuracy changes slightly each run. Horizontal dashed lines depict the average over the 20 runs.

The train accuracy is consistently higher than the test accuracy. That gap of around 5% is due to the model slightly overfitting the training set.

There are a few ways to visualize results from decision-tree. Unfortunately, principal components are rarely interpretable because they are weighted combinations of the data features. But on the other hand, the data features themselves ([CLS] token hidden-state vectors) are also not interpretable. Therefore, Figure 5.42 is more an FYI about how to visualize decision-tree results than a way to interpret this particular analysis.

Figure 5.42: Feature importances plot. Although the PCs themselves are not interpretable, the gradual decrease of importances indicates that the classification is not based entirely on one component, which means that the diagnostic information is distributed across the hidden states.

A second way to visualize a decision-tree analysis is using a tree diagram, which shows the splitting variables and Gini coefficients. That plot is not shown here, but it’s produced in the online code file.

Minor but important point for you to think about: The PCA reduction was based on the data before splitting into train and test sets. Do you think that’s appropriate? We shall return to this issue in Part 6.

Part 5: Collect [CLS] activations from all layers

Section titled “Part 5: Collect [CLS] activations from all layers”

Now you have a pipeline for analyzing data from one layer. The goal of Part 5 is to collect all the data from all the hidden states so that you can analyze them in Part 6.

Task

Copy code from Part 3 to loop over all batches, run a forward pass through the model for each batch, and get the hidden-state activations for the [CLS] token. The new aspect here is extracting the activations from each layer and storing them in a list where each element in the list is a NumPy array of size 3360×1024, corresponding to the [CLS] tokens for each hidden-state layer.

Visualize the averaged [CLS] vectors as in Figure 5.43. This is similar to the visualization from Part 3 but without the violins.

You don’t need to run t-tests to see that there are no visually compelling category differences in the hidden layers.

Figure 5.43: [CLS] token vector averages for each hidden layer, separated for positive (green) vs. negative (red) labels.

The conclusion here is the same as in Part 3: There is no compelling category-specific information in the average of all dimensions in the [CLS] vector. Instead, information is embedded in the patterns in the vectors that are distributed across the 1024 dimensions. We need multivariate analyses to identify those patterns.

Part 6: Laminar profile of classification accuracy

Section titled “Part 6: Laminar profile of classification accuracy”

Now to repeat the decision-tree classification analysis from Part 4 for the data from each hidden-state layer. But there are a few changes to make, so be careful when copying code from earlier in the project.

Here is one change: At the end of Part 4, I invited you to consider whether it was appropriate to dimension-reduce the data before splitting into train and test sets. The problem with that setup is leakage of the train set into the test set. The train and test sets should ideally be independent observations, otherwise the test accuracy could be inflated by overfitting the training set. When the PCA is trained on all the data, information is shared across all samples, which means information leaks from the train set into the test set. This is a minor but important confound, and even if the impact on performance is small, it’s better to avoid it.

A smaller difference here compared to Part 4 is to repeat the classifier analysis five times (instead of 20) to average accuracy values.

Task

Create a double for-loop over the hidden-state layers, and then over five repetitions of the train/test split and classifier evaluation. Within each iteration, (1) split the data into train/test sets; (2) fit a PCA to the train set retaining 80% of the variance; (3) apply the PCA reduction to the train and test sets (hint: use the method .transform); (4) fit a decision-tree classifier as in Part 4 (remember to fit the PCA-reduced train set); (5) calculate the category predictions for the PCA-reduced train and test sets and calculate prediction accuracy; (6) store the repetition-averaged accuracies for the train and test data. The result of this double for-loop will be a 25 (hidden-state layers) × 2 (train vs. test) NumPy array of accuracy values.

Print a message after each layer like this: Finished layer 8/25 with 64.7% test accuracy.

Visualize the train and test performance over layers, as in Figure 5.44.

Figure 5.44: Laminar profiles of classification performance for train and test sets.

The results show low accuracy in the initial embeddings layer and steadily increasing classification accuracy with depth into the model. The consistent gap between the train and test performance is a sign of overfitting. More data or more carefully tuned PCA and depth parameter settings could help increase performance. Decreasing the depth parameter will decrease the train-test gap but also lower accuracy overall, whereas increasing depth will increase train accuracy but may leave test accuracy low.

For reference, top classifier performance on this task is around 90% for random-forest decision-trees. Comparatively, our results of around 70% seems low, but we used only 5% of the dataset, only a single decision-tree, and did not optimize the decision-tree parameters or dataset processing (e.g., number of PCs to retain). Given those limitations, I’d say that 70% accuracy is decent for our educational example.

Part 7: Performance benefit per transformer

Section titled “Part 7: Performance benefit per transformer”

Classification accuracy clearly increases with depth into the model, which means more transformers helped. The question we will address in Part 7 is how much each transformer boosts classification performance. We’ll address this using a linear regression, and by simple averaging. Refer back to Project 21 in Chapter 4 if you need a refresher on fitting regression models using LinearRegression.

Task

Create a predictor variable (the independent variable of the regression model) as the number of transformers coded as integers 1 through 24, and use the LinearRegression function in scikit-learn’s linear_model module to fit a linear regression model to the test accuracies, using only the data from the transformer layers (not the embeddings layer). Make sure to include an intercept term when creating the model object, because the data are not mean-centered.

Print the intercept and slope parameters, make sure you can interpret those coefficients, calculate the regression-predicted accuracy scores, and visualize the data and predictions as in Figure 5.45.

You can specify an intercept term using an optional input argument: LinearRegression(fit_intercept=True)

True is actually the default value of that parameter, so in fact, you didn’t need to specify anything. Part of this exercise is making sure you know about that parameter and its default setting.

The two regression parameters converted to percent are as follows:

beta_0: 57.922% beta_1:  0.518%

To interpret the intercept term, (a.k.a. constant term, a.k.a. β_0), remember that β_0 is the expected prediction accuracy when the predictor variable is zero. Because the predictor variable was defined starting from 1, the constant term indicates the expected classification performance with no transformers, which in our dataset, corresponds to an extrapolated prediction about classification in the embeddings layer.

The slope (a.k.a. β_1) term is the expected increase in accuracy for each additional transformer in the model. Thus, the model shows that each additional transformer led to an accuracy boost of roughly one-half a percentage point.

Figure 5.45: Results of the regression analysis. The blue circles indicate the test performance accuracy, same as in Figure 5.44. The black line is the predicted accuracy from the regression.

Keep in mind that linear regressions cannot be infinitely extrapolated. That is, you cannot simply extend the BERT model with 100 more transformers and expect 120% prediction accuracy ;)

Relatedly, transformers in an LLM are not statistically independent of each other; they form a sequential causal chain. Thus, the increase in accuracy is not simply the number of transformers, but also the way that each transformer learns to improve upon the information it receives from previous transformers in the chain.

The slope from the regression analysis is the expected improvement in performance per transformer. How does that compare to the empirically calculated average increase in performance? That’s the final task in this project.

Task

Calculate the empirical expected per-transformer performance boost as the average difference between accuracy scores for each successive pair of accuracies. Report the results from both the regression and differencing analyses.

The regression-predicted and empirical results are comparable though not identical.

Regression: boost per transformer: 0.5183% Empirical:  boost per transformer: 0.5435%

The difference is that the regression estimates the slope based on minimizing least-squared residuals, whereas the empirical result is simply the average of subtractions. In noiseless data, those two approaches would give the same results. In the presence of noise and with the assumption of linearity, the regression approach should provide a more statistically robust estimate.

Discussion about PCA and decision-trees In general, PCA dimension-reduction is not a standard — or generally recommended — data processing step before a decision-tree analysis. Decision trees can handle correlated features, so there is no need to orthogonalize the features (all PCs are orthogonal). Decision trees can also handle many features, as long as the number of observations is much higher (e.g., a ratio of 50×). Furthermore, one of the advantages of a decision-tree analysis is that each leaf split can be interpreted in the context of the features. But in our case, the original features (embeddings dimensions) are themselves individually uninterpretable, and so linear combinations of uninterpretable features are no less uninterpretable.

The conclusion is that a PCA should not generally be part of a decision-tree analysis pipeline, but it’s useful for this project because (1) it offers more opportunities for implementing and learning about PCA, (2) it helps increase the ratio of observations to features without arbitrarily removing embeddings dimensions, and (3) the mixing of features in a PCA that impedes interpretability is irrelevant for hidden-state vectors that already reflect complex mixtures of the entire text sequence.

We shall return to decision-tree classifiers using XGBoost in Project 47.

day-mode Bookmark

Logit lens

The “logit lens” is a simple yet clever way to peer into the transformations of the hidden-state vectors, and in particular, how each token is transformed from a representation of the current token into a prediction for the next token or for a masked token.

Here’s the idea: The normal flow of information in an LLM is that the final transformer layer leads to the unembeddings matrix, from which the final output logits are calculated and tokens are selected. The idea of the logit lens is to decode the output of an earlier transformer layer, by pushing those hidden state vectors through the unembeddings matrix. In other words, we treat the hidden-state vectors as if they were the final output logits, and force the model to pick a token before it finishes its calculations.

Breaking out of the full transformer stack is not desirable for applications (e.g., a chatbot) but it provides an opportunity to inspect how the LLM incorporates an increasing amount of information at each depth to generate token predictions.

The logit lens can be expanded in many ways for many detailed investigations; in this project you will learn the foundational approach to implementing a logit lens experiment and visualizing the results.

For this project, we’ll use the RoBERTa model, which I introduced you to in Project 14 (Chapter 3). The goal of Part 1 is to import the model, tokenize a short text, and examine the accuracy of single-token prediction. Remember that RoBERTa is trained using masked-token prediction, not causal next-token prediction.

Task

Import the RoBERTa-large model and its tokenizer. Tokenize the following text: “The way you do anything is the way you do everything.” Print out the tokens and their indices.

Run the tokens through the model, and output the hidden states. Extract the hidden-state activations from layer 23. Calculate the logits by pushing those activations through the lm_head layer of the model — that layer contains the unembeddings matrix to get from logits (or, in our case, hidden-state vectors) to tokens in the vocab.

Transform the logits to log-softmax probability and find the predicted token index for token position index 3. Visualize the log-softmax values, the actual token in position 3, the predicted token based on the max-logit value, and the log-softmax value of the predicted token (Figure 5.46).

Here’s the tokenization:

Token     0 is “<s>” Token   133 is “The” Token   169 is ” way” Token    47 is ” you” Token   109 is ” do” Token   932 is ” anything” Token    16 is ” is” Token     5 is ” the” Token   169 is ” way” Token    47 is ” you” Token   109 is ” do” Token   960 is ” everything” Token     2 is ”</s>”

Note the special tokens <s> and </s>. Those are different from the BERT special tokens.

The size of the hidden-state activations is 1 × 13 × 50265, and the actual and predicted tokens from position index 3 are:

   Actual token is ” you” Predicted token is ” you” Predicted log-sm is -0.00010

Figure 5.46: Log-softmax probability values for the fourth token. The red circle indicates the maximum-logit token.

It’s not surprising the the model guesses correctly: It incorporated the word “you” into its prediction that that word should be “you.”

But the important thing here is seeing that we can use the hidden states to generate predictions about token values. That’s not trivial: The model isn’t trained to have accurate predictions before the final layer.

A much less trivial assessment of the model’s token-prediction capabilities is to predict a masked token. The goal of Part 2 is to examine whether the findings from Part 1 are still present when using masked-token prediction.

Task

Replace the second appearance of the word “way” with the tokenizer’s mask_token. Tokenize the new sentence, run the new tokens through the model, and repeat the max-token identification and visualization from Part 1.

Here’s the tokenization:

Token     0 is “<s>” Token   133 is “The” Token   169 is ” way” Token    47 is ” you” Token   109 is ” do” Token   932 is ” anything” Token    16 is ” is” Token     5 is ” the” Token 50264 is “<mask>” Token    47 is ” you” Token   109 is ” do” Token   960 is ” everything” Token     2 is ”</s>”

Notice that RoBERTa’s mask token is <mask> compared with [MASK] in the BERT model. This is another demonstration that you should never assume that code developed for one LLM will work without modification with another LLM.

Here’s the prediction:

Unmasked token is " way"
Masked token is "<mask>"

Predicted token is ” way” Predicted log-sm is -0.00003

The model guessed the correct token even before the final layer, with a very large log-softmax value (exp(−0.00003) ≈ .999).

Now you know how to calculate the logit lens for one layer and one masked token. The next step is to make predictions for one masked token over all the hidden layers.

The two goals for Part 3 are (1) to create a laminar profile for predictions of one token, and (2) to develop code to perform a regression analysis to examine how the model’s predictions change over the layers.

Task

Create a for-loop over all hidden layers. In each layer, extract the hidden-state activations, push them through the lm_head layer to get the logits, and transform to log-softmax. Identify the predicted token (the one with the largest logit), and store the log-softmax value of the target token (the actual token from the unmasked sentence).

Print the text with each predicted token in quotes for each layer.

I won’t print all of the layer predictions, but here’s a sample:

Layer  0 lens: <s>The way you do anything is         the” song” you do everything</s> Layer 10 lens: <s>The way you do anything is         the” current” you do everything</s> Layer 20 lens: <s>The way you do anything is         the” way” you do everything</s>

The model got the correct answer in the last third of the layers.

The top token is interesting to look at, but difficult to interpret because it is either categorically correct (“way”) or incorrect (“song” or “current”). The log-softmax of the target token, on the other hand, is a continuous measure of the model’s probability of picking the correct token.

Let’s explore that by fitting a regression line to the log-softmax values. The regression equation is the following:

y^k=β0+β1k(5.8)\hat{y}_k = \beta_0 + \beta_1 \sqrt{k} \tag{5.8}

where y^k\hat{y}_k is the predicted log-softmax value for the target token at layer k, β_0 is the intercept (constant), β_1 is the slope, and k\sqrt{k} is the square root of the hidden layer index.

Task

Use scikit-learn’s LinearRegression function to fit Equation 5.8. Extract and print the constant and coefficient terms. Visualize the data and best-fit line as in Figure 5.47.

The intercept and slope are as follows:

const: -20.45 slope:   4.42

Figure 5.47: The log-softmax value for the target masked word (in this example, it’s “way”) plotted as a function of the hidden layer. Green circles depict the data; red line depicts the predicted logit values from a linear regression.

The figure is quite revealing: Even though the model was categorically incorrect in many layers, it steadily increased the probability of the correct target token. If you’d like an additional plotting challenge, you can use different marker shapes and colors depending on categorical accuracy (e.g., a red square for incorrect predictions vs. a green circle for correct predictions).

I have two questions about the square root term in the model that I’d like you to answer before reading my answers below.

  1. Is it still a linear regression if the predictor variable has a nonlinear transformation?

  2. But why even fit a square root? Is there a theory behind modeling log-softmax as a function of the square root of the hidden-state layer?

Here are the answers:

  1. Yes, it is still a linear regression. A linear regression can have nonlinearities in the dependent and independent variables; what must be linear are the regression coefficients (the β values). Thus, β1k\beta_1\sqrt{k} is linear in the coefficients, whereas β1\sqrt{\beta_1} is not a linear regression (such a model could be fit using, for example, gradient descent).

  2. Here I must be honest: I developed the regression model after looking at the results. Thus, this is an ad-hoc model that should be interpreted more as a description of the data than as an hypothesis-driven inferential analysis.

We’re getting close to the full analysis. The final step is to figure out how to replace the tokens with the mask one step at a time.

Task

Create a for-loop over the tokens. In each iteration of the loop, create and print a new token sequence that is copied from the original but with each token masked in turn.

Figure 5.48 shows the first four results.

Figure 5.48: Replacing each token in turn with the mask token.

Now you’re ready for the full analysis, which involves combining Parts 3 and 4.

Task

Create a double for-loop over all token positions in the sentence (as in Part 4) and over all layers in the model (as in Part 3). You’ll need to run the model for each mask position, but you don’t need to run the model for each layer. Calculate and store two log-softmax values: for the target (masked) token, and for the maximum log-softmax. Also store predicted token to visualize in Part 6.

After the inner for-loop over the layers, calculate two regression analyses as in Part 3 (Equation 5.8), one for the target log-softmax and one for the maximum log-softmax. Store the two slope values for each token.

Visualize three sets of results: heatmaps of the target and max-token log-softmax values as in Figure 5.49A-B, and scatter plots of the regression slopes as in Figure 5.49C.

The heatmaps show the tokens on the x-axis, hidden-state layer on the y-axis, and log-softmax value in the color axis.

Figure 5.49: Log-softmax probability values and regression slopes of the change in log-softmax over the layers.

Qualitatively, we can see from panel A that the word “the” was the easiest to predict (higher logits in earlier layers), while “everything” was more difficult (lower logits throughout the model).

It is sometimes desirable to match the color limits of heatmaps for direct visual comparison; but in this case, that would be a poor visualization choice given the four-fold difference in numerical values.

Finally, note that the results in panel A and the blue circles in panel C are easier to interpret, than the results in panel B and the red squares in panel C: The log-softmax and regression slope of the target come from the same token in all layers, whereas the max-value log-softmax and regression slope correspond to different tokens in different layers.

The final part of this project is to create a text heatmap. Have a look at Figure 5.50 to see what you’ll create.

Figure 5.50: A text heatmap used to visualize the logit-lens. The text at each [token, layer] coordinate is the model’s predicted token, and the color is its scaled log-softmax probability.

Each row is a layer and each column is a token position. The text heatmap shows how the token selections evolve as the transformers update the hidden-state vectors. The color box behind each token is mapped onto the log-softmax value.

Follow the instructions in the task box to create the figure.

Task

Create and place one axis in a figure of size 13 × 11.

Loop over the hidden-state layers. Within each layer, define the y-axis coordinate as 1 − k∕L, where L is the total number of hidden-state layers and k is the current layer (current iteration in the loop). Draw each i^th token with an x-axis coordinate of x_i∕T for T tokens in the sequence. The background box of the text object is the log-softmax value for that token, min-max scaled such that the color value of 0 is the smallest log-softmax over the entire layer-by-token matrix, and the color value of 1 is the largest value in the matrix. The colormap is plt.cm.Reds.

And that’s the basics of the logit-lens analysis. There are several extensions and modifications of the logit-lens technique that you can read about in the LessWrong post linked in the online code file.

day-mode Bookmark

Patching hidden states in indirect object identification

Consider the following text: “When Mike and Emma went to the cafe, Mike gave a coffee to ___” What word do you think belongs at the end? If you guessed “Emma” (or “her”) then you have successfully identified the indirect object.

Can LLMs identify indirect objects? And if so, where does that capability emerge in the model? Those are the questions we will address in Project 32.

GPU Having GPU access for this project is useful but not necessary. If you have limited computing access, you can use GPT-2-small on a CPU instead of GPT-2-xl on a GPU.

The goal of Part 1 is to setup the task, run it through the model, and analyze and visualize the results.

Task

Import GPT-2-xl and move it to the GPU. Tokenize the following two sentences (excluding the numbers): 1. When Mike and Emma went to the cafe, Mike gave a coffee to 2. When Mike and Emma went to the cafe, Emma gave a coffee to

Find the token indices for “ Mike” and “ Emma” (including the preceding spaces).

Push both token sequences through the model and output the hidden states. You can do one forward pass with batched input, although I found it more convenient for subsequent analyses to have two separate runs with separate output variable names.

The sizes of the hidden-state tensors are 1 × 14 × 1600 corresponding to one sequence per model output (that would be “2” if you ran both texts in a batch), 14 tokens, and an embeddings dimensionality of 1600.

The terminology in IOI tasks can get confusing. For this project, I’ll refer to the sentence where “Emma” is the target as ME (for Mike → Emma) and the the sentence where “Mike” is the target as EM (for Emma → Mike). I’ll use phrasing like “the ME model” and “the EM score.”

Task

Determine whether GPT-2-xl solves the IOI task by identifying the token with the largest logit in the final token position. Print out both sentences with the newly generated ending.

Make a scatter plot of the raw logits in the final token position for both sentences, and highlight the vocab indices for “ Mike” and “ Emma” as in Figure 5.51A-B. Show a scatter plot of the logits for the final token from the two sentences as in Figure 5.51C.

Calculate the IOI score as the raw logit values for “ Mike” minus “ Emma” in both sentences. These IOI scores will be a clean baseline for the results of the patching experiment later in the project.

The model gets both sentences correct:

>> When Mike and Emma went to the cafe,         Mike gave a coffee to” Emma” >> When Mike and Emma went to the cafe,         Emma gave a coffee to” Mike”

Figure 5.51: Visualizing the results of the IOI task. Panels A and B show raw logits for the final token (“to” in both sequences), with the two target tokens highlighted. Panel C shows their relationship.

The model assigned high logits for both proper nouns, and the indirect objects were correctly identified in both sentences. The scatter plot in panel C is interesting: The logits are from the exact same token and the sentences are nearly identical but for one word (“Mike” or “Emma”); the differences between the two sets of logits is attributable to the different contextual information that the transformers extracted, i.e., the indirect object.

Because the IOI score is calculated as “ Mike” minus “ Emma”, it is negative for the Mike gave to Emma text and positive for the Emma gave to Mike text.

Logit difference for text “ME”: -3.313 Logit difference for text “EM”:  2.177

Why did I instruct you to calculate the IOI scores using the raw logits instead of the log-softmax probabilities?

The raw logits are a cleaner indicator of token-specific predictions, because the softmax probability of each token incorporates the logits from all other tokens. That said, it doesn’t actually matter for the IOI score because the log-softmax transformation cancels in a two-element comparison. That is, (ln σ(g_1) − ln σ(g_2)) = (g_1 − g_2) where g is a raw logit and ln σ(g) is its log-softmax transform. Still, using raw logits is more theoretically sensible here.

Now that you have code to implement the IOI task for one sample, you are ready to manipulate the model to determine the layer at which the model extracts the IOI information.

The type of manipulation we’ll do here is called patching. The idea is to “patch” the activations from one model into another. In particular, we will replace hidden-state activations from the EM model with activations from the ME model.

We will first focus on patching one layer, and then expand out to all the layers in the next part.

Task

Choose layer L − 2 (L layers) to patch. Write a hook function that replaces the transformer outputs from the final token with the corresponding activations from the ME hidden states that you extracted from the model output in Part 1.

Attach that hook to transformer layer L − 2. Run the EM tokens through the model. Remove the hook function.

Calculate and report the IOI scores from the patched and clean models.

Calculate and show the logits from the clean and patched models as in Figure 5.52A-B, and their token-wise differences, as in Figure 5.52C. In all plots, highlight the two target tokens.

Be mindful of indexing: Transformer layer L − 2 corresponds to hidden-state layer L − 2 + 1.

The sign of the IOI score flips compared to the clean version. What does that flip mean?

  Clean IOI score:  2.177 Patched IOI score: -3.316

The manipulation took activations from the ME model and implanted them into the EM model. And here’s the important part: We didn’t actually replace the activation for the token “ Mike”; instead, we replaced the activation for the final token position (“ to”). But that hidden-state vector has absorbed information from the rest of the sentence, and that absorbed information was transplanted from ME to EM.

Figure 5.52: Results of the patching experiment, showing the logits from the clean EM model (panel A), the patched model (panel B), and their difference (panel C). The y-axis in panel C is Clean minus Patched, meaning that negative values correspond to increased probability from patching while positive values correspond to decreased probability from patching.

The logit differences (panel C) shows that the manipulation was not selective: All the logits were modified to some extent, not only the logits for the target tokens. What other tokens were strongly impacted by the patch?

Task

Find and print out the top-20 impacted tokens. Print the manipulation impact (Δ = clean minus patched logits) and the token string.

Because we’re looking for the overall impact of the manipulation, find the top-20 Δ magnitudes regardless of their sign. Of course, the direction of the effect is relevant for interpretation. Several of the top-modulated tokens are sensible: Δ (C-P) = -3.437 for “ Emma” Δ (C-P) = -2.681 for “ himself” Δ (C-P) = 2.056 for “ Mike”

However, many other large-modulated tokens are less interpretable, e.g., Δ (C-P) = 1.728 for “ Pegasus” Δ (C-P) = 1.719 for “ Scor” Δ (C-P) = -1.697 for “hess”

Now for the full experiment, which involves wrapping the experiment code you just wrote into a for-loop. I’ll add a manipulation check to confirm the accuracy of the hook functions.

You will also notice a difference in how the hook functions are implemented here compared to previous projects: Previously, you implanted a hook function into all layers and activated only one of those functions in a for-loop; here you will implant a hook into only one layer at a time inside the for-loop, and remove that hook function immediately after the forward pass.

Task

Loop over all transformer layers. Inside the for-loop, create a hook function only for that layer to patch in ME hidden-state vectors as in Part 2. Run a forward pass on the model using the EM tokens. Calculate and store the IOI score.

Here is the manipulation check: Calculate the norm of the vector defined by the difference between the patched and the clean hidden state activations for the current layer. Do this for the penultimate token position, and for the final token position. The hook function only patched the final token position, so the penultimate hidden-state vector should differ (meaning non-zero norms), whereas the final vector should match perfectly (meaning the difference vector norm should be zero).

Spoiler: The manipulation check will fail for the final layer. Understand why it failed and how you could fix it — but don’t correct it in the code (the incorrect result will be used later).

Visualize the laminar profile of the patched IOI scores, along with the clean IOI scores, as in Figure 5.53.

A good experiment design has manipulation checks built in. Coding these kinds of experiments is tricky, and it’s very easy to make mistakes. The “good” mistakes cause your script to crash. The “bad” mistakes are the ones that don’t cause errors or warnings (a.k.a., silent errors), and thus can be difficult to fix — if you can even find them.

The ideal manipulation checks show (1) a change when you expect a change, and (2) no change when you expect no change.

The manipulation check works for the first L− 1 layers, but it fails for the final layer:

array([[ 3.896, 0. ],
[ 4.650, 0. ],
[ 5.186, 0. ],
[ 5.580, 0. ],
...
[ 6.068, 28.196]])

The first column is the differences between the penultimate hidden-state vectors for the ME vs. EM models. Those two vectors differ because they come from different sentences and thus have different contexts. But the second column should be all zeros, because that’s the patched vector: the vectors in the ME and EM models should be identical because that’s the goal of the hook function.

However, they are different for the final layer.

The discrepancy comes from the final hidden state vectors including the final layerNorm transformation. That comes after the transformer, as you learned in Project 26.

Perhaps the solution to this problem is to invert the final layerNorm in the hook function? In theory, layerNorm is invertible — but only if you know the mean and standard deviation of the pre-normed data. Hugging Face models do not store those data, which makes the layerNorm transformation practically non-invertible.

A better solution would be to patch the transformer outputs of the ME model, instead of patching the hidden states. That would require hooking into the ME model during a forward pass instead of relying on the hidden-state output. That’s certainly feasible to do, although I will proceed with the project without that fix, because I’ll incorporate this discussion into Part 5.

Most importantly: This is the worst kind of code bug because it produced no warning messages or errors, and could easily have been missed if we hadn’t incorporated a manipulation check.

Anyway, back to the experiment. The results in Figure 5.53 are very interesting: Patching the early layers had nearly no impact on the final result. That is, the model correctly predicted that Emma gave the coffee to Mike until around layer 20, at which point the manipulation became increasingly effective.

Figure 5.53: Visualization of the laminar IOI task results. The x-axis shows the manipulated layer and the y-axis shows the IOI score. The red and blue horizontal lines are the “clean” IOI scores from the non-manipulated models. The result from the final layer is drawn as a red “x”.

The final layer is clearly an outlier, which shouldn’t be surprising given the results of the manipulation check. This data point is invalid and we’ll exclude it from subsequent analyses.

The laminar profile looks like an inverted-sigmoid function. The goal of the rest of this project is to model that curve and mathematically estimate the layer at which the manipulation had an inflection point.

We’re going to put the LLM data on hold for a bit to focus on the mechanics of curve-fitting. Then you’ll apply the code to the IOI scores.

The general idea of curve-fitting is similar to that of regression: Start with a mathematical model of the data, and find the parameters that best match the model to the data. For this project, we’ll fit a sigmoid function:

y^=A1+exp⁡(−k(x−x0))+b(5.9)\hat{y} = \frac{A}{1 + \exp(-k(x - x_0))} + b \tag{5.9}

For our project, x are transformer layer indices, y are the IOI scores (the observed data), and ŷ are the model-predicted IOI scores. The goal is to find the values of A, k, x_0, and b that minimize the squared discrepancies between y and ŷ. The equation is nonlinear in the parameters so we cannot solve it using least-squares as we would for a standard regression analysis. That’s why we use a nonlinear curve-fitting optimization.

You can fit a curve in SciPy using the curve_fit function, which is in the scipy.optimize module. Read the four steps below that describe the pipeline; you’ll implement each of these steps in the rest of Part 4.

  1. Create a Python function to fit (in our case, that’s the translation of Equation 5.9 into code). The function takes as input arguments the x-values and a set of parameters, and returns y = f(x). The goal of curve-fitting is to find the set of parameters that best fit the data, which means minimizing ∑ (y −ŷ)^2.

  2. Define a vector of initial guesses for the parameters. The more accurate the initial estimates, the better the fit will be.

  3. Call the curve_fit function with the fitting function from Step 1, the x and y values (the observed data), and the vector of initial parameter estimates.

If the purpose of the model-fitting is to generalize to new data, you would want enough data to separate into a train set and test set (e.g., by repeating the experiment with many other IOI sentences). However, here we have only one set of IOI scores so we will interpret the results as a quantitative description of the data without worrying about generalization performance.

  1. The output of curve_fit is a set of parameters that you can use to generate predicted data.

Task

Write a Python function, called sigmoid_fun, that takes five input arguments, corresponding to the five terms in Equation 5.9, in this order: x,A,x0,k,b. The function implements Equation 5.9 and returns the values of ŷ.

Test the function by generating 50 linearly spaced numbers between -10 and 10. Then define y using the sigmoid function with parameters A = 10, x_0 = 0, k = 1, b = 2. Then add some random noise and visualize as in Figure 5.54.

Figure 5.54: Some noisy sigmoid data that we’ll use to test the curve-fitting analysis.

These are our simulated data with known ground-truth parameter values. Let’s see whether SciPy’s optimization library can recover those values based on fitting the function to the noisy data.

Task

Estimate initial parameters for the search as follows: A is the maximum value of y; x_0 is the median of x; k = 1; b is the minimum value of y.

Call the curve_fit function with the following input arguments: the sigmoid function you wrote earlier, the x-values, the y-values, and the initial parameter estimates. The first output is an array of parameter estimates in the same order as they are listed in the sigmoid function, and the second output is the covariance of the parameter estimates (not used here).

Print a table of the ground-truth and model-estimated parameters.

Here’s my table; your second column will look slightly different due to random number generation.

    Truth | Estim. ---+------+--------  A |  10  |  9.55 x0 |   0  | -0.15

k | 1 | 1.56
b | 2 | 2.03

The estimated parameters are a fairly good match to the ground truth values. The discrepancies are due to non-systematic noise. You can try running the code again with less noise or a larger sample size, and you’ll see a closer match.

Task

Plot the data again, this time adding the model-fitted curve. To generate the model predictions, call the sigmoid function again with the same values of x but the model-estimated parameters instead of the ground-truth parameters. Plot the data, the model predictions, and a vertical line at x_0, as in Figure 5.55.

Figure 5.55: Same data as in Figure 5.54 but with the model fit drawn as a green line.

The fit is quite good overall. Now you’re ready to apply this pipeline to the real LLM data.

Task

Remove the final data point from the vector of IOI scores.

Copy and adapt the code from Part 4 to model the IOI scores. The x values are the transformer layer indices, and the y values are the IOI scores.

Visualize the results as in Figure 5.56.

Figure 5.56: The data are the same as in Figure 5.53, but with the model-predicted sigmoid plotted in green, and the value of the x_0 parameter indicated with the vertical dashed pink line.

The fit looks pretty good, although it failed to capture the drop in the last several transformer layers. The estimated value of x_0 shows the inflection point where the model’s representations of long-range semantic dependencies flipped its decision from labeling “Mike” to “Emma” as the indirect object.

When you have working code, you can try fitting the data again without removing the incorrect final-layer data point. You will observe the strong impact that one outlier data point can have on model-fitting.

These findings highlight how much information can be packed into each hidden-state vector. Indeed, all of these results are based on the token “ to”, and yet the transformers loaded context from earlier in the text onto that vector, so that it begins pointing towards the indirect object that was referenced earlier in the sentence.