Skip to content
ImagineWorld

MLP

node_idnode-book_50-ml-projects-to-understand-llms_chapter-07-mlp
node_typechapter_node
schema_profileworld.chapter_node.v1
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
statusactive
chapter_num7
chapter_titleMLP
sections7.42 Project 42: MLP weights and activations characteristics, 7.43 Project 43: Characterizing the MLP progression, 7.44 Project 44: Grammar tuning in MLP projections, 7.45 Project 45: Minkowski distance, mutual information, and token positions, 7.46 Project 46: Statistics-based lesioning in MLP neurons, 7.47 Project 47: Supervised probing with XGBoost, 7.48 Project 48: Can vs. can't classification via logistic regression, 7.49 Project 49: Successive median-replacement of MLP activations, 7.50 Project 50: Recommender systems with MLP projections
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Background: The multi-layer perceptron (MLP) block

Section titled “Background: The multi-layer perceptron (MLP) block”

The MLP block of the transformer is a lot less complicated than the attention block — but no less important for the capabilities of modern LLMs.

Figure 7.1 shows the basic formulation of the MLP block, and highlights the four stages of processing that you’ll separate and examine in this chapter. Each stage is separated by a mathematical operation.

Figure 7.1: Diagram overview of the MLP block of the transformer layer. “S1” stands for “processing stage 1.”

I will describe each of the stages below, and you’ll learn how to access, visualize, and analyze them throughout the chapter.

Stage 1: Input

The input to the MLP block are the hidden-state vectors after passing through the attention block and after the second layerNorm.

Stage 2: Linear expansion, pre-GELU

The vectors are multiplied by a weights matrix W_1 that increases the dimensionality from the embeddings dimensionality (e.g., 768 for GPT-2-small) to 4× that size (e.g., 3072 for GPT-2-small). This dimensionality-expansion is linear because it’s implemented by matrix multiplication. That means that all the information in the vectors at Stage 1 is present at Stage 2 — no information is lost or gained. Instead, the information has been distributed over a larger space.

There is a good reason to expand the dimensionality, which I’ll explain in the next subsection. But there is no mathematical requirement for the expansion to be a factor of 4. That’s a common choice, but some LLMs expand by factors of, e.g., 2.5 or 3 or 8.

Stage 3: Expanded dimensionality, post-GELU

A nonlinear activation function (Gaussian Error Linear Unit) is applied to the expanded-dimensionality data. I’ll describe the GELU function below, but it basically just dampens negative activation values, similar to the ReLU nonlinearity common in deep learning. At this point, the information at Stage 3 is different from that at Stage 2, and is amenable to sparse feature selection.

Stage 4: Projection (post-contraction)

The purpose of the MLP block is to calculate adjustments to the hidden-state vectors to improve next-token selection based on context and world knowledge learned during training. Therefore, the MLP adjustments need to be compressed back to the embeddings dimensionality. That’s done through multiplication with a matrix W_2. The result of that dimension-contraction is a set of vectors that project back onto the hidden-state vectors.

Note: The code to produce this demo and Figure 7.2 is in the code notebook for Project 42.

The GELU nonlinear activation function is conceptually simple: Preserve the positive activation values while dampening the negative values. It is illustrated in Figure 7.2.

Figure 7.2: Impact of the GELU activation function. The x-axis shows simulated raw activation values (e.g., at Stage 2), and the y-axis shows the activation values after passing through the GELU function (e.g., Stage 3). The color indicates the squared magnitude of the impact of GELU. The main point is that positive values pass through while negative values are severely dampened.

In that figure, the color of each marker encodes the squared difference between the pre-GELU “raw” activation and the post-GELU value. The positive values are almost perfectly preserved, and thus are colored near-black. The more negative the pre-GELU activation value, the more it is changed by the activation function.

If you’ve studied deep learning before, you’ll recognize that GELU is very similar to the popular ReLU nonlinear function. The two differences are (1) ReLU zeros out all negative values while GELU only dampens them, and (2) GELU is smoother while ReLU has a sharp transition from negative to positive values.

Here is a question that people often ask when learning about ReLU and GELU activation functions: Does this mean that the model can no longer compute negative numbers? The answer is that the model can indeed process negative numbers, because the weights can be negative. A positive post-GELU activation value can be multiplied by a negative weight, thus passing a negative value onto the hidden-state vectors.

Then what is the purpose of the GELU activation? One of the key properties of the GELU is that it sparsifies the representations: Any irrelevant information can be assigned a negative activation value, which means it will be zeroed-out from the GELU activation.

Note: The code to produce this demo and Figure 7.3 is in the code notebook file for Project 42.

Why expand the dimensionality only to contract it back to the original dimensionality (after a nonlinearity)? This is a common “trick” in ML for improving classification performance, and here I’ll show a toy demo of that concept in 2-3D for visualization.

Consider panel A of Figure 7.3. There are two categories of data, which are defined as noisy rings. It is visually obvious that the two categories are perfectly separable — but they are not linearly separable. There is no way to draw a line in the graph that would separate the green circles from the red squares.

Figure 7.3: Toy example of how dimensionality expansion plus a nonlinearity can make linearly inseparable data (panel A) easily separated (panel B). This facilitates feature extraction and selection.

I therefore expanded the dimensionality from two to three, where the third dimension is defined as the Euclidean distance to the origin in the 2D data. With the dimension-expansion and nonlinearity, the two categories are now perfectly linearly separable using a horizontal plane between the two rings.

Thus: linearly inseparable in 2D yet perfectly linearly separable in 3D.

On the one hand, this is a contrived example that I crafted specifically to illustrate the concept. But I hope it provides some visual intuition for why the expansion-contraction trick is used in ML classification. Of course, in MLP blocks the data cannot be visualized: even GPT-2-small goes from 768 to 3072 dimensions.

In the MLP block, the reason for the post-nonlinearity contraction is that the feature selection ultimately needs to be added back onto the hidden-state vectors.

day-mode Bookmark

MLP weights and activations characteristics

Let’s begin by characterizing the weights (static features) and activations (dynamic features) of the four MLP stages I outlined in Figure 7.1. You will discover that the distributions of the learned weights are not terribly insightful on their own, while the distributions of the activations reveal the nonlinear and sparsifying nature of the MLP block.

You’ll also learn how to extract the weights, and how to hook GPT-2 models to extract activations in the four stages of MLP processing.

The goal of Part 1 is to extract and visualize the weights and bias terms, and inspect their distributions.

There are two sets of weights in the MLP block, labeled W_1 (linearly expands the dimensionality) and W_2 (linearly contracts the dimensionality after the GELU nonlinearity). In GPT-2 models, those are also called the “fully connected” (c_fc) and “projection” (c_proj) layers. They have different names in different models, as you’ll see in later projects with BERT.

Task

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

Extract the weights and biases from layer 5. Count the total number of learned parameters in each, and the percent of total learned parameters for each block (that is, the % total for W_1 is the percentage of all parameters in the MLP block). Report the results as in the table below.

 Type |     Size     |   Count   | % total ------+--------------+-----------+---------

W1 | [768, 3072] | 2,359,296 | 49.959%
b1 | [3072] | 3,072 | 0.065%
W2 | [3072, 768] | 2,359,296 | 49.959%
b2 | [768] | 768 | 0.016%

The table formatting can get a bit tricky; if you encounter errors or difficulties, try changing the data type, e.g., from torch.Size to a list or string.

One important take-home here is that the bias terms, though important in the model for allowing non-mean-centered calculations, are only a tiny fraction of the total number of trained parameters. That’s why people often ignore the bias terms when initializing models or when characterizing the weights.

In fact, you can ignore the bias terms for the rest of the project, and just focus on the weights.

Brief linear algebra comment. The W_1 and W_2 matrices may seem like inverses of each other, because W_2 “undoes” the expansion from W_1 (Figure 7.1). Although a post-expansion contraction could be accomplished using the inverse of the expansion matrix, this is not the case in the MLP block, because the goal is not only to contract, but also to select features separated in the high-dimensional space to be added to the hidden-state vectors. The online code file includes a quick demo of the unique nature of the two weights matrices, by showing that their product is not the identity matrix.

Task

Calculate the histograms of the two weights matrices you extracted, and visualize as in Figure 7.4. Use the same bin boundaries of 201 steps between -.8 and .8.

Next, loop over all transformer layers to extract the distributions of the two weights matrices. Store the histogram values in matrices and visualize in heatmaps as in Figure 7.5. Use the same color scaling in both plots.

The two distributions are roughly Gaussian: one central peak with smooth symmetric decays on either side.

Figure 7.4: Histograms of the two weights matrices in the MLP block from transformer layer 5 in GPT-2-small.

The W_2 contraction matrix has a narrower distribution, but don’t over-interpret that observation before seeing whether that feature is consistent over the layers.

Figure 7.5: Histograms of the two weights matrices for all transformer layers. Each row corresponds to a line from Figure 7.4, and the color corresponds to the height of the distribution.

The shape of the W_1 weights is constant throughout the model, whereas the W_2 weights distribution gets wider as the model approaches the final token selection layers.

Part 2: Hooks and single-layer activation distributions

Section titled “Part 2: Hooks and single-layer activation distributions”

We will now move from examining weights to activations — the product of the weights with hidden-state vectors at the input into the MLP block. Remember that the MLP internal activations (stages 2-4) are not hidden-state vectors; they are adjustments to those vectors that help transform the vectors from representations of the current token to predictions about the next token.

Task

Implant a hook function into the mlp block of transformer layer 5. The hook should calculate and extract the four computational stages and store them as items in a dictionary. To calculate each stage, you will need to call the sublayers from module.

Tokenize the following text: Would you prefer a strawberry-flavored peanut or a peanut-flavored strawberry? Run a forward pass through the model to get the MLP activations. Remove the hook and print the sizes of the activations matrices in each key.

Finally, calculate and visualize the histograms of the activations in each stage across all tokens, and report the total number of activation values, as in Figure 7.6. Use the same bin boundaries of -3 to 3 for all histograms.

The output of the model call contains the final output logits (and optionally other variables like the hidden states). We’re not using those data in this project, and so you don’t need to define an output variable when running a forward pass.

To get all four processing stages, you can either create and implant several hooks for each model layer, or you can call the layers like this:

X1 = input[0] X2 = module.c_fc(X1) X3 = module.act(X2) X4 = module.c_proj(X3)

This approach is (in my opinion) superior in terms of conceptual clarity and educational value. On the other hand, the disadvantage is that the calculations are redundantly repeated. That is, all the calculations in c_fc are done twice: Once in the hook function and then again when the model gets to each c_fc sublayer.

In this project, that additional compute time is irrelevant because the model is small and there are only 17 tokens. But this could be a concern for larger models and more tokens.

The more computationally efficient approach is to implant separate hooks into each MLP sublayer to store the already-calculated activations. On the other hand, that approach is more complicated and requires more code.

Either way, you should get the following keys and value sizes in the dictionary:

[1, 17,  768] in stage “input” [1, 17, 3072] in stage “expansion” [1, 17, 3072] in stage “gelu” [1, 17,  768] in stage “projection”

The sizes confirm the progression from embeddings dimensionality to expanded dimensionality, and back down to the embeddings dimensionality.

The histograms in Figure 7.6 reveal how the MLP stages shape the distributions of activations.

Figure 7.6: Histograms of MLP activation values at each of the four processing stages from transformer layer 5.

A few observations:

  1. The input activations are distributed around zero, but the shape of the histogram is closer to a Laplace distribution than a Gaussian.

  2. The linear transformation from input to expansion broadens the distribution and shifts it negative. What is the purpose of making the distribution more negative? Think of an answer to the question; I’ll discuss it below.

  3. The nonlinear activation (GELU) of the expansion truncates the negative values. Indeed, the bulk of the distribution is now between around -.2 and 0.

  4. The linear contraction from the high-dimensional space back to the embeddings dimensionality produces a distribution that looks somewhat similar to that of the input but wider.

Now to discuss the extreme data-value constriction from the GELU. The point of the expansion is to facilitate feature extraction, and the negative shift plus the “clipping” from the GELU facilitates sparsity. There are relatively few positive-valued activations (note the small mass of the distribution with positive values), which means fewer and more selective features will be added back onto the hidden-state vectors.

Please make an effort to commit these distribution shapes to memory. They are important for understanding how to interpret and manipulate different MLP processing stages, and therefore are relevant to most projects in this chapter.

The distributions in Part 2 incorporated all tokens in the sentence; do the distributions change for different token positions? That’s what you’ll investigate here.

Task

Repeat the analysis from Part 2 in a for-loop over token positions (still using the data from layer 5). Use the same histogram bin boundaries that you used in Part 2. Visualize the heatmaps as in Figure 7.7.

The overall shapes of the distributions remain qualitatively the same for all token positions except the first.

Figure 7.7: Each row in the heatmaps corresponds to the histograms in Figure 7.6 for a different token position (y-axis) from one transformer layer, with color mapping onto probability density. All four heatmaps use the same color scaling.

Part 4: Laminar profiles of MLP distributions

Section titled “Part 4: Laminar profiles of MLP distributions”

The goal of Part 4 is to repeat the analysis in Part 2 but over all the layers.

Task

Implant new hook functions in each transformer layer. Each hook should be similar to the hook in Part 2 but the key name for the dictionary must include the layer number. One more change from Part 2: Use the output argument instead of calling module.c_proj for the Stage 4 projection activations.

Run a forward pass to get the MLP activations. Remove the hooks and print the names of the keys and the shapes of the tensors in the MLP activations dictionary to confirm that all four stages were stored for all layers.

Calculate histograms for each of the four stages in each layer, for all tokens except the first, using the same bin boundaries as in previous parts. Store the data in matrices of transformer layer × histogram bins. Visualize as in Figure 7.8.

The items in the dictionary include:

L0_input has size [1, 17, 768]
L0_expansion has size [1, 17, 3072]
L0_gelu has size [1, 17, 3072]

L0_projection has size [1, 17, 768]

And so on for all transformer layers.

The results of the histogram analysis show that the shapes of the distributions remain roughly constant across the layers, with exception of the final contraction stage, in which the distributions become broader deeper into the model.

Figure 7.8: Similar to Figure 7.7, but now pooling over all tokens (except the first) and separating the distributions per layer (y-axis).

Regarding the change in hook function from (redundantly) calling the c_proj module in Part 2 to detaching the module output here: In terms of computation time there isn’t much of a benefit, but I want you to see that the output of the c_proj layer is the result of Stage 4 in the MLP block.

T-SNE is a nonlinear dimension-reduction method that is often used to identify and visualize clusters in high-dimensional data, by projecting them down to a visualizable number of dimensions (typically, two). Briefly, the idea is that the probability of two points being “neighbors” is proportional to their Euclidean distance. The T-SNE analysis finds a lower dimensional map where the probability distribution is the same as in the higher dimension. In other words, the goal is to find a low-dimensional representation of the data where the distances might differ, but the probability distribution of the distances is as close to the distribution in the high-dimensional data as possible.

An ideal result of a T-SNE analysis is clearly identifiable clusters in the lower-dimensional space that provide insight into how the data samples are related to each other in the higher-dimensional space.

The matrix of mappings is randomly initialized and optimized through gradient descent, which means the solution will differ each time you rerun the analysis on the same data.

The key parameter of the T-SNE analysis is called “perplexity” and determines the balance between local and global structure. Higher perplexity values allow for identifying more complex, nonlinear structure in the data, but at the risk of less interpretable results. Perplexity should be less than the number of samples (in our case, that’s the number of tokens).

We will use T-SNE here to explore whether the tokens in our text can be grouped into clusters based on the MLP activations. It’s an interesting exploration because several tokens are repeated but in a slightly different context. As a reminder, the text is Would you prefer a strawberry-flavored peanut or a peanut-flavored strawberry?

You can implement a T-SNE analysis using the sklearn.manifold library.

Task

Run two T-SNE analyses on the activations from Stage 1 (input) and Stage 4 (projection) from layer 10. Set the number of components (the dimensionality of the result) to 2 and the perplexity to 4. Visualize the results as in Figure 7.9A-B. Then create a scatter plot of the two data matrices as in Figure 7.9C.

Notice that two identical tokens that appeared in different sequence positions can be close to each other (e.g., “peanut”) or further apart (e.g., “a”). These differences reflect different contexts calculated by the MLP stages.

Figure 7.9: Results of two T-SNE analyses in layer 10 Stage 1 (MLP input; panel A) and Stage 4 (MLP output; panel B). Panel C shows a scatter plot of the input by the projection values, with each marker corresponding to an embeddings dimension.

The input and projections are near-zero correlated (Figure 7.9C). The scale of the x- and y-axes appear to be very different, but most of the projection values are close to zero (you can see this as well from Figure 7.8D), while a relatively small number have relatively large values — those are not noisy outliers, but instead are the sparse adjustments that were selected from the post-GELU expansion stage and are then provided back to the hidden-state vectors.

The lack of correlation between the inputs into and outputs from the MLP block should be no surprise: They are completely different representations! The inputs to MLP are the hidden-state vectors while the outputs from MLP are the adjustments to the hidden-state vectors. Indeed, if the correlation in Figure 7.9C were nearly 1, then it would mean that the MLP block simply doubled the hidden-state vectors — lengthened the vector without changing its direction. That’s the opposite of what the MLP block should do; it should adjust the orientation of the hidden-state vectors to nudge them away from the token in the current position to a prediction about the token in the next position.

By the way, do your T-SNE results look exactly like mine? I’m sure they don’t: The mapping matrix is randomly initialized. In a T-SNE analysis, you should look for how the samples relate to each other within the map, not their precise numerical coordinate values.

Task

Without changing any parameters, rerun the T-SNE analysis and visualization multiple times. Notice that the results change each time, due to the random initializations.

Explore the perplexity parameter. It must be a positive number greater than zero and less than the number of samples. Try extreme but valid values like .1 and 16.9. Also try negative numbers and numbers above 17. You can try different values informally; no need to setup an experiment with a parametric manipulation of this parameter.

Smaller perplexity values produce tighter clusters, while larger values produce a larger number of clusters, to the extreme where all data points are roughly equidistant.

Choosing an appropriate perplexity value can be tricky, and is often based on a combination of expectations, explorations in preliminary datasets, and choices made by other researchers with similar datasets. As a rough guideline, you can choose perplexity values between 5 and N/3 (for N samples), but not over 100. If you see many more clusters than you expect, try increasing perplexity. Or if the results appear as an amorphous cloud, try decreasing perplexity.

Importantly, rerun the T-SNE analysis multiple times to observe whether the clustering (that is, the grouping of data points, not the exact numerical results) appears similar across runs. If the results change qualitatively, then either the perplexity score is not appropriate, or there is no meaningful structure in the data that can be identified using T-SNE.

I must admit, the T-SNE results are not very insightful in this example. But the method and code can be used to study larger datasets with more meaningful token groupings, such as tokens separated according to grammatical or semantic category.

The final part of this project is simple: Rerun the code with only one change: Use GPT-2-large instead of GPT-2-small.

Before rerunning the code, I recommend taking screenshots of the figures to facilitate comparison.

In particular, look for:

  1. Whether the hard-coded parameter values that were set based on GPT-2-small, like the boundaries of histograms and color limits of heatmaps, are still appropriate for GPT-2-large.

  2. Whether the overall patterns of results are the same.

Findings in one model do not always generalize to other models, but the analyses in this project do appear visually consistent.

Many of the visualizations are also preserved without need for adjustments, with some minor exceptions such as the formatting of the table in Part 1.

By the way, all models in the GPT-2 series use the same tokenizer, so you can import, e.g., the GPT-2-small tokenizer and the GPT-2-large model. That said, using matching names in the imports makes your code look cleaner.

day-mode Bookmark

Characterizing the MLP progression

This project follows from the previous, by investigating MLP activations and adjustments in more detail. In particular, you will explore RSA and effective dimensionality, and learn an alternative measure of effective dimensionality, called the participation ratio.

Throughout this project, we will compare a 94-token sequence against 94 repetitions of the same token. In both batches, the number of tokens is the same, as is the macro-context (all tokens are from a Wikipedia page about Vietnamese coffee).

Task

Import GPT-2 and its tokenizer. Use the wikipedia library to import the text from the page for Coffee_production_in_Vietnam.

Confirm that the string “ coffee” is encoded as a single token, and find the indices of all instances of that token in the text. Define a variable for the number of target tokens. You should get 94.

Create two batches of tokens. The first is one sequence comprising the first 95 tokens (corresponding to a first token to exclude from analyses, and 94 tokens to analyze), and the second comprises 94 sequences of 10 tokens each, where the final token is the target. Check the position of first target token to make sure that the first sequence will be properly indexed (e.g., if the first appearance of “ coffee” is before the tenth token). Print out shapes of both batches.

Once you import the wikipedia library, downloading the text from a Wikipage is as simple as running the following code: text = wikipedia.page(pagename).content

Where pagename is the name of page. You should reproduce the following confirmations:

” coffee” comprises token(s): [6891]

There are 94 " coffee" tokens,
and the first is in position 31

Each sequence in the second batch begins 9 tokens before each target token. If the first appearance of the target token had been at, e.g., position 2, then Python would create that sequence by wrapping around to index tokens from the end of the Wikipedia page. If that happens, the solution is to exclude any target tokens before the context length.

Each sequence in the 94 × 10 batch ends with token index 6891. The other batch is of size 1 × 95, corresponding to one sequence with 94 tokens to analyze, and the first token to exclude.

Henceforth, I’ll refer to the batch with one long sequence as the “one-sequence batch,” and I’ll refer to the other one as the “many-sequence batch”.

The goal of Part 2 is to obtain activations from one transformer layer for the four processing stages (input, expansion, GELU, projection).

Task

Create a hook function that calculates and stores all four stages of the MLP block. Implant the hook into each transformer layer. For analyzing the data in for-loops later in the project, it will be convenient to name the keys using stage integers like “1”, “2”, “3”, and “4”; but for labeling the results, you’ll need a list of short-hand labels like Inpu, Expa, and so on.

Run two forward passes for each of the two batches. You won’t need the logits or hidden-states, so you don’t need to assign an output variable when calling the model. Make a copy of the MLP hooked activations after each forward pass to avoid overwriting.

Print out all the keys and the sizes of their corresponding values, and visualize the histograms of all tokens from the one-sequence batch, and the final token from the many-sequences batch, for all MLP stages from layer index L∕2 for L transformer layers, as in Figure 7.10.

Here’s a selection from the one-sequence batch (first four) and the many-sequence batch (second four):

“L0_1” is shape [1, 96, 768] “L0_2” is shape [1, 96, 3072] “L0_3” is shape [1, 96, 3072] “L0_4” is shape [1, 96, 768] … “L0_1” is shape [95, 10, 768] “L0_2” is shape [95, 10, 3072] “L0_3” is shape [95, 10, 3072] “L0_4” is shape [95, 10, 768]

Make sure you understand what the sizes correspond to.

Figure 7.10: Distributions of activations in the four processing stages of MLP. Data are from transformer layer 6. The y-axis is trimmed for visibility.

The shapes of the four distributions are broadly similar to what you observed in Project 42. Furthermore, the two sets of histograms for the two sequences look similar to each other. That is not trivial considering that panel B shows data from the same token repeated 94 times (though with different preceding contexts).

By the way, when making a copy of the dictionary between model calls to avoid overwriting, you can optionally clear out (re-initialize) the dictionary like this:

model(oneLongSeq)
mlp_oneseq = mlp_values.copy()
mlp_values = {} # re-initialize dictionary
model(batch)

In this case, re-initializing is not necessary because the dictionary key names will match exactly for the two runs, and thus all items will be overwritten. But re-initializing the dictionary might be useful for an application with multiple hooks saving data to the same dictionary using different keynames. I’ll show an example of this in Project 44.

The goals of Parts 3 and 4 are to develop code for an in-depth inspection of one layer, and then to calculate and visualize summary statistics over all the layers.

Task

Continuing with the same layer you used in Part 2, calculate and visualize the all-to-all token cosine-similarity matrices for all four processing stages and both batches (Figure 7.11). Use all tokens except the first from the one-sequence batch, and the target token from the many-sequence batch. Allow Python to auto-select color limits for each heatmap, and show the colorbars for comparisons.

Extract the non-redundant off-diagonal elements of the matrices to create distributions as in Figure 7.12.

Throughout this book, you’ve learned several implementations of cosine similarity: “manual” calculation via the matrix multiplication of unit-normed vectors, PyTorch’s implementation, and Scikit-learn’s implementation. In my solution to this project I used the scikit-learn function cosine_similarity.

Figure 7.11: Cosine similarity matrices for all pairs of tokens, separated for the four processing stages (columns) and the “one-sequence” vs. “many-sequences” batches (rows). Note that each heatmap has its own color scaling.

The similarity values are generally higher for the many-sequence batch compared to the one-sequence batch. That’s not surprising: It’s the same token 94 times. On the other hand, the context from preceding tokens is different for each sequence, and the goal of the MLP block is to calculate adjustments to hidden-state vectors, which are sequence-unique.

Figure 7.12: Distributions of the non-redundant cosine similarity values from the matrices in Figure 7.11. Panel A shows data from the one-sequence batch, and panel B shows data from the many-sequences batch.

The strongest inter-vector similarities are in the linear expansion pre-GELU stage. The 94 vectors go from 768D to 3072D, but because the transformation is linear, no new information can be added. Instead, the information already available at Stage 1 is distributed into a higher dimensionality, which increases the statistical redundancies across the vectors. The GELU nonlinearity allows for sparsity and feature-extraction, and thus the cosine similarities drop to below the input level.

Because of the changes in dimensionalities, it is not possible to compare directly, e.g., the input with GELU vectors. However, the two pairs of stages with the same dimensionality can be directly compared, and all pairs can be indirectly compared via an RSA. We’ll get back to RSA in Part 4.

Task

Calculate the cosine similarity matrices between the input and projection stages, and between the expansion and GELU stages, in the one-sequence batch. Visualize as heatmaps and histograms, as in Figure 7.13. Consider which (if any) of these results can be meaningfully interpreted.

Keep in mind that although cosine similarity matrices of a data matrix with itself is symmetric, the similarity matrix between two different data matrices is not symmetric. In this case, we have the similarities between two distinct MLP stages, and thus, their corresponding matrices are not symmetric.

Figure 7.13: Cosine similarity matrices between the dimensionality-matching pairs of MLP processing stages, and their distributions. Note that the matrices in panels A and B are non-symmetric: the tokens match but the rows and columns correspond to different processing stages.

The implication of this asymmetry is that the histograms are calculated from the entire matrix, not just the upper-triangular elements.

What do these results show and do they make any sense? In a strict mathematical sense, cosine similarity can be calculated between any two vectors that have the same dimensionality (e.g., Stages 1 and 4). But that doesn’t mean the results are interpretable. In this case, the data from Stages 1 and 4 are completely distinct: Stage 1 (the input) is the layerNormed hidden-state vectors whereas Stage 4 (the projection) is the adjustment to the hidden-state vectors. They are completely different representations and it actually doesn’t make sense to calculate their similarity values. That’s why the similarity values are close to zero.

The data from Stages 2 and 3 are only somewhat more sensible to compare: They reflect the expanded-dimensionality representations before vs. after the GELU nonlinearity. However, the feature selection happens during the contraction, and thus the cosine similarity values here are really just telling us about the drop in linearity due to the GELU.

Thus, neither of these analyses is really interpretable. But it is important to understand why they are not interpretable, and to understand that comparing the representations across the processing stages can be done appropriately, by comparing their internal relational structure. That’s the segue to Part 4.

The goal of Part 4 is to write and test a function that implements an RSA on MLP activations in a specified layer and between a specified pair of processing stages. RSA (representational similarity analysis) was introduced in Projects 12 and 38; please refer back to those projects if you need a refresher on the goals and implementations of RSA. As a brief reminder: The RSA score quantifies how the internal representations (measured through cosine similarity of many sample pairs) in one space (e.g., Stage 1) are related to the internal representations in another space (e.g., Stage 4).

Task

Create a Python function, called calc_RSA, that takes two dictionary key names as inputs, calculates RSA between the MLP data corresponding to those two key names, and returns the RSA scores for the one-sequence and many-sequence datasets. As a brief reminder, an RSA analysis works by calculating the cosine similarity values across all vector pairs within each processing stage, extracting the non-redundant off-diagonal elements of each similarity matrix, and then correlating those similarity values between two different processing stages. Scores closer to 1 indicate that the internal relational structure between samples is similar, even if the representations (and their dimensionalities) differ between processing stages.

Calculate the RSA score among all pairs of processing stages for one layer. Visualize the results in bar plots as in Figure 7.14.

The reason to put the analysis code into a function is that you’ll call this function for each layer in a for-loop in Part 7.

Figure 7.14: RSA scores for each pair of processing stages. “I” is input; “E” is expansion; “G” is GELU; “P” is projection.

Two observations about these results: First, the RSA scores are generally higher for the many-sequence compared to the one-sequence batch. Second, the lowest RSA scores are in pairs that involve the projection stage.

Part 5: Participation ratio and effective dimensionality in one layer

Section titled “Part 5: Participation ratio and effective dimensionality in one layer”

I introduced the concept, calculation, and interpretation of effective dimensionality in Project 28 (Chapter 5). Briefly, it is the number of dimensions that make “significant” contributions to the overall variability of the data, where “significant” is based on a threshold such as 95% of the total data variability. If the data matrix contains a large number of dimensions, the effective dimensionality can be a sensitive measure. But imagine a data matrix with only four features; the only possible values of effective dimensionality would be 0, 25, 50, and 100%.

The participation ratio is an alternative dimensionality analysis that measures the number of dimensions that meaningfully contribute to a multivariable dataset. It has units of “dimensions” and, unlike, the discrete nature of effective dimensionality, is continuous and can take any non-negative value.

You can calculate the participation ratio from the eigenvalues (from a PCA) or from the singular values (from an SVD) as follows.

PR=(∑i=1dλi)2∑i=1dλi2=(∑i=1dσi2)2∑i=1dσi4(7.1)PR = \frac{(\sum_{i=1}^{d} \lambda_i)^2}{\sum_{i=1}^{d} \lambda_i^2} = \frac{(\sum_{i=1}^{d} \sigma_i^2)^2}{\sum_{i=1}^{d} \sigma_i^4} \tag{7.1}

where λ are the eigenvalues and σ are the singular values. The eigenvalues of matrix A^⊤A are the squared singular values of A, which is why the σ values are squared in the equation. For non-square matrices, it’s easier to calculate participation ratio from the singular values.

Note: It is important to mean-center the data before calculating participation ratio for the same reason that mean-centering is important for PCA: global shifts in the data will skew the dimensionality analysis to reflect offsets rather than distributed structure in the data. For this analysis, you can mean-center along the token dimension (first dimension in the data matrices).

Task

Write a Python function that takes a dictionary key name as input, calculates effective dimensionality and participation ratio for the one-sequence and many-sequence datasets, and returns effective dimensionality and participation ratio for the two batches. Inside the function, extract the singular values from the mean-centered datasets (tip: use the input argument compute_uv=False to save computation time and return only the σ’s) and remember to square the singular values for both analyses. Use an effective dimensionality threshold of 95% variance explained.

Using data from one layer (I used layer 6), extract the two dimensionality measures and visualize each metric using bar plots, and their relationship using scatter plots, as in Figure 7.15.

Figure 7.15: Comparisons of participation ratio and effective dimensionality results for transformer layer 6. Panels A-C show data from the one-sequence batch, and panels D-F show data from the many-sequence batch.

Across the four panels of bar plots, the results paint a consistent picture of dimensionality decreasing from input to expansion, then increasing at later stages. The reduction in effective dimensionality at the linear transformation of input to expansion is particularly striking because the ambient dimensionality increases by a factor of 4 (768 to 3072 for GPT-2-small). In other words, the data space became more spacious, although the data itself hadn’t yet filled in that additional space.

Although participation ratio and effective dimensionality show slightly different results, the pattern is quite similar, as evidenced by the scatter plots. On the other hand, N = 4 is quite low to establish a meaningful relationship. On to Part 6…

The final part of this project involves calculating and visualizing effective dimensionality and participation ratio for the four processing stages. You’ll create two visualizations of the results; the first is more comprehensive but is a lot of information, while the second is easier to interpret but aggregates more data.

Task

Initialize two variables to store data:

  • dimension_results as a 12 (layers) × 4 (processing stages) × 4 (result type) tensor to store the outputs of the function calc_partrat_effdim. Those outputs are the participation ratio and effective dimensionality from the one-sequence and the many-sequence batches.
  • RSA_results as a 12 (layers) × 2 (one-seq and many-seq) × 6 (pairs of stages) tensor to store the outputs of the function calc_RSA.

The first visualization (Figure 7.16) is a 3 × 3 geometry of subplots that show, in panels A-F, how the dimensionality results and RSA evolve over layers (x-axis) for each processing stage (marker color and shape); and that show inter-variable relationships (panels G-I), with marker shape indicating processing stage and color indicating layer number.

The second visualization (Figure 7.17) shows violin plots for each of the dimensional measures and batches. The layers are collapsed into each violin plot.

The first visualization takes some time to absorb.

Figure 7.16: Summary descriptive statistics for all measures in this project, and all transformer layers.

Here are a few observations:

  • There are differences in dimensionality results between the different processing stages. The next visualization is designed to focus on these.
  • The RSA scores in panel C are lowest for the three pairs that involve the projection stage, which is the final projection from the MLP back onto the hidden-state vectors. That seems broadly consistent with a segragation of computations: The two expansion stages create features, and the projection selects only the important features.
  • The RSA scores are generally higher for the many-sequence batch compared to the one-sequence batch. That is particularly visible in panel I, which has matching x- and y-axis limits. However, that is not trivially the case, as many one-sequence RSA scores are also quite high.
  • The two dimensionality analyses are robustly though imperfectly correlated (r > .8 in panels G and H). The differences are attributable to participation ratio being a smooth estimate of how evenly variance is distributed across dimensions, whereas the effective dimensionality analysis uses a hard threshold to count the number of “significant” dimensions in a data space.

The violin plot analysis allows you to focus more on the differences across processing stages while glossing over potential differences in layer distribution.

Figure 7.17: Same results as shown in Figure 7.16, but the layers are collapsed into each violin. This visualization better highlights the differences across the processing stages. Note that the ambient vector dimensionality is four times higher for “Expa” and “GELU” compared to “Inpu” and “Proj” (3072 vs. 768).

Here we see more clearly that the effective dimensionality drops from the input to the expansion stage, only to increase again after the nonlinearity (GELU). The projection stage has the longest violin, because the MLP output projections vary considerably across layers in terms of how much adjustment information is added back to the hidden-state vectors.

day-mode Bookmark

Grammar tuning in MLP projections

As I’m sure you guessed from the title of this section, the overall goal of this project is to identify whether there are projections in MLP that are “tuned to” (that is, statistically distinguish between) words of different grammatical categories. We’ll focus on nouns vs. verbs.

In many projects where we’re interested in individual tokens, we analyzed tokens in context, e.g., the final token of a sequence. However, here we will analyze tokens individually by creating a batch of N × 1. Thus, all tokens analyzed will be the first token in the sequence. That may seem inconsistent with my repeated claims that the first token in a sequence is an outlier and should be excluded from analyses. I’ll get back to this point towards the end of the project.

Effect size with Cohen’s d Before starting the project, I’ll give some background about a common measure of effect size. “Effect size” is a measure of the magnitude of a statistical finding. It’s different from a p-value, which is the probability that a finding could have been observed by chance. With large sample sizes, very small effects can be statistically significant, which is why effect size is an insightful complement to p-values. A common measure of effect size is called “Cohen’s d.” The essence of the formula for Cohen’s d is the difference of the means scaled by the standard deviation:

d=∣xˉ−yˉ∣s~(7.2)d = \frac{|\bar{x} - \bar{y}|}{\tilde{s}} \tag{7.2}

where x is the average of dataset x and s~\tilde{s} is the pooled standard deviation. The full formula for s~\tilde{s} depends on the sample sizes and standard deviations of the two groups, and I won’t discuss all of its nuances here.

Equation 7.2 looks similar to the equation for a t-value. They are indeed closely related; the key difference is that Cohen’s d is scaled to a more interpretable range that is independent of the sample size.

Common thresholds for Cohen’s d from the quantitative psychology literature are d > .2 for a small effect size, d > .5 for a medium effect size, and d > .8 for a large effect size. I’ll use those thresholds here as heuristics without implying equivalence to psychological effect sizes.

You can calculate Cohen’s d in Python using the compute_effsize in the pingouin library.

For this project, we’ll work with the LLM “GPT-neo-125M” from Eleuther-AI, which is an org focused on LLM interpretability. The “125M” indicates that the model has 125 million trainable parameters. It is comparable in size and performance to GPT-2-small (indeed, GPT-neo uses the OpenAI tokenizer, so the vocabs are the same), but the organization and naming conventions are somewhat different.

Task

Import the EleutherAI/gpt-neo-125m and its tokenizer from the Hugging Face transformers library. The import code is the same as with GPT-2; you simply specify a different model name. Switch the model to eval mode and inspect the model architecture. Notice in particular the names of the model components and matrix sizes, compared to what you’re used to with the OpenAI models.

As an example of the model implementation differences, check out the attention layer, printed below.

(attention): GPTNeoSelfAttention( (attn_dropout): Dropout(p=0.0, inplace=False) (resid_dropout): Dropout(p=0.0, inplace=False) (k_proj): Linear(in_features=768, out_features=768) (v_proj): Linear(in_features=768, out_features=768) (q_proj): Linear(in_features=768, out_features=768) (out_proj):Linear(in_features=768,out_features=768)

The Eleuther model separates the three W matrices whereas OpenAI concatenates them into one wide matrix. These kinds of differences across models are not computationally consequential, but they are important to be aware of as you write code to investigate them. It is another reason why you wouldn’t expect code written for one model to trivially run for other models.

That said, the naming conventions in the MLP block are comparable between GPT-neo and GPT-2.

Task

The helper and solutions files have urls for files containing 10,000 English verbs and nouns, as well as the reference to the GitHub repository where those files are posted. Import the files and identify the first 2000 words that are encoded as a single token when prepending a space. Store the token index and the length (number of characters) for each single-token verb or noun.

Then split the lists into two. The result will be four lists of tokens, each containing 1000 tokens, with two lists comprising non-overlapping verbs and two lists comprising non-overlapping nouns. Name your variables verbs_split1 etc. Create one split using the odd-numbered elements (that is, indices [1,3,5,…]) and the second split using the even-numbered elements (indices [0,2,4,…]). That interleaving avoids a confound of having the two splits come from words with different frequencies.

Print the first five tokens from each list.

The files linked in the online code provide 10,000 verbs, 6259 of which are single-token (when tokenizing with a preceding space). When splitting the single-token data into two sets, be mindful that the words are listed in descending order of frequency. Thus, the first 1000 tokens are more frequent than the second 1000 tokens. That can introduce systematic biases, and that’s why I instructed to split based on index parity.

The purpose of having two lists of each grammar category is to perform statistical test-retest analyses, which you’ll do in Part 4.

The first five tokens from each list are as follows:

First 5 split-1 verbs:    [’ is’, ’ be’, ’ have’, ’ were’, ’ has’] First 5 split-2 verbs:    [’ was’, ’ are’, ’ had’, ’ can’, ’ been’] First 5 split-1 nouns:    [’ time’, ’ way’, ’ years’, ’ man’, ’ work’] First 5 split-2 nouns:    [’ people’,’ life’,’ world’,’ state’,’ system’]

Later in the project we will use statistical testing to determine whether MLP Stage-2 activations differ between nouns and verbs. But what if the nouns are simply longer than the verbs, and MLP activations code for word length? That could be a confound of the investigation.

Task

Show bar plots of the number of characters in the 2000 nouns and 2000 verbs (hint: use np.bincount) as in Figure 7.18. Perform an independent-samples t-test and report the results, as well as Cohen’s d, in the title.

Figure 7.18: Histograms of character lengths of nouns and verbs used in this project.

The histograms show largely overlapping distributions, though with a noticeable rightward shift in verbs compared to nouns. The t-value is statistically significant, although the effect size is quite small, well below the threshold of .2. The discrepancy between the small p-value and the small effect size is the large sample size — even tiny effect sizes can be highly statistically significant if the sample size is large. This is a primary reason to calculate and report effect sizes in addition to p-values.

However, a small effect size doesn’t completely rule out the possibility of a confound in the experiment. I’ll get back to this issue later.

Part 2: Implant a hook and get activations

Section titled “Part 2: Implant a hook and get activations”

The goal of Part 2 is to obtain MLP activations from the pre-GELU expansion stage (c_fc) for all four lists of tokens.

Task

Implant a hook function into the MLP block of transformer layer 8 that stores the pre-GELU expansion activations in a dictionary called mlp_acts. Convert the tensor to NumPy and squeeze it to remove singleton dimensions. The key name of the dictionary is a variable whichdata that you will define during the forward pass.

Create batches of tokens with 1000 sequences comprising one token each, corresponding to the 1000 tokens in each list. Run four forward passes to obtain MLP activations from each of four lists. Name the dictionary keys nouns_split1, verbs_split2, etc. Print the names and sizes of all items in the dictionary.

Visualize some of the data as in Figure 7.19, which shows data from nouns_split1.

Creating batches from the list of token indices is straightforward: torch.tensor(nouns_split1).unsqueeze(1)

Applying the unsqueeze(1) method along the second dimension is important, because the models expect a 2D tensor of size batch × tokens. After running the forward passes, you should find that all items have the same shape:

mlp_acts[’nouns_split1’] has shape [1000, 3072] mlp_acts[’nouns_split2’] has shape [1000, 3072] mlp_acts[’verbs_split1’] has shape [1000, 3072] mlp_acts[’verbs_split2’] has shape [1000, 3072]

Figure 7.19: Visualizations of Stage-2 MLP values (pre-GELU expansion) from one layer.

The vertical stripes in panel A show that individual neurons have strong preferences to certain activation values across all nouns in the batch. That observation will be relevant for interpreting histograms in Part 5.

The scatter plot in panel B shows that the expansion neurons have a negative shift, replicating a finding you observed in Project 43. Panel C shows that the activation to nouns and verbs is, at least in this case, very highly correlated. If there are differences between nouns and verbs, they will be subtle.

The goal of Part 3 is to write code that will implement and explore t-test results. You’ll continue developing the investigations over the next several parts.

This will involve running 3072 t-tests. That’s a lot of tests to run, and it’s likely that some of those t-values would have small p-values simply by chance. Therefore, you’ll need to apply a multiple comparison correction. Given the correlational structure of MLP neurons, the FDR (false discovery rate) correction method is appropriate. Briefly, FDR works by analyzing a distribution of observed p-values, and determining how many of those p-values are likely to be observed if the effect were not present. You can use the false_discovery_control function in scipy.stats library.

Task

Define a variable for the number of expansion neurons.

Perform an independent-samples t-test on each of the 3072 MLP activations to nouns vs. verbs in split-1. Fortunately, the ttest_ind function allows you to input matrices and test all columns independently but simultaneously, so you don’t need to write a for-loop. But you need to specify the axis along which to calculate the t-test.

Calculate the effect size of each neuron using Cohen’s d. Unfortunately, the compute_effsize function does not allow for matrix input, so you’ll need to write a for-loop over neurons. Specify that the data are not paired. Plot the t-values by Cohen’s d (Figure 7.20).

The t-values and Cohen’s d are, at least by visual appearance, perfectly related to each other. That is not a universal result, but happens in this case because the sample sizes are identical and the standard deviations are comparable. That is, t-values and effects sizes are not trivially correlated except when the sample sizes and standard deviations are held constant. As I wrote at the outset of this project, the key advantage of using Cohen’s d for this project is that the numerical values are more interpretable, e.g., d > .8 is considered a large effect size.

Figure 7.20: Scatter plot showing t-values vs. Cohen’s d. Each marker corresponds to one neuron.

A comment about using t-tests in this project: The neurons are not statistically independent elements, because they are calculated as linear weighted combinations of a smaller set of vectors. That correlational structure is not incorporated into the independent t-tests, and can inflate the significances. FDR correction helps address this issue, although we will use the p-values more as heuristics to threshold neurons rather than precise measures of statistical inference.

Task

Calculate a boolean vector of statistical significances based on applying the FDR correction method to the p-values, using a corrected significance threshold of p < .05.

Write code to generate Figure 7.21. The red x markers show non-significant t-tests (p < .05), the empty green circles show statistically significant t-values that had a Cohen’s d < .8, and the filled circles indicate neurons in which d > .8.

Figure 7.21: T-values for all neurons in this layer, with marker color and shape indicating non-significance (red x’s), significant but small effects (empty green circles) and significant large effects (solid green circles).

These results show that, at least for this layer, most of the neurons have a t-value above the significance threshold, and around 26% had large effects sizes (that’s 30% of the p < .05 neurons). The significant neurons were not consistently positive or negative, indicating that individual neurons could exhibit tuning for nouns or for verbs.

Part 3 showed that a majority of MLP expansion neurons in layer 8 have a significant difference in activation for nouns vs. verbs. The goal of the next several parts of this project is to confirm this finding by replicating it in a separate dataset (Part 4) and exploring the data in more granularity (Part 5).

Task

Run t-tests on the split-2 dataset. Show a scatter plot of the split-1 vs. split-2 t-values as in Figure 7.22A. Plot each pair of t-values using a red “x” for neurons where neither test was significant, a red circle for neurons that had a significant t-value for one dataset but not the other, and a green square for neurons where both tests were significant. Correlate the t-values across neurons and report the coefficient in the figure title.

Instead of using FDR correction for multiple comparisons, use the Bonferroni method, which involves setting the p-value threshold to be .05∕N, where N is the number of tests.

Repeat the analysis and plot, but using the cross-split datasets, thus comparing nouns_split1 with verbs_split2 (Figure 7.22B).

The results show remarkable consistency between the two lists of words. The words themselves are distinct from split-1, meaning that the t-test results you observed in Part 3 were due to intrinsic features of the neurons with respect to parts of speech.

Figure 7.22: Each marker corresponds to a neuron and the scatter plots show the relationship between the neurons’ t-values for nouns vs. verbs for the two independent data splits (cross-validation).

Why did I ask you to use FDR in Part 3 and Bonferroni correction here? To be honest, I instructed using different methods only for educational purposes. Within a real research project or application, it’s best to use one method consistently.

The Bonferroni method assumes that the tests are independent and is therefore more conservative compared to FDR. In the case of LLMs, the MLP expansion neurons are not independent, because they come from a linear combination of the input stage. This means that Bonferroni correction is overly conservative, which means there could be more neurons with significant t-values that our test rejected. Nonetheless, we still find that most neurons have significantly different activation values between nouns and verbs.

With such large t-values, it is reasonable to expect salient visual differences in the histograms of the neurons for nouns vs. verbs. The goal of Part 5 is to investigate such histograms with increasing granularity.

Task

Extract histograms of all neurons from all four lists, and visualize their counts as in Figure 7.23.

Using counts instead of density is valid for these histograms because all datasets have the same number of data points.

Figure 7.23: Histograms of activation values from one layer for the two categories and two splits. The legend indicates the data from which the distributions were drawn, e.g., “Nouns 1” are the data from ’nouns_split1’.

All histograms are remarkably overlapping, and there is not even a subtle hint of distributional shifts between nouns vs. verbs.

But should we expect differences when pooling all activations from all neurons? Remember that around half of the neurons have positive t-values (nouns > verbs) while around half of the neurons have negative t-values (verbs > nouns). Also remember that individual neurons have strong activation shifts overall (Figure 7.19 from Part 2), and thus the differences between nouns and verbs will be minor in comparison. Thus, the overall distributions are more indicative of mean activation levels rather than subtle linguistic properties.

Task

Using only the data from split-1, create and plot four histograms corresponding to nouns vs. verbs, for neurons that had a negative vs. a positive t-value. Visualize as in Figure 7.24. I used density instead of counts; is that an arbitrary choice or is it necessary to use density here?

These distributions do show differences, although not how you might expect: Perhaps you were expecting a visible shift in the distributions between nouns and verbs, whereas the figure shows mostly overlapping distributions with small “bulges” that separate negative from positive t-valued neurons — whereas nouns and verbs still appear largely overlapping.

Figure 7.24: Histograms of activation values, now split by t-value.

The reason why these histograms should be density-normalized is that the sample sizes differ (different number of neurons with positive vs. negative t-values). When sample sizes are the same, then counts can be directly compared across datasets.

The complete overlap between the activations for the nouns and verbs is still puzzling, given the distributions of t-values. Perhaps we need to zoom-in further.

Task

Identify the neuron with the maximum t-value from split-1, and the neuron with the minimum t-value from split-1. Then extract the distribution of activations from those two neurons, separated by nouns and verbs. Visualize as in Figure 7.25.

Now we see a very different pattern: Clear separation of the distributions for nouns vs. verbs, and in the opposite direction for the maximum (solid lines) vs. minimum (dashed lines) t-value.

Figure 7.25: Histograms of activation values split by t-value, for the two neurons with the minimum and maximum t-values.

Take a moment to inspect and compare the x-axis values in Figures 7.24 and 7.25. For example, the differences in the means for the two categories within a neuron in Figure 7.25 is around .05 to .1, which is a tiny fraction of the x-axis in Figure 7.24. Thus, individual neurons can have a strong category separation while the population-level activity appears completely overlapping. Population-level statistics and visualizations are not wrong per se, but can be misleading because individual neurons can be narrowly tuned to particular language features.

As a final confirmation of the results before moving on, let’s run a within-category across-split tests. That is, we’ll test nouns vs. nouns and verbs vs. verbs. If a neuron is tuned to grammatical category, we would expect no significant effects — after all, the two splits of the within-category words are arbitrary. But if our previous results were simply due to overfitting random noise, then we would expect the within-category results to look similar to the across-category results.

Task

Repeat the t-tests but comparing nouns_split1 with nouns_split2, and same for the verbs. Make scatter plots of the cross-category t-values from split-1 by the within-category t-values, as in Figure 7.26. Use the same x- and y-axis limits.

Calculate Cohen’s d for these results, and visualize the histogram of |d| values for the within-category analysis and the across-category analysis from split-1 (calculated in Part 3) (Figure 7.27). Draw vertical lines indicating typical thresholds for a small effect (d = .2) and a large effect (d = .8).

Figure 7.26: Control analysis showing scatter plots of t-values for the nouns vs. verbs (x-axis in both panels) with t-values for nouns across the splits (panel A) or verbs across the splits (panel B). Axis limits are matched to facilitate visual interpretation.

Clearly, the t-values for the within-category analysis are small relative to the across-category analysis. In theory, the t-values should be zero; any non-zero values can be attributable to random sampling in limited sample sizes.

The distributions of effects sizes are also revealing.

Figure 7.27: Histograms showing the effects sizes from the analyses shown in Figure 7.26. Vertical lines demarcate effect size thresholds.

In this case, there wasn’t a single neuron that passed the threshold of a “small” effect (the largest d was .16).

Remember from Part 1 that we considered whether token length could be a confound, and observed that verbs were slightly longer than nouns. Although we haven’t completely ruled out a contribution of token length on the effects, the Cohen’s d of the that analysis was .09, which is much smaller than the effect sizes we have observed for the analyses.

Final comment about Cohen’s d: The metric can be reported signed or unsigned. The magnitude of the d-score is meaningful, but the sign is arbitrary and simply reflects the order in which the means are subtracted in the numerator. Therefore, it is common to report the absolute value.

We will now transition from detailed analysis of a single layer, to summary statistics over all layers.

If you haven’t already, it will be useful to define a variable encoding the number of transformer layers.

Task

Remove the hook you installed in Part 2. Implant a new hook into each layer that extracts the same data, but the key names include the layer number as well, for example, ’L9_nouns_split1’.

Run four forward passes for each list of tokens, as you did earlier. You’ll use these hooks in Part 8, so don’t remove them here. Report the names and shapes of all dictionary items.

In a for-loop over layers, run the across-category t-tests for both splits. For each layer, calculate and store the following: (1) proportions of neurons with significant t-tests from each split (use FDR correction), (2) the average absolute values of the significant t-values from each split, and (3) the correlations between all t-values from split-1 and split-2.

Visualize the results as in Figure 7.28.

All hooks store data from the same MLP stage, and so the sizes should all be the same. Here are the first three of 48 items in the dictionary.

mlp_acts[’L0_nouns_split1’] has shape [1000, 3072] mlp_acts[’L1_nouns_split1’] has shape [1000, 3072] mlp_acts[’L2_nouns_split1’] has shape [1000, 3072]

The proportion of neurons exhibiting a significant t-value is high for all layers, from around 66% in the first layer up to around 90%. The correlation between the two splits remains quite high.

Figure 7.28: Summary results of t-tests over the transformer layers.

I’d like to wrap up this project with an investigation and discussion about the validity of analyzing single-token sequences in LLMs. The idea will be to process a set of tokens three times: as one sequence in order, as one sequence with a scrambled order, and split into N one-token sequences.

Task

The online code file contains a sentence about coconuts, taken from Wikipedia. Tokenize the sentence and report the number of characters and tokens.

Create a scrambling index using torch.randperm. Then define a new token sequence as the randomly scrambled tokens. Also define the inverse scrambling to be able to undo the scramble (hint: use torch.argsort). Print out the original, scrambled, and inverted (recovered) decoded token sequences.

We need the “inverse scrambling” index to match the tokens in the analyses. Here’s an example of the scrambled and un-scrambled sentences:

Original sentence:

The coconut (Cocos nucifera) is a member of the
palm family (Arecaceae) and the only living
species of the genus Cocos.

Scrambled sentence:

family theC member. of n)aceaea) livingTheuc and
the only ( is coconut theos genus palmosAocrec a
( species Cocifer of

Inverted scrambling:

The coconut (Cocos nucifera) is a member of the
palm family (Arecaceae) and the only living
speciesof the genus Cocos.

Of course your scrambled sequence will be different, but the original and inverted texts should match.

Task

Run three forward passes to extract the MLP expansion activations: (1) using the tokens as they appear in the text (name this key sentence); (2) using the tokens as a 34-sequence batch where each sequence has one token (name this key words); and (3) using the tokens in one sequence but with a randomly scrambled order (name this key scrambled). Confirm the key names and sizes of all items in the dictionary.

A comment about re-using hook functions: In Project 43 I mentioned that not re-initializing the dictionary between forward passes may cause some confusion if different hook functions use different dictionary key names. This task illustrates an example: The dictionary mlp_acts includes data from the forward passes in Part 7, and after the three forward passes here, it will include three additional items. That isn’t wrong and it won’t create errors, but it could cause confusion, for example if you have a for-loop over dictionary items. You can clear out the dictionary by re-initializing it to be empty.

Because the squeeze() method was applied in the hook function, all data matrices have a shape of 34 × 3072 (34 tokens in the text). However, the pre-squeezed data matrices had different sizes: 1 × 34 × 3072 for the sentence and scrambled datasets, and 34 × 1 × 3072 for the words dataset.

Now we have the data; the question is whether the MLP neurons process those tokens differently depending on their organization. On the one hand, LLMs are autoregressive models, so it is trivial that the temporal sequence will impact the processing at least somewhat. The question is how big the differences are.

Task

Make three scatter plots showing the relationships between pairs of datasets in one layer (I used layer 3). The comparison is valid only on matching tokens, which means you need to invert the scrambling before the plotting. It’s a lot of data to draw, so you should consider drawing, e.g., only every 10^th data point. Report the correlations in the titles, as in Figure 7.29 (don’t skip data points for the correlation).

In a for-loop over layers, calculate the three correlations for each layer. Visualize the correlation coefficients as in Figure 7.30.

Figure 7.29: Scatter plots showing the relationships among activations for the same tokens but presented as one intact sequence (“Sentence”), as one sequence of scrambled tokens (“Scrambled sentence”), and as N single-token sequences (“Words”).

The conclusion from the scatter plots is that the MLP adjustments are strongly correlated between the intact and scrambled sequences, while being moderately correlated with the single-token sequences. Thus, even with no context, the MLP block can encode some intrinsic properties of tokens.

Figure 7.30: Correlations of the data shown in the scatter plots in Figure 7.29 for each layer. Small x-axis offsets were added to facilitate visual comparisons.

Over the layers, the correlations are consistently positive (with an exception of layer 5, where the coefficients dip a bit negative). The correlations between the scrambled and intact sentence are relatively strong, although getting weaker in middle to later layers.

Taken together, these findings show that order matters in LLM interpretability analyses. Analyzing single-token sequences may seem appealing because it offers a “pure” (context-free) look into how LLMs work — but LLMs don’t work by isolating and processing single tokens; instead, they work by adding an increasing amount of context from surrounding tokens and learned world knowledge from training.

day-mode Bookmark

Minkowski distance, mutual information, and token positions

The overall goal of this project is to explore whether tokens that are closer to each other in a text share more information between their MLP and attention adjustments vectors. Importantly, we’ll only analyze data from the same target token (“ coffee” in a Wikipedia page about Turkish coffee), which means that we don’t need to worry about potential confounding factors like token frequency or word length.

But before getting to the project, I’ll provide a brief introduction to the interpretation, math, and code implementation of Minkowski distances and mutual information. We’ll start working with LLM data in Part 3.

Minkowski was a mathematician who made multiple important contributions to humanity, including developing the math that underpins Einstein’s theories of relativity. “Minkowski distance” is perhaps not his most important contribution, but is widely used in ML. Minkowski distances are all related by the same basic equation with different values of p.

dp=∑i=1N(∣xi−yi∣)1/p(7.3)d_p = \sum_{i=1}^{N} (|x_i - y_i|)^{1/p} \tag{7.3}

When p = 1, Equation 7.3 is commonly called Manhattan or L_1 distance; and when p = 2, it’s commonly called L_2 or Euclidean distance. Mathematically, Equation 7.3 is defined for any p > 0, although values of 1 and 2 are most often used in applications.

There are several ways to characterize the differences between L_1 and L_2 distances. Statistically, L_1 is more robust to outliers or large deviations because L_2 squares the differences. I’ll provide a more specific interpretation later in the project when you use these distance measures in analyses.

For now, let’s focus on implementing Minkowski distance.

Task

Generate two variables x and y as 100 numbers randomly drawn from a standard normal distribution. Calculate Minkowski distance for p = 1 and p = 2 twice: Once by directly translating Equation 7.3 into NumPy code, and second using the minkowski function in the SciPy library. Print the results.

Here are my results:

p = 1:

manual: 100.981
scipy: 100.981

p = 2:

manual: 12.042
scipy: 12.042

Your numbers will differ, of course, because of random number selection. But the exact values don’t matter; what matters is that the two calculations match.

By the way, the notation can be a bit confusing because p and L are sometimes used interchangeably. In general, p is used to indicate the parameter in the equation while L is used to name the metric or interpretation. For example, “setting p = 1 in Equation 7.3 gives the L_1 distance.”

Part 2: Mutual information: manual and scikit-learn

Section titled “Part 2: Mutual information: manual and scikit-learn”

Mutual information is a bivariate (between two variables) analysis that answers the question: How much do I know about one variable if I know about a second variable?

That sounds like the same question answered by correlation or cosine similarity, and indeed, mutual information and correlation can be closely related under some circumstances. The key difference between mutual information and correlation (and related analyses like cosine similarity and covariance) is that mutual information is able to measure nonlinear relationships, whereas correlation can detect only linear relationships. You’ll see an example below.

Mutual information is based on a quantity called entropy, which is a measure of variability. It is conceptually similar to variance — indeed, variance is to covariance as entropy is to mutual information. But whereas variance is the average dispersion around the mean, entropy is a measure of how probable different values are.

Here’s the formula for entropy:

H=−∑i=1Np(xi)log⁡2(p(xi))(7.4)H = -\sum_{i=1}^{N} p(x_i) \log_2(p(x_i)) \tag{7.4}

Where p(x_i) is the probability of value x_i occurring. The minus sign is for interpretational reasons: Probabilities are between zero and one, their logs are all negative, and so the summation is a negative number. Flipping the sign means that more entropy corresponds to more information (more variability).

Therefore, to calculate entropy, you need to know the probability function of a variable — or estimate it using a histogram. And therein lies the challenge of calculating entropy for continuous variables like MLP activation values: The exact values of a histogram depend on the number of bins and the boundaries of those bins. The histogram of a dataset using 40 bins will be different from the histogram of the same dataset using 45 bins. Of course, the overall shape of the distribution will be nearly the same, but the numerical values will differ, which means that H will differ.

One solution to the bin-dependency of entropy is not to bin the data at all, and instead to point-wise estimate a probability density. That’s the approach implemented in scikit-learn and I’ll show that in a bit, but implementing the math directly is (in my humble opinion) a better way to build intuition for how an analysis works.

Task

Translate the following equation into NumPy code and visualize it as in Figure 7.31A.

y=3cos⁡(2x)+ln⁡(x)+N(0,0.52)(7.5)y = 3\cos(2x) + \ln(x) + \mathcal{N}(0, 0.5^2) \tag{7.5}

where x ranges from .001 to 2.7 in 347 steps, and N(0,.5^2) refers to normally distributed noise with a mean of zero and a standard deviation of .5.

Use the histogram2d function in NumPy to bin the data into an 8 × 8 grid, and visualize as in Figure 7.31B.

The function is clearly nonlinear, and the goal of the rest of this Part is to calculate the mutual information between x and y.

Figure 7.31: Simulated data showing a nonlinear relationship between x and y. Panel A shows the data as it is calculated, and panel B shows the result of discretizing the data in a 2D grid. The color of each grid cell indicates the number of data pairs in that cell.

There are several ways to define mutual information; the equation below is compact and easy to interpret.

I=Hx+Hy−Hxy(7.6)I = H_x + H_y - H_{xy} \tag{7.6}

In other words, mutual information is the total entropy in the two-variable system, minus the entropy attributable to either variable alone. That interpretation may initially seem like the opposite of what the equation shows, but remember that the equation for entropy includes a minus sign.

One minor but important point before implementing that equation in Python: The log of zero is undefined (look back at Equation 7.4), which can happen when no data points fall into a histogram bin. The solution is to add a very small number (e.g., 10^(−13)) to the log term.

Task

Implement Equation 7.6 and report the resulting mutual information score. Tip: You’ve already calculated the 2D histogram of the data; the marginal entropies for x and y can be calculated by summing the 2D probabilities along each axis.

One common cause of mistakes when calculating entropy is using counts instead of probabilities. Make sure the 2D histogram data is converted to probability values (not densities) by dividing the counts matrix by its sum. That is:

p_Z = Z / Z.sum() entropy_Z = -np.sum( p_Z * np.log2(p_Z+eps) )

Then you can calculate H_x using:

p_x = np.sum(p_Z, axis=1) entropy_x = -np.sum( p_x * np.log2(p_x+eps) )

The exact mutual information score will vary because the dataset includes random noise, but it should be around 1.

A parameter-free implementation The scikit-learn library has a function called mutual_info_regression, which you can use when at least one variable is continuous. miSk = mutual_info_regression(x.reshape(-1,1),y)[0] This implementation takes the two variables as inputs (the first input must be a multidimensional array, hence the reshaping), but it does not take number of bins as input. Instead, the scikit-learn function estimates the probability density using a robust estimation method based on nearest-neighbor clustering. That gives a parameter-free estimate of mutual information.

Task

Calculate mutual information using scikit-learn’s implementation, and report the result.

In a for-loop over bin counts from 4 through 24, repeat the “manual” mutual information calculation from above, and visualize the results as a scatter plot of mutual information as a function of bin count, with the scikit-learn result as a horizontal line (Figure 7.32).

Finally, calculate and report the Pearson correlation coefficient between x and y, and consider whether that result accurately captures the relationship seen in the data.

Again, your mutual information score from scikit-learn will vary slightly because of the noise in the data, but should be around 1 — comparable to the manual calculation.

However, that manual result varies considerably depending on the choice of bins.

Figure 7.32: Comparison of mutual information estimates from manually implementing the formula with varying bins, with the output of scikit-learn’s function.

Let me be clear: The wrong conclusion from Figure 7.32 is that you should always use 7 bins when manually calculating mutual information. While it is true that 7 bins provided the closest match to the scikit-learn implementation, that happened in this demo because of the unique characteristics of the data, not because “7” is a magic number. Furthermore, the scikit-learn implementation is simply a different way to estimate mutual information; it’s not necessarily more accurate.

Instead, the correct conclusion is that mutual information cannot be known in observed data; it can only be estimated. Different estimation techniques will give different results. Scikit-learn’s implementation is advantageous because it doesn’t require a decision about binning — but that doesn’t mean it gives the “correct” mutual information score; it simply means that the assumptions of the analysis are implicit (that is, the kernel estimation algorithm) instead of explicit (the number of bins).

In fact, the scikit-learn implementation is computationally expensive and therefore slow. You won’t notice the slow-down on small datasets, but if you’re calculating a large number of mutual information scores in large datasets, it’s probably better to use a manual implementation with a carefully chosen number of bins.

Regardless, the best way to avoid introducing systematic biases into your analyses is to choose one algorithm and parameter set, and apply that consistently.

Anyway, back to the task at hand: The correlation coefficient in this dataset is around zero. Clearly, there is a strong relationship between x and y, and yet that relationship is nonlinear and so a correlation coefficient cannot capture it.

Mutual information as nonlinear distance? Mutual information is not formally a distance metric. When calculating mutual information, each observation is considered a random sample from a distribution such that the collection of samples can be used to estimate a probability distribution. However, I’ll use mutual information in this project as a nonlinear measure of distance between two projection vectors, where the value at each embeddings dimension is treated as an “observation.” That’s a nonstandard application, but understanding why it is nonstandard — and understanding how to interpret the results — will help you understand the assumptions and applications of mutual information, and will help interpret the Minkowski results.

Thus, I will use mutual information in Parts 3-6 as a nonlinear measure of similarity between two vectors, as opposed to “shared information content” in the Shannon sense. Then in Part 7, I will show you an application of mutual information that is closer to how it is typically used.

Part 3: Model, hooks, tokens, and activations

Section titled “Part 3: Model, hooks, tokens, and activations”

After learning about Minkowski distances and mutual information, I’m sure you are super-excited to learn how to incorporate those analyses into investigations of the MLP block. The goal of Part 3 is to obtain a dataset to analyze in the rest of the project. The data come from text about coffee, so I think you’ll like it :)

Task

Import GPT-2-large and its tokenizer. Create and implant two hooks into each transformer layer: one to grab the attention projections (attn.c_proj) and one to grab the MLP projections (mlp.c_proj). Transform the activations tensors into NumPy arrays. Use key names of, e.g., att_4 for the attention adjustments from transformer layer 4.

Import the text from the Wikipedia article about Turkish coffee (see online code file for url and importing syntax). Tokenize the text and report the number of total and unique tokens. You’ll use the full-text tokens again in Part 7.

Find the first 10 indices of the token “ coffee”. Run a forward pass on the tokens from the start until the 10^th target token index. Report the key names and sizes of the tensors in the hooked activations dictionary.

You should find 5209 tokens in the text, of which 1718 are unique. The first 10 indices of the “ coffee” token are 1, 6, 17, 54, 59, 65, 90, 96, 101, 123. (Due to occasional Wikipedia edits, your counts might be slightly different.)

The token positions will be used in later parts of the project to calculate token position distances. For example, the first two target positions are 6 − 1 = 5 “position index units” apart while the first and third are 17 − 1 = 16 units apart. The question is whether the distances between adjustment vectors of different appearances of “ coffee” are related to the token position distances.

The matrix sizes are all the same: the internal workings of the attention and MLP blocks are, of course, very different from each other, but their outputs are adjustments to the hidden-state vectors and thus have the same shape. Here’re the first two items in the activations dictionary:

att_0 has shape (1, 123, 1280) mlp_0 has shape (1, 123, 1280)

That list gets long because there are 36 layers in GPT-2-large. The matrix sizes correspond to one sequence, 123 tokens (from token position index 0 until 122), and an embeddings dimensionality of 1280 in GPT-2-large.

Part 4: Relationships between distance measures

Section titled “Part 4: Relationships between distance measures”

Before getting to the main analyses, let’s see whether and how the three measures are related to each other. The code you write here will also be used in Parts 5 and 6.

Task

Inside a double for-loop over the target tokens, extract the MLP data from transformer layer 3 for each pair of target tokens. Calculate the three measures (mutual information and L_1 and L_2 Minkowski distances) between each vector. Store the results in a 10 × 10 × 3 matrix, corresponding to the pairs of target tokens and three measures. Also calculate the inter-token index distances and store in a separate 10 × 10 matrix.

Visualize all pairwise scatter plots as in Figure 7.33A. The results do not provide any meaningful visual insights because the scales are so different. Therefore, plot the same relationships after max-value normalizing each variable (that is, divide each measure by its maximum), as in Figure 7.33B.

Because all measures under consideration here are symmetric, you don’t need to calculate the full matrix. Instead, you can have the inner for-loop begin at the outer for-loop index value, like this:

for toki in range(len(target_idxs)):
for tokj in range(toki+1,len(target_idxs)):

The lower-triangle and diagonal of the matrices are zeros, and you’ll need to exclude them when creating the scatter plots. This is the same as isolating the non-redundant and non-trivial values from a cosine similarity matrix.

Figure 7.33: Relationships among mutual information (MI) and the two Minkowski distance measures. The data in panel B are the same as those in panel A after max-value normalizing.

From panel A, you might think that the three measures are all orthogonal to each other. But that is an incorrect conclusion, because the plot is misleading: the three measures have very different scales, and thus they cannot be visually interpreted in the same plot without normalization.

Hence the max-value normalization in panel B. Here you see that the L_1 and L_2 Minkowski distances are strongly positively correlated, while they are both negatively correlated with mutual information. In theory, Manhattan (L_1) and Euclidean (L_2) distances are nonlinearly related to each other; however, when the data values are constrained to a relatively small range, the relationship can be approximately linear.

The negative relationship with mutual information also makes sense: Mutual information is a measure of relatedness while Minkowski are measures of distances. The stronger two variables are related, the smaller the distances between them.

Part 5: Projection distances by position distances

Section titled “Part 5: Projection distances by position distances”

The goal of Part 5 is to examine the relationship between the distance measures and the target token position distances, for the data you worked with in Part 4.

We’ll use the Kendall correlation analysis to relate projection vector pair distances to token position distances.

Kendall’s τ correlation So far in this book, you’ve used the Pearson and Spearman correlations. The Pearson correlation is the most commonly used correlation (dot product between two centered variables, scaled by the product of their norms), and the Spearman correlation involves calculating the Pearson correlation on rank-transformed variables. The Kendall correlation is used when one variable is ordinal, which means sortable categorical data. For example, the variable educational degree is ordinal, because it takes on sortable categorical values (high-school, bachelor’s, master’s, PhD) but you cannot do math on those values (e.g., high-school + bachelor’s ≠ master’s).

In this project, mutual information and Minkowski distances are continuous, but inter-token distance is ordinal. It’s ordinal because a gap of six tokens between two targets is larger than a gap of three tokens, but six units is not equal to twice a gap of three units.

Kendall’s correlation (indicated using τ) is calculated by labeling data pairs as concordant (they are both above or below the median) or discordant (one is above while the other is below the median), summing over concordances, and scaling such that the resulting coefficient is bound by ±1. You can interpret the Kendall τ in the same way as you interpret a Pearson or Spearman correlation.

You can implement the Kendall correlation using the function kendalltau in the scipy.stats library.

Task

Show the four distance matrices as in Figure 7.34A-D. Extract the non-zero elements of each distance matrix, and show the relationship with the target token position distances in scatter plots with the Kendall τ in the title (Figure 7.34E-G).

Even before looking at the scatter plots, you can see that the mutual information and inter-token distances are negatively correlated (check the inverse pattern of coloring), while the Minkowski distances are somewhat positively correlated.

Figure 7.34: Relationships between target token position distances and the three vector distance measures, in the MLP block of transformer layer 3.

In other words, the closer two “ coffee” tokens are to each other in the text, the more similar are their adjustment vectors — at least in layer 3; we haven’t confirmed this in any other layer. But that observation should make sense: the transformer uses context information to adjust the token representations, and the closer two tokens are in a text, the more local context they share.

The goal of Part 6 is to repeat the analysis in Part 5 but for all layers and also for the attention projections.

Task

Create a loop over transformer layers. Inside the loop, paste the code from Part 3. However, additionally calculate the measures for the attention projections. Because there is only one text sequence, you don’t need to re-calculate the inter-token distances.

From each layer, extract and store the average of the three distance measures, and the correlation coefficient between each measure and the inter-target token distances.

Visualize the results as in Figure 7.35, where the top row shows the results from the attention projections and the bottom row shows the results from the MLP projections. The average values in panels A and C are max-value normalized so that all three measures can be visualized on the same graph.

Figure 7.35: The correlations visualized in Figure 7.34 we run over all layers and separately for the attention and MLP projection vectors, and visualized here.

The results show a general decrease in pairwise mutual information and an increase in distances with increasing depth into the model. The correlations with inter-token distance remained consistently negative for mutual information and positive for the Minkowski distances, and the correlation strengths seem to decrease with increasing model depth.

Another interesting finding is that mutual information and Minkowski distances exhibited similar findings (you can see this better by flipping the sign of the mutual information correlations). It is not trivial that those measures give the same results; instead, it indicates that the pairwise relationships are linear or at least monotonic. Strongly nonlinear relationships would show robust mutual information but weak Minkowski distances (as in Part 2).

Part 7: A standard application of mutual information

Section titled “Part 7: A standard application of mutual information”

As I wrote in Part 2, using mutual information as a nonlinear measure of “distance” is a slight abuse of the analysis, because mutual information is designed to measure the relationship between probability distributions estimated through random samples (observations), whereas the projection vectors are not random samples drawn from a distribution.

Although it was insightful — and I believe that understanding why the analysis is non-standard will help you understand when and how to use mutual information — I wanted to include a more typical application of mutual information.

In this case, we will consider that repetitions of the token “ coffee” in the Wikipedia article are random samples of the same word. The feature to calculate mutual information over will be the norm of the adjustment vector, and we will evaluate whether shared “information” (now used in the Shannon sense) across pairs of transformer layers is related to inter-layer distance.

Task

From the full tokenized text that you extracted in Part 3, create a 100 × 10 batch of tokens where each of 100 sequences ends with the token for “ coffee” and contains the 9 tokens preceding it. Print the batch to ensure that each sequence ends with token index 6891, and that the batch is integers not floating-point numbers.

Run a forward pass on the batch and check the sizes of the hooked projection vector tensors.

Although I did not explicitly mention this in the instructions, you need to exclude any targets that are less than the context window from the beginning. For example, the second token in the text is “ coffee” but it does not have nine tokens before it to create a sequence. That step reduces the number of targets to 149.

Therefore, the first row in the batch is the third instance of the word “ coffee”: [287, 257, 2906, 89, 303, 1262, 845, 32566, 2323, 6891].

All hooked projections are 100 × 10 × 1280, corresponding to 100 sequences of 10 tokens each, and an embeddings dimensionality of 1280. The analyses will focus on the final token.

Task

In a double for-loop over transformer layers, extract the norms of all the projection vectors for the final token for each pair of layers, and calculate mutual information between them. Do this for the attention vectors and the MLP vectors, and store the results in a layers × layers × 3 matrix, where the “3” corresponds to the attention mutual information, the MLP mutual information, and the inter-layer distances encoded as integer differences (e.g., layers 4 and 15 are 15 − 4 = 11 units apart).

Visualize the matrices of pairwise mutual information as in Figure 7.36A-B, and the matrix of inter-layer distances as in panel C. Then visualize scatter plots of the relationship between mutual information and inter-layer distances as in Figures 7.36D-E, and the relationship between mutual information in the attention and MLP projections as in panel F.

This application of mutual information is more consistent with the traditional interpretation, because we are treating each target token as a random observation, and the projection vector norm as the feature. Then the question we are asking is whether there is shared information in the distribution of projection norms between the hidden-state adjustments in different layers.

Figure 7.36: An example of mutual information via random sampling of repeated tokens, over layer pairs instead of token pairs.

The inverse relationship between mutual information and inter-layer distance is clear from visual inspection of the heatmaps in the top row. The scatter plots show that this inverse relationship is not linear: It is the case the mutual information is low for distant layer-pairs, but it is not necessarily the case that neighboring layers have high mutual information. From visual inspection, it seems that the strongest inter-layer mutual information is in early to middle layers for the attention projections and middle to later layers for the MLP projections.

A final observation is that the mutual information scores seem uncorrelated between MLP and attention. To be clear, panel F does not show a lack of mutual information directly between MLP and attention; instead, it shows that the shared information within each block and across layer pairs is unrelated.

day-mode Bookmark

Statistics-based lesioning in MLP neurons

The overall goal of Project 46 is to identify MLP expansion neurons that statistically differentiate “him” from “her” in one dataset, and then manipulate those neurons in an independent dataset to determine whether those neurons are causally involved in gender-word processing.

Part 1: Get MLP activations for him vs. her

Section titled “Part 1: Get MLP activations for him vs. her”

By the end of Part 1, you’ll have an LLM, tokens, and MLP activations that you’ll use for later analyses.

Task

Import the bert-large-uncased model and its tokenizer. Define a variable for the number of neurons in the MLP expansion layer (note that the BERT model uses different naming conventions than OpenAI’s GPT models). Create and implant a hook function into transformer layer 9 that extracts the MLP expansion neurons’ activations, converts them to NumPy arrays, and stores them in a dictionary with a key name corresponding to the layer number.

The online code contains a list of 108 sentences (generated by Claude from a few examples I wrote). The first 54 sentences contain the word “him” (but not “her”), and the next 54 sentences are identical but with “her” instead of “him”. Tokenize the sentences to create one batch with 108 sequences. The sentences have varying lengths, so you’ll need to use padding. Define variables for the token indices for the targets “him” and “her”.

The expansion layer in BERT is called intermediate.dense, and it contains 4096 neurons.

The target indices for “him” and “her” are 2032 and 2014. Remember that the BERT tokenizer ignores spaces, so there’s no need to worry about preceding spaces here.

Task

Because the target words can appear in any position in each sentence — as opposed to, for example, always being the final token — create a PyTorch tensor of 108 integers that indicate the target token position of each sequence.

Run a forward pass through the model to get the MLP activations, and then remove the hook. Finally, create a 108×4096 (sequences by neurons) matrix of extracted MLP activations from the target token position in each sequence. Remove the hook function.

Because of differing sequence lengths, you’ll need to tokenize by calling the main tokenizer object, not the .encode() method, and you’ll need to set padding=True. That will return a dictionary with input_ids and attention_mask.

To identify the target locations in each sequence, you can use code like the following:

targs = torch.tensor([ target_token_him,
target_token_her ])
for senti in range(len(sentences)):
targBool = torch.isin(
tokens[’input_ids’][senti],targs)
target_indices[senti] = torch.where(targBool)[0]

In other words, find all indices that contain either the “him” or the “her” tokens, and then take the first of those indices. That solution works here because I hand-crafted the sentences to contain exactly one target each. You’d need to adapt the code if you’re using natural text that contains multiple targets per sequence.

The result is a 1D PyTorch tensor that starts with 3, 3, 3, 3, 4, 3. That means that the target word is in position 3 in the first sequence, and so on.

After running the tokens through the model, you should find that the shape of the data matrix is 108 × 11 × 4096, corresponding to 108 sequences, 11 tokens (that’s the longest sequence; the shorter sequences are padded to match the length), and 4096 MLP expansion neurons.

From there, you can loop through all the sequences and grab the activation values from the target token position in each sequence. That will produce a 108 × 4096 data matrix.

Part 2 involves writing code to identify MLP neurons that have a significant difference in activation levels for the words “him” vs. “her.” You’ll use that code in Part 3 to identify neurons to silence in Part 5.

The t-tests and multiple comparisons methods in this project were introduced in Project 44.

Task

Perform an independent-samples t-test on the MLP neuron activations you extracted in Part 1. Identify “him” and “her” neurons as those with a p-value less than .05 (corrected for multiple comparisons using the FDR method) and a t-value sign corresponding to the order in which you provided the inputs to the ttest_ind function.

Show the results in a scatter plot with different markers for different significance types (Figure 7.37). Count the number of significant neurons in each significance category and report the raw numbers in the title of the scatter plot, and show the results as a pie chart.

Figure 7.37: T-values and statistical significances (p<.05, FDR-corrected) in MLP expansion neurons. The pie chart to the right shows the break-down of the percentages of neurons in different statistical categories.

Around 2/3 of the neurons have significant tuning to one of the two gendered words, roughly evenly split between “him” and “her.”

If you’d like an additional challenge here, you can calculate Cohen’s d as in Project 44, and further label neurons according to having a relatively small (d < .8) or relatively large (d > .8) effect size. But that’s optional and not shown in the online code solution.

Now that you can identify significant neurons in one layer, let’s adapt that to all the layers.

And to make it more interesting, you’ll put the t-test code into a hook function.

Task

Create and implant a hook function into the intermediate.dense layer of all transformer layers. Inside the hook function, extract the MLP expansion neuron activations, create a matrix of activations to target positions, perform a t-test for “him” vs. “her” targets, and store two Boolean vectors in a dictionary that identify the p < .05 (FDR-corrected) “him” neurons and “her” neurons. The key names would be, e.g., mlpTs[’L5_him’].

Run another forward pass on the tokens from Part 1. Print the names of the keys to confirm that all layers have a pair of keys, and that they are of size 4096. Remove the hooks.

Visualize the proportion of “him” and “her” neurons in each layer as in Figure 7.38.

Notice that the vectors in the dictionary are Boolean vectors with a length corresponding to the number of neurons (4096). That data type will be relevant for Part 7.

The y-axis in the figure shows the proportion of the total neurons for each of the two categories, so the total proportion of significantly tuned neurons would be their sum, e.g., the first transformer layer has around 26% non-significant neurons.

Figure 7.38: Percentage of neurons with p < .05 (FDR) in each layer.

Final discussion point before moving on: Is it a good idea to put analysis code into a hook function? The answer depends on how long the code takes to run, how many tokens and forward passes you need to implement, and how much time you can afford to wait for the results.

Hook functions increase computation time, and complicated code inside a hook function can really slow down model performance. For our educational application here with a relatively small number of tokens and only one forward pass, a few extra seconds is no big deal. Even if you’re doing a real research project with a very large dataset, then the additional computation time might be fine, e.g., if the model runs on GPUs overnight and you don’t mind waiting hours to get results.

But if you’re working on a deployable application such as a chatbot that should interact with users in real-time, then a hook function that adds even a few seconds per forward pass might be a fatal feature.

Part 4: Gender word predictions in an independent dataset

Section titled “Part 4: Gender word predictions in an independent dataset”

The 108 sentences you’ve worked with so far are the training set. We won’t use them anymore in this project. Instead, we’ll switch to using a test set, where the neurons identified from the training set will be silenced to determine whether that impacts the model’s ability to predict the words “him” and “her”.

In particular, we will use the following sentences:

  1. Robert helped Lucy with her project, and she thanked him for his hard work.

  2. Robert helped Lucy with [MASK] project, and she thanked him for his hard work

  3. Robert helped Lucy with her project, and she thanked [MASK] for his hard work.

All three sentences are identical except that sentences 2 and 3 have the word “her” or the word “him” replaced with [MASK]. BERT is trained using masked token prediction, so the idea is to compare the model output logits on the [MASK] token in sentences 2 and 3, before and after silencing the significantly gender-tuned neurons identified in Part 3.

You’ll perform the ablation experiment in Part 5; the goal here in Part 4 is to write code to implement the test and visualize the results, and to obtain baseline values against which to compare the experimental results.

Task

Tokenize the three sentences listed above (without the initial numbers), as three sequences in one batch. Identify the positions of the mask token in sentences 2 and 3.

Run a forward pass on the batch and print the shape of the output logits (make sure the hooks from Part 3 are removed, otherwise you’ll overwrite the t-test results). Create a 3 × 2 × 2 NumPy array that you populate with the output logits where the first dimension is the sentence index, the second dimension is for the “her” and “him” tokens, and the third dimension is the logits corresponding to vocab items “her” and “him”. Name the variable target_logits_clean.

This analysis is done on the raw output logits, not the softmax-probability logits. That’s not mathematically necessary but instead is a choice I made. Why might I have made that decision? In other words, what is the difference in interpretation between the raw logits and log-softmax probabilities?

The output logits should be of size 3 × 18 × 30522, corresponding to three sentences, 18 tokens, and 30522 vocab elements in BERT.

You should find that the first sentence has the following 2 × 2 logits in variable target_logits_clean:

array([[[24.285, 0.774],
[ 4.858, 19.697]]

The reason I instructed to use the raw logits here is to focus the interpretation on how the model processes each of the two target tokens. In contrast, the softmax-probability values of each individual token are modulated by the values of the rest of the tokens (remember that the denominator of the softmax function is the sum over all logits). Thus, the raw logits are a more sensitive measure of processing individual tokens whereas log-softmax is a more sensitive measure of the selecting the most likely tokens from the vocab, given the logits of all other tokens. Importantly, both transformations are valid and appropriate, but have slightly different interpretations.

Task

Visualize the 3 × 2 × 2 results with bar plots as in Figure 7.39. This figure has a lot of results, so please take your time to work through understanding it.

This figure is tricky to create and to interpret. Feel free to copy my code to create the multi-line x-axis labels.

Figure 7.39: Bar plots showing output logits to “him” and “her” vocab items depending on the token position.

Now for interpreting the figure. There are three rows in the x-axis labels. The bottom row organizes the sentence that each group of bars are from. The middle row organizes the position in the sentence, either corresponding to the word “her” or “him”. And the top row indicates the token (her or him) from which each logit is shown.

The expected result is an alignment between the token and position. For example, we expect the “her” token logit to be larger at the “her” position, and we expect the “him” token logit to be larger at the “him” position. I organized the bars such that we expect a U-shaped pattern for each sentence (in statistics, this is called a cross-over interaction).

Part 5: Ablate “him” and “her” neurons in MLP

Section titled “Part 5: Ablate “him” and “her” neurons in MLP”

Now for the experiment: We will switch off the statistically significant neurons identified in Part 3 and run the experiment in Part 4. Here in Part 5 we’ll do this for one layer, then in Part 6 over all transformer layers.

Task

Create and implant a hook function into the MLP expansion stage of the final transformer layer. The hook function selectively zeros out only the “significant” neurons identified from Part 3, only for the mask position, and only for the relevant sentence. That is, ablate the “her>him” neurons in the “her” token position in the “her” sentence. And likewise for “him.” There are no manipulations to the first (unmasked) sentence.

Run a forward pass and remove the hook function. Create Figure 7.40A, which is organized in the same way as Figure 7.39 from Part 4, but shows the difference in logits between this ablated model and those from the clean model. The scatter plot in Panel B shows the impact on all target logits, with each marker corresponding to one of the elements in the results matrices.

These results show several findings. For developing and checking analysis code, the most important findings are the null results: the difference bars are zero for the conditions that were not manipulated.

Figure 7.40: Panel A: Same organization as Figure 7.39, but showing the change in logits after the ablation. Panel B: Scatter plot showing that the overall impact of the manipulation was small (a perfect linear relationship would indicate no impact).

On the other hand, that is not a trivial result that we would expect from manipulating all layers: Manipulated MLP neurons can change the hidden-state vectors, and those changes are incorporated into the MLP calculations in the next layer. Here we manipulated the final transformer layer, so there isn’t an opportunity for complex down-stream impacts. That is to say, selectively manipulating the “him” neurons can have downstream impacts on the processing of the “her” position.

The scatter plot in panel B shows that the impact on the final output logits was very small. That’s also to be expected: the manipulation was extremely targeted in terms of token position and location in the model, so the impact on the final output logits is unlikely to be large.

Part 6: Laminar nullification of MLP neurons

Section titled “Part 6: Laminar nullification of MLP neurons”

Now for the full experiment, in which you will repeat the manipulation from Part 5 in a for-loop over all transformer layers. Showing the set of bar plots for each of 24 layers is technically possible but not a good idea, so we will collect summary statistics about the modulations instead.

Task

In a for-loop over layers, create a hook function that zeros-out the “her neurons” on the “her” token in the “her” sentence, and the “him neurons” on the “him” token in the “him” sentence. Run a forward pass and then remove the hook function so it doesn’t interfere with the layer-specific manipulation in the next loop iteration. Collect the output logits and calculate their difference relative to the clean logits.

Store three results from each layer: (1) the overall manipulation impact, measured as the average absolute value of the logit differences in the two masked sentences; (2) the “her-specific” impact, measured as the change in logits for the “her” token in the “her” sentence; and (3) the “him-specific” impact, measured as the change in logits for the “him” token in the “him” sentence.

Visualize the results as two scatter plots as in Figure 7.41.

Figure 7.41: Summary statistics of the overall impact of the manipulation (panel A) and the targeted manipulation (panel B).

The manipulations appear to grow in magnitude with deeper layers, although the signs of the impacts are not consistently positive or negative. Thus, the ablation does have some impact on final token representations, but the nature of the impact is not very clear from this one sentence.

The lack of clear direction of the effect in Part 6 is thought-provoking but perhaps a bit troubling: What if the impact isn’t as targeted as we would like, and any manipulation of any MLP neurons would have a comparable impact?

The goal of Part 7 is to run a control experiment to address that question.

Task

Go back to the code for Part 3 where the Boolean vector of significant neurons was stored in the dictionary. Replace the data stored in the dictionary to be the count-matched neurons with the weakest effects — that is, the neurons with t-values closest to zero. Do this separately for the positive (him > her) and negative (her > him) tests. Thus, you are now tagging for manipulation the neurons that showed the least modulation by gendered words.

In Part 3, those results were stored as Boolean vectors; here you should store the results as indices of the neurons to ablate.

Rerun all the code and inspect any differences in the results. It’s a good idea to take screenshots of the results before the change.

One coding comment: The code works the same regardless of whether the neurons to ablate are stored as a Boolean vector (as I implemented in Part 3) or as integer indices (as I implemented here in Part 7). That flexibility is a feature of Python that makes it easy to use — but can also cause confusion and “silent errors” (those that do not cause error messages). It also impacts some visualizations, for example Figure 7.38.

Keep in mind that this experiment is based on one sentence and a very targeted manipulation. My focus here is more on setting up this experimental control, rather than making meaningful insights into LLM mechanisms. Therefore, your comparison between the most-significant and least-significant manipulations should be more qualitative than quantitative.

Nonetheless, the results with the least-tuned neurons show qualitatively comparable magnitudes of manipulation impacts, again without a consistent sign to the effects.

Are you disappointed in the results? I was when I first saw them! An ideal result would be a lack of impact of the manipulation with the near-0 t-valued neurons. But there are two important caveats and one important conclusion:

  1. Although we masked out the words “her” and “him”, the sentence still contains the gendered words “she” and “his”. Therefore, it is possible that the test was too easy for the LLM to solve, and perhaps a more ambiguous sentence (e.g., those in Project 23) would show more consistent effects.

  2. This experiment was run on only one set of sequences. A real experiment would require dozens, ideally hundreds, of sample sentences. It is possible that with more data, consistent patterns would emerge with the max-t-value manipulation whereas no consistent patterns would be observed with the near-0 manipulation.

  3. Progress in science comes from chasing the truth even if we don’t like the results. Of course, being disappointed or annoyed at a result is perfectly fine — in fact, it’s shows dedication to the research — but we should allow compelling findings to change our preconceived ideas, not ignore or suppress whatever doesn’t fit into our desired worldview.

day-mode Bookmark

Supervised probing with XGBoost

The goal of project 47 is to use the XGBoost algorithm to classify different grammatical categories that the word “that” can take, and to explore causal evidence for a subset of MLP neurons in grammatical concepts. I’ll provide an intro to XGBoost here, and a brief background into the grammar of “that” in Part 2.

Background on XGBoost XGBoost (short for eXtreme Gradient Boosting) is a machine-learning ensemble-based optimization method that develops a predictive model by combining many weak models. The idea is to rely on “wisdom of the crowd” by assuming that the collective predictions made by a group of mediocre models is more reliable than the predictions made by one sophisticated model. XGBoost begins by training a decision-tree model (Project 30), then training a new model on the residuals of that first decision-tree, and so on until enough trees have been added that prediction accuracy reaches an acceptable threshold performance (or fails to improve, leading to stopping). There are, of course, important nuances, implementational details, and cost-benefit balances when selecting parameters; my goal in this project is to provide an introduction to the implementation and interpretation of XGBoost.

GPU We need a lot of data for XGBoost, which means running large batches through the LLM dozens of times. I recommend using a GPU for this project. If you don’t have GPU access, then I recommend using a smaller version of GPT-2 and reducing the sample size of the dataset.

The goal of Part 1 is to illustrate the XGBoost method, and then you’ll apply the code developed here to LLM data in Part 4.

Let’s start by creating a two-category dataset.

Task

Create a dataset of 1000 × 10 random Gaussian-distributed numbers stored in a NumPy array. The first 500 observations (“class 0”) have 10 features that each has a mean of zero and a standard deviation of one, and the next 500 observations (“class 1”) have 10 features with means that vary from .7 to -.7 in 10 linearly spaced steps, and a standard deviation of one. The goal of XGBoost will be to categorize each observation as belonging to class “0” or “1.”

Visualize the data as in Figure 7.42, with the data matrix in panel A and a scatter plot of all data and features in panel B.

To create the dataset, I created two separate datasets of size 500 × 10, then concatenated them. An efficient way to create the second class with varying means is to input an M-element array into the np.random.normal function, where M is the number of features.

Figure 7.42: Panel A shows the data matrix used in the XGBoost demo, and panel B shows a scatter plot of all observations, with small x-axis offsets for each feature.

The heatmap of the data matrix shows that earlier features contribute “positively” while later features contribute “negatively.” On the other hand, the scatter plots in panel B show that classification is not possible when averaging the features together (that is, the averages of “0” and “1” are the same).

Task

Use the train_test_split function in scikit-learn to split the data into a 75% training set and 25% test set. Make sure to stratify the split to ensure equal group sizes in the train and test sets. Then use the code below to build an XGBoost model (you can copy it from the online code).

model = xgb.XGBClassifier(
n_estimators = 100,
max_depth = 2,
learning_rate = .1,
subsample = .8,
colsample_bytree = .8,
eval_metric = ’logloss’
)

Fit the model to the training set, then use the predict method to obtain model predictions and prediction accuracy on the train and test sets. Report the accuracy.

Here’s a brief description of the parameters in the XGBoost object:

  • n_estimators: This is the number of trees that are created. Each tree is added sequentially to predict category label from the residuals of the previous tree.
  • max_depth: The depth of each tree (in Project 30 we set this parameter to 4). The large number of trees in combination with the small depth of each tree means that we’re training many shallow decision-makers. If you think of each individual tree as a simple “if-then” model, then the entire XGBoost method has 100 simple “if-then” classifiers stacked.
  • learning_rate: XGBoost is based on gradient descent, which means that the model tweaks the parameters (including the contribution of each tree) at each iteration to improve final classification performance. Smaller learning rates slow down optimization but can lead to better generalization performance. Setting this parameter is not trivial and is often done by cross-validation or exploration in a smaller dataset. We’ll leave it at .05 here.
  • subsample: This is the proportion of data to sample at each iteration. Reducing this parameter speeds up model optimization and helps ensure that the model learns patterns across the entire dataset, instead of memorizing a few individual samples.
  • colsample_bytree: This reduces the number of features that any given tree can see. In other words, each of 100 trees in our model can classify based on a random sample of .8×10 = 8 features. That helps improve the performance of individual trees as well as reducing the reliance on a single feature.
  • eval_metric: The goal of XGBoost (as with other gradient-descent-based methods) is to minimize the loss function. Binary classification tasks use log-loss, which is the discrepancy between the probability of each sample being labeled as each category vs. the actual category label.

It is also possible to include regularization methods into the model object. We’ll incorporate two regularizations into the models in Part 4.

XGBoost initializes trees randomly, so the exact results will differ each time you run the model — even without changing the data. Nonetheless, you should get somewhere around 80% training accuracy and 75% test accuracy. That gap reflects overfitting.

You can try changing the learning rate from .05 to .3; you’ll find that the training accuracy goes up (e.g., >95%) while the test accuracy goes down. In fact, many optimization parameters exhibit this balance whereby increasing performance on the training set impairs performance on the test set. The art of setting parameters is to find the parameter sets that increase test performance without increasing training performance too much (some overfitting is acceptable).

I encourage you to explore the other parameters as well. For example, increasing the number of trees to, e.g., 1000 will result in overfitting, whereas setting it to, e.g., 2 will cause underfitting. The two subsampling options have minimal impact in this toy example, but are more important for larger datasets with more features.

Task

Use the get_booster().get_score method to calculate the gains of each feature, and visualize as in Figure 7.43.

The booster method returns a dictionary with keys corresponding to feature labels (defaulting to f0, f1, etc) and values corresponding to the per-feature gain values averaged across all splits that used that feature. This provides a nice visualization of which features drove classification performance to what extent.

Figure 7.43: Scatter plot showing the performance gain (y-axis) from each feature used by the model (x-axis).

In this example, all features had a non-zero gain in at least one tree, but in other examples (e.g., with the LLM data later in this project) you’ll find that some features were never used by any tree. Their gain is zero and they are left out of the dictionary.

Are you surprised that the gains are U-shaped while the feature means decreased linearly? Keep in mind that the “gain” here refers to the importance of each feature in classification; it’s not a comparison of means like a t-test. Thus, negative data values can still contribute “positive gain” to the predictions.

Background: Grammar of “that” The word “that” is quite common in English, and it serves several different grammatical purposes, including the following.

“That” as a complementizer

A complementizer is a part of speech that introduces another part of a sentence. When “that” is used as a complementizer, it does not refer to a particular noun, but instead indicates that another clause is about to appear. For example, she expected that the exam would be hard.

“That” as a demonstrative pronoun

A demonstrative pronoun replaces a noun that appeared earlier or is implied. For example, that is my phone or I didn’t expect that to happen.

“That” as a demonstrative determiner

A demonstrative determiner modifies a noun to help specify which among several possible nouns is indicated. For example, Please hand me that plate or I like that idea.

In this project, we will focus on “that” as complementizer and “that” as demonstrative determiner. I mention the demonstrative pronoun because part of identifying determiner cases involves excluding pronoun cases.

The different grammatical categories of “that” provide a beautiful experimental setup, because we can build token sequences that all end in the same token and the LLM will need to use preceding context to understand which type of “that” is being used. This is a particularly difficult language task, because the grammatical category of “that” is often identified based on what comes after, although we won’t give the LLM access to the words after “that.”

Task

Import the GPT-2-small tokenizer. Import and tokenize the wikitext-2-raw-v1 training set from Wikitext (see Project 18 for wikitext code, or copy the code from the notebook for this project). Report the total number of tokens, and define a variable for the token index of “ that”.

You should find 2,428,601 tokens in the wikitext dataset.

Now to identify “that”s of different grammatical categories. Important note: The algorithm described below is an imperfect linguistic filter. It may misclassify some “that”s, but it’s good enough for our purposes here of exploring an application of XGBoost.

Task

Tokenize the following list of words (including preceding spaces) that often follow “that” as complementizer: he, she, it, they, we, I, you, the, a, an, this, that, these, those.

Tokenize the following list of words (including preceding spaces) that often follow “that” as demonstrative pronoun: is, was, are, were, has, have, had, do, did, does, works, happened, sucks, matters, helps, fails, changed.

Initialize three lists corresponding to “that” as complementizer, as demonstrative pronoun, and as demonstrative determiner. Loop through all tokens and implement the following checks: If the current token is not “ that”, then skip to the next token. If the token after the current token is one of the post-complementizer words, then add the current index to the complementizer set. If the token after the current one is one of the post-demonstrative pronoun tokens, then add the current index to the demonstrative-pronoun set. And if neither of the two previous categories are true, then add the current token index to the demonstrative determiner set. In other words, check whether each “that” precedes a complementizer word or a demonstrative-pronoun word, and if both tests are false, then the “that” is a demonstrative determiner.

Report the number of “that”s in each category.

Here’s the breakdown by grammatical category:

There are

4717 complementizer "that"s
8394 demonstrative determiner "that"s
1027 demonstrative pronoun "that"s

We now have the target indices that we need to create batches.

Task

Create two batches of 2500 6-token sequences, corresponding to the complementizer and the determiner categories. Each of 2500 sequences comprises the target token and the five tokens preceding it. Because the number of available tokens is greater than the sample size, randomly select from the tokens you’ve identified.

Print out the sizes and a selection of the batch sequences to confirm their shapes and that each sequence ends with token 326.

Make sure to sample without replacement, because you don’t want the same sequence to appear in a batch multiple times.

Here is a sample of my output. Your results will look different because of random sampling, but the sizes of the batches and the final token in each sequence must be the same.

batch_detr has shape: [2500, 6] And it looks like this:

tensor([[ 340, 925, 607, 1975, 366, 326],
[ 8769, 353, 366, 290, 2630, 326],
[ 503, 837, 329, 1672, 837, 326],

batch_comp has shape: [2500, 6] And it looks like this:

tensor([[ 670, 837, 475, 484, 1965, 326],
[ 4454,21635, 319, 262, 4308, 326],
[13362, 837,12382, 12981, 2630, 326],

Is five preceding tokens enough? There are several trade-offs with sequence length. For one thing, a batch size of 2500 is fairly big for most commercial GPUs and GPT-2-medium, and so a sequence length of, e.g., 100 tokens might be too large to be processed by many readers. At the other extreme, having only one preceding token probably doesn’t give the model enough context to make accurate grammatical assignments. Of course, you could break the batches into smaller chunks, e.g., running 250 forward passes using a batch size of 10 with a sequence length of, e.g., 200. But do you even need that much context? Longer sequences are important for rich, context-dependent answers from an LLM, but here we’re only evaluating a local grammatical assignment, and so having more tokens would provide diminishing returns at the expense of increased computational needs and time.

I bring up this discussion because these are real decisions you need to make in research, and it’s not always the case that longer context windows are better.

We will analyze activations from the post-GELU expansion neurons. The goal of Part 3 is to obtain the activations from each layer for later analyses.

Note 1: In this project you’ll work with two models: the LLM and the XGBoost. Use different and meaningful variable names to avoid confusing the two!

Note 2: If you don’t have access to a GPU, use GPT-2-small and reduce the batch size to, e.g., 500.

Task

Import GPT-2-medium and push it to the GPU. Create a hook function that stores the post-GELU activations (hint: it’s the output of .mlp.act) in a dictionary called mlp_acts. Bring the data back to the CPU and convert to a NumPy array. Implant the hook into all transformer layers.

Run two forward passes, corresponding to the two batches you created in Part 1. Note that the mlp_acts dictionary will be overwritten at each forward pass, so you’ll need to make a copy of the data before the second model call. You’ll also need the output logits for Part 6, so extract the logits from the final token position in all sequences, copy them to the CPU, and store them in two variables named logits_clean_detr and logits_clean_comp.

Print the key names and tensor sizes. Remove all hooks.

Show two visualizations of the data. The first (Figure 7.44) shows heatmaps of activations for the target token for the two batches from layer 10 and their histograms. The second (Figure 7.45) shows a heatmap in which each row is the histogram of the differences between determiner and complementizer (again, just the activations for the final token).

When making a copy of the dictionary, remember that Python assignment creates a new reference to the same object in memory, not a new copy of the data. In other words, if your code looks like this:

gpt2(batch_detr.to(device))
detr_mlp = mlp_acts
gpt2(batch_comp.to(device))
comp_mlp = mlp_acts

Then you will have lost the detr_mlp data. Instead, you need to make a copy using detr_mlp = mlp_acts.copy().

You should find that all matrices are of size 2500 × 6 × 4096 corresponding to 2500 batches per grammar category, 6 tokens, and 4096 neurons (that’s 4x the embeddings dimensionality of 1024).

Figure 7.44: Visualizing the activations and distributions from one MLP layer, separated for two grammatical forms of “that”.

The vertical stripes in the heatmaps reveal that individual neurons have intrinsic shifts such that they maintain a particular level of activation across all “that” tokens — replicating results you’ve observed in several previous projects.

The histograms are nearly perfectly overlapping — that shouldn’t be surprising considering how much data is being aggregated and that the two classes are the same token.

Figure 7.45: The differences between the two histograms in Figure 7.44C) were extracted for each transformer layer (y-axis) and pseudocolorized to indicate density differences.

That said, the heatmap in Figure 7.45 suggests some categorical differences, though they are subtle (compare the color-axis scaling in Figure 7.45 compared to the y-axis in Figure 7.44C) and narrowly confined in the x-axis due to the compression from the GELU nonlinearity. The most salient differences seem to occur towards the end of the transformer stack, where the hidden-state vectors have shifted from the current token (“that”) to a prediction about the next token.

Now we’re ready to integrate what you learned in Part 1 with the data you extracted in Part 3.

Task

Create a data matrix of size 5000 × 4096 by vertically stacking the MLP activations from layer 4 for the final token (corresponding to the target word “that”) for the 2500 determiner samples and the 2500 complementizer samples. These are the data you hooked in Part 3. Create a 5000-element labels vector that is zeros for the determiners and ones for the complementizers.

Split the data into train and test sets, using 25% of the data for test, and stratify according to the labels. Construct an XGBoost object using the same parameters as in Part 1, and additionally include L_1 and L_2 regularization with parameters of α = λ = 5.

Fit the XGBoost model to the training data, and report the train and test accuracy. Finally, calculate and plot the feature gains and their histogram, as in Figure 7.46.

The two additional parameters compared to Part 1 are L_1 (input argument reg_alpha) and L_2 (input argument reg_lambda; the reg is for regularization). L_1 regularization promotes sparsity (it’s called “lasso” in regression models) while L_2 regularization promotes smaller weights (it’s called “shrinkage” or “ridge” in regression). Regularization helps prevent overfitting and is particularly important for small datasets.

But wait — is this really a “small” dataset? We have a sample size of 5000!

What’s important in XGBoost is not the number of samples per se, but the number of samples relative to the number of features. Our dataset has a samples-to-features ratio of 1.2:1. That is very small. For real analyses, you should aim for a ratio of 20:1, ideally even higher (e.g., 50:1). For our dataset, a ratio of 20:1 would correspond to around 80,000 samples. Also keep in mind that an acceptable ratio depends on the data quality and separability of the categories: A lower ratio is fine for more easily separable data.

In Project 30, we dealt with this issue by using PCA to reduce the number of features; here we will ignore the issue in the interest of focusing on the code and visualizations.

Anyway, back to the results: There are several sources of random variation in the results, but you should find accuracies somewhere around 70% for the training set and 65% for the test set (cf 50% chance level). I think that’s a pretty good result, considering (1) the data are from the internal calculations in an early layer (as opposed to output logits after a full sweep of processing), (2) all activations are from the same token, (3) the LLM has only five tokens from which to extract meaningful context, and (4) the sample size is quite small relative to the number of features.

Figure 7.46: Visualizing the “importances” of the neurons for XGBoost classification. Panel A shows which neurons were used by the model (small y-axis jitters added to facilitate visual inspection), and panel B shows a histogram of the gain scores of the “important” neurons.

The scatter plot in panel A shows which neurons were used in the analysis. Most of the neurons were actually not used. Does that result indicate that only 195 neurons are tuned to “that” grammar categories? Think of an answer to that question; I’ll get back to it at the end of this project.

Of the neurons with a significant contribution to the model, most of their contributions were clustered in relatively small gain values, with a small number of neurons having a higher gain (more impact on the categorization).

The goal of Part 5 is to repeat the XGBoost analysis for each layer. You don’t need to run any new LLM forward passes because you already have all the data from Part 3. These results will also provide a baseline comparison for the causal experiment in Part 6.

Task

Create a for-loop over the transformer layers. At each iteration, repeat the code from Part 4 to extract the MLP activations from that layer into a 5000×4096 data matrix, split the data into train and test sets, create a new XGBoost model and train it on the data, and calculate the train and test accuracies. Store the average accuracy results per layer in a variable called results_clean, and additionally store a list of which neurons had non-zero gains per layer.

Visualize the summary results as in Figure 7.47, which shows laminar profiles of train and test accuracy in panel A, and the number of “important” neurons in panel B.

Something to be mindful of: You need to re-create an XGBClassifier object for each layer. You cannot re-use a model object that you previously created and trained. The reason is that the trained weights are stored in that variable, and so re-training it on new data is akin to fine-tuning an existing pretrained model. What we want here is a fresh model instance to fit separately on each layer.

Figure 7.47: Performance metrics of the classification models per layer. Panel A shows train and test accuracy, and panel B shows the number of neurons used by the XGBoost model.

The train accuracy is both higher and less variable than the test accuracy. That’s a typical pattern in ML: The higher accuracy reflects overfitting while the reduced variability reflects the higher sample size. As long as the test accuracy isn’t too much lower, some overfitting is acceptable. The accuracies overall seem to increase slightly with increasing depth into the LLM, by around 1% except for the first few layers in the test data.

On the other hand, the number of neurons it takes to perform the classification decreases from around 200 to around 170 — a drop of around 15%. In other words, the XGBoost model can achieve comparable (or slightly improved) performance using fewer features in later transformer layers.

Part 6: Ablate the “important” neurons

Section titled “Part 6: Ablate the “important” neurons”

Are the “important” neurons causally involved in the LLM’s ability to use proper grammar? The findings from Part 5 provide correlative evidence but not causal evidence. For example, what if those “important” neurons are not causally involved at all, but instead are loudly cheering on the other, quieter, neurons that actually are causally involved?

As you know, to establish causality we must perform causal experiments. However, making valid causal inferences is surprisingly difficult in complex systems like LLMs, for reasons I will discuss at the end of this project.

There are several ways to address causality here. One experiment setup, for example, could involve zero-ing out the “important” neurons, and using the model output logits to test the hypothesis that the subsequent token prediction would be grammatically inconsistent with the use of “that” in the sequence. That would be a great experiment, but would require additional complexity to assess the grammatical correctness of the newly generated token(s).

The approach we’ll take here is to zero-out the “important” neurons and then to rerun the XGBoost analysis as before. If those neurons really are vital to the classification, then ablating their activation should strongly impair the classification accuracy.

Warning: This is the most computationally-intensive analysis in this project, and one of the most intensive in this book. If you don’t have access to a GPU, use GPT-2-small and reduce the sample size. Your results will be less reliable, but at least you’ll get a plot before the sun goes supernova.

Task

Create a for-loop over transformer layers. Make sure the hooks from Part 3 have been removed. Create a hook function that ablates only the neurons for the current layer labeled “important” from Part 5, and only in the final token position. After the ablation, store the activations in a dictionary in NumPy format as you did in Part 3. Run forward passes on the two batches and copy the mlp_acts dictionary to new variables, as you did in Part 3. Remove the hook.

Extract the output logits from the final token position for all sequences. That is a 5000×50257 matrix, and the difference between the “clean” and “ablated” versions of that matrix reveals the impact of the ablation on the final model outputs. Calculate and store the norm of that difference matrix in a 2 (determiner and complementizer) × layers matrix.

Paste in the classification code from Part 5 where you extract the MLP activations from the current layer, split the data into train and test sets, create a fresh XGBoost object and train it, and store the average train and test accuracies per layer. Make sure to use a different variable name for the list of “important” neurons so it doesn’t overwrite the previously-created variable.

Visualize both the average accuracies as in Figure 7.48A, the difference between the manipulated accuracies and “clean” accuracies from Part 5 as in Figure 7.48B, and the number of “important” neurons over layers as in Figure 7.48C.

Finally, visualize the norms of the logits differences as in Figure 7.49.

Make sure to store the activations data after zeroing out the neurons. Because this hook is implanted into one layer at a time, you don’t necessarily need to include the layer number in the key name in the activations dictionary that stores the MLP activations. For example, I named it mlp_acts[’acts’].

Figure 7.48: Classification performance in the ablation experiment. Panel A shows train and test classification performance, panel B shows the change in accuracy compared to the clean run (the data that were shown in Figure 7.47A), and panel C shows the number of “important” neurons used in the XGBoost model (cf Figure 7.47B).

The results in panel B show only a tiny modulation in accuracy compared to the clean model. From this plot, it appears that there is a subtle but systematic difference, with accuracy being around 1% higher in the clean model. However, those fluctuations are due to randomization of the XGBoost model and train/test split; if you rerun the experiment a few times, you will not see consistent (even subtle) patterns. (That said, it is possible that consistent effects would emerge with a larger dataset.)

These results might seem surprising: After all, we ablated the neurons identified as being most important for classification in the exact same dataset and same model.

On the other hand, the ablation clearly impacted the output logits, as shown in Figure 7.49.

Figure 7.49: Impact of layer-specific ablation on the final-token logits, as measured through the matrix norm of the difference between the “clean” and “ablated” logits.

Here’s the important thing to understand about multivariate predictive models like XGBoost: Their goal is to predict the label using any combination of input features that they can. Thus, the focus is on predicting the outcome, not on isolating the features that make causal contributions.

Consider this analogy: Imagine you give a medical report to 100 expert doctors and ask them to diagnose the patient. You then ask the first 20 doctors and they all give the same diagnosis. Do you need to continue surveying the rest of the 80 doctors? No, that would be a waste of time and resources. Now imagine that your dog ate your homework including the first 20 doctors’ reports. No problem — just survey the next 20 doctors and the diagnosis will be just as accurate.

When there are redundancies in the features (which is definitely the case here, considering all the mixing to get from the embeddings dimensionality to the expansion dimensionality), XGBoost does not need to use every feature; it will use only those features it needs to, given constraints such as random feature selection, regularization, etc.

Furthermore, the random initialization of the XGBoost model means that the random starting values of the weights may anchor onto different features each time it’s run on the same data. Going back to the medical diagnosis analogy: If you and I start with the same data but randomly sample different groups of 20 doctors, then your and my lists of “important” doctors will differ.

I don’t mean to suggest that causality cannot be established in LLMs. Instead, it is important to understand the details of the analysis being performed, and to understand whether the analysis is identifying the exact neurons that contribute, vs. using features of a dataset to make predictions. XGBoost is a fantastic method to understand how much information is available in a set of features, but a mass-univariate logistic regression would better identify which neurons are individually modulated by category.

day-mode Bookmark

“Can” vs. “can’t” classification via logistic regression

Here’s an interesting thing in GPT-2’s tokenizer: “ can” comprises one token while “ can’t” comprises two tokens: “ can” and “’t”.

The goal of Project 48 is to determine whether we can categorize each appearance of the token “ can” according to whether it’s used as a positive modal verb (“you can do it!”) or a negative modal via contraction (“No I can’t do it.”). On the other hand, “can” can also be a noun (e.g., “a can of worms”). Therefore, it will be necessary to create an algorithm that identifies modal verbs while filtering out other grammatical uses of “can.”

You will use logistic regression on pre-GELU expansion activations to determine how many MLP neurons exhibit tuning for “can” vs. “can’t”. It’s a nice follow-up to the previous project, because we’re again classifying groups based on identical tokens, and because the previous project focused on multivariate classification whereas this project focuses on classifying each neuron separately.

GPU There are only two forward passes for this project, but they involve large batches (500 × 11). A GPU is helpful but not necessary. Most of the time-consuming computations in this project are from repeatedly fitting logistic regression models, which is done on the CPU using the statsmodels library.

Part 1: Create two batches of “can” tokens

Section titled “Part 1: Create two batches of “can” tokens”

By the end of Part 1, you’ll have two batches of tokens that you’ll use to get data and build logistic regression models.

We will use the allenai/c4 dataset, which is a large dataset filtered from Common Crawl that has non-natural language content removed (e.g., code and formatting). It’s a very large dataset, but we can “stream” it using the Hugging Face load_dataset function, which means importing the data one sample at a time as we need it.

Task

Import the GPT-2 tokenizer. Check the tokenizations of the words “can”, “ can”, “can’t,” and “ can’t”.

However, there are several apostrophes that have different byte sequences, and the GPT-2 tokenizer treats them as separate tokens. The online code file contains six different versions of “can’t” that use different apostrophes. Show their tokenizations.

The screenshot in Figure 7.50 shows various apostrophes and their tokenizations.

Figure 7.50: Screenshot showing GPT-2 tokenization of the word “can’t” with different forms of the apostrophe.

That is annoying for tokenization, because (1) many apostrophe forms are multi-token sequences, and (2) they can all indicate contraction, differing only due to arbitrary typographical preferences and publication styles.

For this project, we will only search for the standard (plain ASCII) apostrophe. We can safely ignore the other variations, because the goal of this project is to find some targets to analyze, not to find all instances and varieties of “can’t”. But this is an issue for you to be aware of in text-based research. One easy solution is to replace all forms of the apostrophe with the standard ASCII form, before tokenization.

FYI, Figure 7.51 shows a list of the unicodes for different apostrophes.

Figure 7.51: Screenshot showing unicode values for different forms of the apostrophe.

Task

Import the English training set of the allenai/c4 dataset using the load_dataset function, and set the streaming parameter to True. Inspect the dataset.

When imported using streaming mode, the dataset looks like this:

IterableDataset({
features: [’text’, ’timestamp’, ’url’],
num_shards: 1024

})

You can use an IterableDataset variable in a for-loop to import the data one sample at a time.

Task

I will now explain an algorithm to identify target tokens. If you’d like to think of your own algorithm, then don’t read the last paragraph in this Task Box. The final result should be two batches of size 500×11 corresponding to 500 sequences and 10 tokens preceding each “ can” token. One batch is for the positive modal verb and one batch is for the negative modal verb (but excluding the token “n’t”). (Note for the linguists: This is not a perfect filter, but it should exclude most of the non-modal-verb cases, and it’s good enough for this educational application.)

Report the number of positive and negative modal tokens identified. Is there an imbalance? If so, do you think this will be problematic (i.e., a confound) for the classification analysis? And if you think it is problematic, is there a solution?

Here’s the algorithm: Find the tokens for “ can” and “n’t”. Then make a list of exclusion tokens: “ of”, “ with”, “ from”, “ in”, “ on”, “ for”, and “ not”. Define two empty lists called can_tokens and cant_tokens. Here’s how the algorithm works: Tokenize each text sample. Loop over tokens to see if it’s a “ can” token. If it is, check (1) whether the following token begins with a space and (2) whether the following token is not in the excluded list. If those conditions are met, then the current token is a positive modal. If the next token is “n’t” then the current token is a negative modal. Continue streaming new samples from the dataset until you’ve found 500 indices of “can’t.”

If you followed my algorithm, you got 18,916 positive modals vs. 500 negative modals. That’s a huge difference in sample size!

Is it a confound for a classification analysis? The answer is yes it is: Any classifier could simply always predict that the final token is a positive modal and it would be correct most of the time.

Fortunately, though, this is an easy confound to fix: Randomly sample 500 of the positive modals to match the sample sizes.

On the other hand, this 40-fold difference in sample size indicates that the positive modal is much more common in the text dataset. Is that a confound even if the sample sizes are matched? The answer here is no, because corpus frequency is not the same as dataset frequency. That is, we are not decoding the “n’t” token; instead, we are decoding the model’s expectation of negation while processing “ can”, and corpus frequency does not bias this once classes are balanced. The predictions are based on LLM data, but the predictive model is a logistic regression that will be trained on a sample-size-balanced dataset.

Task

Print out a few of the decoded token sequences from each batch. How accurately could you determine which sequence is a positive vs. negative modal?

Make sure each batch is a PyTorch tensor of size 500 × 11, and make sure the positive modals are randomly sampled. It’s a good idea to randomly sample (that is, shuffle) the negative modals as well, in the interest of consistency and avoiding any potential sequence effects. Confirm that the batch sequences all end in token index 460.

Here are two examples from each batch:

Some “can” sequences: CC usually works in “file mode” and it can  clone a drive you did NOT boot from, it can

Some “can’t” sequences:

year, sometimes more than once, but I really can
could buy. Again, maybe that’s why I can

To be honest, I’m not sure that my predictions would be so accurate.

The goal of Part 2 is to hook MLP activations that you can analyze in the rest of the project.

Task

Import GPT-2-medium and move it to the GPU if available.

Implant a hook function into all layers that stores the MLP pre-GELU expansion neuron activations in a dictionary, in NumPy format and on the CPU.

Run forward passes using the two batches and copy the MLP activations dictionary after each run, to avoid overwriting. Check the key names and shapes of the items in the dictionary.

GPT-2-medium has 24 transformer layers, and the size of each MLP activations tensor should be 500 × 11 × 4096.

Part 3: Logistic regression in all neurons from one layer

Section titled “Part 3: Logistic regression in all neurons from one layer”

The goal here is to train and evaluate logistic regression classifiers for each neuron from one layer. You’ll do this using the statsmodels library. If you need a refresher on interpreting logistic regressions and implementing them in statsmodels, please refer back to Project 21 in Chapter 4.

Here you will focus on the data from layer 3, and then you’ll expand that to all transformer layers in Part 4.

Task

Create a Boolean vector of category labels that contains 500 False and 500 True elements. Define a variable for the number of neurons.

In a for-loop over the 4096 neurons, create a 2 × 1000 NumPy array where one column is the activations to the final token stacked from the two categories, and the other column is all 1’s corresponding to an intercept (hint: use the statsmodels function add_constant).

Use the train_test_split function to split the data into a training set (80% of the data) and a test set (20% of the data). Stratify using the category labels to ensure a category-balanced split.

Build and fit an sm.Logit model. Set a maximum of 3000 iterations and incorporate L_1 regularization with α = .1. Calculate and store the regression coefficient (β value) and its p-value, prediction accuracy in the train set, and prediction accuracy in the test set.

Write code to create Figure 7.52. The p-value threshold for the marker shapes and sizes is a Bonferroni-corrected p < .05 (that is, p < .05∕N for N neurons). Finally, create Figure 7.53, which shows histograms of prediction accuracies over all 4096 neurons.

The logistic regression model has two parameters: intercept and slope. Make sure you store the coefficient and p-value from the slope (the term associated with the activation values), not the intercept (the column of all 1’s). If you constructed the design matrix using sm.add_constant, then you would store the second coefficient and p-value.

There are both positive-signed and negative-signed coefficients. The sign is determined by the order with which you concatenate the positive and negative modal categories. The magnitudes and p-values, however are unaffected by this choice. In other words, a β value could be positive or negative, but it’s important to know how to interpret them. I associated “can” with False labels and “can’t” with True labels, so a neuron with β < 0 means more activation predicts “can” whereas β > 0 means more activation predicts “can’t”.

Figure 7.52: Statistical results from Part 3. Panel A shows β coefficients for all expansion-stage neurons in one transformer layer, with separate markers for direction (“can” vs. “can’t”) and statistical significance (p < .05, Bonferroni correction). Panel B shows β values by their log-transformed p-values. Panels C and D show p-values by prediction accuracy for the train and test datasets.

The scatter plots on the bottom row show that the statistical significance (here expressed as −log _10(p)) is moderately but not perfectly correlated with the β value and prediction accuracy. p-values are a product of several quantities including the coefficients, their standard errors, and sample sizes. p-values are important statistical quantities, but they don’t tell the whole story.

And there is an additional complexity that limits our ability to interpret p-values in this case: Because we’ve included an L_1 regularization term, the p-values are no longer valid, strictly speaking. Briefly, the reason is that p-values are based on unbiased and normally distributed maximum likelihood estimates of the coefficients obtained by minimizing the non-regularized loss:

β^=arg⁡min⁡βL(β)(7.7)\hat{\beta} = \arg\min_\beta L(\beta) \tag{7.7}

where L is the loss function. Including a regularization term like this:

β^=arg⁡min⁡β(L(β)+α∥β∥1)(7.8)\hat{\beta} = \arg\min_\beta (L(\beta) + \alpha \|\beta\|_1) \tag{7.8}

Makes the estimate biased and non-normal (because E[β^\hat{\beta} ]≠β).

The upshot is this: we treat the p-values more as a heuristic filter for selecting neurons, not as a formal labeling of statistical significance. An alternative approach would involve permutation testing to incorporate the regularization into the null-hypothesis distribution, but that’s a level of detail we don’t need to worry about here.

The histograms of accuracy values in Figure 7.53 show that the neurons are roughly normally distributed with a peak of around 55-60%. Although the bulk of the accuracy scores are above 50%, the effect size appears quite small.

Figure 7.53: The roughly Gaussian distributions of classification accuracy over neurons suggests that the representation of grammar category was more distributed than sparse; and the comparable distributions between train and test argues against overfitting.

The shape of the distribution is also informative. It suggests that each neuron carries a small, noisy projection of the underlying signal, as opposed to a small subset of specialized neurons with high accuracy. This suggests that the grammar coding is distributed across the population at this stage (a downstream projection could combine this information to produce a sparse code). The overlap between the two curves is also important, because it argues against overfitting.

The final part of this project is to repeat the analyses over all the layers. Using a GPU won’t help you here, because the analysis is done using the statsmodels library on the CPU.

Task

Write a double for-loop over all layers and over all MLP neurons. Repeat the code from Part 3 to create the design matrix, split the data into train and test, construct and train the logistic regression model, and store the p-value, coefficient, and train and test accuracies.

Visualize the results as in Figure 7.54. Panel A shows the percent of neurons in each layer that had p < .05 (Bonferroni corrected within each layer), and panel B shows averaged prediction accuracies only from the significant neurons.

This analysis takes around 7-10 minutes on a standard CPU. I recommend using the tqdm function to provide status updates, and having something to distract you while waiting. Also, while developing your code, I recommend trimming the loops, e.g., only testing two layers and the first 40 neurons. That will allow you to iterate quickly until you’re confident the code is correct.

There are two reasons for the long computation time:

  1. Splitting train and test sets per neuron instead of over all neurons per layer involves additional overhead. Although splitting per layer would decrease computation time, the per-neuron split provides more randomization across neurons.

  2. Statsmodels cannot be vectorized to fit all neurons simultaneously. This is the main bottleneck. Scikit-learn does have an implementation of a logistic regression that allows vectorization, which would remove the loop over neurons and decrease computation time by a lot. However, scikit-learn does not calculate p-values or any other inferential statistics that you might need. The additional computation time for statsmodels is acceptable for this educational project, but these are issues you need to think about in real research where the datasets are orders of magnitude larger.

Figure 7.54: Results from the laminar sweep of logistic regression classification performance. Panel A shows the percent of neurons with a significant β coefficient per layer, and panel B shows train and test classification accuracy for both categories.

The results show that individual MLP neurons weakly but consistently encode whether “’t” is likely to follow “ can”. That prediction is relatively low in the earliest and middle layers, and only increases up to around 62% towards the end of the transformer stack. The accuracies were only slightly higher for train compared to test, indicating that overfitting isn’t a concern.

Each logistic regression isolates the activity from one neuron and ignores how information might be distributed or pooled across many neurons. On the other hand, remember that the expansion neurons do not directly contribute back to the hidden states; they pass through a GELU nonlinearity and then are linearly combined to obtain the projection neurons. It is, therefore, possible that the classification would be higher, and the indicative features more sparsely encoded, at the projection stage.

day-mode Bookmark

Successive median-replacement of MLP activations

The goal of Project 49 is to replace large MLP activation values with the median value, and explore the impact of that manipulation on changes in hidden-state vectors and final output logits. You will also manipulate all layers per experiment iteration, instead of isolating only one layer at a time as you’ve often done in this book.

Remember that the median is the value that splits a dataset in half, such that half of the data values are below, and half are above, the median. The median and the mean are identical (or nearly) for a symmetric distribution, but the median is robust to outliers.

GPU There aren’t a lot of tokens or batches to process, but this project does involve many forward passes to manipulate different proportions of neurons targeting different stages of MLP processing. A GPU will be useful if available, but is not crucial.

The goal of Part 1 is to obtain a set of MLP activations to develop code for the analysis, and to obtain a “clean” set of output logits to compare against the manipulations later in the project.

Task

Import GPT-2-large and its tokenizer, and move the model to the GPU. Create a hook function that extracts the pre-GELU expansion neuron activations from layer 9. Bring the activations back to the CPU.

Tokenize the text “It was a dark and stormy” (without the quotes) and move the tokens to the GPU.

Run a forward pass on the tokens and extract the hidden-state vectors, and then remove the hook. Transform the output logits to log-softmax and store in a variable called logsm_clean. These will provide a baseline comparison for later experiments. Check the sizes of the hooked MLP activations and the output logits.

Create Figure 7.55, which shows the log-softmax probabilities to the final token, with the maximum token indicated in green.

You should find that the MLP activations comprise a 1 × 7 × 5120 tensor, corresponding to one sequence, seven tokens, and 5120 MLP expansion neurons. The output logits are of size 1 × 7 × 50257 corresponding to the same number of tokens and 50,257 items in the vocab.

Figure 7.55: Scatter plot of model logits, transformed to log-softmax, for the final token in the sequence, with the predicted next token highlighted in green.

You’ve seen scatter plots like Figure 7.55 many times in this book; the main point here is to show that GPT-2 is familiar with cliché prose ;)

The token “ night” is the target token that you’ll use for the rest of the project. Define a variable for the vocab index of this token.

Part 2: Exploring median-based replacement

Section titled “Part 2: Exploring median-based replacement”

Part 2 involves writing code to replace a proportion of the MLP activations with the distribution median. The code will be used in later parts, and the visualizations will help you understand the conceptual reasons for particular experiment choices about replacing positive vs. negative activation values.

Task

Make a copy of the activations for the final token from layer 9. Calculate the mean and median activation values. Find the indices of the neurons with the top 10% activations, and replace those values with the median value. Show histograms of the original and manipulated datasets as in Figure 7.56, with the median and mean drawn on top. Use the same bin boundaries of -5 to 2 in 41 steps for both histograms.

Think about why the mean and median are nearly identical here, and why I stated that we’ll use the median instead of the mean for this project. Also think about why we’re replacing values with the median instead of zeroing them out as you’ve done in previous projects.

The mean and median are nearly identical here because the distribution is roughly symmetric and without outliers. It doesn’t matter that it’s shifted negative; that impacts the numerical values but not the relationship between the mean and median. That said, the median is a more appropriate value for the post-GELU replacement that we’ll do later due to the non-normal shape of the distribution.

Figure 7.56: Comparison of histograms of pre-GELU expansion activations before (green) and after (red) replacing the largest 10% of neurons with the median value. The histogram bins are the same but small x-axis offsets were added to facilitate visual inspection.

The two distributions are identical at most bins, except for the spike at around -1.8 and above zero. That difference corresponds to replacing 10% of the right tail of the distribution with the median. In the experiment in the next two parts, you will implement this replacement during the forward pass using increasing proportions of neurons.

As for the difference between replacing activations with the median vs. zeros: If we set the activations of the top 10% of neurons to zero, then their activation would still be greater than most of the distribution of values. By replacing with the median, the central tendency of the population is nearly the same, while only the largest values (and the layer variance) are affected.

Final point here: The distribution of activation values is negatively shifted, and the median is around -1.5. The values to the left of the median are more extreme in terms of magnitude (distance to zero) than the values to the right of the median. Why did I instruct you to replace only the right-tailed values and not the values from both tails? Would it make sense to take the 10% extreme magnitudes instead (e.g., implemented as torch.topk(acts.abs())?

The answer is in the next paragraph, so please stop reading to think of your answer before continuing :)

The answer is that in the pre-GELU expansion stage, negative values are suppressed by the GELU. That is, the most negative values are zeroed out by design, and replacing them will have almost no downstream impact. See also the stage-specific distributions from Project 42.

Part 3: Impact of replacement on hidden states and logits

Section titled “Part 3: Impact of replacement on hidden states and logits”

Now for the experiment. The idea is to manipulate different proportions of MLP neurons in all layers — not one layer at a time as in previous projects. For example, in one iteration you will identify the 15% most active neurons in each layer, and replace those activation values with the median of the population from that layer. In other words, the manipulations are based on layer-specific statistics, but all layers are manipulated at each experiment run.

The goal will be to determine the impact of the manipulation on the hidden-state vectors and on the final logit to the target token “night.”

Task

Define a vector of proportions of neurons to replace as 21 linearly spaced numbers between .01 and .99. In a for-loop over those proportions, implant a hook into the pre-GELU expansion stage of all transformer layers to identify the top k% active neurons from the final token and replace those activations with the median. Run a forward pass and then remove all the hook functions.

Transform the output logits from the final token position to log-softmax and store the log-softmax value for the target token. Then loop over all hidden-state layers and calculate the vector norm of the difference between the hidden-state vector to the final token from the manipulated run and the corresponding “clean” hidden-state vector from Part 1. The variables that store your results should end with _ex (for “expansion”) so you can differentiate them from similar variables in the next few parts.

Create Figure 7.57. I set the maximum color limit in panel A to be 80% of the maximum difference norm. The horizontal dashed line in panel C is the softmax probability to the target from the clean run.

Notice that the heatmap in panel A is dominated by x-axis changes, with comparatively little changes along the y-axis. That is, the primary impact of median-replacement is the accumulated changes in the hidden layers; the impact of going from 1% to 99% replacement is minor in comparison.

Figure 7.57: Visualizing the impact of successive median replacement on hidden-state vector norms (panels A and B) and output logits (panel C). Panel B shows the total impact of median replacement by averaging over all replacement values (rows in panel A). Horizontal dashed line in panel C shows the target log-softmax value from the clean model.

Panel C demonstrates a clear decrease in the output logits to the target token, but not a clear monotonic impact of the manipulation. Quite different from panel B, which shows that the impact of manipulating the MLP neurons accumulates as the vectors go deeper into the model.

The conclusion from this figure is that replacing any extreme MLP expansion neurons with their median has a clear impact, but there does not appear to be a compelling consistent relationship between the number of neurons replaced with an impact on hidden-states or output logits.

Please continue thinking about what this finding might mean. I’ll discuss it in more detail towards the end of the project.

Task

Perform three separate sanity-checks to ensure your hook function code is accurate. First, set the lowest replacement percentage to be zero instead of .01. Confirm that when replacing 0% of the neurons, the output logits are the same as in the clean model.

Second, implant the hook starting in layer 10 to confirm that panels A and B show zero difference compared to the clean hidden-state vectors until layer 10. Then reset the hook function loop.

Third, change which hidden-state vector is compared (e.g., use the penultimate instead of the final token); the manipulation only targeted the final token, and so the hidden-state vectors for the other tokens should be unaffected.

Do each of these checks separately, and reset the code after each check. After running all the checks, reset the code without the sanity checks and run it again — you need the results to compare with Parts 4 and 5.

Including these kinds of manipulation checks help you refine your code and catch bugs — especially the worst kind of bugs: those that do not crash the program.

Note: The rest of this project involves copying the code from Part 3 with only minor changes. Please make sure your Part 3 code is correct, and that the sanity-checking changes have been undone.

Part 4: Comparison with post-GELU expansion

Section titled “Part 4: Comparison with post-GELU expansion”

Part 4 is quite simple and requires little coding.

Task

Copy and paste the code blocks from Part 3. Make two changes: Define the variable names to end in _ge (for “GELU”), and manipulate the post-GELU activations instead of the pre-GELU as in Part 3.

The visualization here is slightly different, though (Figure 7.58), because it showcases the comparison of manipulating the pre- vs. post-GELU activations.

The main difference in the code is implanting the hook into .mlp.act instead of .mlp.f_fc.

Figure 7.58: Similar to Figure 7.57 but manipulating the post-GELU neuron population.

There is a small difference in the impact of the pre- vs. post-GELU manipulation on the hidden-state activations, but the findings are overall quite similar.

The final part of this project is to manipulate the MLP projection stage.

As with Part 4, this entails only minor changes to the code you’ve already written, but there is one major conceptual change: The manipulation in the expansion neurons targeted only the right tail of the distribution (positive values), but here we need to target both tails of the distribution (positive and negative values). Why?

The reason is that the negative values in MLP projections are not suppressed by a nonlinear activation function. Instead, the projections distribute the features calculated and selected in the expansion stage back to the hidden-state vectors. In this case, large negative values are just as influential as large positive ones.

Therefore, the goal here is the same as in previous parts: target the largest contributions of each layer for median-replacement. But the “largest contributions” are based on positive values in the expansion neurons and are based on magnitude in the projection vectors.

Task

Copy the experiment code from Part 3 but make four changes: (1) end the results variables with _pr (“projection”); (2) modify the hook function to target projection dimensions instead of expansion neurons; (3) select the top p% values based on their magnitude (absolute value); (4) update the translation of percent to number based on the embeddings dimensionality instead of the number of expansion neurons.

Visualize the results as in Figure 7.59. The heatmap in panel A is the average of the results from Parts 3 and 4.

By the way, if your hook function contains an error that crashes the code during the forward pass, the code to remove the hook might not get run before you change the function. That would leave the buggy hook in the model. Therefore, if you continue getting errors even after fixing bugs, try re-importing the GPT-2 model to clear out any remaining hooks.

Figure 7.59: Similar to Figure 7.58 but including the comparison with manipulating the MLP projection stage.

The results here are striking: There is a clear, roughly linear decrease in target log-softmax probability for the projection vector manipulation compared to the expansion neurons manipulation.

This indicates sparse encoding of features in the expansion layer vs. a dense and distributed integration at the output projections.

In particular, the goal of the expansion stage is to facilitate feature selection. If those features are carried by a small number of neurons, then removing those activations would filter out the critical information. In other words, once the sparsely coded features were removed, removing even more values had little additional impact.

On the other hand, the selected features become distributed across the projection vector to integrate back into the hidden-state vector. The goal of the MLP adjustment is not to highlight any one dimension in the embeddings space, but instead to rotate the hidden-state vector so that it incorporates context-appropriate information. The dimensionally-distributed nature of that information means that disrupting a few dimensions is not so detrimental.

By the way, regarding the change in the code about taking the absolute values of the activations, you can rerun the code for Part 5 without the absolute value — that is, median-replace values only in the right tail of the distribution. You’ll see a stunning difference that highlights how both tails contribute. You can also try replacing only the extreme negative values by using -vals in the hook.

day-mode Bookmark

Recommender systems with MLP projections

Before starting this project, a word of warning: The analyses in this project reflect real ML practices, but the application is… utterly senseless. You’re going to build a recommender algorithm to suggest MLP projection vectors that someone might “like” based on similarities to other sets of vectors. From a practical (e.g., applications-oriented) perspective, it’s completely nonsensical.

However, this is the final project in the book and I wanted it to be a little light-hearted while also introducing you to a real ML topic. So, please stay focused on the analyses and don’t over-interpret the meaning of the results.

We will work with the following three texts. They form the opening of Lewis Carroll’s poem Aged Aged Man, which is a parody of Wordsworth’s Resolution and Independence. Both are worth a read.

Text A

I’ll tell thee everything I can; There’s little to relate. I saw an aged aged man, a-sitting on a gate.

Text B

“Who are you, aged man?” I said. “And how is it you live?”

Text C

And his answer trickled through my head, like water through a sieve.

Task

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

Tokenize the three sentences above into three variables (named, e.g., tokens_A). Count the number of tokens per sentence minus 1 (minus 1 because we will consistently exclude the first token from analyses in this project), and make a table of the number of tokens in each text.

Implant a hook function into all transformer layers to extract the MLP projection vectors, transform them into NumPy arrays, and store them in a dictionary. The key names should be the text letter and the layer number, for example mlp_projs[’A_4’] for the activations from text A in transformer layer 4.

Run three forward passes on the three token sequences. Make sure to define and update a variable name for which text is pushed through the LLM. Print the key names and matrix sizes of all items in the dictionary.

Here’s the table of token count per text:

 Text | tokens ------+-------

A | 29
B | 19
C | 16

And here’s the main line inside my hook function: mlp_projs[f’{whichtext}_{laynum}’] = output.detach().numpy()

The layer number is given by the outer hook function, and I defined the text label before each forward pass, like this:

with torch.no_grad():
whichtext = ’A’
model(tokens_A)

All key-value pairs look like this:

mlp[’A_0’] has size [1, 29, 768] mlp[’A_1’] has size [1, 29, 768]

The sizes correspond to one sequence per text, 29 tokens, and 768 embeddings dimensions. Text B has 19 tokens and text C has 16 tokens. The analyses in this project do not require aligning corresponding tokens, so the differences in token counts isn’t a problem. You could encode all three texts into one batch, but in my opinion, that creates unnecessary hassle later in the code.

Task

Calculate the vector norms of each token position (excluding the first) in each sequence for each transformer layer. Note that this is the norm of each individual MLP projection vector, not the norm of the matrix holding all of those vectors.

Visualize the three sets of norms as in Figure 7.60. Set the color limits for each heatmap as the 5^th to 95^th percentile of the values in each matrix.

If you input a matrix to the NumPy function linalg.matrix_norm, it will calculate the matrix norm. If you want a sequence of vector norms, you can provide an optional input argument axis=-1 to calculate the vector norms over the final dimension (which, in this case, corresponds to the embeddings dimensionality).

Figure 7.60: MLP projection vector norms over token positions (x-axis) and transformer layers (y-axis), for the three token sequences. Note the text-specific x-axis limits.

Perhaps the most striking result is the increase in vector norms in the first, and then in the last few, transformer layers.

Part 2: Token-average target vector recommender

Section titled “Part 2: Token-average target vector recommender”

Modern commercial recommender systems can be sophisticated; here I will introduce you to a simple recommender algorithm to give you a sense of how they work.

Mathematically, the recommendation is accomplished by representing each item (e.g., text or movie or song) as a dense embeddings vector, and then applying some linear algebra. In the equations below, imagine that a and b represent two movies that you like, and the goal is to find movie c that you would also like based on your preference for a and b.

a:b∼b:c(7.9)a : b \sim b : c \tag{7.9} b−a≈c−b(7.10)b - a \approx c - b \tag{7.10} c≈2b−a(7.11)c \approx 2b - a \tag{7.11}

Equation 7.9 provides some linguistic intuition (“A is to B as B is to C”); Equation 7.10 gives a more formal vector-based definition, and Equation 7.11 rewrites Equation 7.10 to how it’s implemented in the analysis.

You can think of Equation 7.10 geometrically (Figure 7.61). The idea is that if you like vector a and vector b, then a simple linear model predicts that you’d like another vector along the same trajectory (c). This is called “directional extrapolation” and is similar to the analogy vectors that you explored in Project 15 (Chapter 3).

Figure 7.61: Simple diagram of extrapolation-based recommender systems. Vectors a and b are items in an embeddings space (e.g., movies, books, or tokens). If the user liked going from a to b (gray dashed vector b-a), then we assume that they would also like an item that is the same directional vector away from b, as b is from a. Thus, we predict that the user would like item c.

Notice that this is different from a recommendation about the average (e.g., if you liked these movies, then you’ll like this other movie that’s basically the same). Instead, the extrapolation approach makes recommendations based on a change in preference from one item to another, and assuming that the user would like another item with the same direction and magnitude of change.

Vector c is not formally an analogy vector, so I will refer to it as a “target vector.” You can think of it as the ideal recommendation, and the analyses will reveal which embeddings vector is closest to that ideal.

The goal of Part 2 is to define a and b as the average MLP projection vectors of texts A and B, and then use cosine similarity to determine which token in text C best matches the target vector, i.e., which token is most strongly recommended.

Task

Use data from layer 6. Create two mean vectors as the average of all projection vectors (excluding the first position) in texts A and B. Then create the target vector using the right-hand-side of Equation 7.11. Visualize the average vectors as in Figure 7.62.

Calculate the cosine similarity between each projection vector in text C with the target vector. The one with the highest similarity is the one that best matches c in Equation 7.11. Visualize the results as in Figure 7.63.

Averaging across all token position vectors isolates the text-general processing at the expense of variability across tokens. From a practical standpoint, it makes the analysis simpler. We’ll expand on this in Part 4.

Figure 7.62: Panel A shows the token-position-average MLP projection vectors from layer 6, for texts A and B. Panel B shows their relationship and cosine similarity value.

What do you think of those two large values at around 450 dimensions in panel A and in the upper-right in panel B? If those were outliers, we could exclude those points from the analyses, for example, imputing them with the average value or using Spearman correlation instead of cosine similarity.

While it is the case that those data points inflate the cosine similarity value, it is not the case that those data points are noise and should be disregarded. Instead, they reflect meaningful though extreme values of the adjustments calculated by the MLP.

Figure 7.63: Cosine similarity between each projection vector from text C with the target vector calculated from texts A and B. The token with the maximum similarity is the “recommended token” from this set.

Apparently (according to Figure 7.63), if we liked both text A and text B, then we should also like the MLP adjustment to the token “through”. We can understand the analysis — and the averaging — by thinking about tokens as individual movies and texts as genres. Imagine that the tokens in text A were horror movies, the tokens in text B were sci-fi movies, and the tokens in text C were action movies. Then the analysis is recommending a specific action movie given that we generally like the transition from horror to sci-fi movies.

Part 3: Recommendations through the layers

Section titled “Part 3: Recommendations through the layers”

The goal of Part 3 is to repeat the analysis in Part 2 but for each layer.

Task

In a for-loop over transformer layers, paste the code from Part 2 but use the layer-specific projections. Visualize the data as in Figure 7.64, which shows the maximal cosine similarity in each layer with the best-matching text printed on top.

Figure 7.64: Maximum similarity value analysis from Part 3 was repeated for each transformer layer, and the similarity value and its corresponding token are shown here.

The maximal similarity values were generally lowest in the early to middle layers, indicating stronger token-level processing at the start and end of the model.

Averaging to obtain a central tendency is certainly an important principle in statistics, but it also ignores the rich variability inside a dataset. The goal of Part 4 is to expand the recommender system to a pair-level analysis: Rather than testing which token in text C is most recommended based on averages, we will test which token in text C is most similar to each pair of A and B tokens. That is,

ck≈2bj−ai(7.12)c_k \approx 2b_j - a_i \tag{7.12}

We’ll start writing the code using just one layer, then adapt that code for layer-specific recommendations.

Task

Use data from layer 6 and exclude the first token. Create a double for-loop over token positions in A and B, and calculate a target vector for each pair of positions. Then write another for-loop over all token positions in C to calculate the cosine similarity between each combination of projection vector in C with each target vector formed from each pair in A and B. Store the similarity values in a 28×18×15 NumPy array, corresponding to the tokens in texts A, B, and C.

Visualize some of the results as heatmaps as in Figure 7.65. There are four maps corresponding to four equally-spaced tokens in text C. The x- and y-axes correspond to the tokens in texts A and B, and the color of the heatmap corresponds to the cosine similarity with that token in text C. The title of each heatmap indicates the token in text C and its largest cosine similarity A-B pair. All maps have the same color scale of .05 to .3, and the color palette is “magma.”

There are 7560 elements in the cosine similarity cube — and we’re only working with small vectors. You can see that there is a scaling problem when it comes to all-to-all item-level recommendations.

Figure 7.65: Cosine similarity was calculated between the projection vector for each token in text C (four of which are shown here) with each pair of vectors from texts A and B, using data from transformer layer 6. The colors in the heatmaps show the similarity values (same color scaling of .05 to .3 in all four maps). The titles of each heatmap show the token in text C and the maximum-similarity A-B pair underneath.

The results show that some tokens in text B are generally more associated with tokens in text C. For example, the “ his” token in text C has relatively strong similarity to all tokens in text A paired with ’??¨\ddot{?}’ in text B.

Going back to the movie analogy, this analysis is like recommending a specific action movie given that someone likes a pair of movies from the sci-fi and action genres.

These data are shown only from one vector. Visualizing the results over all layers is a challenge and requires some reduction.

Final point: You could vectorize the calculations to eliminate the for-loop over text C tokens if you’d like a small additional challenge.

The final part of this project involves repeating the analysis in Part 4 but over all the layers. It is infeasible to show the heatmaps for all tokens and all layers, so the idea here will be to show the maximum cosine similarity value to each pair.

Task

Repeat the analysis from Part 4 over each transformer layer. Print out a list of each token in text C and its maximum similarity pair. The main visualization is the heatmap in Figure 7.66, which shows the maximum cosine similarity value for each token in text C in each transformer layer.

I won’t print out the full list of maximum pairs, but here’s a sample:

Layer 9:

" his" is paired with ( aged,,)
" answer" is paired with ( man, you)
" trick" is paired with ( aged,?")
"led" is paired with ( aged, you)

Figure 7.66: The analysis in Part 4 was repeated for all layers, and the maximum cosine similarity value for each token in text C is visualized here.

The summary results show that inter-token similarities in general were strong at the first transformer block and towards the end of the transformer stack.

As I wrote at the beginning of this project, the analysis is real and the project is challenging, but the application is… a bit silly. The MLP projections don’t actually map onto tokens, and people generally don’t search the Internet for MLP projection vectors that they might enjoy looking at. Nonetheless, I hope you found it educational and enjoyable.