Embeddings
local graph
Background: Embeddings vectors
Section titled “Background: Embeddings vectors”Embeddings vectors are another way to represent tokens using numbers. Whereas tokenization maps one token to one integer, embeddings maps one token to hundreds or thousands of floating-point numbers in a vector (Figure 3.1). Indeed, in LLMs, the entire purpose of a token index is to reference a particular row in an embeddings matrix.
Figure 3.1: Short pieces of text are initially represented as tokens (left), which are then converted into embeddings vectors (right). An embeddings vector is a dense, floating-point, high-dimensional representation that allows language models to associate rich, diverse, subtle, and precise information with each token. Only three elements of the vector are shown here, but LLM embeddings vectors have hundreds or thousands of elements.
Why is it better to represent text using a dense, high-dimensional vector instead of one integer? Isn’t that inconsistent with the motivation for a simple and compressive integer-based encoding that you learned about in the previous chapter?
There are two advantages of representing tokens using high-dimensional embeddings vectors instead of integers.
-
Embeddings allow for rich, contextual information to be associated with each token. For example, apple and pear are closely semantically related, yet their GPT-2 tokens (17180 and 25286) cannot encode the multiple similarities between the two tokens (e.g., both fruits, similar size and shape, used in pies and juices).
-
Dense, high-dimensional vectors can be adjusted (rotated and scaled) in subtle and nuanced ways. For example, if we’re prompting ChatGPT about apple pie vs. apple juice, we want the model to understand that it’s the same fruit but used in different ways. The token index 17180 doesn’t allow for that kind of context-based modifications.
It is also true that high-dimensional floating-point representations of tokens expand rather than compress the dimensionality of the text. But while compression may be a good thing for tokenization, dimensionality-expansion is the key to allowing LLMs to incorporate context and world knowledge into predictions for generating new text.
Consider the 2D axis in Figure 3.2. It’s a 2D embeddings space where the two axes are Size and Friendliness. We can represent animals in this space according to how big they are (x-axis) and how friendly they are (y-axis).
Figure 3.2: Toy example of an embeddings space for animals.
The numbers on the right are (x,y) coordinates that indicate the position of each animal in this space. Those are the embeddings vectors for the words. You can see how the embeddings vectors capture information about the relations among the animals (e.g., dogs and cats are similar size and friendliness; ladybugs are only a little bit bigger than mosquitoes but are much friendlier), compared to a tokenization scheme of dog=1, cat=2, ladybug=3, etc.
Furthermore, the embeddings vectors are not static; they can change. Let’s say we’re talking to ChatGPT about how our neighbor’s cat hisses and scratches; ChatGPT can subtract from the Friendliness dimension without changing the Size dimension. So, the LLM can use context (previous tokens) to adjust the embeddings vector for the word cat to [.4,.6].
I hope Figure 1 and my description highlight the advantages of dense embeddings over single integers. But the embeddings used in real language models are much more complicated — and much less interpretable — for several reasons:
-
Token embeddings are very high-dimensional. Even a “small” LLM might have an embeddings dimensionality in the thousands. The GPT-2-small LLM has an embeddings dimensionality of 768 and the xl version has 1600 dimensions.
-
Actual embeddings dimensions are not human-interpretable. There is no Size axis or Friendliness axis. Researchers have tried to define interpretable axes inside embeddings spaces, but it doesn’t work that well, as you will discover in Projects 14 and 15.
-
The embeddings vectors change as they pass through the model. At each processing step inside the LLM, an adjustment to the vector is calculated and added, like with the analogy of reducing the Friendliness dimension in my neighbor’s antisocial cat. This means that the effort you put into making a human-interpretable embeddings axis won’t hold up after just the first of many transformations that the vectors undergo.
-
The embeddings vectors are different for different language models. For example, all models in the GPT-2 family have exactly the same tokenizer, but they have completely different embeddings vectors. Even if you create two LLMs of the same size and train them from scratch on exactly the same text data, they will have different embeddings vectors simply because of the different random initializations.
None of these points are limitations — quite the opposite. But they are reasons why individual embeddings vectors are not human-interpretable. On the other hand, relations across embeddings vectors can be interpreted to some extent, which you’ll explore in several projects in this and the following chapters.
The key point is this: Embeddings vectors endow tokens with rich semantic information that can be adjusted according to previous tokens in the text, and according to world knowledge that the model learned during training.
Positional embeddings The token embeddings I discussed above are based on the linguistic identity but not on the positions of words. But, obviously, word positions are important (“man bites dog” vs. “dog bites man”). LLMs need a way to incorporate the order in which tokens appear in text, into their calculations. That is done by positional embeddings. As a very simple example, imagine a text that is encoded as a sequence of 10 tokens. Now imagine two positional vectors: one that contains integers 0 to 9, and a second that contains integers 9 to 0 (counting backwards). An LLM that incorporates those positional vectors as weights could learn to focus differently on earlier vs. later parts of the text.
In practice, positional embeddings are learned by the model during training (though they can also be hard-coded using a Fourier-like basis) and incorporated into the embeddings layer before the vectors reach the first transformer block. I won’t discuss positional embeddings further in this book, and I mention them here because they are an important part of what allows LLMs to maintain coherence and focus over longer sequences.
Extracting embeddings vectors
Section titled “Extracting embeddings vectors”Note: Code accompanying this background section is in the notebook file for Project 8.
The embeddings matrix is the first layer of the LLM. You can extract it by importing a model into Python, for example using the Hugging Face library. The code below shows how to import the BERT model and extract its embeddings matrix.
from transformers import BertModelM = BertModel.from_pretrained(’bert-base-uncased’) embeddings = M.embeddings.word_embeddings. weight.detach()
Different models have different naming and matrix organization schemes, and you’ll learn how to find the embeddings matrix for different models in different projects.
That embeddings matrix is 30522 × 768, corresponding to 30,522 tokens in the vocab, and an embeddings dimensionality of 768. A dimensionality of 768 seems very large compared to the toy example in 2D, but it’s actually relatively small for LLMs. For example, GPT-3 has an embeddings dimensionality of 12,288. The exact dimensionalities of modern commercial LLMs like ChatGPT, Claude, and Gemini, are not known exactly, but are probably around 15,000 to 20,000.
High-dimensional vectors are visualized using the dimension index on the x-axis and the dimension value on the y-axis. Figure 3.3 shows an example of the embeddings vectors for the tokens “hello” and “world”.
Figure 3.3: Embeddings vectors for the words “hello” and “world” from the BERT-base LLM.
The heatmap in Figure 3.4 shows the entire embeddings matrix. Notice the horizontal and vertical stripes in the image: Horizontal stripes indicate that some dimensions have a non-zero offset across tokens, while vertical stripes indicate groupings of tokens that have similar embeddings vectors. You’ll learn more about that left-most grouping in Project 8.
Figure 3.4: The entire embeddings matrix from BERT-base. Each column is a token and each row is an embeddings dimension.
Background: Cosine similarity
Section titled “Background: Cosine similarity”Note: Code accompanying this background section is in the notebook file for Project 8.
Cosine similarity is one of the foundational analysis methods in ML — and in LLM investigations. The idea of cosine similarity is to assess the relationship between two vectors, where a vector is an ordered list of numbers, such as embeddings vectors for two different tokens. The first equation below is cosine similarity between vectors x and y, and the second equation is the Pearson correlation coefficient.
Cosine similarity (shortened to S_c for “similarity of the cosine variety”) is the dot product between two variables, normalized by the product of their vector norms. The correlation coefficient is nearly identical, except that the variables are first mean-centered. In other words, mean offsets are considered an irrelevant feature in a correlation, whereas those offsets have a significant impact on similarity. You’ll see examples of that distinction in the code.
For both measures, the normalization brings the similarity and correlation to between -1 (perfectly anti-correlated) and +1 (perfectly correlated), with 0 indicating no linear relationship.
Cosine similarity in simulated data There are several ways to calculate cosine similarity in Python, including manual implementation, scikit-learn, and PyTorch. I’ll introduce the manual implementation here, and you’ll learn the other methods in the projects. The online notebook file contains code to create Figure 3.5, which shows the similarity between two correlated variables, calculated as a direct implementation of Equation 3.1:
num = np.sum(x*y) # numerator norm_x = np.sum(x**2) norm_y = np.sum(y**2) den = np.sqrt( norm_x*norm_y ) # denominator cs = num/den
Figure 3.5: Cosine similarity between two variables in simulated data.
That’s for two variables; in LLM data we often want to calculate the pairwise similarity values among dozens or hundreds of embeddings vectors. That leads to the matrix implementation of cosine similarity. It is simply XX^⊤, where X is a matrix in which the columns contain features and the rows contain observations. In other words, a data matrix times its transpose contains all pairwise cosine similarity values.
That matrix multiplication is only the numerator of Equation 3.1; thus, before the multiplication, you need to normalize each column of X by dividing by its vector norm. Here’s how it looks in Python:
X_norm = X / np.linalg.norm(X,axis=0,keepdims=True) csM = X_norm.T @ X_norm
Variable csM is a cosine similarity matrix in which the value at each (row, column) index is the similarity between each corresponding pair of columns in the data matrix.
But wait a minute: That code is “backwards” from my claim that similarity is calculated as XX^⊤! Well, I also wrote that that ordering is valid if the data matrix is features × observations. In the code file for this demo, I created data matrix X to be observations × features. In general, you need to be mindful of the orientation of the data matrix. The way to confirm is by making sure that the similarity matrix (variable csM) is of size features × features, not observations × observations.
Figure 3.6 shows an example of a cosine similarity matrix, and also a comparison between cosine similarity and correlation. I created a data matrix as 15 features and 100 observations, with each feature having a different mean offset (visible as the change in color levels along the y-axis).
Figure 3.6: Cosine similarity among multiple variables, and its relationship to the correlation coefficient, in simulated data.
Panel B shows the all-to-all cosine similarity matrix, with the color value at each matrix element corresponding to the cosine similarity between each pair of features. Panel C shows the correlation matrix in the same data, and panel D shows the (lack of) relationship between similarity and correlation. Those differences arise because of the mean offsets, which impact cosine similarity but not correlation. You can observe a tight relationship between the two measures by modifying the code to comment the mean offset (the addition of the linear offsets).
Non-zero vector means indicate offsets from the origin of the embeddings space, and are a part of the representations. That’s why cosine similarity is the preferred measure for investigating LLM embeddings and hidden-state vectors.
Bookmark
3.8 Project 8:
Section titled “3.8 Project 8:”Distribution of cosine similarities
The goal of Project 8 is to explore the distribution of cosine similarities across all pairs of embeddings vectors in two LLMs: BERT and GPT-2-small. Along the way, you’ll learn more about tokenizers, about unused (“reserved”) tokens in BERT, and about calculating cosine similarity using PyTorch functions and using a direct translation of Equation 3.1.
You’ll also learn about memory management and the decisions you need to make in practical analyses with large matrices and limited computing resources, including decisions about downsampling and reducing precision of matrices.
Part 1: Similarity of embeddings pairs
Section titled “Part 1: Similarity of embeddings pairs”Let’s begin by exploring a pair of embeddings vectors, and then we’ll build up to similarity between all pairs of embeddings.
Task
Use the NumPy function choice to select two tokens at random between index 3000 and 6000 from the BERT tokenizer, and print their corresponding strings.
Extract the two embeddings vectors from the BERT model, and create a scatter plot between them as in Figure 3.7.
Here’s an example of my output (yours will differ due to random selection):
5789 is "makeup" 4909 is "receiving"After extracting the two embeddings vectors, confirm that their vectors each have 768 elements.
Figure 3.7 shows the scatter plot between them.
Figure 3.7: Scatter plot showing the relationship between a pair of embeddings vectors. Each dot is the value on one dimension for each token.
From visual inspection, the two vectors appear to be weakly positively related. How can we quantify that relationship? Of course you know the answer: cosine similarity.
Task
Calculate cosine similarity between the two embeddings vectors. Run the analysis twice: Once by directly implementing the formulas you learned at the start of this chapter (if you copy code from earlier in the code file, be mindful that the embeddings vectors are PyTorch tensors, not NumPy arrays), and again using the cosine_similarity function in PyTorch. Print both results to confirm they are identical.
Note that many PyTorch functions are sensitive to the dimensionality of the input tensors. For example, although a 768 dimensionless tensor and a 1 × 768 tensor have identical elements, some PyTorch functions will treat them differently — and will produce an error if the dimensions are inconsistent with its expectations. Therefore, to accomplish this task, you may need to reshape or unsqueeze the embeddings vectors.
Below are my results of calculating cosine similarity twice. Again, your numerical results will differ due to random token selection; the important finding is that the two implementations match.
Manual cosine similarity: 0.28003 Pytorch cosine similarity: 0.28003
You can run the code multiple times to observe the cosine similarity between random pairs of words. Are the cosine similarity values higher or lower than what you expect based on the word pairs?
Final task before moving on: Rather than randomly selecting a token pair, use the words “sunshine” and “pineapple.” What happens when you encode and then decode those two words? Hold on to that observation; it will be the main focus on Part 3!
Part 2: All-to-all cosine similarity
Section titled “Part 2: All-to-all cosine similarity”The goal of Part 2 is to produce Figure 3.8. Panel A shows a pseudo-colorized matrix of the cosine similarity values between all pairs of tokens, and panel B shows the distribution (histogram) of all the inter-token similarities. Before creating the figure, we’ll cover a few memory-saving tips.
Figure 3.8: Cosine similarities across token pairs (downsampled by a factor of 3). Panel A shows the matrix representation with color mapping onto similarity value, and panel B shows a histogram of the non-redundant and non-trivial similarity values.
Task
Create the cosine similarity matrix as EE^⊤ where E is the tokens × embeddings dimension matrix.
The matrix needs to vector-unit-normalized first, which you can implement by dividing each token embeddings vector by its norm. You can calculate the norm using torch.linalg.norm, but make sure to include a dim= input argument to calculate the norm of each vector, not the norm of the entire matrix. Also be sure to use the keepdim= input argument so you can broadcast-divide rather than needing a for-loop over all the embeddings vectors.
Store the normalized embeddings in a separate matrix so that you don’t overwrite the original embeddings.
There are 30,522 embeddings vectors, which means the all-to-all matrix is that number squared, which is nearly 1 billion elements. At full precision, that’s a lot of RAM just to store the matrix, let alone work with it. Even if you have enough RAM for this project, it’s good to know what steps you can take to reduce memory load.
Task
Monitor your RAM usage before and after each of the following steps. If you’re using Google Colab, you can click on the Runtime menu option, then click on View resources. That will open a tab on the right that shows RAM usage. You can also click on the RAM/Disk button on the upper-right of the screen.
Then implement the following steps.
- Reduce the precision of the cosine similarity matrix from full floating point precision to 16-bit (float16), by recasting the cosine similarity matrix using the .to() method on the PyTorch tensor.
- Downsample the reduced precision matrix by creating a submatrix formed from every 3^rd row and column. That submatrix is 10174 × 10174, giving 103,510,276 elements. Still a lot to count by hand, but much more manageable for a commercial CPU.
- Delete the normalized embeddings matrix after calculating the cosine similarity matrix (hint: use the function del).
Now you can write code to create Figure 3.8.
When creating the histogram in panel B of Figure 3.8, remember that half of the cosine similarity matrix is redundant, and that the diagonal is trivially 1’s. Therefore, extract just the non-redundant elements of the matrix (tip: np.triu_indices) to create a histogram.
There are two striking results of the cosine similarity values.
The first striking result is that the cosine similarities are nearly all positive with most values between .3 and .6. That may seem surprising considering that a randomly selected pair of words is unlikely to be semantically related. Indeed, if embeddings followed semantic meaning, you might expect many negative similarity values (e.g., man-woman; past-future; tall-short). Recall from the outset of this chapter that cosine similarity is enhanced when the two vectors have common offsets. Embeddings vectors are not uniformly distributed throughout the embeddings space, but instead are somewhat clustered into a hyper-conoid, meaning that they have common offsets that increase their collective cosine similarities.
The second striking result is the unusual block of cosine similarity values in the top-left block of the cosine similarity matrix. Those values are extremely highly similar to each other, and are clustered into the small bar in the histogram (panel B) close to 1.
That block contains unused tokens. They have no pretrained mapping onto byte sequence, and are reserved for fine-tuning models to domain-specific texts. Do you want to know more about those unused tokens? Keep reading!
Part 3: BERT’s unused tokens
Section titled “Part 3: BERT’s unused tokens”To begin our investigations of the unused tokens, print out the first 20 tokens as below (I’m showing only the first six here).
Token 0 is “[PAD]” Token 1 is “[unused0]” Token 2 is “[unused1]” Token 3 is “[unused2]” Token 4 is “[unused3]” Token 5 is “[unused4]”
The PAD token is a special token that is used to fill in missing tokens in multi-sequence batches. For example, imagine providing two text sequences to an LLM, one that contains 10 tokens and the other with 11 tokens. LLMs can process multiple sequences in batches — this is used, for example, during training to decrease computation time and increase smoothness of gradient descent (“batch regularization”). However, the token sequences must be provided in matrices, which means each sequence must be the same length. PAD tokens are used to get each sequence to the same length.
The next several tokens are “unused” with a number. Also note the square brackets encasing the text. Those brackets indicate special tokens.
Are these the only unused tokens in the tokenizer, or just the ones we happened to find by printing out the first 20 tokens? Let’s find and count all the unused tokens.
Task
Create a Boolean vector that equals True for any unused token and False for all other tokens. Then create Figure 3.9 to show which tokens, and how many, are unused. Be careful with the string matching: There might be other tokens that contain the word “unused” but are not actually the [unused] tokens you want to identify.
Adding small, random offsets to a plot can facilitate interpretation, but must be used judiciously and carefully. For example, it would be inappropriate to add random offsets to the x-axis (token index) in this plot.
Figure 3.9: Boolean scatter plot showing that the unused tokens in BERT are in the beginning of the vocab. Small random y-axis offsets were added for visibility.
Why are there so many unused tokens? A common application of the BERT model is classification or categorization. For example, a company might want an LLM to classify product reviews as positive or negative, or a scientific research proposal as fitting into a scientific category such as biology, chemistry, or physics. Application-specific fine-tuning might require training the model on additional keywords, phrases, non-linguistic character sequences like a chemical structure (e.g., H2O), or medical terminology. The BERT model can be fine-tuned to use those unused tokens.
From Part 2, you saw that the cosine similarity values in the upper-left block are high. How high are they?
Task
Create a submatrix of cosine similarity values from the unused tokens you previously identified. Extract the non-redundant cosine similarity values, and report the total number of elements, the number of unique values, and the unique similarity values.
Here are my results, which you should be able to reproduce.
There are 493,521 non-redundant values, 13 of which are unique.The unique values are:
[0.9854 0.986 0.9863 0.987 0.9873 0.988 0.9883 0.989 0.9893 0.9897 0.99 0.9907 0.991 ]Part 4: GPT-2 all to all, done differently
Section titled “Part 4: GPT-2 all to all, done differently”Some principles of tokenizers and embeddings are common across different models, such as BERT, GPT-2, DeepSeek, Claude, and Gemini. Other aspects, however, are different. For example, the first few hundred GPT-2 tokens are letters, digits, punctuation marks, and formatting characters such as tab, space, and newline. Definitely not tokens you’d want to ignore or overwrite!
The goal of Part 4 is to repeat some of the analyses from Parts 1 and 2 in the GPT-2 embeddings. However, I will guide you through a different implementation that will give you more options for analyzing large matrices with limited computer RAM.
Task
Import the GPT-2 model (you don’t need the tokenizer for this exercise), and extract the embeddings matrix as a separate variable.
Downsample the “vocab” dimension of the embeddings matrix by a factor of five (leave the embeddings dimension at its original dimensionality), and reduce the precision to 16-bit floating point. Make sure to alter the copy of the embeddings matrix, not the embeddings matrix inside the LLM.
There are several variants of the GPT-2 LLM, which all have a similar architecture and training set, but vary by size (number of layers and parameters). For this rest of this book — and in LLM research and education more generally — the label “GPT-2” refers to the small version. Other variants are termed medium, large, and xl. In fact, the Hugging Face import code defaults to the small version of GPT-2 if you don’t specify the size.
Anyway, the procedure here for working with the embeddings is different from that in the BERT analysis: In Part 2, you kept the embeddings matrix as full-sized and full precision, and downsampled the results (the cosine similarity matrix). In contrast, here you are downsampling and reducing the precision of the data matrix before running the analyses. What are the advantages and limitations of these two procedures? I’ll discuss those in more detail in the next subsection, but I’d like you to think about it before reading my answer.
Anyway, you can confirm that the embeddings matrix is now 10052 × 768, reduced from the original 50k vocab size.
Task
Calculate the all-to-all cosine similarity matrix, but block-wise instead of in one multiplication. Begin by normalizing the embeddings matrix as you did previously, but this time, using the normalize function in the nn.functional module of PyTorch. (Hint: the Euclidean norm is also called the p_2 norm).
To calculate cosine similarity block-wise, you need to use a for-loop over “block.” Define each block to be k = 1024 rows. In the for-loop, calculate the matrix product of a k × N embeddings submatrix and the N × E embeddings matrix (E is the embeddings dimensionality of 768). That result will be k rows in the all-to-all cosine similarity matrix. With a block size of 1024 and a reduced embeddings matrix with 10052 vectors, there will be 10 blocks. You can use the tqdm library in Python to show a visual status bar that updates the progress.
After the calculation finishes, visualize the results as in Figure 3.10. This is similar to the figure for Part 2 but the y-axis of the distribution in panel B is logarithmically scaled.
Figure 3.10: Cosine similarity matrix and distribution in GPT-2’s embeddings matrix.
The GPT-2 similarities matrix doesn’t have a block of very high values as the BERT embeddings did. But other features are similar, in particular, most cosine similarities are positive. The log-scaled y-axis better reveals the lower-probability features of the distribution, whereas the linear-scaled y-axis better reveals the most prominent features.
Part 5: Compare correlation and similarity
Section titled “Part 5: Compare correlation and similarity”The final part of this project is to compare cosine similarity with correlation coefficients on the same embeddings matrix.
Task
Copy and paste the code that calculates cosine similarity from the embeddings matrix in blocks, and modify it to calculate correlation coefficients. Remember that the only difference between correlation and cosine similarity is that the variables are mean-centered for correlation.
Extract the non-redundant elements of the correlation matrix and create a scatter plot of the correlations by the similarities, as in Figure 3.11A. (Due to the excessive number of data points, I recommend plotting a subsample, e.g., every 50,000^th element.)
To understand why the results are what they are, calculate the arithmetic and L_1 means of the embeddings vectors, using the following formulas.
Then show the histograms of the two means as in Figure 3.11B.
The correlations and similarities are nearly identical. Why is that the case?
Figure 3.11: Cosine similarity matrix and distribution in GPT-2’s embeddings matrix. The gray dashed line in panel A indicates unity — where cosine similarity and correlation coefficients are exactly equal.
Remember that the only difference between correlation and cosine similarity is the mean-centering. When all variables have means of exactly zero, then correlation exactly equals cosine similarity.
For these embeddings vectors, the means are not exactly zero, but they are very small relative to the values in the vectors — that’s demonstrated by the difference between the arithmetic and L_1 means.
To be clear, this doesn’t mean that cosine similarity is the same as correlation coefficient everywhere inside the LLM: You’ll see in Chapter 5 that the vector means change as the embeddings vectors pass deeper into the model.
Should you downsample the data or downsample the results?
Section titled “Should you downsample the data or downsample the results?”When possible, it’s best to leave the data as rich, high-dimensional, and high-precision as possible during the processing and analysis stages, and then downsample the final results if necessary.
The reason is that downsampling or reducing precision before applying analyses risks introducing numerical errors into the calculation. For example, let’s say we want to multiply the numbers 2.43 and 4.33. Their product is 10.5219. But now imagine that we have a computer that is limited to two digits after the decimal point. That means that 2.43 × 4.33 = 10.52. On the one hand, that is a reasonable approximation of the true answer — the error is only .0019. For some applications, that truncation error is so small as to be meaningless. But if the result 10.52 is used in another operation, then that subsequent operation is less accurate, and the next operation is even less accurate… and the errors keep propagating and accumulating.
All that said, reducing precision of the data (in this case, the embeddings matrix) before analyses is sometimes necessary when working with large datasets and limited computing resources.
Bookmark
3.9 Project 9:
Section titled “3.9 Project 9:”Sequential cosine similarity
The goal of this project is to calculate the cosine similarity between each word in a sentence and the previous word (technically we’re working with tokens not words, but all the words in these examples correspond to individual tokens). You’ll gain more experience with calculating and visualizing cosine similarity.
More importantly, in this project you’ll learn the single most important limitation of “fixed” embeddings vectors for natural language generation: embeddings cannot be reinterpreted based on context. That is the limitation that the transformer architecture fixes, by adjusting the embeddings vectors according to local context and learned world knowledge.
Part 1: Sequential cosine similarity in one sentence
Section titled “Part 1: Sequential cosine similarity in one sentence”In this part, you will work with the sentence “my phone is in the kitchen near the cold ice cream” (no period at the end).
In the previous project, you calculated cosine similarity by directly implementing the equation; here you will use the cosine_similarity function in the scikit-learn library.
Task
Import the BERT tokenizer and model, and extract the embeddings matrix.
Tokenize the sentence, calculate the cosine similarity between each token and the previous using the cosine_similarity function, and visualize the results in a bar plot as in Figure 3.12.
The scikit-learn library can be picky about the data format and array dimensionality. If you encounter errors when calculating cosine similarity, read the error message, check the shapes of the variables (embeddings vectors), and consider reshaping.
Figure 3.12: Cosine similarity between each word and the previous.
The height of each bar is the cosine similarity between each token on the x-axis tick and the previous. Thus, there is no bar for “my” because it has no preceding token.
The results seem sensible: “ice” and “cold” are semantically similar, and therefore their cosine similarity is higher than that between “cold” and “the.”
Part 2: Are embeddings vectors context-dependent?
Section titled “Part 2: Are embeddings vectors context-dependent?”Consider the following two sentences:
- The conductor waved his hands as the train departed and people sat down.
- The conductor waved his hands as the orchestra began and people sat down.
When you read those sentences, your brain reinterprets the word “conductor” depending on the local context (the word train or orchestra) and on knowledge about the world. LLMs can do that as well — but not at the stage of the initial embeddings vectors. The vectors in the embeddings matrix are “fixed” in that once the LLM training is complete, those vectors never change.
Task
Write code to produce Figure 3.13, which shows sequential cosine similarity for the two sentences.
Figure 3.13: Sequential cosine similarities for two sentences that differ by two words.
The cosine similarities for the two sentences are identical except for three sets of bars that involve similarities with the two words that differed. Of course, that is not a surprising result. But it will be interesting to compare against the embeddings vectors as they pass through the transformer layers, where the attention and MLP blocks will modify their dynamic representations of the token embeddings according to context.
Bookmark
3.10 Project 10:
Section titled “3.10 Project 10:”Sequential number cosine similarity
This project is a direct follow-up to the previous. Here you will explore cosine similarity between numbers. To clarify: you will calculate similarity between strings that represent numbers, like “1”, “7”, and so on.
The first two parts of this project are about tokenization, and the later parts will focus on sequential and all-to-all cosine similarities of number embeddings vectors.
Part 1: Token counts of numbers
Section titled “Part 1: Token counts of numbers”How are numbers tokenized? Obviously it cannot be the case that each number corresponds to one token, because there is an infinite number of numbers but a finite number of tokens. But perhaps there are only 11 tokens to represent all numbers (digits 0-9 and the decimal point)?
For this project we will only use integers, but after working through this project, you can continue exploring how LLMs tokenize fractions and floating-point numbers, as well as numerical symbols like π or x^2.
Task
Import the GPT-2 model and its tokenizer, and extract the embeddings matrix from the model (you’ll start using the embeddings in Part 3).
In a for-loop over integers from -1000 to +1000, convert each number to a string, tokenize, and store the token indices and the number of tokens. Create a scatter plot of the encoded number by the number of tokens, as in Figure 3.14.
The y-axis values represent token counts and can therefore only be integers; I added random jitters to improve visibility of the concentration of the dots.
Figure 3.14: The number of tokens (y-axis) that GPT-2 needs to encode various integers (x-axis).
Interestingly, many though not all positive numbers are encoded using one token, whereas negative numbers are never represented using a single token. Actually, from visual inspection, it seems like the negative numbers might be encoded using the same tokens as the positive numbers but with an additional token for the negative sign. Of course, visual inspection doesn’t prove that, but the importance of visual inspection for inspiration and hypothesis-generation cannot be understated. We’ll get back to this in Part 2, but first, there is another plot to make.
Task
Write code to create Figure 3.15, which plots the numerical values of the token indices. Blue circles correspond to the first token in the number, green squares correspond to the second token in the number, and red triangles correspond to the third token in the number.
Figure 3.15: Mapping of multi-token indices to numbers represented as strings.
It might appear as if there are no “first token” markers for the negative numbers, but every negative number has an initial first marker of 12, which corresponds to the negative sign.
Creating a legend with so many markers can be tricky; one “hack” solution is to draw three additional data points with labels and alpha (transparency) set to 0, then add a legend and set its alpha to 1. I show this solution in the online code file.
The encoding of integers spans the entirety of the vocab. That is, it’s not the case that the numbers -1000 through 1000 are represented using 2000 neighboring token indices.
The apparent visual symmetry provides additional tantalizing suggestions that negative numbers and positive numbers have the same encoding except for an initial minus sign. The goal of Part 2 is to test that observation.
Part 2: Opposite sign, equal token indices
Section titled “Part 2: Opposite sign, equal token indices”Task
Write code to test whether the token sequence of −N is the same as the token sequence sequence of N (except for the minus sign) for the integers used in Part 1. That is, are the tokens identical for the strings “-543” and “543” except for an additional token to encode “-”?
There are several ways you can confirm this equality, and I want to give you the freedom to develop your own solution. But here are a few tips in case you need some inspiration: (1) check whether the token sequence in the first half of the numbers (-1000 through -1) matches that in the second half of the numbers (1 through 1000). (2) Check both the token counts and the token indices. (3) Sum the total number of matches.
However you set it up, you should find that the tokenization of integers is mirrored across zero (with the additional token for the minus sign), at least up to ±1000.
Part 3: Successive digit cosine similarity
Section titled “Part 3: Successive digit cosine similarity”Let’s move from tokenization to embeddings vectors similarities.
Task
Calculate pairwise cosine similarity between sequential pairs of tokenized numbers from 0 through 10, and show the results in a bar plot.
It’s interesting to compare Figure 3.16 to the similar analysis from Project 9 (Figure 3.12): The digits similarities are considerably higher and closer to each other. That is sensible: words have more diverse interpretations than single digits.
Figure 3.16: Cosine similarity between successive digits tokenized from strings.
Part 4: All to all number similarities
Section titled “Part 4: All to all number similarities”The final part of this project is to create a cosine similarity matrix for a larger range of numbers. Let’s use single digits and 10s.
Task
Confirm that the integers 0 through 10, and the integers 10, 20, 30, …, 100 are all single-token strings.
Extract the embeddings vectors for the numbers 0, 1, …, 10, 20, 30, … 100 into a submatrix. Calculate the cosine similarity matrix manually by multiplying that submatrix by its transpose after normalization with the PyTorch function normalize, which is in the nn.functional module. Visualize the matrix as a heatmap as in Figure 3.17.
The result is pretty neat: There is strong cosine similarity among the embeddings vectors for the single digits and for the tens (note the two blocks on the diagonal), and relatively low similarity between those blocks. Additionally, there are “stripes” of stronger similarity in the off-diagonal blocks, which indicates increased similarity between 2 and 20, 3 and 30, and so on.
Figure 3.17: Cosine similarities across embeddings vectors for integers 0-9 (in steps of 1) and 10-100 (in steps of 10).
A comment about tick marks in symmetric heatmaps like similarity matrices: Whether you should label each tick mark depends on the labels (e.g., long text vs. numbers) and on the number of ticks. A balance that I find useful is to have even labels on one axis and odd labels on the other axis. That shows all the tick labels without overcrowding.
Bookmark
3.11 Project 11:
Section titled “3.11 Project 11:”Network graphs of cosine similarities
The goal of this project is to learn how to create network graphs like the one in Figure 3.18 (and a variant of that in Part 3).
In that graph, the dots around the circle are the tokens in a sentence (it’s the opening line of Kafka’s Metamorphosis), the connecting straight lines indicate the strength of the cosine similarity between embeddings vectors of token pairs (yellower and thicker lines correspond to stronger similarity), and the size of the dot corresponds to the number of connections that exceed a threshold. Thus, we are thinking about a text as being a “network” and visualizing how the different nodes of the network relate to each other as measured by cosine similarity.
Figure 3.18: An example of a connectivity graph that you will create in this project.
That graph is the result of Part 2 (Part 1 is creating the data matrix that creates that graph), and Part 3 will be a variation on that theme.
Part 1: Cosine similarity matrix
Section titled “Part 1: Cosine similarity matrix”The goals of Part 1 are to tokenize some text and create an all-to-all cosine similarity matrix.
Here’s the text (no final period): As Gregor Samsa awoke one morning from uneasy dreams he found himself transformed in his bed into a gigantic bug
Task
Import the BERT large model and its tokenizer. Extract the embeddings matrix from the model.
Confirm that the text comprises 21 tokens with no repetitions.
Extract a submatrix of embeddings vectors for the tokens in the sentence, then calculate the all-to-all cosine similarity using any of the coding approaches you learned in previous projects.
Extract the non-redundant and non-trivial elements of the matrix, calculate a threshold as the median plus one standard deviation (this threshold will be used when creating the graph), and show the matrix and a histogram of the non-redundant values as in Figure 3.19.
As a reminder, the median of a dataset is the value that splits the data into two equal-sized bins.
You can print the results like this:
There are 21 tokens in the text, 21 of which are unique.Token index 2004 is “as” Token index 16973 is “gregor” Token index 3520 is “sam” Token index 3736 is “##sa” Token index 19179 is “awoke”
Unlike in previous examples with the BERT tokenizer, not all words here correspond to a single token. In particular, the name “Samsa” is broken up into two subwords. BERT uses the double hash (##) to indicate that a token is a continuation of a multi-token word.
Figure 3.19: Cosine similarities across all pairs of embeddings vectors (panel A), and the histogram of those similarity values (panel B). The vertical dashed line is the threshold used in later parts.
What’s the point of the threshold? And why did I pick the median plus one standard deviation? I will answer these questions at the end of Part 2, and I would like you to think of your own answers before reading that far.
Part 2: The network similarity graph
Section titled “Part 2: The network similarity graph”Now to create the network graph.
Task
Read the descriptions below and translate them into code. The result should be Figure 3.18.
The outer ring
The unit circle on which each dot is drawn is a gray line that connects the coordinates (cos(𝜃),sin(𝜃)) for 𝜃 in N linearly spaced steps (N tokens) between 0 and 2π − 2π∕N.
The dots for tokens
The location of each dot is the coordinate described above. The size of each dot is , where is the vector of cosine similarity values between each token and all other tokens, and κ is the threshold calculated earlier (vertical dashed line in Figure 3.19). In other words, five times the square root of the number of supra-threshold similarity values. That result is the size of the marker in plt.plot(). Because every token embeddings vector has S_c = 1 with itself, the marker size will be at least 5 even when there are no above-threshold similarity values.
Token labels
The labels are the tokens. Their horizontal alignments are defined as the sign of cos(𝜃), and their vertical alignments are defined as the sign of sin(𝜃).
Connecting lines
If the cosine similarity between a pair of tokens is greater than the threshold, a straight line is drawn between their coordinates. The line thickness is defined as 3 times the cosine similarity value, and the color is defined as an index into the plasma colormap. Colormap indices must be between 0 and 1, and thus the index value is:
S_max is the maximum nontrivial cosine similarity value from the entire matrix, where “nontrivial” refers to the similarity values less than one (with some allowance for small rounding errors).
Following those steps will reproduce the graph in Figure 3.18. Please note that the instructions above are one way of creating a network graph; it is not THE only way. I want you to appreciate that creating these kinds of data visualizations is not difficult, but I also want you to understand that there are many ways to create and stylize graph data. Indeed, the goal of Part 3 is to show a variation on the theme.
But first I want to answer the two questions I posed earlier: What is the purpose of the threshold and why did I define the threshold as the median plus one standard deviation?
The answer to the first question is that connecting lines in graphs are often interpreted as indicating the presence of a binary connection. In some datasets, it really is the case that two nodes are either connected or they are not. For example, two airports either are or are not connected by a direct flight. With cosine similarity, however, there is always some similarity value, and the null-hypothesis similarity value of exact zero will never be observed in real data, partly because of noise and sampling variability, and partly because a similarity of zero is not an appropriate null value for token embeddings (see Project 8).
Therefore, a common approach for visualizing graphs of continuous connectivity data is to define some threshold and then show a line on the plot only if the connection is above that threshold.
And that leads to the next question: Why use the threshold that I defined? Why the median and not the mean? Why one standard deviation and not two or .7235? Why not calculate statistical significance of each similarity value and show only the significant values?
There are no specific answers to this question. Nearly any threshold will be arbitrary and subjective (with some exceptions for physical systems that have thresholds based on equipment settings or mathematical constraints). That said, the median is more robust to outliers than the mean while being roughly equal to the mean for symmetric distributions, and one standard deviation is a simple and common choice. That doesn’t mean it’s the most appropriate threshold in every situation, but it produces a graph that balances information with sparsity.
Before moving on to the next part of this project, I encourage you to spend some time exploring different thresholds to see how that impacts the visual appearance of the graph.
Part 3: Graphing number networks
Section titled “Part 3: Graphing number networks”In this part, you will create a cosine similarity graph of the numbers you used in the previous project: 0, 1, 2,…, 10, 20, 30, …, 100.
Task
Calculate the all-to-all cosine similarity matrix. You can copy your code from Project 10, or rewrite it for an additional challenge.
Write code that creates the graph in Figure 3.20. There is no threshold and the node marker sizes are all the same, but the procedure is otherwise the same as I described in Part 2.
Figure 3.20: Network connection graph for numbers.
Note about visualizing graphs. There are several Python libraries that can create network graphs that look nicer than those you created here. For professional applications, you should consider using established libraries. My goal in this project was to guide you through creating a basic network graph so you understand how they are created. More aesthetic graphs start from the same fundamental mechanisms and then add various elements like bending the lines according to the angle between the vertices.
Bookmark
3.12 Project 12:
Section titled “3.12 Project 12:”RSA to compare GPT-2 & BERT embeddings
All LLMs have an embeddings layer, but not all embeddings layers are the same. Different training sets, embeddings dimensionalities, and model training goals produce different embeddings vectors in different models. And because the embeddings matrix is initialized from random numbers, even the exact same LLM architecture with the exact same training data will have different embeddings vectors.
So how can we directly compare the embeddings vectors from different models? The answer is we cannot directly compare them.
However, it is possible to compare different embeddings matrices by examining whether they have similar internal statistical structures.
The goal of this project is to introduce you to an RSA. RSA stands for representational similarity analysis (side note: writing “RSA analysis” is redundant in the same way that “ATM machine” or “pdf format” is redundant), and is a technique to compare representations across multiple encodings.
The idea is this: Instead of correlating embeddings vectors directly between models, calculate similarities within models across tokens, and then determine whether the patterns of across-token similarities are similar.
In other words, the embeddings vector of “banana” might be very different between BERT and GPT-2, but the way that “banana” and “apple” relate to each other within each model might be very similar.
Part 1: Embeddings from two LLMs
Section titled “Part 1: Embeddings from two LLMs”Task
Import the BERT large model and tokenizer, and the GPT-2 medium model and tokenizer. Extract the embeddings matrices from both models. Use different variable names to avoid confusion or overwriting (e.g., modelB and modelG).
Print out the sizes of the vocabs and embeddings matrices.
You should get the following sizes:
BERT vocabulary size: 30522 GPT2 vocabulary size: 50257
BERT embeddings shape: [30522, 1024] GPT2 embeddings shape: [50257, 1024]
The vocab sizes are different, but the embeddings dimensions are exactly the same. That means we can directly compare the embeddings vectors between the two models. That’s the goal of Part 2, and spoiler alert: it will not be insightful. And that, in turn, will lead us to Part 3, where you will discover that an RSA can be insightful. And then in Part 5 you will see that the embeddings dimensionalities do not need to match for RSA to work.
Part 2: Comparing model embeddings
Section titled “Part 2: Comparing model embeddings”For the rest of this project, we will use 18 words in three semantic categories (space, furniture, fruit). The words are printed in the online code files.
Task
Tokenize each word twice: once with a preceding space and once without a preceding space. Report the number of tokens in each encoding for the two models as in the table below (“G” is for GPT, “B” is for BERT, “-s” means there is a preceding space, and “-n” means no preceding space).
Store the with-space tokens in two lists (one for the BERT tokens, one for the GPT-2 tokens). Use those lists to extract submatrices from the embeddings matrices. Confirm the sizes of the matrices.
Here are the first few lines of my table:
Word | B-n | G-n | B-s | G-s -----------+-----+-----+-----+-----
space | 1 | 1 | 1 | 1 spaceship | 1 | 3 | 1 | 1 planet | 1 | 1 | 1 | 1 moon | 1 | 1 | 1 | 1You will discover that all words are single-token encodings in BERT regardless of preceding spaces (as you learned in Chapter 2), whereas some of the words are multi-token encodings in GPT-2 without a space — but all words are single-token encodings with a leading space.
The two submatrices have sizes corresponding to the number of words (18) by the embeddings dimensionality (1024):
BERT embeddings shape: [18, 1024] GPT2 embeddings shape: [18, 1024]
Task
Calculate the correlation coefficient between the BERT and GPT-2 embeddings for each word. Show one example word in a scatter plot and the rest of the correlations in a second plot, as in Figure 3.21.
Think about what the analysis and results mean, and what conclusions you can draw. Also think about why I asked for the correlation coefficient and not cosine similarity.
Keep in mind that this analysis is based on a small number of words, but the results seem quite compelling: The embeddings from different models are not directly comparable.
Figure 3.21: Panel A shows a scatter plot of embeddings from two models for the same word, and panel B shows the correlation coefficient across the 18 words under consideration.
Indeed, it’s only possible to run the analysis because GPT-2-medium and BERT-large happen to have the same dimensionality (more on this in Part 5).
The only valid conclusion from this analysis is that the analysis isn’t even valid. Instead, we need an alternative and suitable method for comparing embeddings across models.
Regarding the question of cosine similarity vs. correlation coefficient: Mean offsets in the variables impact the cosine similarity but not the correlation coefficient. That is,
In some applications, the mean offsets are meaningful and should be incorporated into the analysis. However, in this case, we’re interested in whether the embeddings dimensions encode the same features regardless of their numerical values, which could differ across models for reasons like normalization or scale. Therefore, correlation coefficient is more appropriate.
Part 3: Representational similarity analysis
Section titled “Part 3: Representational similarity analysis”Embeddings vectors cannot be directly compared across models. But, the relations across vectors within models can be compared. That’s the motivation behind the RSA.
Task
Perform and visualize an RSA. First, calculate the cosine similarity between all pairs of embeddings vectors within each model. That will produce two 18 × 18 cosine similarity matrices, and you can visualize them as heatmaps as in Figure 3.22A-B.
Second, extract the 153 non-redundant elements in each matrix (e.g., from the upper-triangle excluding the main diagonal). Third, make a scatter plot of the cosine similarities from BERT and GPT-2 and visualize as in Figure 3.22C. Finally, calculate the RSA score as the correlation coefficient between the cosine similarities, and print in the title of the scatter plot.
Explain why the RSA score is a correlation coefficient instead of a cosine similarity score.
Figure 3.22: Panels A and B show the cosine similarity matrices for the same words in BERT (panel A) and GPT-2 (panel B), with equal color scaling. Panel C shows the relationship between the similarity values.
The three semantic categories are visible as the block-diagonal structure in the similarity matrices. The cosine similarities appear overall stronger in GPT-2 compared to BERT (note the color levels with equal color map limits).
The more interesting result, however, is the RSA scatter plot. Here’s the interpretation: The token pairs that have higher similarity in GPT-2 also have higher similarity in BERT. This indicates that although the embeddings spaces are different, there are statistical patterns inside the embeddings spaces that are similar across these two models.
As for why the RSA score is a correlation although the within-model relations were calculated using similarity: Within each model, the mean offsets of different vectors are relevant and meaningful. Across models, however, cosine similarities might be overall stronger or weaker; the question we ask with RSA is whether the relationships across token pairs are similar in different models. For that analysis, we do not want mean offsets to bias the score. Indeed, the distribution of similarity values is different between GPT-2 and BERT (see x- and y-axes in Figure 3.22).
Part 4: Different embeddings sizes
Section titled “Part 4: Different embeddings sizes”The goal of Part 4 is to demonstrate one of the advantages of RSA: it is robust to the dimensionality within each model.
Task
Rerun the project code file but use differently sized models that have different embeddings dimensionalities. For example, GPT-2-small has an embeddings dimensionality of 768 and GPT-2-large has an embeddings dimensionality of 1280. You can use any BERT variant and any GPT-2 variant, just make sure that you pick two models with different embeddings dimensionalities.
Which code blocks still run, and which produce errors? Does the RSA score change dramatically when you use different model pairs?
Finally, use two different versions of the same model — either BERT “base” and large, or two GPT-2 model sizes.
Three comments before closing this project: First, RSA is a simple yet versatile approach for quantifying relationships across different vector spaces, and is used in a wide range of applications in ML and neuroscience.
Second, if you’ve heard of RDA (“representational dissimilarity analysis”), you might be wondering how the RDA relates to the RSA that you just learned about. The answer is: They are the same. Dissimilarity is generally just 1 − S. You would use an RDA instead of an RSA when the primary within-modality metric is distance, such as Euclidean distance.
Third, there is an entire discipline in the natural language processing and computational linguistics fields that focuses on comparing and translating between different word embeddings spaces (including, for example, evaluating whether there are Platonic universal embeddings), and which has developed sophisticated analysis methods to test those hypotheses. That level of depth is beyond the scope of this book, but if you found this project thought-provoking, then I encourage you to continue pursuing these ideas.
Bookmark
3.13 Project 13:
Section titled “3.13 Project 13:”Word similarity via distance and cosine
You’ve seen in the past few projects that words or numbers that are similar to each other have higher cosine similarity. The relationship between semantic similarity of tokens, and cosine similarity of their embeddings vectors, is nuanced and complicated for reasons that you will learn about in the next two projects (and again in Chapter 5).
But there is some semantic information in the embeddings space, and the goal of Project 12 is to utilize that information as a kind of thesaurus. For example, are the embeddings vectors that have high similarity to the vector for “table” related words like “chair,” “counter,” or “floor”?
There are several ways to measure the relationship between two vectors, including cosine similarity and correlation coefficient. In Parts 1-2 of this project, you’ll learn about Euclidean distance and how it relates to cosine similarity using simulated data and mathematical analysis, and then in Parts 3-5 you’ll use those analyses to find semantically related words based on analyzing embeddings vectors.
Part 1: Cosine similarity vs. Euclidean distance
Section titled “Part 1: Cosine similarity vs. Euclidean distance”The goal of Part 1 is to explore the relationship between similarity and distance in three simulations, and then in Part 2 you will perform a mathematical analysis of that relationship.
You already know the formula for cosine similarity, and I’m repeating it below for reference. The equation below that is for Euclidean distance.
Task
At each of 1000 iterations, create two vectors of 768 random numbers drawn from a standard normal distribution, calculate cosine similarity and Euclidean distance by translating the equations into code, and store the results. Without generating new random data, repeat the calculation for three cases within each iteration:
-
Standard random numbers (mean of zero, standard deviation of one).
-
Shrink the standard deviation of one variable by dividing the vector by 10 without changing the other vector.
-
Divide both vectors by their norm so that both vectors have a norm of 1.
Visualize the results in one scatter plot as in Figure 3.23, and then re-plot the same data in three separate panels as in Figure 3.24.
Figure 3.23: Results of three simulations showing the relationship between cosine similarity and Euclidean distance, based on the variances of the two variables.
It’s difficult to build intuition for the relationship between similarity and distance from that figure, because the x-axis ranges are so different between the cases. That’s the motivation to re-plot the data in separate axes as in Figure 3.24.
Figure 3.24: Same data as in Figure 3.23 but plotted in separate axes. Note the difference in x-axis limits of the three panels.
Now we can appreciate the relationship between distance and similarity. For random numbers with similar but non-unit variance (Case 1, panel A), similarity and distance are negatively correlated but the relationship is far from perfect. For unequal variance (Case 1, panel B), there is no visually compelling linear relationship between similarity and distance. And for the unit-normed vectors (Case 3, panel C), the relationship between distance and similarity appears perfect: one variable seems deterministically related to the other.
Why are there such striking differences and how do we make sense of them? That’s what you will understand in Part 2.
Part 2: Relationship between similarity and distance
Section titled “Part 2: Relationship between similarity and distance”Most of Part 2 is done using paper and pen, and the coding aspect is only to confirm your math.
The goal is to rewrite Euclidean distance into a form that clarifies its relationship to cosine similarity. To begin, consider the equations below, which are cosine similarity and squared Euclidean distance written in vector form.
Task
Using pen and paper, rewrite the squared Euclidean distance (Equation 3.9) as a function of cosine similarity (Equation 3.8).
Assume that the vectors are normalized, such that x^⊤x = y^⊤y = 1.
Starting with squared distance simplifies the algebra but doesn’t change the conclusions. The sequence of equations is below.
x^⊤y is the cosine similarity for unit-norm vectors. The upshot is that we have obtained an exact relationship between distance and similarity for normed vectors.
Task
Implement Equation 3.13 in code. To confirm the accuracy of the equation, subtract the left-hand-side from the right-hand-side, and plot the differences for the 1000 vector pairs you created in Part 1. The differences should all be zero within a reasonable numerical precision tolerance of around 10^(−15).
I didn’t include that figure here, but it’s just a plot with 1000 zeros plus some tiny computer precision errors on the order of 10^(−16).
The conclusion of that analysis is constrained by the assumptions of unit-normed vectors. The next goal is to repeat the mathematical analysis without the normalization assumption.
Task
Follow the same mathematical procedure as above but without restricting the vector magnitudes. The final answer is this:
Implement both sides of Equation 3.15 in code and make a scatter plot of their difference for the 1000 vector pairs. The differences should be zero (again, within precision tolerance).
The upshot of this part of the project is that cosine similarity and Euclidean distance are related to each other, and it is possible to define one from the other. But their relationship depends on the magnitudes of the vectors. In a dataset where the vectors have various magnitudes, plotting distance by similarity may appear to be unstructured noise (as in Figure 3.24B).
Part 3: Word synonyms via distance and similarity
Section titled “Part 3: Word synonyms via distance and similarity”Now that you understand and can implement Euclidean distance and cosine similarity, the rest of the project is focused on developing an algorithm that identifies semantically similar words based on high similarity and low distance.
Task
Import the bert-large-uncased model and tokenizer. Extract the embeddings matrix.
Choose a “seed” word and confirm that it is encoded using one token (I used “beauty”). Calculate cosine similarity and Euclidean distance from its embeddings vector to all other embeddings vectors. Replace the trivial self-distance and self-similarity values with NaN.
Visualize the results in scatter plots as in Figure 3.25. Create a copy of the seeded distance and similarity vectors that are min-max scaled to index the plasma color map. “Min-max scaling” means to re-scale a data vector to have a minimum value of 0 and a maximum value of 1. The formula for min-max scaling is:
The word “beauty” is indeed a single-token word: The token “beauty” comprises these indices: [5053]
Figure 3.25: Distance (left) and cosine similarity (center) between all embeddings vectors and the seed embeddings vector. The right panel shows their relationship.
The dots in the third panel look… a bit like the Star Trek communicator badge. But it also looks like panel B in Figure 3.24, with vectors of unequal norms.
To remove the trivial self-similarity value, I recommend using this line: cossim[torch.argmax(cossim)] = torch.nan
Instead of this line: cossim[cossim==1] = torch.nan
Why is the first line better than the second? I’ll answer that question in Part 4, so you have some time to think about it :)
Part 4: Top-k closest and most similar
Section titled “Part 4: Top-k closest and most similar”Now for the “thesaurus.” The idea is to find the embeddings vectors that are similar and/or close to the seed vector, and consider whether those similar vectors are semantically related to the seed.
Task
Find and print the tokens for the 10 closest vectors that you analyzed in the previous part, using cosine similarity and Euclidean distance. If you use “beauty” as a seed token, you should be able to reproduce my results below.
If you set the trivial self-distance to NaN, then you should get my results below. If the trivial distance is in the vector, then the first vector in the list below will be “beauty” with a distance of zero.
Minimum distance 10 words to “beauty”:
Distance of 1.211 to "beautiful" Distance of 1.406 to "gorgeous" Distance of 1.412 to "lovely" Distance of 1.427 to "attractive" Distance of 1.427 to "elegant" Distance of 1.444 to "sweet" Distance of 1.444 to "1954" Distance of 1.446 to "girl" Distance of 1.447 to "1928" Distance of 1.448 to "1886"I will make some remarks about the results below; first, my results for cosine similarity.
Most similar 10 words to “beauty”:
Similarity of nan to "beauty" Similarity of 0.475 to "beautiful" Similarity of 0.403 to "elegance" Similarity of 0.380 to "sweetness" Similarity of 0.367 to "perfection" Similarity of 0.363 to "purity" Similarity of 0.363 to "fragrance" Similarity of 0.361 to "charms" Similarity of 0.356 to "lovely" Similarity of 0.352 to "attractive"Are you surprised that the word “beauty” showed up in this list but not for distance? PyTorch sorts NaN’s to the top (demonstrated in the online code file), so it showed up when calling torch.argsort with the descending=True input argument. On the one hand, this is easy to ignore (e.g., find the top 11 results and ignore the first, or set the similarity to zero instead of NaN). But on the other hand, it’s important to know about and could be easy to miss if you don’t print out the results for visual inspection.
Some remarks:
- Remember that similarity and distance are negatively related to each other. Synonyms are identified as minimal distance or maximal similarity.
- The two lists are similar but not identical, highlighting the distinctions between similarity and distance for non-unit-normed vectors.
- Distance identified several nonwords (e.g., “1954”) that do not seem to be semantically related to the seed word.
- The magnitudes of the similarities and distances indicate that the effects sizes are fairly weak. For example, “beauty” and “beautiful” have a cosine similarity of .47, which may seem surprising considering that the two words are nearly identical in meaning. On the other hand, the goal of an embeddings matrix is not to extract and represent semantic relations. You’ll learn more about this in Projects 14 and 15, and even more in Chapter 5.
In practice, Euclidean distance is not often used in LLM mechanisms or research, but it is an important analysis in other ML applications.
Finally, the answer to the code syntax question at the end of Part 3: In theory, cosine similarity of a vector with itself is exactly 1, but in practice it could be slightly off due to precision errors (e.g., .999999999 or 1.000000001). Thus, a test for exact equality (cossim==1) could fail to identify the trivial self-similarity value.
Part 5: Normalized distance
Section titled “Part 5: Normalized distance”The final part of this project involves confirming the theoretical result you discovered in Part 2 with the synonym analysis in Part 4.
Task
Normalize the embeddings vectors so they each have unit norms. Then repeat the visualization in Parts 3 and 4. You should find that the right-most panel in Figure 3.25 is a nearly straight line, and that the top-10 smallest-distance words match the top-10 maximal-similarity words.
Bookmark
3.14 Project 14:
Section titled “3.14 Project 14:”Linear semantic axes
We will continue our investigation into whether embeddings spaces can be human-interpretable. This is not mere academic curiosity: The interpretability of LLM internal representations and calculations is one of the most important avenues for LLM safety, as well as for increasing the efficiency (and reducing costs) of fine-tuning base models.
You will discover in this and the next project (and more throughout the book) that some results suggest human-interpretable elements inside LLMs, but those results tend not to generalize across examples and internal states of the model.
The goal of Project 14 is to calculate a “semantic axis” by subtracting two vectors that have opposite meanings. For example, if we want to create a vector representing the concept of time, we could subtract the vector for the token “past” from the vector for the token “future.” The assumption underlying this analysis is that there are straight lines in the embeddings space that map onto human-interpretable concepts, and that we can identify those lines using linear operations (subtraction) on embeddings vectors.
Part 1: Extract and normalize an embeddings matrix
Section titled “Part 1: Extract and normalize an embeddings matrix”In this project we will use the RoBERTa LLM (and explore other LLMs in Part 5). RoBERTa stands for Robustly Optimized BERT Pretraining Approach. You can import it using the transformers library from Hugging Face as with the BERT and GPT-2 models. You can figure out how to import the model or start from the online code file. You will explore the model and its tokenizer more in Project 15.
Task
Import the roberta-base model and extract the embeddings matrix. Convert the embeddings matrix into a NumPy array because this project is done without PyTorch.
Calculate the norm of each embeddings vector, and visualize as in Figure 3.26. Create a copy of the embeddings matrix that is unit-normed, and check its shape.
The RoBERTa embeddings matrix has size 50265 × 768.
The embeddings vector norms have varying lengths, indicating that different vectors are closer to, or further from, the origin of the embeddings space.
Figure 3.26: Vector norms of the RoBERTa embeddings matrix. The norms of the normed embeddings are not so interesting to look at.
You can confirm that the normalization worked by calculating and printing the norm of a randomly selected vector in the original and normalized embeddings matrix. You should find that the norm of the normalized embeddings vector is 1, whereas the norm of the original embeddings vector is around 3 to 4.
Part 2: Create a “semantic axis”
Section titled “Part 2: Create a “semantic axis””A semantic axis is created by subtracting two vectors corresponding to tokens with opposite meaning, such as fast-slow or good-evil.
The goal of Part 2 is to create semantic axes in two ways: Subtracting normed vectors or normalizing the subtraction of two non-normed vectors. This is an important distinction because the difference of two unit-norm vectors is in general not unit-normed. As a simple example, the vectors [1,0] and [0,-1] each have a norm of 1, but subtracting those vectors yields the vector [1,1], which has a norm of .
Task
Tokenize the words “ future” and “ past” (note the preceding spaces) and confirm that they are single-token words.
Create two semantic axis vectors: (1) subtract the two non-normed embeddings vectors and then unit-normalize the difference vector; and (2) subtract the normed vectors.
Compare the norms of the two semantic axis vectors by printing their vector norms and visualizing them as in Figure 3.27.
The two versions of the normed semantic axis vector are highly correlated, because their original vectors had similar norms. You can confirm that in the code. Other word pairs would match less closely if their norms differed more, although they would generally always be strongly correlated.
Figure 3.27: Two ways of creating a difference vector (before vs. after normalization), shown in embeddings dimensions (panel A) and as a direct comparison in a scatter plot (panel B).
That said, although Figure 3.27 suggests that it doesn’t matter how we create the semantic axis vector for this token pair, the next analysis will involve cosine similarity calculations, and therefore it is convenient to use vectors that are unit-normed. Thus, use the normalized embeddings matrix for the rest of the project.
Part 3
Section titled “Part 3”The data are now ready for the semantic axis analysis.
Task
Calculate the vector-matrix product vE^⊤, where v is the semantic axis vector and E is the embeddings matrix. Visualize the dot product results as well as their histogram, as in Figure 3.28.
Find the 10 vectors with the most positive dot products, and the 10 most negative dot products, and print their dot products and tokens as in the tables as below. These are the tokens that maximally project onto the positive and negative “poles” of the semantic axis.
Note that if you use the unit-normalized embeddings matrix and semantic axis vector, then the results are cosine similarities. If you use non-normalized vectors, then the dot products can be considered linear projections of the embeddings vectors onto the semantic axis.
Figure 3.28: Projections of all embeddings vectors on the “time axis” defined as the difference between the embeddings vectors for “future” and “past.” The y-axis in panel B is log-scaled to better visualize the small number of larger-magnitude similarity values.
The table below shows the results of the largest positive cosine similarities, which correspond to the tokens that map most strongly onto the “future” side of the semantic axis.
10 most positive-projected words: Proj. | Word ---------+------------
0.589 | " future" 0.450 | "Future" 0.392 | "future" 0.388 | " Future" 0.281 | " someday" 0.278 | " tomorrow" 0.250 | "Tomorrow" 0.241 | " futures" 0.229 | " upcoming" 0.225 | " eventual"Many of the most-similar words are variants of the selected word. You could include additional code to filter out these trivial results. The non-trivial results make sense: “future” is semantically similar to “tomorrow,” “upcoming,” and so on.
Here are the most negative-projecting words:
10 most negative-projected words: Proj. | Word ---------+------------
-0.594 | " past" -0.436 | " Past" -0.400 | "Past" -0.389 | "past" -0.219 | " passed" -0.171 | " previous" -0.169 | " Previous" -0.161 | " Bush" -0.154 | " pat" -0.153 | "last"Some of the non-trivial results make sense, like “previous” and “last.” Other results are less easily interpretable, although “ Bush” could be a reference to George Bush, two former US presidents.
Part 4: Try other semantic axes
Section titled “Part 4: Try other semantic axes”The results from Part 3 provide some support for the concept of a linear semantic axis. Without setting up a rigorous experiment, you can gain more intuition by trying some additional word pairs to explore other putative semantic axes.
Task
Rerun the code for Parts 2 and 3 using different antonym pairs. Some suggestions to try: good/evil, young/old, big/small. You can also try including vs. excluding preceding spaces.
As you try more examples, I think you will discover that some results seem consistent with the concept of a semantic axis created by subtracting two embeddings vectors, whereas other results are inconsistent with the idea, or at least don’t seem to have any semantic relationship to either “pole” of the axis.
Part 5: Try other embeddings
Section titled “Part 5: Try other embeddings”The goal of this part is simple: see what happens when you run the same code but using embeddings matrices from other LLMs.
If you use the BERT or GPT-2 models, you won’t need to change the code. If you are already familiar with, or are interested in learning more about, other non-LLM embeddings like Word2Vec or GLoVe, then you can use the same analysis pipeline that you developed in this project, but some parts of the code may need to be adjusted due to differences in data type and organization.
Bookmark
3.15 Project 15:
Section titled “3.15 Project 15:”Analogy vectors
An analogy is a relationship that highlights similarities. For example, finish this analogy: “glove is to hand as sock is to…”
I guess that you guessed that the next word should be “foot.”
Mathematically, we can represent an analogy as the equality of differences:
Equation 3.17 states that the differences are roughly equivalent (differences are used instead of ratios because the numerical representations may contain zeros), which means that we can “subtract” foot from both sides of the equation to isolate sock. That will be key to solving analogies using embeddings vectors.
In particular, if embeddings spaces have human-interpretable semantic structure that can be accessed through linear operations on embeddings vectors, then it should be possible to construct an “analogy vector” as glove minus hand plus foot and the resulting vector should be the embeddings vector for the word “sock.”
That’s the idea we will explore in Project 15. It’s a fantastic opportunity to learn more about embeddings matrices and ML analyses, but you will discover that we cannot reliably use linear analyses to solve analogies with LLM embeddings spaces. Before we begin, let me clarify two points:
-
Analogy vectors work in some hand-picked examples (and by “work” I mean that the analysis reveals the correct answer), but they do not work in many other examples. And when they do work, the statistical evidence tends to be weak.
-
LLMs — especially frontier commercial LLMs like ChatGPT, Claude, and Gemini, can solve analogies with high accuracy. But the mechanism by which LLMs solve analogies is different from the mechanism of assuming linearity and human-interpretable semantic axes.
Part 1: Explore the RoBERTa model
Section titled “Part 1: Explore the RoBERTa model”Take a moment to look at the description of the architecture of the RoBERTa model (Figure 3.29). If you are new to LLMs, then it might look intimidating, but don’t worry: you’ll learn these model components in later chapters. For now, we will focus on the first block called embeddings.
Figure 3.29: Overview of RoBERTa model architecture.
The embeddings block contains three embeddings matrices. We will use only word_embeddings in this project.
The encoder block describes the 24 transformer layers, each of which includes three components: attention, intermediate, and output (the OpenAI models combine intermediate and output into one block called MLP; you’ll learn about this in Chapters 5 and 7).
The embeddings matrix is 50265 × 1024, which corresponds to 50,265 tokens in the vocab and an embeddings dimensionality of 1024.
Task
Extract the embeddings matrix from the model.
Encode and print the tokens for the words “list”, “computer”, “apple”, and “spaceship”. Also print the tokens for those words with a preceding space.
You’ll get the following output:
“list” is indices [0, 8458, 2] ” list” is indices [0, 889, 2]
“computer” is indices [0, 36327, 2] ” computer” is indices [0, 3034, 2]
“apple” is indices [0, 27326, 2] ” apple” is indices [0, 15162, 2]
“spaceship” is indices [0, 4182, 11667, 4128, 2] ” spaceship” is indices [0, 39881, 2]
The first and final tokens are special tokens added to the tokenization, just like with the BERT model. We’ll get back to those tokens in a minute.
Also noteworthy is that the tokens are different for the words with vs. without the preceding space. The impact of the space is most striking for “spaceship,” which is a single token with a preceding space but three tokens without a space.
Task
Print the first 20 tokens.
Below are the first four:
Index 0 is “<s>” Index 1 is “<pad>” Index 2 is ”</s>” Index 3 is “<unk>”
Tokens 0 and 2 are used to demarcate sequences of text. The fourth token is for “unknown.” As with the BERT tokenizer, you can exclude the special tokens by adding the optional input argument add_special_tokens=False.
Task
Examine the tokens for [’ king’] and ’ king’. Notice the impact of the square brackets, which changes the input from a string to a list containing a string.
Without the square brackets, the token index is 8453. With the brackets, the token is 3 (“<unk>”).
There are many details and subtleties to each LLM’s tokenizer. The important take-home message from this part is that different tokenizers have different behaviors. When you start using a new model with a new tokenizer — even if it’s a different model from the same company or research lab — you need to check the tokenizer inputs and outputs carefully. Don’t assume that the behavior of one tokenizer is the same as the behavior of another tokenizer.
Part 2: Extract four embeddings and make a dataframe
Section titled “Part 2: Extract four embeddings and make a dataframe”We will work with the analogy King is to man as queen is to woman. The goal will be to perform arithmetic on the embeddings vectors for “king,” “man,” and “woman,” and see if the resulting analogy vector points towards the token “queen.” In particular, we will implement the following arithmetic:
We can calculate v? using the embeddings vectors for the three words on the left-hand-side of Equation 3.20. I will call the right-hand-side of Equation 3.19 the “analogy vector.” The question at hand is whether that analogy vector equals (or at least is very similar to) vqueen.
Creating the analogy vector and calculating similarity are goals for later parts. The goal of Part 2 is to extract and visualize the embeddings vectors for the four words.
Task
Check that the four analogy words (king, man, woman, queen) are encoded as single tokens when including preceding spaces.
Create a Pandas dataframe in which each of four columns corresponds to a token, and each row corresponds to an embeddings dimension. Show the summary description of the dataframe as in Figure 3.30.
All four tokens have a small negative offset, and their statistical characteristics are roughly comparable.
Figure 3.30: Descriptive characteristics of the four analogy vectors in Pandas.
Part 3: Visualize using pairplots
Section titled “Part 3: Visualize using pairplots”The Seaborn library has nice visualizations that are easily integrated into Pandas dataframes. One of them is called a pairplot, and produces all scatter plots of pairwise interactions, and histograms on the diagonal.
Task
Visualize the dataframe using pairplots as in Figure 3.31. Figure out how to specify properties like colors, transparencies, marker shapes, and the best-fit regression line. You can use your favorite colors instead of the ones I chose.
Figure 3.31: Pairplot from the Seaborn library, showing distributions and scatter plots of all four vectors in the Pandas dataframe.
Two observations of this result:
-
The embeddings vectors are roughly normally distributed with a mean close to zero. This shows that the representations are dense as opposed to sparse. Of course, this is just four out of 50k tokens so we should not make bold statistical claims based on a few examples, but these characteristics are representative. In Chapter 5 you will observe how the distributions of embeddings vectors change as the vectors pass deeper into the LLMs.
-
All pairs of vectors are positive correlated, at least by visual inspection.
That second observation is qualitative, but we can quantify the relationships using cosine similarity.
Part 4: Visualize cosine similarities
Section titled “Part 4: Visualize cosine similarities”Task
Calculate pairwise similarity using the function cosine_similarity from the scikit-learn library. Visualize the results as in Figure 3.32. You can call the plt.text function inside a double for-loop to print the numbers.
Figure 3.32: Cosine similarity matrix across the four embeddings vectors.
These results confirm that all pairs of vectors are positively related to each other. It will be interesting to compare the magnitudes of these relationships with the analogy vector in the next two parts.
Part 5: Arithmetic with embeddings vectors
Section titled “Part 5: Arithmetic with embeddings vectors”The goal of Part 5 is to calculate an analogy vector for our example analogy. Then in Part 6 you will expand on this specific example by creating a Python function that creates and reports an analogy vector for any incomplete analogy you wish to provide.
Task
Calculate the analogy vector according to Equation 3.20.
Calculate cosine similarity between that vector and all embeddings vectors. Visualize the similarity values and their distribution as in Figure 3.33. Set the color index of token i into the colormap cool to be , and set the size of each marker to be 60c_i^2, where c_i is the cosine similarity between the analogy vector and embeddings vector i. Also note the logarithmic scaling of the y-axis in panel B.
Setting the y-axis to be log-scaled helps visualize the small extreme values on the left and right of the distribution, which is useful here because we are interested in identifying the few extreme values in the cosine similarity distribution.
Figure 3.33: Cosine similarity between all embeddings vectors and the analogy vector.
There are relatively few large cosine-similarity values whereas the bulk of the similarity values are between .2 and .4.
Task
Find and print out the 10 most similar tokens to the analogy vector. Report the cosine similarity of the token with the analogy vector, and the percent of shared variance, which you can calculate as the squared correlation coefficient.
The idea of this analysis is that the tokens that are most similar to the analogy vector are the model’s solution to the missing word in “king is to man as ___ is to woman.” Of course we’re looking for the answer “queen.”
CosSim | R^2 | word ---------+---------+-------------
0.784 | 61.1% | " king" 0.715 | 50.7% | " queen" 0.604 | 35.9% | " King" 0.600 | 35.5% | " Queen" 0.589 | 34.1% | " princess" 0.566 | 31.6% | " kings" 0.564 | 31.5% | " woman" 0.558 | 30.5% | " monarch" 0.549 | 29.7% | " queens" 0.545 | 29.3% | " women"Shared variance is a measure of how much variability one variable (in this case, the analogy vector) explains in another variable (in this case, the token embeddings vectors). For a simple regression analysis, the shared variability equals the squared correlation.
Many of the highly-similar token embeddings are words in the analogy (“king” and “woman”) or variants thereof. Excluding those results, the analysis has identified “queen” (and its variants) as solving the analogy. The other words in that list (“monarch” and “princess”) are incorrect but are semantically related to the analogy words.
Part 6: An analogy-completing function
Section titled “Part 6: An analogy-completing function”The code you’ve written thus far is hard-coded for this particular example. The goal of this final part of Project 15 is to create a Python function that takes three words as input and prints out the table that you created in Part 5.
Task
Your Python function should take three input arguments, corresponding to the words for “(1) is to (2) as ___ is to (3).”
The content of the function should have the following elements.
-
Print the word analogy. For example, if the function inputs are “hand”, “glove”, and “shoe”, then the function would print “ hand” is to “ glove” as “_____” is to “ shoe”
-
Tokenize the words. Be mindful of special tokens and preceding spaces.
-
Check that each input word is encoded as one token. If a word contains multiple tokens, the function should raise an error and exit. Also check for an “unknown” token and raise an error if an input word is unknown. After the input checks, it might be helpful to have the tokens as integers in a list.
-
Extract the three vectors from the embeddings matrix.
-
Calculate the analogy vector.
-
Calculate cosine similarity between the analogy vector and all embeddings vectors.
-
Print the table as in Part 6.
Test your function by inputting “king”, “man”, and “woman” to confirm that the printed table is identical to that in Part 5. Also confirm that errors are properly identified by inputting multi-token words, misspelled words, etc.
When you confirm that your function works, explore the impact of spacing. Then try other analogies (see the online code file for some examples).
In general, you will find that some analogies give correct results, others give nonsense results, and others give results that are incorrect but semantically related.
I would like to close this project with a few remarks:
-
Embeddings vectors in LLMs are dynamic, not fixed. They change depending on the rest of the text, and on the depth in the LLM transformer stack. You’ll see this in later chapters.
-
Analogy vectors assumes linearity, whereas there is no reason to think that LLMs represent language and meaning using straight lines in spaces with straight, orthogonal axes. Indeed, LLMs are highly nonlinear.
-
Many words are encoded using multiple tokens. This is problematic for the simplistic arithmetic, though there are principled ways of analyzing multi-token words (briefly: information and context from earlier tokens are loaded onto later tokens, so the solution is to analyze the final token in a multi-token word).