Output Logits
local graph
Background: Model output logits
Section titled “Background: Model output logits”What are “logits”? The word “logit” has a specific meaning in statistics: It is a number associated with the probability of a binary event occurring (specifically, the logarithm of an odds ratio). But you don’t need to worry about that definition here. The important thing to know for an LLM is that the logits are the final numerical outputs of the model, which are transformed into probabilities of picking a new token.
How many logits does an LLM calculate? Each token in the input sequence leads to a vector of logits the size of the vocab. For example, if you prompt a GPT-2 with a five-token sequence, then the final output of the model will be a matrix of size 5 × 50257. In other words, the entire LLM can be thought of as a mapping between each input token and logits for the entire vocab.
What do LLMs do with logits? For a generative LLM like GPT or Claude, each logit corresponds to the likelihood that that token is the next token. Thus, after all the internal calculations across all the transformer layers, the LLM associates each input token with a distribution of probabilities for the token that comes thereafter. LLMs designed for text classification can have a specialized final layer in which the logits are used to calculate the likelihood of the text belonging to specified categories. But in this chapter, we will focus on LLM architectures that map input tokens onto vocab items.
Transforming logits into probabilities The “raw” logits are not probabilities, but can be transformed into probabilities using the softmax transform, which you’ll learn about in Project 16. However, for several reasons including numerical stability, log-probabilities are often used.
How do you get logits from the model? When using models provided by Hugging Face, the final logits are provided in the output of the model call. You’ll learn about this in Project 16. Figure 4.1 shows an example of logits. The x-axis has 30k elements corresponding to the vocab in BERT, and the y-axis shows the logit value.
Figure 4.1: Scatter plot depicting output logits from BERT. Each dot corresponds to the logit value for one token index in the vocab. The raw logits can be transformed into probability values for token selection.
Because logits are transformed into probabilities of token selection, the token indices with larger logit values are more likely to be chosen.
4.16 Project 16:
Section titled “4.16 Project 16:”Softmax probability distributions
The softmax transform converts a collection of numbers into a probability distribution. A probability distribution describes the chances of various events occurring or being observed. In particular, a probability distribution has the following constraints:
Equation 4.1 is the item-level definition of a probability function to which the two subsequent statements apply. Equation 4.2 says that probability values are non-negative (s.t. stands for “such that”); Equation 4.3 says that events within the set X must be exclusive (the probability value at f(x_i) of any event other than x_i is zero); finally, Equation 4.4 says that the sum over all probabilities must equal 1.
If you want to create a probability distribution from an array of numbers that are not probabilities (for example, counts of observations), you can simply divide by the sum, as in this example:
That approach works for all-positive values like counts, but it doesn’t scale to arrays with negative numbers like logits.
The softmax transformation is more general in that it can create probability distributions from negative numbers. It also has properties that are useful for text generation, such as stretching out the probability distributions to reduce the number of likely tokens. More on these nuances later; for now, here’s the softmax formula:
Note that e^x is positive for all values of x, even if x is negative.
Softmax is widely used in machine-learning, deep learning, and optimization. Softmax has two notable applications inside LLMs: weighted averaging in the attention algorithm, and probabilistic token selection when generating text. You’ll learn about the former application in Chapter 6, and you’ll learn about the latter in this chapter.
Part 1: Softmax in NumPy and PyTorch
Section titled “Part 1: Softmax in NumPy and PyTorch”The goal of Part 1 is to implement the softmax transform twice: by translating Equation 4.8 into NumPy code, and by calling a PyTorch function. Translating an equation into NumPy code helps you learn the transformation, but there are numerical stability issues that the PyTorch function alleviates; you’ll see an example of that in Part 5.
Task
Transform the following list of numbers into a softmax distribution by translating Equation 4.8 into NumPy code. Print the softmax probabilities and confirm that they sum to 1. z = [1,1.1,2,3,5,6,6.1]
Repeat the calculation using PyTorch’s softmax function. Be mindful of datatypes. Print out the softmax probabilities and confirm that they match the NumPy output.
Show both results in a graph as in Figure 4.2.
You can access PyTorch’s softmax function via the F.softmax function, where F is a common alias for torch.nn.functional. You need to specify the dimension along which to calculate the softmax transformation; if you’re applying the function to 1D arrays, you can set dim=-1. In fact, any time you call the softmax function on output logits, you’ll use dim=-1.
You should get the following softmax numbers: [0.0026, 0.0029, 0.0072, 0.0195, 0.1440, 0.3913, 0.4325]
Figure 4.2: Comparison of manual (red squares) and PyTorch (blue x’s) implementation of the softmax transformation on the same numbers.
This figure reveals several interesting properties of softmax, including the nonlinear nature of the transform. For example, consider the first two numbers and the last two numbers: Both are .1 units apart in the original data, but the distance spanned on the y-axis is larger for the last two numbers compared to the first two.
This highlights the “stretching” characteristic of softmax: Relatively small numbers are compressed while relatively large numbers are stretched. The impact of this stretching, as you’ll soon see, is to suppress the probability of most tokens in the LLM’s vocab while selecting a small number of most-likely tokens.
Part 2: Temperature
Section titled “Part 2: Temperature”The “stretching” of the softmax transform can be regulated by a parameter called temperature. The temperature is literally just a scalar-division of the data before they are transformed.
When the temperature parameter is not explicitly included in the softmax function as in Part 1, then it is implicitly set to 1.
Task
Create a PyTorch tensor comprising 55 linearly spaced numbers from -5 to 5. Transform that tensor into softmax probabilities using four temperature values (.3, .6, 1, 1.4), and visualize the results as in Figure 4.3.
Figure 4.3: Impact of the “temperature” (T) parameter on the softmax transformation. All four lines come from the same dataset but with different temperature values.
The lower the temperature, the more extreme the difference between the low-probability and high-probability values. In other words, lower temperature makes a smaller number of values “pop out” from the rest of the distribution.
On the other hand, higher temperatures flatten the distribution, giving more values comparable probabilities.
You’ll learn about the impact of temperature on token generation in LLMs in the next project.
Log-scaling the y-axis is insightful, and shows how strong the suppression becomes for negative numbers. That’s not shown here, but you can modify the code to log-scale the axes.
Temperature values in LLMs range from around .2 to 1.5. Lower values make the model’s output more deterministic while higher values increase randomness. Appropriate values are task-dependent: You want an LLM to give definite answers when discussing history or legal arguments (lower temperature), and to give more creative answers when writing a children’s story or brainstorming marketing ideas (higher temperature).
Part 3: Softmax LLM output logits
Section titled “Part 3: Softmax LLM output logits”The goal of Part 3 is to explore the impact of softmax on model logits.
Task
Import the GPT-2-small and GPT-2-large models. Use different variable names for the models, although they use the same tokenizer, so you only need to import that once. Use the num_parameters attribute to print the number of parameters in the two models.
When running forward passes on trained models (as opposed to training models through gradient descent), it is important to switch the models in “eval” (evaluation) mode. Briefly, there are several operations in the model that are used during training that should be switched off during inference (runtime), such as dropout regularization. To switch a model into evaluation mode, call model.eval(). You only need to switch the model into eval mode once (unless you’re training the model and need to switch it between eval and train). Get into the habit of including that toggle as soon as you import a model into Python.
You won’t need the large version of the model until the next part, but it’s convenient to load both models in the same code block. Here are the sizes:
GPT-2-small has 124,439,808 parameters. GPT-2-large has 774,030,080 parameters.
Causal autoregressive LLMs like GPT are trained on next-token prediction. That means that the output logits of each token position are predictions for the token in the next position. The goal of this part of the project is to prompt the model with some text and see what new token the model selects.
Task
Tokenize the sentence “It was a dark and stormy”. Make sure the tokens are stored as a PyTorch tensor. Print a table of each token index and text.
Your code should produce the following output:
The text comprises 7 tokens.
1026 is "It" 373 is " was" 257 is " a" 3223 is " dark" 290 is " and" 6388 is " storm" 88 is "y"The model produces 50,257 logits for each token (one logit value for each vocab item), but for generating new text, only the logits to the final token are used. The idea is to find the token index with the largest logit, and then append the corresponding token text to the prompt.
Task
Input the token sequence into GPT-2-small and assign the output of the model to a variable called outputs. Check the size of the logits attribute.
Apply the PyTorch softmax transform to the logits for the final token and store in a new variable. Confirm that the sum over all raw logits does not equal 1, while the sum over all softmax probabilities equals 1.
Make three scatter plots of the raw logits, their softmax-transformed values, and the relationship between the raw and softmax values, as in Figure 4.4.
Finally, find the maximum logit and report its softmax probability value and its corresponding token string.
The size of the logits tensor is [1, 7, 50257]. It’s a 3D tensor. The first dimension corresponds to the number of sequences in the batch. LLMs can process multiple token sequences simultaneously, which saves computation time. You’ll learn how to batch sequences in a later project. Here we’ve provided only one sequence, so there is only 1 element in this dimension.
The second dimension is the tokens in the sequence. The inputted text comprises seven tokens.
The third dimension is the vocab; there is one logit per token position per vocab item.
Figure 4.4: “Raw” logit values (panel A), their softmax transform (panel B), and their relationship (panel C).
Notice that the softmax transform suppresses most of the probability values to near-zero while boosting a small number of probabilities.
The maximum logit is index 1755 with a softmax probability value of 46.2%, and its corresponding token is “ night”. Thus, when presented with the phrase “It was a dark and stormy”, GPT-2 calculates that the most likely next word is “night.”
Minor terminological note: After applying the softmax transformation, the numerical values are no longer logits; instead, they are probabilities. Calling them “softmax-transformed logits” can be used to clarify which variable the probabilities were calculated from (cf the “softmax attention scores” that you’ll learn about in Chapter 6, which fit the formal definition of probabilities but are not used for probabilistic interpretation or sampling).
Part 4: Top 10 probabilities and temperature
Section titled “Part 4: Top 10 probabilities and temperature”If LLMs only ever generated the token with the largest logit, they would be… uninteresting. Instead, tokens are selected probabilistically using techniques you’ll learn about in the next project.
Here we will explore the impact of the temperature parameter on the 10 highest-probability tokens.
Task
Find and print the top 10 tokens and their probabilities. Use torch.topk.
You should get the following result:
It was a dark and stormy ___
1755 (46.2%) is " night" 1110 (23.5%) is " day" 6180 ( 5.9%) is " evening" 3329 ( 4.4%) is " morning" 6672 ( 4.1%) is " afternoon" 3931 ( 1.3%) is " summer" 640 ( 1.3%) is " time" 7374 ( 1.2%) is " winter" 5041 ( 0.4%) is " weekend" 11 ( 0.4%) is ","The top nine choices are grammatically correct and semantically sensible. The probabilities drop quickly, though even .4% is large compared to the vocab size of 50k.
Task
Calculate the softmax probabilities using three temperature parameters of .5, 1, and 1.5, find the top-10 logits, and compare their probabilities visually as in Figure 4.5.
Is it necessary to re-calculate the top 10 tokens for each temperature value?
Note that the y-axis in Figure 4.5 is logarithmically scaled. That helps highlight the suppression of small probability values. In contrast, linear y-axis scaling highlights the boosting effect for larger probabilities.
Figure 4.5: Impact of softmax transform on the top 10 logits using different temperature values. Softmax is a monotonic transformation, so although the numerical values change, their ordering does not.
The answer to the question of re-calculating the token strings is No, it is not necessary. Softmax is a monotonic function, meaning that σ(x_1) > σ(x_2) when x_1 > x_2. In other words, the ordering of token probabilities is the same even though the probability values change. That said, the probability values will differ, as you see in Figure 4.5.
Part 5: Numerical instabilities and normalization
Section titled “Part 5: Numerical instabilities and normalization”There are two goals of this part: compare the logits from GPT-2-small with those of GPT-2-large, and discover numerical issues that arise in softmax transformation of very large arrays and how to resolve them.
Task
Tokenize and input the sentence “A plethora of platypuses.” (including the final period) into both models. Extract the logits to the final token from both models and visualize the raw logits in scatter plots as in Figure 4.6.
Figure 4.6: Comparison of raw logits in GPT-2-small and GPT-2-large to the same input. Notice the different y-axis limits.
The figure reveals two striking results:
-
The logits from GPT-2-small are much more negative than those of the large version. That is the source of the numerical problems that you’ll soon observe.
-
The logits of the two models are correlated but certainly not identical, despite both models processing identical text sequences. That result shouldn’t be surprising: GPT-2-large has six times as many parameters, so its internal calculations will differ even for identical text.
Now to examine the impact of softmax.
Task
Transform the logits from the two models to softmax, by translating Equation 4.8 into PyTorch code. Do not use PyTorch’s built-in softmax function.
Show the results as in Figure 4.7. Print out the raw logit and the softmax logit for one token from GPT-2-small.
The results look like something is missing. The middle panel has data, but the left and right panels appear empty.
Figure 4.7: Same as Figure 4.6 but after softmax transforming the logits.
The problem is that the GPT-2-small softmax probabilities are all NaN (not-a-number). You can confirm that by printing out the raw and softmax logits for one token:
logits_small[3000], sm_manual_small[1000] >> (tensor(-115.9721), tensor(nan))
The raw logit value is a real-valued finite number. No problems there. But its corresponding softmax probability is NaN. The problem is numerical: e^(−110) is such a fantastically tiny number that computers have difficulties using it for operations like summation and division.
The GPT-2-large model has larger raw logits, so it doesn’t encounter this issue.
Task
Repeat the previous task and figure, but first normalize the raw logits by subtracting the maximum logit value from the rest of the logits. Reproduce Figures 4.6 and 4.7. Confirm that the raw logits are closer to zero, and that the softmax probabilities are finite numbers.
I don’t show the figure of the raw logits here (though it is produced in the online code file), but you will find that the raw logits for both models are in the range of -20 to zero. The results for the softmax transformation are shown in Figure 4.8; the key observation is that the softmax transform now produces finite numbers for GPT-2-small.
Figure 4.8: Same as Figure 4.7 but after normalizing the logits before calculating the softmax transform.
Task
Use PyTorch’s softmax function on the raw (non-normalized) logits. Reproduce Figure 4.7.
Now you’ll find finite softmax probability values for GPT-2-small, despite the logits being the same as what produced NaN’s in the manual implementation of softmax.
Many LLM calculations risk numerical instabilities, and therefore, many PyTorch functions have built-in normalizations or other techniques to minimize these risks.
What is the conclusion of this demonstration? Please do not conclude that you should never code math yourself and instead only use functions provided by PyTorch (or any other library). Coding math gives you flexibility and adaptability that allows you to custom-tailor analyses to your goals and needs.
Instead, the right conclusion here is to visualize and sanity-check your results often, and be mindful of potential issues that might arise and how to resolve them. In some cases, using library-provided functions is best; in other cases, coding your own analyses or normalizations is best.
Bookmark
4.17 Project 17:
Section titled “4.17 Project 17:”Probabilistic token selection
If generative LLMs only ever picked their most-likely next token, they would be repetitive, predictable, and overall uninteresting to interact with. Quite boring.
On the other hand, if LLMs generated text by selecting tokens completely at random, the output would be uninterpretable garbage.
Therefore, LLMs are crafted to select tokens probabilistically, but the probabilities of token selection are constrained by the logits distribution.
The goal of this project is to learn four methods for next-token selection. Along the way, you’ll learn how to identify and fix some common PyTorch errors. And you’ll learn how chatbots work, even creating your own chatbot! (Although I must admit that the chatbot you’ll make here has educational value but is not exactly a rival to the latest ChatGPT.)
Part 1: PyTorch’s multinomial function
Section titled “Part 1: PyTorch’s multinomial function”PyTorch has a function called multinomial, which allows you to select probabilistically from an array of numbers. It’s an important function to understand, but can be tricky at first. Thus, before working with LLM data, we will spend some time understanding how the multinomial function works, and some common errors to watch out for.
Task
Create a torch tensor of floats from the list [1,2,5]. Name the variable vect. Run the following code multiple times to gain some intuition for the function’s output. torch.multinomial(vect,1)
Next, run the following code several times to build some more intuition: vect[torch.multinomial(vect,10,replacement=True)]
Here are two observations that I hope you made:
- The outputs of the multinomial function are indices into the vector, not elements of the vector. In this case, the function returned indices “0”, “1”, and “2”; one could also imagine that the developers crafted the function to return the values “1”, “2”, and “5”.
- The returned numbers do not appear equally often. I’m sure you found that the the second line of code (vect[…]) produced the value “5” more often than “1” or “2.”
Let’s follow-up on that second observation.
Task
Generate 10,000 samples from the same vector. Set the input argument replacement to be true. Use torch.unique to count the number of times each of three elements was selected. Print the count and proportion of times that each number was selected.
By the way, you could use the NumPy function np.unique here instead of the PyTorch version. Integrating NumPy and PyTorch can be confusing, because some functions have the same names and can work the same way (as with unique); other functions have the same names but work differently or take different input arguments; some functions work similarly but only on certain data types; etc. In general, it’s preferable to use PyTorch functions on torch variable types and to use NumPy functions on numpy variable types, but there will be situations where calling NumPy functions on PyTorch data is the easiest and least confusing solution.
Anyway, I got the following result for this task; your result should be similar though of course the exact numbers will differ.
“0” was sampled 1253 times (12.53%) “1” was sampled 2457 times (24.57%) “2” was sampled 6290 times (62.90%)
Given that there are three options to randomly select from, why aren’t the probabilities each approximately 33%?
Task
Calculate the expected probability for each vector element using the formula p(v_i) = v_i∕∑ v, where v_i is each element in variable vect. Write code to print the table below.
Here’s my table. Your numbers in the “observed” column will be somewhat different, but you should get identical “expected” column values.
Value | Observed | Expected ------+----------+----------
"0" | 12.53% | 12.50% "1" | 24.57% | 25.00% "2" | 62.90% | 62.50%Your final task here is to examine the function docstring by running the code torch.multinomial??. Basically, the function works by transforming the input numbers into a probability distribution and then probabilistically sampling values according to that distribution. In the demo above, the number “5” appeared most often because 5∕(1 + 2 + 5) = 5∕8 = 62.5%.
Part 2: Common errors with torch.multinomial
Section titled “Part 2: Common errors with torch.multinomial”The goal of this part is for you to see — and fix — four incorrect ways of using the multinomial function. But this isn’t just about using one PyTorch function correctly; some of these errors are common issues in many PyTorch functions.
Task
The online code file contains the following lines of code. All lines produce errors; your goal is to understand why those errors arise and then fix them. I will describe the problems and their solutions below.
# error 1torch.multinomial([1.,2,.3],1)torch.multinomial(np.array([1.,2,.3]),1)# error 2torch.multinomial(vect,len(vect)+1)# error 3torch.multinomial(torch.tensor([1,1,1]),1)# error 4torch.multinomial(torch.tensor([-1,1.,1]),1)-
Requires torch tensor. You cannot use lists or NumPy arrays. As I wrote earlier, PyTorch and NumPy sometimes seamlessly integrate; here is a counter-example.
-
Default behavior is no replacement. “Replacement” in sampling means drawing the same data point multiple times. You cannot take N + 1 samples from an N-element vector unless you replace each value after it is sampled.
-
Inputs must be floats. The multinomial function requires floating-point numbers as inputs. The erroneous code has only integers.
-
Inputs must be non-negative. The calculation of probability is based on sum and division — it’s not a softmax transformation. Thus, negative numbers in the input would produce “negative probability” values, which are invalid. If you want to sample using the multinomial function with negative values, you can softmax-transform the data first. You’ll implement that later.
In conclusion, the first input into the multinomial function must be real-valued, non-negative, floating-point numbers stored as a PyTorch tensor. You can draw as many samples from that input as you want if you sample with replacement.
Part 3: Deterministic token selection
Section titled “Part 3: Deterministic token selection”The goal of Part 3 is to perform deterministic token selection. It’s similar to what you implemented in the previous project, so writing code fresh here instead of copying from the previous project file is a great way to evaluate your learning.
Task
Import the GPT-2-small model and its tokenizer. Tokenize the text “I don’t want to grow” and input the tokens into the model. Isolate the logits to the final token and transform to softmax.
Find the maximum logit and print its token string. Visualize the logits as in Figure 4.9.
The maximum token is “ up” with 33.8% probability. I find it sweet and cute that GPT-2 doesn’t want to grow up :)
Figure 4.9: Raw (panel A) and softmax-transformed (panel B) logits to the final token in the sequence. The red hexagon indicates the model’s top prediction for the token that should come next.
As I wrote earlier, deterministic token selection produces models that generate rigid text that doesn’t sound human-like. The next parts of the project will introduce you to three probabilistic selection methods.
Four comments before moving on:
-
I didn’t explicitly instruct to switch the model into evaluation mode, but you should do that whenever you import a model — unless you are training the model, which you won’t do in this book.
-
The online code file wraps the model forward pass in an additional piece of code with torch.no_grad(). PyTorch performs many calculations related to building and keeping track of the flow of gradients inside a model. Those calculations are required for training a model, but are not necessary during runtime. On the one hand, for a relatively small LLM and a small token sequence, the computational cost of tracking gradients is negligible. But it does add up for larger models or a lot of data, so it’s good to get into the habit of using torch.no_grad().
-
Because the softmax transformation is monotonic, the token with the maximum raw logit is the same as the token with the maximum softmax probability.
-
That said, the softmax transformation can be very impactful for probabilistic token selection. In particular, the largest raw logit doesn’t appear so much bigger than the rest of the distribution, but its softmax transformation really pops out (see Figure 4.9).
Part 4: Multinomial probabilistic selection
Section titled “Part 4: Multinomial probabilistic selection”Task
Use the multinomial function to select 10 tokens at random, from the entire vocab, with replacement. Print the 10 sentences along with the new-token probabilities. Run the code multiple times to observe the differences.
You cannot input the raw logits into multinomial function, because they contain negative numbers (see error #4 from Part 2). Instead, you input the softmax-transformed logits. Here is an example of my results.
I don’t want to grow” into” (2.18%) I don’t want to grow” any” (1.47%) I don’t want to grow” your” (0.83%) I don’t want to grow” up” (33.87%) I don’t want to grow” them” (0.39%) I don’t want to grow” a” (4.36%) I don’t want to grow” or” (0.25%) I don’t want to grow” this” (1.72%) I don’t want to grow”."" (0.37%) I don’t want to grow” in” (2.07%)
Each time you run the code, you’ll get different results. I hope you’ve made the following observations:
-
The probabilities of each token are always the same (that is, the probability of “ up” is always 33.87% because that value comes from the softmax probabilities, not from the multinomial function.
-
Although you get different results each time you run the code, the high-probability tokens tend to keep showing up in the list.
A chatbot running multinomial token selection would select whatever is the top token in that list, even if it’s not the token with the highest logit.
Part 5: Top-k sampling
Section titled “Part 5: Top-k sampling”Here’s the thing about multinomial sampling from the entire vocab: It is possible to get senseless results like “I don’t want to###”. The probability of picking the ### token (index 21017) is 10^(−6)%. That’s very small, but not zero. And chatbots can generate a lot of tokens.
Therefore, the idea of top-k sampling is to sample randomly — but only from the top-k tokens.
Task
Find the tokens with the 10 largest logits. Print the token indices, softmax-probabilities, and token strings, as you see below.
Calculate the total probability mass explained by the top 10 tokens.
Will you get different results each time you run the code? Think of your answer before confirming it.
Here are my results; yours should match exactly.
I don’t want to grow ___
510 (33.9%) is " up" 616 ( 7.4%) is " my" 257 ( 4.4%) is " a" 1165 ( 2.3%) is " too" 656 ( 2.2%) is " into" 262 ( 2.1%) is " the" 287 ( 2.1%) is " in" 428 ( 1.7%) is " this" 340 ( 1.6%) is " it" 1468 ( 1.5%) is " old"
The top 10 options account for 59.1% of the probability mass.Identifying the top-10 is a deterministic procedure; each time you run the code you’ll get identical results. Of course, the results will differ if you use a different prompt or a different LLM.
These top-10 tokens account for 59% of the probability distribution. That is quite high, considering that 10 tokens is 0.019% of the vocab.
These 10 tokens do not form a probability distribution, because their probabilities do not sum to 100%.
Task
Renormalize the top-10 raw logits back into softmax probabilities to form a new probability distribution of only the top-10 values.
Use the multinomial function to generate 10 new sentences by sampling from the top-10 distribution.
Be careful here: The re-normalization is based on the raw logits from the top-10 tokens, not on the softmax probabilities that were calculated based on the entire vocab.
My results are below. The ordering of your results will differ, although the probability values should match.
I don’t want to grow” a” (7.39%) I don’t want to grow” the” (3.52%) I don’t want to grow” up” (57.35%) I don’t want to grow” in” (3.50%) I don’t want to grow” my” (12.52%) I don’t want to grow” this” (2.91%) I don’t want to grow” old” (2.55%) I don’t want to grow” too” (3.89%) I don’t want to grow” into” (3.70%) I don’t want to grow” it” (2.67%)
Part 6: Top-p sampling
Section titled “Part 6: Top-p sampling”Top-p sampling is also called “nuclear sampling.” The procedure is similar to top-k sampling, except the set of high-probability tokens from which to sample is created by finding the minimum set of tokens that accounts for p% of the probability distribution.
Task
Find the minimum set of tokens that collectively explains p = 90% of the softmax-logit distribution. (Hint: consider sorting and taking the cumulative sum.)
Print the number of tokens to get to 90% probability.
Re-normalize those probabilities to create a probability distribution and use the multinomial function to randomly generate new tokens, as you did with Part 5.
You should find that 282 tokens accounts for 90% of the probability (if you got 281, then keep reading to learn about that off-by-one discrepancy). That’s a much larger pool of potential tokens to select compared to the top-k approach. And if you would use p = 99%, that count would increase to 6,432.
Below are example results; as with the top-k sampling, remember that the renormalization is based on the raw logits. You shouldn’t softmax-transform the set of softmax probabilities.
I don’t want to grow” up” (37.63%) I don’t want to grow” within” ( 0.02%) I don’t want to grow” those” ( 0.14%) I don’t want to grow” with” ( 0.40%) I don’t want to grow” a” ( 4.85%) I don’t want to grow” his” ( 0.16%) I don’t want to grow” apples” ( 0.05%) I don’t want to grow” on” ( 0.65%) I don’t want to grow” back” ( 0.51%) I don’t want to grow” more” ( 0.49%)
You’ve seen the probabilities change with each sampling method. For example, the token “ up” had probabilities of 33.9%, 57.3%, or 37.6%. The raw logits hadn’t changed; what had changed is how many other tokens were included in the softmax calculation. That’s a feature of softmax: The probability of a given token depends not only on the logit value of that token, but also on the distribution of all other tokens under consideration.
Here is a point of ambiguity when implementing top-p sampling: Should you consider the tokens before p% or just after p%? For example, if 281 tokens accounts for 89.9% probability while 282 tokens accounts for 90.1%, do you consider the “nucleus” to be 281 or 282?
This may seem like a minor and inconsequential point, but it could cause errors, for example if the top token already accounts for 91% probability. Thus, it’s better to include the first token that exceeds the threshold (thus, 282 tokens instead of 281).
Part 7: Chat with GPT-2
Section titled “Part 7: Chat with GPT-2”Let’s build a chatbot!
Well, OK, truth be told, this isn’t really going to be a chatbot. But you will see the core method of how chatbots work.
Task
Start with a user-defined prompt. You can continue working with the prompt we’ve been using so far, or write a new one.
In a for-loop over 15 iterations, tokenize the text and push it through the model. Implement one of the probabilistic token-selection techniques that you just learned about (multinomial, top-k, or top-p) to pick a new token. Append that new token onto the text. In the next iteration of the for-loop, the text is now one token longer.
Print out the text at each iteration so you can watch the text being generated one token at a time.
Below is one of my results. I’m printing only the first seven iterations.
Prompt : I don’t want to grow Iter. 1: I don’t want to grow up Iter. 2: I don’t want to grow up just Iter. 3: I don’t want to grow up just yet Iter. 4: I don’t want to grow up just yet. Iter. 5: I don’t want to grow up just yet. We Iter. 6: I don’t want to grow up just yet. We have Iter. 7: I don’t want to grow up just yet. We have to
In real chatbot interactions, the initial user prompt is removed before being displayed on screen. But behind the scenes, this is how chatbots work: take in a token sequence, generate a new token based on the logits from the final token, append that new token, and repeat the process.
A final minor comment about the code: Tokenizing a large text can be slow, yet in my code solution I re-tokenize the text with each new token generation. That’s fine for a small example but something to avoid in applications such as real-time chatting. It’s more efficient to leave the tokens as an integer sequence and then decode after token generation has completed.
Bookmark
4.18 Project 18:
Section titled “4.18 Project 18:”Token prediction accuracy
LLM evaluations are difficult, complicated, and nuanced, because LLMs are complex, generative, and capable of performing many tasks. There are quantitative measures like token prediction accuracy (Project 18), loss (Project 19), and perplexity (Project 20); but those measures fail to capture qualitative features like coherence and flow, historical/legal/medical/ scientific accuracy, creativity, hallucinations, and so on. Many LLM evaluations are done by humans reading and rating LLM outputs.
The focus of this project is token prediction accuracy, which simply quantifies the model’s ability to correctly predict the next token. That seems straightforward — next-token prediction is literally what causal autoregressive LLMs are trained to do.
However, you will discover in this project that prediction accuracy is not so straightforward. That is a primary motivation for using more sensitive measures like negative log-likelihood loss and perplexity, which you’ll learn about in upcoming projects.
Part 1: Token prediction
Section titled “Part 1: Token prediction”The goal of Part 1 is to introduce you to the implementation of categorical token prediction, which will be the foundation for the rest of the project.
Task
Import GPT-2 and its tokenizer.
Tokenize the sentence “Cubism is an art movement that sparked innovations in music and architecture” and print out a table of its tokens and token indices.
Run a forward pass and extract the logits for token position index 5 (starting from an index of 0, so this is actually the 6^th token position), find the token with the maximum logit, and visualize as in Figure 4.10.
Determine whether the model prediction is accurate. Consider whether the analysis is incomplete because it’s based on raw logit values instead of softmax probabilities.
All words in this sentence are encoded as one token with a preceding space, except the first, which was split into Cub and ism.
Remember that the logits at position N are the predictions for token N + 1. Thus, the 6^th token in the text is movement, but the logits shown in the figure below are the predictions for the word that.
Figure 4.10: Scatter plot of all logit values for one token position, with the maximum prediction indicated with a green circle.
In this case, the model made an accurate prediction: The scatter plot shows the logits for the token position for “ movement”, and the largest-valued logit corresponds to the token “ that”, which was the next token in the sentence.
Is this a trivial result? Actually no, not at all. Autoregressive LLMs like GPT have time-causal masks built in, which means that when the model processes the token for “movement,” it has no access to the tokens that come next. The mathematical implementation of that causal mask is quite simple (and it involves softmax!) and you’ll learn it in Chapter 6. But the point is that GPT-type models can attend to the current and previous tokens, but not tokens that come later, even if they are in the input token sequence. (Models trained for classification like BERT don’t have that causal mask. More on this in a later project.)
The last piece of the task was to determine whether this analysis should have been done on softmax probability values instead of raw logits. The answer to that question is No, it doesn’t matter. Softmax is a monotonic transformation, so the largest-logit token is also the largest-softmax token. Transforming to softmax would produce the same result using additional calculations.
Anyway, the upshot of Part 1 is this: To calculate token-prediction accuracy, extract the logits from each token position, find the token with the maximum logit, and compare that predicted token against the subsequent token in the text. There is, obviously, no token after the final token in the sequence, and thus token prediction accuracy can be calculated for at most N − 1 tokens in an N-token sequence.
Part 2: Per-token predictions
Section titled “Part 2: Per-token predictions”Now you’ve seen one example of accurate next-token prediction. Are all tokens so accurately predicted?
You’re probably guessing that the answer is no, but let’s test this empirically. The goal of Part 2 is to evaluate token prediction accuracy using all tokens in the sentence, and then in Part 4 we’ll expand to a larger dataset.
Task
Loop over all tokens in the sentence and repeat the analysis implemented in Part 1. Print the sentence with the predicted token inserted using quotes. Indicate whether each prediction is correct (✓) or incorrect (X), and report the average accuracy.
Actually, you cannot loop over all tokens; you loop over all but the final tokens. My results are shown in Figure 4.11. I’ve omitted the tokens after the predictions, because GPT only uses previous tokens to generate predictions.
Figure 4.11: Predicting each token in a sequence.
15% accuracy seems really bad! On the other hand, many of the predictions actually seem reasonable (e.g., “art” instead of “architecture”).
In other words, many of the predictions are categorically incorrect but are grammatically and semantically correct. That presents a challenge for quantitative assessments.
Part 3: Top-k predicted tokens
Section titled “Part 3: Top-k predicted tokens”The goal of Part 3 is to follow-up on the idea that predicted tokens can be categorically incorrect while still being sensible predictions.
Task
Extract the logits from token position 5 (same as in Part 1), find the top 10 logits and print out the sentence up to those logits, surrounded by quotes.
Be mindful that if you used the same variable names for Parts 1 and 2, you might need to rerun some code. Below are my results; notice that without seeing the rest of the sentence, all 10 of the possibilities could be correct.
Original text:
Cubism is an art movement that sparked innnovations in music and architectureGPT-2 predictions:
Cubism is an art movement" that" Cubism is an art movement"," Cubism is an art movement"." Cubism is an art movement" and" Cubism is an art movement" which" Cubism is an art movement" in" Cubism is an art movement" based" Cubism is an art movement" founded" Cubism is an art movement" of" Cubism is an art movement" with"I asked you to print the text only up to the target and not thereafter, because the model’s predictions of each token depend on the preceding tokens. So we wouldn’t expect the token that comes after the quoted tokens in the list above to be the same.
The upshot of this exercise is that categorical accuracy is easy to explain and easy to calculate, but should not be used as the sole measure of LLM capabilities.
Part 4: Token prediction accuracy in Wikitext
Section titled “Part 4: Token prediction accuracy in Wikitext”There are two goals to Part 4: (1) introduce you to the Wikitext dataset, and (2) test token prediction accuracy in a larger dataset.
You can import the Wikitext dataset using the load_dataset function in the datasets library, which is provided by Hugging Face. They make many datasets available for training and evaluating deep learning models, including LLMs, computer vision models, and more.
The online code file shows how to import a part of the Wikitext dataset. That code imports over 287,000 tokens. That may seem like a very big dataset. It’s certainly more than enough for our purposes here, but is quite small for a rigorous professional evaluation, and certainly not nearly enough to train an LLM from scratch.
The online code file also introduces you to the organization of the dataset. Spend a few moments to explore the dataset.
Task
Find and report the maximum token sequence length of the GPT-2-small model. It’s listed in the model.config information. The maximum sequence length is the largest number of tokens that a model is able to process in one sequence.
Push one maximum-length token sequence through the model to get the output logits. In a for-loop over tokens, calculate and report token-prediction accuracy. Visualize the accuracies in a scatter plot as in Figure 4.12.
GPT-2 can accept up to 1024 tokens in one sequence. As you learned in Chapter 2, that’s a very small context window for any real applications. The context window of modern chatbots like ChatGPT is in the hundreds of thousands to millions of tokens.
Of the first 1024 tokens in the Wikitext dataset, 528/1023 (51.61%) were accurately predicted.
Figure 4.12: Per-token prediction accuracy. Small random y-axis jitters were added to improve visibility of the density of the scores.
You can inspect the scatter plot to see whether there are continuous regions of high or low accuracy, which would indicate that parts of the text are more or less predictable. For example, parts of the text with technical terms, titles, citations, and proper nouns are more difficult to predict.
(Optional) If you want to try larger sample sizes, you can wrap this code into another for-loop, or use multiple sequences in batches. I’ll introduce creating batched inputs in Project 21.
Bookmark
4.19 Project 19:
Section titled “4.19 Project 19:”LLM loss function
LLMs can process and generate language because they are trained on enormous text datasets such as the Internet, books, scientific journal articles, and textbooks.
The objective of the model training is to minimize the loss, where the loss is the output of the loss function. There are several loss functions used in ML, depending on the nature of the model and the data. For training LLMs, the most important loss function is called negative log-likelihood (a.k.a. cross-entropy). It is defined as the negative logarithm of the model’s conditional probability of selecting the correct next token, given all previous tokens:
where y^∗ is the target token. Probabilities are between zero and one, so their logarithm is negative. The negative sign therefore flips the log-probability to positive, and thus minimizing the loss involves maximizing the probability that the model predicts the target token. To make this more concrete: Imagine we give the prompt A common way to learn a programming language is to output the words “hello. If the logit for the final token position has a 99% probability associated with the vocab token “ world”, then the loss would be around .01. On the other hand, if the probability for that token were 10%, then the loss would be around 2.3.
Contextual information from previous tokens is already incorporated into each logit via the attention and MLP adjustments, which you’ll learn about in the next three chapters. Therefore, in practice, the single-token loss is calculated using only the log of the softmax-probability of the target token:
Where z is the vector of raw output logits, σ is the softmax transform, and ^∗ is the target token index. Calculating single-token loss in practice involves translating Equation 4.11 into PyTorch code.
But loss functions aren’t only used to train models; they’re also used to evaluate models. The idea is simple: The lower the loss, the better the model. That’s a major improvement over categorical accuracy in the previous project, because the loss provides a continuous measure of performance that is much more sensitive than binary categorical accuracy.
On the other hand, evaluating generative AI is not so straightforward: A capable LLM doesn’t simply predict target tokens; it produces text that is coherent, helpful, factual, unbiased, and so on. Thus, as with the previous project, keep in mind that simple quantitative measures of performance are meaningful and insightful, but cannot be used as sole indicators of LLM usefulness, capabilities, or safety.
The main goal of Project 19 is to calculate the loss manually using NumPy and PyTorch functions.
Part 1: Manual negative log-likelihood loss
Section titled “Part 1: Manual negative log-likelihood loss”The goal of Part 1 is to build intuition for the loss function by coding it manually.
Do this part of the project using NumPy, not PyTorch.
Task
Define a NumPy array with values [-1,2.3,.1]. This is a simulation of model output logits with a vocab of three elements. Calculate the log-softmax transform of that array by translating the softmax formula you learned in Project 16 (Equation 4.8; page §).
Calculate three values of negative log-likelihood loss, simulating when index 0 is the correct result, when index 1 is the correct result, and when index 2 is the correct result. The logit and log-softmax values remain the same; only the “correct” category label changes.
Print your results as in the text below.
Raw model outputs: [-1. 2.3 0.1]
Log-softmax model outputs: [-3.43774803 -0.13774803 -2.33774803]
Loss is 3.4377 when correct output is index “0” Loss is 0.1377 when correct output is index “1” Loss is 2.3377 when correct output is index “2”
Why do the loss values differ? Consider that when index 0 is correct, the model wasn’t just technically incorrect, it was qualitatively terrible: The first logit should have been the largest, but it was negative. When the correct answer is index “1”, the model was technically correct (index “1” had the highest logit), but the loss guides the model not only to be categorically correct, but also to suppress activations of the incorrect responses.
Also note that the loss values are simply the negative log-softmax probability of the target category, following Equation 4.11.
Part 2: NLLLoss in PyTorch
Section titled “Part 2: NLLLoss in PyTorch”This part is conceptually easy: reproduce the results of Part 1 but using PyTorch instead of NumPy.
Task
Create a loss function instance of the class nn.NLLLoss. Repeat the loss calculations from Part 1 but use that PyTorch instance instead of direct calculations. Confirm that the output matches that of Part 1.
Some general advice when you’re using and learning about classes in Python: Use the dir() function to print out the list of attributes of the instance to see the properties and methods associated with that variable.
loss_function = nn.NLLLoss() dir(loss_function)
I won’t print the list of attributes because it’s long and most of it is irrelevant for our purposes here. I also won’t show the output of the task because it’s identical to what I printed in Part 1.
The nn.NLLLoss class expects the input to be log-softmax values, not raw logits. Thus, you need to softmax-transform the logits (in this case, the three numbers), and then log-transform those probability values. In practice, you can use the function F.log_softmax. This function requires specifying the dimension along which to calculate the softmax; you can use dim=-1 when the input has only one dimension.
The main challenge — and the important skill practiced here — is figuring out how to use PyTorch classes and datatypes.
An aside on extracting numbers from PyTorch tensors You will often need to cast PyTorch results into NumPy or regular Python ints or floats. If the PyTorch tensor contains only a single number, you can use the method .item(). For example,
T1 = torch.tensor([3.4]) T1.item()
The second line of code extracts the number 3.4 as a regular Python float, which you can then use, for example, to populate a NumPy array.
On the other hand, the .item() method produces an error if the tensor contains more than one number. The online code file shows examples of getting these errors.
In these cases, you can use the .numpy() method to cast a PyTorch tensor into a NumPy array. Again, check the online code file for a demo. You’ll see the .item() method again in Project 40 when moving data from the GPU back to the CPU.
Part 3: Cross-entropy loss for next-token prediction
Section titled “Part 3: Cross-entropy loss for next-token prediction”The goal here is to calculate the average loss during next-token prediction.
Task
Import the GPT-2 model and its tokenizer. Tokenize the text in the online code file (it’s lyrics to the Beatle’s song In my life), and confirm that there are 28 tokens.
Create a vector that contains the target token for each token in the text. Remember that the goal of the model is to predict the subsequent token, Thus, the table is as simple as associating each token t + 1 with token t. Print out the table as below.
I’ve printed only the first few lines. The main point is to confirm that the targets are simply the token indices, offset by one position. Thus, the first token’s target is the second token, the second token’s target is the third token, and so on. The final token must be omitted from the table, because it has no next-token.
Input | Target -------+--------
1858 | 389 389 | 4113 4113 | 314 314 | 3505 3505 | 477 477 | 616Task
Run a forward pass with the tokens, and extract the logits for all but the final tokens. Log-softmax-transform the logits. Confirm the sizes of the log-softmax and target tensors, as I report below.
Use the loss function you defined in Part 2 to calculate the loss.
Below are the sizes of the logits and targets.
Shape of logits: [27, 50257] Shape of targets: [27]
The output of the loss function is 4.0177.
In Parts 1 and 2, there was one vector (with a vocab of three elements) and thus one loss value. But here we have 27 vectors and still only one loss value. Were you expecting 27 loss values for each token prediction? If so, then think about why the result here was only one number. And if you expected only one number, then what was your expectation based on?
Part 4: Manual loss calculation
Section titled “Part 4: Manual loss calculation”There are three goals to Part 4: (1) calculate the loss manually, (2) interpret and visualize the single-token losses, and (3) understand why the 27 tokens produced only a single loss value.
Task
Calculate and store the per-token negative log-likelihood loss value in a for-loop over all but the final tokens. Use NumPy calculations as you did in Part 1; don’t use the PyTorch loss function you used in Parts 2 and 3.
Visualize the per-token losses in a bar plot as in Figure 4.13. The color of the bars comes from indexing the magma colormap with min-max-scaled per-token losses.
Determine whether the sum, median, or mean of the token loss functions corresponds to the output of the PyTorch loss function (4.0177).
The bar plot reveals which tokens the model was better at predicting.
Figure 4.13: Bar plot depicting per-token prediction accuracy. The color is mapped onto the loss value (same as the y-axis height).
Be careful when interpreting this graph, because the correct interpretation depends on how the visualization is done. Notice that the x-axis tick marks begin with “are” and not “There”, and notice that the final x-axis tick is “.” and not “remain”. Thus, the way I’ve coded this figure, the y-axis is the loss of predicting the token in the current x-tick based on the previous token. You could alternatively plot the loss of the current token for predicting the next token.
These results show that some tokens are easier for the model to predict. For example, the loss for “life” is quite small, because the model considered “life” to be highly likely to follow “my” (and all the tokens preceding). On the other hand, the model had difficulties predicting that “forever” would follow “some” (that’s a sensible result considering that “Some forever” makes for poetic song lyrics but is grammatically unusual).
Part 5: Using the model’s internal loss calculation
Section titled “Part 5: Using the model’s internal loss calculation”Hugging Face LLMs have an optional input that allows you to specify the targets in order to get the model-calculated loss in the output.
Task
Run a forward pass through the model using the same tokens as in previous parts. Figure out the optional input argument to obtain the loss value of 4.0177 in the output.
The optional input argument is labels= with the actual tokens. That is, the models will internally shift the tokens to create target vectors. Here’s how it looks in code.
outputs = model(tokens,labels=tokens) outputs.loss
The outputs.loss value is 4.0177, matching the results using manual and PyTorch calculations.
Part 6: Expected loss from random tokens
Section titled “Part 6: Expected loss from random tokens”What is the expected loss of an LLM for a random token sequence? That is, what would you expect the loss to be if you prompted the model with a completely random sequence of tokens?
Task
Think of the expected loss of an LLM. That is, what would be the value of L_t from Equation 4.11 for random tokens? Hint: think about the probability of choosing any token at random given the vocab size.
Calculate your expectation using PyTorch and store as a variable for later comparison. Note that this task produces a theoretical expected result; you don’t need an LLM or tokens to implement this calculation.
The answer to this question is actually trickier than you might initially think. Perhaps you came up with the following equation:
where N_v is the vocab size. That calculation gives an expected loss of 10.825 for GPT-2. However, it’s not the expected loss of a trained model like what we download from Hugging Face. I’ll explain why, but first I want you to demonstrate empirically that the loss of random tokens is not 10.825.
Task
Generate a random sequence of 1024 tokens between 0 and the vocab size. In other words, any of the 50,257 tokens is equally likely to be selected in any random order. Push the tokens through the model and calculate the loss.
Repeat that procedure 10 times to get 10 losses from 10 different random token sequences. Visualize the losses and the expected loss as in Figure 4.14.
The figure shows that the empirical loss is around 12 — consistently higher than the expected loss. Why is that the case?
Figure 4.14: Each marker is the average loss from predicting 1023 random tokens. Horizontal dashed line is the “expected” loss from an untrained model with random weights.
Here’s the deal: A completely brand-new untrained model with randomized weights has an expected loss following Equation 4.12, but a trained model does not assign equal probability to all tokens. Some tokens are more frequent than others (e.g., “the” is more frequent than “###”), which means the model is more likely to predict certain tokens than others. Furthermore, the random token sequences lack statistical patterns that LLMs learn during training.
Final comments for this project
Section titled “Final comments for this project”It may seem redundant to have multiple ways to calculate the same result — in this case, prediction loss from single tokens or the average of a sequence. In some sense, that’s true, and being able to solve the same problem in multiple ways risks adding confusion and uncertainty.
But on the other hand, the diversity of analysis methods allows you to craft bespoke analysis pipelines. It gives you freedom to explore, experiment on, and customize models in ways that would be difficult or impossible if you could only use whatever functions the library developers coded.
Bookmark
4.20 Project 20:
Section titled “4.20 Project 20:”Perplexity over sequences, texts, and models
Perplexity is a way to quantify an LLM’s ability to predict tokens. It’s less stringent than categorical accuracy and closely related to loss. Here’s the formula (ŷ^∗ is the softmax probability of the target token):
Perplexity can be calculated for individual tokens by setting N = 1, but single-token perplexity is noisy and highly variable, and therefore it’s more common to average the loss across N tokens, where N can range from hundreds to millions.
Perplexity values closer to zero indicate better token-prediction capabilities of the model. Although that is an important indicator of a model’s training performance, there’s more to a useful language model than just predicting tokens, as I discussed in the previous project.
To help you interpret perplexity, I created a small simulation with five scenarios. Imagine a model with a vocab of four tokens, and the final token is always the correct answer. Figure 4.15 shows the logits for each option in the different scenarios, with the perplexity score (ppl) underneath.
Code to produce this figure is in the online code file for this project, before the code for Part 1.
Figure 4.15: Simulations to illustrate that perplexity depends both on categorical accuracy and the separation of the logits to the target token (“targ”) relative to the rest of the vocab.
This figure illustrates several interpretational features of perplexity.
-
The model chose the categorically correct token in both scenarios “A” and “B”, but perplexity is higher in “B” because there is less separation between the target and non-targets.
-
From a strict categorical accuracy perspective, the model is equally incorrect in scenarios “D” and “E”, and yet perplexity is orders of magnitude higher in “E”. That’s because the model is “more wrong” compared to scenario “D”.
In other words, perplexity is a continuous measure of graded performance, and thus is both more sensitive and more informative than categorical accuracy.
In the rest of this project, you will learn how perplexity is implemented, and you will explore how much it can change within and across different texts, different sequence lengths, and different models.
Using the GPU As I wrote in Chapter 1, I have tried to make most of the projects in this book run on CPUs to make the learning easier and more accessible to readers without access to powerful compute resources. However, this project involves many forward passes on several different models. I strongly recommend running this project on a GPU if you have one available. If you don’t have a GPU, you might want to omit some of the calculations, such as the longest sequences (Part 3) or the largest models (Part 5).
Part 1: Perplexity over “time”
Section titled “Part 1: Perplexity over “time””By “time” I’m referring to the position in the text sequence, which corresponds to time if you think about reading a text from start to end.
The goal of Part 1 is to calculate perplexity in GPT-2-small over segments, and then average perplexity in two ways.
Task
Import the GPT-2 model and its tokenizer. Switch the model into eval mode and push it to the GPU. You’ll import several models later in the project, and use the variable name model in a function in Part 2, so I recommend naming the model here gpt2.
Import the text for the book Frankenstein’s Monster from gutenberg.org. You can find and copy code from Chapter 2, or check the online solution for the importing code.
Define a variable for the sequence length to use in averaging the loss as the maximum sequence length of the model (hint: check gpt2.config), and calculate the number of non-overlapping text segments that can be extracted from the text tokens.
You should find that the book comprises 114,216 tokens, the maximum sequence length is 1024, and the number of non-overlapping segments is 111.
Now the idea is to calculate and visualize the perplexity values of non-overlapping segments.
Task
Create a for-loop over segments, in which the following steps are implemented.
-
Define start and endpoint segment indices into the token sequence. Each segment is 1024 tokens long, and non-overlapping with the previous segment. (Hint: The start index can be defined as a multiple of the looping index variable.)
-
Extract the tokens from those indices and move them to the GPU.
-
Run a forward pass and get the outputs and the loss. You can implement that on your own as you learned in Project 19, although it’s easiest to use the labels= optional input argument when calling the model.
-
Accumulate the segment-averaged loss. This is the summation term inside the natural exponential in Equation 4.13. You only need to sum here; do not apply the natural exponential.
-
Implement the full Equation 4.13 on the loss from this segment, and store as an element in an array to be used for plotting.
-
After the for-loop, finalize calculating the total perplexity from Step 4 by implementing the rest of Equation 4.13.
Visualize the per-segment perplexity values, the perplexity of the accumulated losses (from Step 6), and the average of the per-segment perplexities (from Step 5), as in Figure 4.16.
The difference between Steps 4&6 vs. Step 5 is subtle: In Steps 4&6 you accumulate the losses and then apply the natural exponential only after all losses have been averaged (thus, the N term is 1024 × 111 corresponding to the total number of tokens in all segments); whereas in Step 5 you implement the full equation at each segment (thus, the N term is 1024).
Figure 4.16: Perplexity scores calculated in non-overlapping segments of 1024 tokens, and two ways of averaging perplexity across segments.
The per-segment perplexity values span a large range, from 50 to 250, with most values around 150-200. This variability reflects local text characteristics: Some text segments have simpler language and are easier to predict, while other segments contain chapter headings, tables, or text that is less predictable (e.g., containing lower-frequency words or proper nouns).
Also notice that the two ways of averaging give slightly different results. In general, summing over the losses first, and then dividing and taking the natural exponential (Steps 4&6) is preferred over averaging the per-segment perplexity (Step 5).
Note about calculating perplexity in practice The code you wrote here is valid but basic. A better implementation of perplexity for use in real evaluations would include batches, account for padding and other special tokens in the averaging, and use partially overlapping segments to increase stability. But we will keep things simple here in the interest of using perplexity as a tool to learn about LLM outputs, as opposed to developing a professional-grade evaluation pipeline.
Part 2: A perplexity function
Section titled “Part 2: A perplexity function”The goal of Part 2 is to write a Python function that calculates and returns a perplexity score, based on tokens, an LLM, and a sequence length that you provide as input.
You’ll use this function for the rest of the project to compare perplexity scores for different texts, sequence lengths, and models.
Task
Create a Python function that takes three inputs: a token sequence, a model, and a sequence length. Inside the function, calculate perplexity using the code you developed previously (use the accumulated loss described in Steps 4&6). The function should return the perplexity score.
Check the variable names carefully: the function needs to use the tokens, model, and sequence length provided as inputs — not global variables defined in the previous Part.
I set the model and sequence length parameters to default to GPT-2-small and 1024, respectively.
When you’ve written the function, confirm its accuracy by calling it with the same model, sequence length, and tokens that you used in Part 1. If you use the same parameters that I used, you should get 185.4063 as the output of this function, and as the result of the code from Part 1.
Part 3: Impact of sequence length
Section titled “Part 3: Impact of sequence length”The goals of the rest of the project are similar: calculate perplexity scores while selectively manipulating one variable. Here in Part 3, that variable is the sequence length.
Task
Call the perplexity function six times using the same tokens and the same model, but sequence lengths of 2^N for N = [5,6,7,8,9,10]. Report the results as text output, and visualize the results in a bar plot as in Figure 4.17.
Here’s the text output:
Sequence length 32 has perplexity 804.61 Sequence length 64 has perplexity 460.26 Sequence length 128 has perplexity 307.69 Sequence length 256 has perplexity 240.91 Sequence length 512 has perplexity 204.77 Sequence length 1024 has perplexity 185.41
Perplexity clearly decreases with increasing sequence length. To color the bars in the figure, I min-max-scaled the perplexity scores and used the plasma colormap.
Figure 4.17: Perplexity scores from the same text using different sequence lengths.
Remember that smaller perplexity values indicate better model performance. Why does perplexity drop as the sequence length increases?
There are two reasons. One is that individual tokens can vary widely in their predictability. Therefore, per-token perplexity can range from near zero to the thousands, as I showed in Figure 4.15 (the demo figure at the beginning of this project). That’s why averaging over many tokens is preferred — it smooths out the losses to provide a cleaner and more stable estimate of perplexity.
The second reason is that models use context (previous tokens) to predict the next token. Longer sequences provide more context, which means more information the model can use to predict the next token.
Part 4: Perplexities in different texts
Section titled “Part 4: Perplexities in different texts”Now the goal will be to keep the model and the sequence length fixed, but use different texts.
Task
Find and copy code from Chapter 2 to import the 10 English novels from gutenberg.org. In a for-loop over the texts, import and tokenize the text, and calculate perplexity for each text. Use a sequence length of 1024.
Books have different lengths, which presents a confound for a direct comparison. Therefore, calculate the perplexity using only the first 50,000 tokens from each book.
Print the results and show in a bar plot as in Figure 4.18.
Here are my results:
Frankenstein has perplexity 197.82 GreatGatsby has perplexity 150.57 AliceWonderland has perplexity 94.99 RomeoJuliet has perplexity 269.73 HuckFinn has perplexity 148.10 HeartDarkness has perplexity 174.68 GrimmsTales has perplexity 94.35 EdgarAllenPoe has perplexity 65.67 WarOfTheWorlds has perplexity 213.25GulliversTravels has perplexity 163.35
The perplexities vary from 65 to 270. The perplexities are lower overall compared to the previous investigation on the impact of sequence length, but it’s still roughly a 4-fold change from the lowest to largest perplexity score.
Figure 4.18: Perplexity scores from the same LLM for different texts using the same number of tokens per text.
It is interesting to think about which texts have higher vs. lower perplexities. The highest is Romeo and Juliet. Most of GPT-2’s training corpus is modern English, so it makes sense that a play written in the late 16^th century is more difficult to predict.
Part 5: Perplexities in different models
Section titled “Part 5: Perplexities in different models”The goal here is to examine the perplexity scores of four different model variants while keeping the tokens and sequence length fixed for all models.
Task
Import four versions of GPT-2: small, medium, large, and xl. I recommend putting the models into a dictionary with keys corresponding to the model names and values corresponding to the models. That facilitates testing all four models in a loop.
Calculate perplexity of all four models using a sequence length of 1024 and the same tokens. I used the first 50k tokens from the final book in the for-loop from Part 4.
Report the perplexities and show in a bar graph (Figure 4.19).
There are several ways to store the four models, including giving each a separate variable name or storing them in a list or tuple. I recommended using a dictionary here partly to give you more practice with creating and working with Python dictionaries.
Here are the results.
Perplexity of 163.35 for GPT-2-small Perplexity of 77.96 for GPT-2-medium Perplexity of 294.24 for GPT-2-large Perplexity of 278.85 for GPT-2-xl
Curiously, the ratio of largest to smallest perplexity score is again around four.
Figure 4.19: Perplexity scores from different models using part of the Gulliver’s Travels book.
Are you surprised at the results? Perhaps you expected the bigger models to have lower perplexities?
One of the take-home messages of this project is that perplexity scores can vary considerably. Let’s try one more demo.
Part 6: Perplexities in different models (Wikitext)
Section titled “Part 6: Perplexities in different models (Wikitext)”I like using the books from gutenberg.org, but they’re old and not highly representative of the training data. Thus, here we will wrap up this project by using a more modern writing sample.
Task
Copy the code from Part 5, but use the Wikitext dataset instead of a gutenberg.org book. Import the “test” Wikitext dataset (see Project 18, Part 4), join the first 2000 characters from each text, and tokenize. Visualize the results in a bar plot as in Figure 4.20.
There are 136,702 tokens that I extracted from Wikitext. Here are the perplexities:
Perplexity of 29.77 for GPT-2-small Perplexity of 21.40 for GPT-2-medium Perplexity of 18.70 for GPT-2-large Perplexity of 16.91 for GPT-2-xl
Figure 4.20: Perplexity scores from different models using part of the Wikitext dataset.
These results are strikingly different from the other perplexity scores you’ve seen. In particular, they are much smaller, going down to just under 17 for GPT-2-xl. And they decrease monotonically with increasing model size.
Why such striking differences compared to the previous demos? GPT-2 models were trained on a large corpus of text, but a lot of those data were from Wikipedia and other websites that have a modern writing style.
Final comments
Section titled “Final comments”Perplexity is a simple measure of token prediction that can be calculated without access to model internals, as long as you have the final output logits.
On the other hand, perplexity scores depend on many factors and parameters of the analysis and dataset. Therefore, perplexity also provides insights into datasets and sequences, not only into models. This is why perplexity-based evaluations are based on pooling together results from many texts, and varied sources of texts.
Bookmark
4.21 Project 21:
Section titled “4.21 Project 21:”Predict token position with linear and logistic regressions
Here’s a question: If I give you single-token loss values, could you tell me whether the token is the first, second, third, etc., in the token sequence?
That’s the question we’ll address in this project. Along the way, you’ll learn about linear and logistic regressions, the differences between running regressions in the statsmodels vs. scikit-learn libraries, confusion matrices, train vs. test sets, and why the first token in a sequence is special for LLMs. It’s an action-packed project, so let’s begin.
Part 1: Create a dataset
Section titled “Part 1: Create a dataset”The main goal of the project is to use linear and logistic regressions to predict the token position based on the single-token losses. To do that, we need a dataset of single-token losses for many samples. Creating that dataset is the goal of Part 1.
We’ll use the HellaSwag dataset for this project. HellaSwag is a text dataset used for model evaluation. You’ll learn more about the dataset in Project 22; here you’ll just import it and create a batch of tokens.
Task
Import GPT-2 and its tokenizer.
Import the hellaswag validation set from the Hugging Face load_dataset library (same library you used to import Wikitext).
Create a “batch” of tokens to input to the model. A batch is simply a collection of token sequences, organized into a PyTorch tensor, that the model processes in parallel. In a for-loop over the first 500 text samples of HellaSwag, tokenize the text from the ctx_a key, and store the first six tokens. The result will be a 500 × 6 tensor of tokens.
Push the tokens through the model and check the size of the output logits.
All sequences in a batch must be equal length. By construction, that’s the case in this project. But there is no guarantee that all sequences are always equal-length for all datasets. Unequal-length sequences require pad tokens and attention masks. I’ll teach you about those in Project 23.
The output logits are of size 500 × 6 × 50257. That corresponds to the number of sequences in the batch (500), the number of tokens in each sequence (6) and the number of vocab items (50257).
LLMs like GPT make predictions about the next token by incorporating context information from previous tokens. That means that a longer history of tokens (the context window) provides more information for the models to make predictions, which in turn means that the models should be better at predicting tokens that appear later in a sequence. And that means that the losses should decrease with later tokens. That’s the idea that we will test here.
Now we have the per-token logits; the next goal is to calculate the per-token losses.
Task
Create a 500×5 NumPy array of losses. Remember that the logits are predictions about the next token, which means that the first token in a sequence cannot be predicted. Therefore, the five columns in the data matrix correspond to single-token losses for the first through fifth tokens, making predictions about the second through the sixth tokens.
To populate that matrix, create a double for-loop over sequences and tokens, find each target token index, and extract the loss as the negative log-softmax at the target token position.
You will also need an equal-sized matrix of ordinal positions for the regression analysis. That matrix is simply the integers 0, 1, 2, 3, 4 repeated 500 times. Flatten (vectorize) both data matrices to create 2500 × 1 arrays.
Finally, visualize the position-specific losses as in Figure 4.21.
The ordinal position matrix should look like this:
array([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], ...,You can print out the shapes of the losses, ordinal positions, and their flattened vectors, and get the following result:
Shape of losses: (500, 5) Shape of losses_flat: (2500, 1)
Shape of ord_position: (500, 5)Shape of ord_position_flat: (2500, 1)
And finally, you can visualize the data as in Figure 4.21.
Figure 4.21: Next-token prediction losses for different token positions. Bar heights in panel A depict the average loss, and the lines in panel B depict the distribution of loss values for each position.
Based on the means (the heights of the bars), it does seem like the losses are higher for the first token. But the distributions of losses are largely overlapping, especially for the later tokens. Visual inspection is informative and important, but subtle patterns in the data might be detected using statistical methods even if they are not visually obvious.
Part 2: Linear regression in statsmodels and scikit-learn
Section titled “Part 2: Linear regression in statsmodels and scikit-learn”Now for the first set of analyses: We will build a regression model to test whether we can predict a token’s ordinal position based on the loss value.
A linear regression is a statistical model of the data, in which the value of the dependent variable (in this case, the token ordinal position) is modeled as a function of an independent variable (in this case, the loss) and some constant offset (also called the intercept). Here’s the equation:
o_i is the ordinal position of the i^th token (integers 0 through 4), β_0 is the intercept (the expected position when the loss is zero), β_1 is the impact of the per-token loss on the predicted position, and 𝜖_i is the variability in the data that the regression doesn’t explain.
The goal of fitting a regression is to find the values of the βs that produce the closet match between the model predictions and the observed data. There are several algorithms for fitting linear regression models, and the most common technique is called least-squares. I will discuss the math of least-squares in Project 36; for now, you can focus on the concepts and implementations.
Linear regression is a workhorse of ML and statistics in countless applications. I’m including linear regression in this project because of its importance, but it’s actually not the most appropriate analysis for our question here. I’d like you to think about why that is the case, and then I’ll discuss the answer before moving on to logistic regression in Part 4.
Anyway, the goal of Part 2 is to perform a linear regression using two libraries: statsmodels and scikit-learn. You’ll see that the regression parameters match although the two libraries are designed for complementary purposes.
Task
Use the OLS method in the statsmodels library (often abbreviated to sm) to regress the flattened losses onto the flattened ordinal positions vector. The design matrix of the regression needs two columns: an intercept and the independent variable. The intercept is a column of 1’s and can be added using sm.add_constant, and the independent variable is the losses.
Print the regression summary. See how many details in the summary table you are familiar with — and keep in mind that there’s much more information in the table than what you need for this project.
Figure 4.22: Screenshot of statsmodels output.
The statsmodels summary table can be intimidating if you’re new to regression models. For our purposes here, there are three pieces of information to notice:
-
The “R-squared” value at the top right. R-squared indicates how much variance in the dependent variable (ordinal position) can be explained by the statistical model. In this case, it’s almost 10%. On the one hand, that’s fairly low — 90% of the token position information is unexplained — but on the other hand, the model is statistically significant (indicated by the Prob p-value being so close to zero), and the loss value itself contains no information about the token identity. So I actually find 10% to be fairly high given the model setup.
-
The const term about half-way down the table. This is the β_0 term in the regression equation. The intercept is mathematically necessary in the model, but it is often not insightful — it corresponds to the predicted token position when the loss is exactly zero, which never happens in the data.
-
The x1 term. This is the β_1 coefficient, and is the key regression parameter here. The value is negative and is statistically significant. That means that larger losses predict smaller ordinal positions. In other words, the loss decreases with later tokens.
Task
Use the LinearRegression function in the scikit-learn library. Check that the two β parameters are the same as those calculated by statsmodels.
If you encounter errors, check the shapes of the two input variables and the error message.
Scikit-learn does not provide a detailed statistical table like statsmodels does. The two libraries can implement the same analyses but are designed for different purposes. The statsmodels library is designed for detailed statistical investigations whereas the scikit-learn library is designed for ML predictions. In practice, you choose which library to use based on the goal of the application.
By the way, there is a subtle conceptual shift from Part 1 to Part 2: In Part 1 we analyzed loss as a function of ordinal position, and then in Part 2 we analyzed ordinal position as a function of loss. Thus, I swapped the dependent and independent variables. In many datasets, variables can either be the predicted or the predictor, depending on the hypothesis under investigation.
Part 3: Does linear regression reconstruct ordinal position?
Section titled “Part 3: Does linear regression reconstruct ordinal position?”The predicted data value in a regression comes from implementing Equation 4.14 with the fitted β values.
Thus, to generate a predicted ordinal position (), scale the single-token loss (L_i) by the regression slope and add the regression intercept. The two β terms do not have i subscripts, because those scale-and-shift terms are the same for all data samples.
Task
Use the predict method on the scikit-learn regression model object to generate predicted ordinal positions based on the losses. Visualize the true positions by the predicted positions as in Figure 4.23.
The code is simple but there is a conceptual issue with the analysis. Based on the plot and on your understanding of regression, think about why this analysis approach isn’t well suited for the problem.
An ideal result in Figure 4.23 would be data clusters at coordinates (0,0), (1,1), (2,2), (3,3), and (4,4). Any data points not at those coordinates are prediction errors.
Figure 4.23: Scatter plot of the true token position (x-axis) by their model-predicted positions (y-axis) from the regression model. Small x-axis jitters were added to facilitate visualization.
Here’s the issue with the results: Ordinal positions are… well, they’re ordinal. You cannot have a token in position 1.4327; it’s either in position 1 or 2. And yet the predicted positions are floating-point numbers.
This is not a bug in the code or a problem with regression. The issue is this: the dependent variable (token position) is categorical but the linear regression treats it as a continuous variable. In other words, the regression model doesn’t “know” that the data are categorical; it’s simply trying to find a linear relationship between the numerical values in the loss vector and the numerical values in the position vector.
So is a linear regression wrong here? Well, it’s not wrong per se — the analysis correctly identified the pattern of smaller losses with increasing ordinal position number. But it’s not most appropriate analysis.
Instead, a better analysis approach would be to treat the token positions as categorical, and predict the probability that each loss value is in each category. That’s exactly what a logistic regression is designed for.
Part 4: Fit a multinomial logistic regression
Section titled “Part 4: Fit a multinomial logistic regression”A logistic regression is conceptually the same as the linear regression: Build a simple mathematical model of the data and find the parameters that best fit the data. The difference is that a logistic regression is based on predicting category probabilities, expressed as pairwise log-odds between two categories.
p is the probability of data sample y_i belonging to one category, and k and j are a pair of categories. If you’re familiar with binary logistic regression, then the equation simplifies to the familiar .
There are several reasons for predicting log-odds instead of the probability itself, including that probability values are restricted to a narrow range (zero to one) whereas log-odds span all positive real numbers, and that optimization can be numerically difficult for numbers very close to zero whereas the log of very small positive numbers are stretched out.
Some algebraic manipulations yields the expression solved for each category probability:
Where k is each of K categories.
Importantly, the coefficients are softmax-transformed. Remember that one of the features of softmax is that the transformed values depend not only on their pre-softmax value, but also on the values of the rest of the vector. Thus, the value — and therefore also the interpretation — of any one β value depends on the values of the other coefficients. The practical implication is that you cannot interpret β values on their own as you can for a linear regression; instead, each per-class β value is interpreted relative to the rest of the model. In other words, relative instead of absolute interpretations.
Task
Fit a LogisticRegression model in scikit-learn. Use the lbfgs solver (it’s an optimization algorithm designed for multinomial regressions). Print the five intercept terms () and the five slope terms (), and visualize them in bar plots as in Figure 4.24.
Here are the beta parameters:
Intercepts (beta_0): [-1.561 0.314 0.180 0.408 0.65 ]
Coefficients (beta_1): [ 0.258 -0.047 -0.019 -0.067 -0.123]
Figure 4.24: Bar plots of the logistic regression coefficients for the slopes (panel A) and intercepts (panel B).
There are two noteworthy observations from these bar plots.
- The magnitude (absolute values) of the β parameters for position “0” is higher than the parameters for any other position. The numerical values of the coefficients depend on the data and on the other coefficients, and so they cannot be interpreted on their own. But relatively larger magnitudes do indicate better statistical predictability of the corresponding ordinal position.
- The slope (β_1) is positive for the first position and negative for the rest. This reflects relatively higher losses for position “0” and relatively lower losses for later positions.
Part 5: Categorical predictions
Section titled “Part 5: Categorical predictions”Because the coefficients are difficult to interpret in an absolute (isolated) sense, it is more insightful to use the coefficients to generate predictions. That is, if I gave you the per-token losses and the logistic regression coefficients, how accurately could you tell me which tokens were in which ordinal positions?
Task
Calculate category predictions using the method predict_proba. Print the size of the predictions matrix. The values in this matrix are probabilities of each token belonging to each category. Confirm that the probabilities for each token sum to 1.
The predicted category for each token is the position with the largest probability value. Calculate the predicted category for each token and visualize in a bar plot as in Figure 4.25A. What is the null-hypothesis prediction level?
Use the confusion_matrix function from sklearn.metrics to calculate a confusion matrix. The confusion matrix shows counts of true by predicted categories. Normalize the confusion matrix to percent of row-wise totals, and visualize as in Figure 4.25B.
I wrote TRAIN in the figure title because Part 6 will involve applying these logistic regression weights to unseen (“test”) data.
The prediction accuracy results are striking, and perhaps a bit puzzling. The prediction accuracy was quite high for the first token and the final token, and very low for the middle three tokens. The null-hypothesis value is the expected accuracy if there were no relationship whatsoever between loss and token position, and is 20% accuracy (because there are five categories). Thus, the prediction accuracies for the middle three tokens were below chance-level performance.
Figure 4.25: Prediction accuracy from the logistic regression, calculated and visualized separately per token position.
Why did that happen?
We can gain insight by examining the confusion matrix. But first let’s think about what that matrix shows and what an ideal result would look like. Each token has a true position (where it actually appeared in the token sequence) and a regression-predicted position. The confusion matrix simply counts the number of each pair. Transforming to percent by dividing by the number of data samples makes the numbers easier to read.
Therefore, the ideal result of a confusion matrix is large numbers (e.g., 100%) on the diagonal elements and small numbers (e.g., 0%) on the off-diagonal elements.
The first row (true position of “0”) looks great. The rest of the rows… not so great, except for the last row (position “4”). Basically what happened is that the logistic regression tried to binarize the solution, such that predictions were pushed towards the extremes. That likely occurred because there is a strong effect of increased loss for the first token but little differentiation among the later tokens.
Part 6: Test on new (untrained) data
Section titled “Part 6: Test on new (untrained) data”In ML — and especially in predictive modeling as we’ve done here — one always needs to be concerned with overfitting. Overfitting is a statistical term that refers to statistical models fitting noise or idiosyncratic patterns that do not generalize to new datasets.
There are several ways to minimize overfitting risk, with testing on new data being a popular method. The idea is simple: Fit the regression model on one dataset, then use those coefficients to make predictions in a different dataset. This is called a train/test split (there are some nuances like having an additional “development” set, but I’ll keep things simple here).
Fortunately, in natural language processing, it’s usually quite easy to obtain test sets, because there is a huge amount of data available.
The goal of Part 6 is to repeat the logistic regression prediction analysis on a test set.
Task
Get a new batch of data. Modify the code from Part 1 to exclude text that was used in previous parts.
Create a new dataset that has the same size (one batch of 500 × 6 tokens) as the training set — but don’t run a new logistic regression. Instead, calculate the predictions on the new data using the coefficients you obtained in Part 4.
Recreate a Figure like 4.25 but for the test data (shown here in Figure 4.26).
The findings are remarkably similar — in fact, the prediction accuracy was a bit higher for the first token, although we shouldn’t interpret that difference without further statistical comparisons. This indicates that we have identified a reproducible pattern in the data that is not attributable to overfitting the training dataset.
Figure 4.26: Same as Figure 4.25 but for the test dataset.
What does it all mean?
Section titled “What does it all mean?”There is clearly something different happening at the first token, as indicated by the larger losses. The reason is that the first token conveys very little information for predicting the next token.
For example, if I give you the word “The” and ask you what word comes next, you’d have no idea. But if I give you “The cat” then you still wouldn’t know for sure what word comes next, but that additional word narrowed the search space from thousands of possible words to perhaps a few dozen.
In fact, the first token in a sequence often produces unusually large values that become outliers in ML analyses. You’ll see this many times in later projects, and you’ll often exclude the first token from analyses. Indeed, the first token even has its own abbreviation: BOS (beginning of sequence).
Bookmark
4.22 Project 22:
Section titled “4.22 Project 22:”Evaluating models with HellaSwag
There are several goals of this project, including (1) learning about quantitative evaluations of LLM language capabilities and world knowledge through the HellaSwag dataset, (2) understanding how differences in model training can impact their capabilities, and (3) the McNemar statistical test for comparing binary outcomes.
Two warnings before we begin: Simple models like GPT-2 do not perform well on the HellaSwag evaluation; secondly, this evaluation is not suitable for BERT-style models. I’ll explain why that’s the case at the end of the project, but seeing the RoBERTa model perform poorly will be instructive as to the key difference between GPT-style (next-token prediction) and BERT-style (masked-token prediction) models.
GPU If you have access to a GPU, I recommend using it for this project.
Part 1: Import and compare GPT-2 and RoBERTa
Section titled “Part 1: Import and compare GPT-2 and RoBERTa”The goal of Part 1 is to import and compare four LLMs. It’s a great opportunity to gain more experience inspecting models and gathering meta-data from the model config attribute.
Task
Import four models: GPT-2-small, GPT-2-large, RoBERTa-base, and RoBERTa-large. The two GPT-2 variants use the same tokenizer, and the two RoBERTa variants use the same tokenizer. Make sure all models and tokenizers have interpretable variable names, e.g., gpt2_s and tokenizerG.
Switch the models to evaluation mode and move them to the GPU.
Write code to create the table below (Xfmr is “transformer”; the number of transformer layers).
Here’s the comparison table:
Model | Tokens | Emb.dim | Xfmr | Parameters -------+--------+---------+------+------------- GPT2-S | 50,257 | 768 | 12 | 124,439,808 GPT2-L | 50,257 | 1280 | 36 | 774,030,080 RoBA-S | 50,265 | 768 | 12 | 124,697,433 RoBA-L | 50,265 | 1024 | 24 | 355,412,057
GPT-2-small and RoBERTa-base are of comparable size in terms of the number of parameters and transformer layers. GPT-2-large has more than twice as many parameters as RoBERTa-large, more transformer layers, and a larger embeddings dimensionality.
Part 2: Import and explore HellaSwag
Section titled “Part 2: Import and explore HellaSwag”You imported and extracted text from the HellaSwag dataset in Project 21; here I will tell you more about it.
HellaSwag is designed to test an LLM’s world knowledge. As an example, consider the following two texts:
-
The boy went to the store. He was hungry so he bought a toy.
-
The boy went to the store. He was hungry so he bought a snack.
Both versions are grammatically correct, but your understanding of the world leads you to conclude that the second sentence is the better choice.
That’s the idea of HellaSwag. Each data sample has four versions of a short text that have the same beginning but different endings, and the goal of the evaluation is to calculate which of the four options is considered the “best choice” by the LLM. “Best choice” is quantified as the average (or sum) of log-softmax probabilities, with the idea that the sentence version with the highest probability is most consistent with the model’s world knowledge.
Task
Import the HellaSwag validation set using the load_dataset function in the datasets library. Examine one sample. Guess the meaning of the keys ctx_a, ctx_b, ctx, endings, and label.
Here’s a printout of the second data sample:
{’ind’: 92,
’activity_label’: ’Clean and jerk’, ’ctx_a’: ’A lady walks to a barbell. She bends down and grabs the pole.’, ’ctx_b’: ’the lady’, ’ctx’: ’A lady walks to a barbell. She bends down and grabs the pole. the lady’, ’endings’: [’swings and lands in her arms.’, ’pulls the barbell forward.’, ’pulls a rope attached to the barbell.’, ’stands and lifts the weight over her head.’], ’source_id’: ’activitynet~v_-lJS58hyo1c’, ’split’: ’val’, ’split_type’: ’zeroshot’, ’label’: ’3’}The ctx key is for “context,” and is the initial text that is shared across all four endings. The label is the index of the target answer.
In the next part, you’ll learn how the quantitative evaluation works, but before reading my explanation, I encourage you to think about how you would implement the evaluation.
Part 3: Visualize the evaluation process
Section titled “Part 3: Visualize the evaluation process”There are four steps to evaluating a model with the HellaSwag dataset: create the prompts, get the log-softmax probabilities from the raw logits, calculate the sentence-level probabilities, and test whether the top-ranked sentence matches the target.
Here in Part 3 you’ll use only one data sample to build the analysis pipeline, and then you’ll expand to many examples later in the project. You can reproduce my results exactly if you use sample 224.
Task
Create two prompts by concatenating the context with two of the four endings: one with the target ending and one with an incorrect ending. Tokenize the prompts using the GPT-2 tokenizer.
Here are my results.
Context:
"People watch a parade where people walk on front a marching band holding a banner and waving the viewers. a man"Correct ending:
"People watch a parade where people walk on front a marching band holding a banner and waving the viewers. a man cross the street holding a small flag and extend his hand."Incorrect ending:
"People watch a parade where people walk on front a marching band holding a banner and waving the viewers. a man wearing an orange jacket falls over from the fall, they help him up."From reading the text, you can see that the phrasing is awkward and not entirely grammatically correct. That is one of the criticisms of the HellaSwag evaluation, which I’ll discuss more at the end of the project.
Task
Run both prompts through the GPT-2-small model. Log-softmax transform the logits.
Create an array of log-softmax prediction values for each token. This is created using a for-loop over the tokens, in which the log-softmax corresponding to the next-token index is extracted. The result of this step will be two NumPy arrays comprising N − 1 tokens for each prompt, where the value in each element is the log-softmax probability of the subsequent token.
Calculate the sentence-level probability as the average of the log-probabilities for the ending tokens (exclude the context tokens). Print the scores and see whether the target ending has a higher probability than the non-target ending.
Answer the following questions: (1) What is the logic of summing the log-probability scores and then dividing by the number of tokens? (2) Is it necessary to exclude the context token probabilities?
I got the following result:
Target ending log-prob: -3.631Non-target ending log-prob: -3.704The target ending is higher, which means the model was correct in this data sample.
Why sum the log-probabilities? The idea is that we want to calculate the probability of the LLM “knowing” that the target ending is correct. That probability is the product of all the individual probabilities, but with such a large vocab and many tokens in the sequence, those products can get so close to zero that the risk of numerical precision errors is unacceptably high.
Fortunately, the logarithm has the neat property that products become sums. That is:
Summing logs is more numerically stable.
And why divide by the number of tokens in the ending? Here the reason is that the endings can differ in length. Shorter endings would have a bias over longer endings, and scaling the sum by the count (that is, taking the average) corrects for that bias. Over thousands of samples, that bias is likely to be non-systematic, but it still adds noise, which could be impactful in a small sample size.
As for whether the context tokens must be excluded: The context is identical for all options, so you might think that including the context would offset all options in the same way. However, if the endings have different lengths, then the context probabilities have a different impact on the different prompts.
Task
To gain visual intuition for the evaluation procedure, write code to create Figure 4.27.
Intuitively, the idea is that the log-probabilities (blue circles) are collectively higher than the red squares. Not every token probability is higher, but taken together, the model considers the target ending more probable than the non-target ending.
Figure 4.27: Visualization of the HellaSwag evaluation. Two token sequences have identical contexts but different endings; the sequence with the highest average log-probability is the one the model considers more likely.
Notice that the endings have different lengths.
Part 4: A function to test one HellaSwag sample
Section titled “Part 4: A function to test one HellaSwag sample”The goal of Part 4 is to create a Python function that takes three inputs — a HellaSwag sample, an LLM, and a tokenizer — and returns two outputs — a NumPy array containing log-likelihoods for the four endings and the target index. You’ll use this function to evaluate and compare the four LLMs in the rest of the project.
Most of this code for this function can be copied from Part 3, but be mindful that the code in Part 3 was written specifically for one LLM and two of the text endings.
But first, I need to teach you about padding when creating batches.
Batches of token sequences must be the same length (equal number of columns in all rows). But not all sequences have the same lengths. This issue is resolved by padding shorter sequences to match the length of the longest sequence.
Let’s say we want to create a batch of tokens from the following three texts:
texts = [ ’hello’, ’my name is’, ’Mike and I like purple.’ ]If the tokenizer has a defined padding token, then we can tokenize with padding. The GPT-2 tokenizer from Hugging Face does not have a default padding token, so we can set it to be the “eos” (end of sequence) token.
tokenizerG.pad_token_id = tokenizerG.eos_token_id
t = tokenizerG(texts,padding=True, return_tensors=’pt’)Notice that I inputted the list of texts directly into the tokenizer instead of using the .encode method, and I specified padding=True. In this case, the output variable is not just a PyTorch array of tokens, but instead is a dictionary with the following keys and values:
“input_ids”:
tensor([[31373,50256,50256,50256,50256,50256], [ 1820, 1438, 318,50256,50256,50256], [16073, 290, 314, 588,14032, 13]])“attention_mask”:
tensor([[1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 1]])The pad token is 50256, and the “attention mask” is 1’s for valid tokens and 0’s for pad tokens. The longest sequence has no pad tokens, and all other sequences are padded to match the length.
The pad tokens are not valid parts of the original sequence, so in analyses, you will need to ignore LLM data from the pad token positions.
Task
Create a function called oneHellaSample that takes a data sample, model, and tokenizer as input, and implements the following operations.
-
Extract the context, context length in tokens, and target answer.
-
Loop over all candidate endings, create the full prompts (that is, the context and the ending), and store all four prompts as strings in a list.
-
Tokenize the prompts by inputting the list of prompts into the tokenizer. Make sure to use padding to account for different sequence lengths.
-
Run all prompts in one batch. Extract the logits from the model outputs. If you’re running the models on the GPU, make sure to move the tokens to the GPU, and the logits back to the CPU.
-
Calculate the log-softmax probabilities from the logits.
-
Calculate the log-likelihoods of each ending. You can copy and adapt the code from Part 3, but be aware that shorter token sequences have padding tokens. You’ll need to exclude both the common context and the padding tokens when calculating the ending-level log-likelihood. The result of this step will be a four-element NumPy array that contains the log-likelihood for each sample ending.
-
Return the log-likelihood array and the index of the target ending.
Test your function on one sample to make sure it produces no errors or warning messages.
If you test on GPT-2-small and sample index 42, you should get the following result:
Log-likelihoods: [-2.944 -5.438 -3.174 -2.287] Target ending: 3 Model was correct!
Part 5: Test all four models
Section titled “Part 5: Test all four models”Now to test the four models on the same HellaSwag samples.
Task
Write a for-loop over N data samples. Inside the for-loop, call the oneHellaSample function four times for the four LLMs you imported in Part 1. Store the accuracy in a 4 × N NumPy array.
If you’re running the analyses on a CPU, set N to be small, e.g., 50. On a GPU, 1000 samples should take a few minutes.
Create two visualizations of the data. First, a bar plot of average accuracy for the four models, as in Figure 4.28. Second, a scatter plot of the number of models that got the target for each sample, as in Figure 4.29. This plot doesn’t show which models were correct, but it does reveal which data samples are relatively easy (all four models were correct) vs. difficult (all four models were incorrect).
I used 2× the accuracy value as an index into the plasma colormap for the bars.
Figure 4.28: Bar plot showing accuracy of each tested model.
For reference, modern LLMs score around 70-90%. The GPT-2 models perform relatively poorly, though greater than the chance-level performance of 25%. The RoBERTa models, on the other hand, performed quite poorly. I mentioned at the beginning of this project that BERT-style models are not suitable for HellaSwag — and here you see a nice demonstration of that. I’ll explain more about this at the end of the project.
Figure 4.29 shows the results in a different way: Here we are focusing on the samples, not on the models.
Figure 4.29: Scatter plot showing the number of models that correctly answered each HellaSwag item. Small random y-axis jitters were added to increase visibility of clustering.
The idea of an analysis like this is to explore the dataset and identify samples that might be too easy or too difficult. For example, imagine you want to improve the HellaSwag evaluation dataset. You could look at results like this (using more, and more capable, models) to adapt or remove samples for which all models are correct or all are incorrect: those samples are not diagnostic about model performance and therefore do not help distinguish the capabilities of different models. Quantitative evaluations can take a long time to run, and thus focusing the dataset on the most relevant samples can save hours to days of compute time.
Part 6: Statistical comparisons
Section titled “Part 6: Statistical comparisons”The final part of this project is to evaluate whether the average accuracies shown in Figure 4.28 are statistically significantly different across the models.
For this comparison, we can use the McNemar test. The McNemar test evaluates differences in pairwise proportions between two groups when there are dependencies between the groups (the models are independent but they process the same text samples).
The McNemar test is based on a 2 × 2 table where the off-diagonals are the counts of differentiated test performance — how often model “A” is correct while model “B” is incorrect, vs. how often model “A” is incorrect while model “B” is correct. The normalized difference between those values is distributed as a χ^2 statistic under the null hypothesis, and we can get a p-value that indicates statistical significance.
Task
In a double for-loop over all pairs of models, count the number of samples where model “A” was incorrect while model “B” was correct, and put that number into the upper-right element of a 2 × 2 matrix initialized with zeros. Then count the number of samples where model “B” was incorrect while model “A” was correct, and put that number into the lower-left element.
The McNemar test can be run using the mcnemar function in the contingency_tables module of the statsmodels.stats library. Store the model mean accuracy differences and the McNemar p-value. Show the results as in Figure 4.30, where the color and numbers correspond to mean accuracy differences, and the asterisk indicates that the p-value was less than .05/6 (that’s the significance threshold with Bonferroni correction for multiple comparisons).
Each of the six comparisons is statistically significant. p-values can be very small when sample sizes are very large. I ran my code using 1000 samples; you will get some non-significant differences if you use smaller samples sizes.
Figure 4.30: Heatmap showing results of pairwise comparisons across the four models. Numbers indicate the difference in accuracy in percentage points, and asterisks indicate statistically significant differences (Bonferroni-corrected).
One tip about creating images in Matplotlib: You can prevent a block from being colored by setting its value to NaN. In some cases, that is better than setting the value to zero and having default values in the matrix interpreted as an interpretable value of zero in the heatmap.
Model architecture matters
Section titled “Model architecture matters”Why did RoBERTa perform so poorly in this evaluation? It’s not that the RoBERTa models are generally incapable. Quite the opposite: BERT-style models can give high performance on other evaluations and are regularly used in commercial applications. It’s also not a difference in architecture: BERT-style models have very similar transformer blocks as GPT-style models, as you’ll learn in the next several chapters.
The key difference is in the training and the causal mask in the attention algorithm. RoBERTa is a masked token model, not a causal autoregressive model. The HellaSwag evaluation as it is implemented here assumes causal language modeling, where the models predict the next token given previous tokens. RoBERTa models aren’t designed for this task; they’re designed to predict masked tokens in the middle of sequences, not to generate sequences left-to-right.
In other words, HellaSwag is designed for causal language generative models like GPT-2, not masked token models like RoBERTa.
That’s not a problem with the HellaSwag evaluation, nor is it a problem with the RoBERTa models. But there is an important lesson here: Models are optimized for specific purposes and therefore must be evaluated based on that purposes. The next project highlights an evaluation used for BERT-style models.
Bookmark
4.23 Project 23:
Section titled “4.23 Project 23:”Measuring language biases
The goal of this project is to learn how to examine language-based gender biases in LLMs, such as considering “doctor” to be a male profession vs. “nurse” to be a female profession. But this project isn’t just about measuring bias; it’s about how to think about logits and how to design experiments to assess “hidden knowledge” that LLMs possess.
As an example, consider the following sentence: The doctor told the patient that ___ needs more tests to make a diagnosis.
Do you think the missing ____ word should be “he” or “she”? Well, given the topic of this project, I’d guess you’re thinking that it could be either: men and women can make equally good doctors. But certainly the word “doctor” is more associated with “he” than “she.” I’m not saying that that gender bias should exist or that it is a justified opinion; I’m saying that it is an existing cultural bias that exists in written language, and therefore might exist in LLMs. And to be clear: LLMs are not initialized to have biases, so any biases in LLMs are learned from data, which means they are learned from us humans.
The idea of testing for biases (in this example, a gender bias) in LLMs is to present a sentence to an LLM and measure the internally-calculated probabilities of choosing “he” and “she” in the position of the missing word.
Causal autoregressive models like GPT are designed to predict the next token given previous tokens. In contrast, masked-prediction models like BERT are designed to predict a missing token using previous and subsequent tokens. The sentences we’ll use in this project have relevant context both before and after the missing word, and therefore, we will use BERT.
Part 1: Import the BERT model and find the mask token
Section titled “Part 1: Import the BERT model and find the mask token”Before getting started on the experiments and data analyses, I’d like to introduce you to two features of the BERT tokenizer that are useful for this and later projects: the mask vocab token and a tokenizer method to find the index of one token.
Task
Import the BERT-large model and its tokenizer.
Tokenize the sentence “I like to eat [MASK] chocolate-covered raisins.” Print out a list of the tokens and their indices.
Find two attributes of the tokenizer: one that encodes the mask token string, and one that encodes the the mask token index. Print those two attributes by completing the following code: print(f’The mask token is “{}”, which is index #{}’)
Finally, re-tokenize the raisin sentence using the tokenizer’s mask ID instead of the string “[MASK]”.
Here’s the tokenization of the sentence:
101: "[CLS]" 1045: "i" 2066: "like" 2000: "to" 4521: "eat" 103: "[MASK]" 7967: "chocolate" 1011: "-" 3139: "covered"15547: “rai” 11493: “##sin”
2015: "##s" 1012: "." 102: "[SEP]"Notice that subwords in the BERT tokenizer have a double-hash, unlike in the GPT tokenizer.
The mask token index is 103. You can find that index by tokenizing the word [MASK], by inspecting the property tokenizer.mask_token, or by evaluating tokenizer.mask_token_id.
Task
Run the following lines (you can also copy them from the online code files) and observe the printed outputs.
tokenizer(’hello’) # 1 tokenizer.encode(’hello’) # 2 tokenizer.convert_tokens_to_ids(’hello’) # 3
tokenizer.convert_tokens_to_ids( ’hello my name is mike’) # 4The outputs are as follows:
{ ’input_ids’: [101, 7592, 102],
’token_type_ids’: [0, 0, 0], ’attention_mask’: [1, 1, 1] } # 1[101, 7592, 102] # 2 7592 # 3 100 # 4
The convert…ids method might be new to you. It’s useful for mapping one token onto one vocab index. It failed for code line #4 (token index 100 is [UNK] for “unknown”) because “hello my name is mike” is not a single token in the BERT tokenizer.
Actually, it is possible to get multiple tokens using the convert_tokens_to_ids method, by inputting a list of strings. For example, replace the input argument in code line #4 above with [’hello’,’my’,’name’,’is’,’mike’]
Part 2: Get logits of four text versions
Section titled “Part 2: Get logits of four text versions”We will work with the following sentence:
The doctor informed the patient that [MASK] would need more tests.
The idea of the bias evaluation is to measure the softmax logits for the tokens “he” vs. “she” in the token position for “[MASK]”. Importantly, neither of those words appears in the sentence, so any non-zero probability of those words must come from learned associations. Perhaps you have guessed that the LLM learned to associate “doctor” with “he” and will therefore have a higher logit to “he” vs. “she”. That’s a reasonable hypothesis, and the goal of this project is to run an experiment to gather evidence that would support — or fail to support — that hypothesis.
Task
Tokenize four versions of that sentence: The he-sentence (replace [MASK] with he), the she-sentence (replace [MASK] with she), the they-sentence, and the mask-sentence (this is what I showed above).
Find the token indices for the target words he, she and they; and find the index of the mask position in the sequence.
You should get the following results:
The mask is in sequence index 7
Target “he” is vocab index 2002 Target “she” is vocab index 2016 Target “they” is vocab index 2027
Task
Run the four token sequences through the model in one batch. Print the shape of the outputs logits tensor and make sure you understand what the dimensions correspond to.
Visualize the raw logits and their softmax transform for the mask-token position in the he-sentence (which also corresponds to the word “he” in that sentence), as in Figure 4.31.
Find and print the token corresponding to the maximum logit.
I instructed to use batch input here to give you more practice with creating batches and indexing outputs. Tokenizing the four sentences into four separate variables would be advantageous because it allows for more informative variable naming, but is disadvantageous because it doesn’t scale to a larger number of sentences (e.g., Part 4). Batching is also faster because the texts are processed in parallel, although the difference in computation time is negligible for this project.
The shape of the output logits is 4 × 14 × 30522. The “4” corresponds to the four versions of the sentence (four sequences in the batch), the “14” is for 14 tokens in each sentence, and the “30522” is the vocab size.
Figure 4.31 reveals a remarkable impact of the softmax transformation. The raw logits clearly show one token that is larger than rest of the distribution, but the softmax really pushes it up to nearly 100% while the rest of the 30k tokens have probabilities near zero.
Figure 4.31: Raw logits (panel A) and softmax probability (panel B) for the token “he” in the he-sentence.
That maximum token is #2002 and is the word “he” with 99.92% probability.
That result is not very surprising — in fact, it is trivial. The word “he” makes sense in the sentence and is literally in the sentence in that position. Nonetheless, these data provide (1) a sanity-check that the code is correct (imagine, for example, that the max-logit token was “potato” with 30% probability; that would indicate a bug in the code) and (2) a reference logit value that provides a baseline for calculating the bias. Actually, we need more than just that one value; we also need the corresponding “she” logit from the she-sentence. Keep reading…
Part 3: Quantify the bias
Section titled “Part 3: Quantify the bias”Before measuring the bias, I want to do one more analysis that is trivial but important: Examining the logits for the target words in the he-, she-, and they-sentences. It’s trivial because the target words are in the sentences as you saw in Part 2, and it’s important because it will help us interpret the bias test.
Task
Extract the logits for the target token position in the non-masked sentences. Softmax transform the logits and extract the probability value for the three target tokens. Show the results as in Figure 4.32 (top row is the log-softmax and bottom row is the softmax-probability). Make sure you understand what the bar plots show, because they are the basis for the bias score that you’ll perform next.
This analysis reveals an important distinction between mask-prediction models like BERT vs. causal autoregressive models like GPT: GPT logits predict the next token whereas BERT logits predict the current token.
Figure 4.32: Softmax-probabilities (bottom row) and log-softmax (top row) of target words in the three non-masked sentences.
Let’s first focus on the bottom row. The probabilities are nearly 100% that the model chooses “he” in the he-sentence, “she” in the she-sentence, and “they” in the they-sentence. The bars for the other targets appear to be missing, but they are so close to zero as to be practically invisible. The log-softmax plots on the top row show a similar phenomenon: The log-probability values are near-zero for the target words and around -11 for the other words.
Why show both the log-probability and softmax-probability? Probability values are easier to interpret for many people while the log-probability values are more sensitive to subtle differences and are more numerically stable. I want you to code and see both versions here for educational purposes, but in a real project it’s best to pick one to use consistently.
Now to perform the bias analysis.
Task
Repeat the analysis but using the logits from the mask-sentence. Visualize as in Figure 4.33. Calculate and print the “bias score” as the difference in log-softmax probabilities for the “he” minus the “she” token.
This analysis is not trivial because the words “he” and “she” do not appear in the sentence. Thus, any difference in logits for those tokens can only be attributed to associations between the target words and the other words in the sentence (e.g., “doctor”).
Figure 4.33: Similar to Figure 4.32 but for the mask-token sentence. The increased probability for “he” compared to “she” indicates a gender bias introduced by the word “doctor”. The left panel shows the log-softmax probabilities and the right panel shows the softmax probabilities.
The bias score is 1.69. This score means that the model assigned a higher probability to “he” than “she” in the mask position.
The result is compelling, but it’s only one example. How do we know that this gender-professions bias really exists in the model or whether I hand-picked one example that happens to show a bias?
The answer is to run an experiment with multiple samples and perform a statistical analysis.
Part 4: Multiple sentences and t-tests
Section titled “Part 4: Multiple sentences and t-tests”I had Claude generate 30 sentences that are similar to the one we worked with but for traditional female roles (N=15) and traditional male roles (N=15). Two examples are below; which do you expect the model to calculate a higher probability of “he” vs. “she” in the mask position?
The secretary explained to the caller that [MASK] would pass along the message. The professor announced to the class that [MASK] would cancel office hours.
Task
The sentences are organized into two lists in the online code files. Tokenize those sentences. Make sure to use padding because the sentence lengths differ. I found it convenient to group the tokens into two batches, one for the “female” sentences and one for the “male” sentences.
Run forward passes with the tokens to get the output logits. In a for-loop over the sentences, calculate the bias score as in Part 3, and store the results in a 2 (female vs. male sentences) × 15 (sample sentences) NumPy array. Be mindful that the mask token is in a different position in each sentence.
Visualize the bias scores as a scatter plot like Figure 4.34.
I calculated the bias score such that positive numbers correspond to stronger activation of the “he” token while negative numbers correspond to stronger activation of the “she” token. If you subtract the other way around, the results will be identical but with opposite sign.
Figure 4.34: Bias scores of each sample sentence.
The results are very clear for the “male” sentences: In every case, the model was biased towards the word “he” based on the context of the sentence.
On the other hand, the results are less clear for the “female” sentences. There are several sentences that had strong negative bias scores while other sentences had scores close to zero or even positive.
To interpret the results better, we need a statistical evaluation.
Task
Perform three t-tests on the bias scores: (1) “female” sentences against zero, (2) “male” sentences against zero, (3) “female” vs. “male” sentences. Report the results as in the table below.
Print the “female” sentences sorted by their bias score.
Difference scores tend to be normally distributed under the null-hypothesis, which justifies the use of a t-test. Here’s the table of statistical results:
Test | df | t-value | p-value -------------+------+-----------+--------- Female vs. 0 | 14 | -1.21 | 0.2448 Male vs. 0 | 14 | 13.68 | 0.0000 Fem vs. Male | 28 | 7.38 | 0.0000
The t-values and p-values for the two tests involving the “male” sentences confirm what the plot revealed. The negative t-value with a non-significant p-value for the “female” sentences indicates that the bias score is numerically but not significantly different from zero. To be clear: That doesn’t mean that the BERT model has no bias involving “female” professions; it means that the average bias score was not significantly different from zero in the 15 sample sentences in this analysis.
Indeed, the spread of the bias scores suggests that some sentences have a stronger bias than others. Figure 4.35 shows the list of sorted bias scores and sentences.
Figure 4.35: Test sentences sorted by bias score.
Inspecting the sentences reveals nuances in the text that would deserve additional investigation if this were a real research project. It’s also interesting to see the differences in bias scores for sentences with the same subject (e.g., “nurse” had bias scores of -2.7 or -.3 in the different contexts).
Sample sizes of 15 are too small to make strong conclusions. In a real research project, thousands of sentences like the ones used here could be found from online text or generated by AI. Nonetheless, this project shows how language-based biases are quantified in LLMs.
Final comments
Section titled “Final comments”Not all biases are as easy to quantify as the examples shown here. There are cultural, legal, socioeconomic, racial, and other biases that are more subtle and qualitative, and are identified by experts judging LLM-generated texts.
Some biases are easy to fix with additional fine-tuning. For example, a gender bias in associating “engineer” with “male” can be fixed by training with additional texts about female engineers. Other biases may be more subtle and therefore more insidious, like using language suggestive of criminal behavior for people from certain religious or geographical backgrounds, or with particular cultural or political preferences.