\n"
- ],
- "text/plain": [
- "\u001b[1mRanks of the answer tokens:\u001b[0m \u001b[1m[\u001b[0m\u001b[1m(\u001b[0m\u001b[32m' Mary'\u001b[0m, \u001b[1;36m0\u001b[0m\u001b[1m)\u001b[0m\u001b[1m]\u001b[0m\n"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "example_prompt = \"After John and Mary went to the store, John gave a bottle of milk to\"\n",
- "example_answer = \" Mary\"\n",
- "utils.test_prompt(example_prompt, example_answer, model, prepend_bos=True)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We now want to find a reference prompt to run the model on. Even though our ultimate goal is to reverse engineer how this behaviour is done in general, often the best way to start out in mechanistic interpretability is by zooming in on a concrete example and understanding it in detail, and only *then* zooming out and verifying that our analysis generalises.\n",
- "\n",
- "We'll run the model on 4 instances of this task, each prompt given twice - one with the first name as the indirect object, one with the second name. To make our lives easier, we'll carefully choose prompts with single token names and the corresponding names in the same token positions.\n",
- "\n",
- "(*) Aside on tokenization\n",
- "\n",
- "We want models that can take in arbitrary text, but models need to have a fixed vocabulary. So the solution is to define a vocabulary of **tokens** and to deterministically break up arbitrary text into tokens. Tokens are, essentially, subwords, and are determined by finding the most frequent substrings - this means that tokens vary a lot in length and frequency! \n",
- "\n",
- "Tokens are a *massive* headache and are one of the most annoying things about reverse engineering language models... Different names will be different numbers of tokens, different prompts will have the relevant tokens at different positions, different prompts will have different total numbers of tokens, etc. Language models often devote significant amounts of parameters in early layers to convert inputs from tokens to a more sensible internal format (and do the reverse in later layers). You really, really want to avoid needing to think about tokenization wherever possible when doing exploratory analysis (though, of course, it's relevant later when trying to flesh out your analysis and make it rigorous!). HookedTransformer comes with several helper methods to deal with tokens: `to_tokens, to_string, to_str_tokens, to_single_token, get_token_position`\n",
- "\n",
- "**Exercise:** I recommend using `model.to_str_tokens` to explore how the model tokenizes different strings. In particular, try adding or removing spaces at the start, or changing capitalization - these change tokenization!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.155840Z",
- "iopub.status.busy": "2024-08-14T01:17:55.155491Z",
- "iopub.status.idle": "2024-08-14T01:17:55.162559Z",
- "shell.execute_reply": "2024-08-14T01:17:55.162081Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "['When John and Mary went to the shops, John gave the bag to', 'When John and Mary went to the shops, Mary gave the bag to', 'When Tom and James went to the park, James gave the ball to', 'When Tom and James went to the park, Tom gave the ball to', 'When Dan and Sid went to the shops, Sid gave an apple to', 'When Dan and Sid went to the shops, Dan gave an apple to', 'After Martin and Amy went to the park, Amy gave a drink to', 'After Martin and Amy went to the park, Martin gave a drink to']\n",
- "[(' Mary', ' John'), (' John', ' Mary'), (' Tom', ' James'), (' James', ' Tom'), (' Dan', ' Sid'), (' Sid', ' Dan'), (' Martin', ' Amy'), (' Amy', ' Martin')]\n"
- ]
- }
- ],
- "source": [
- "prompt_format = [\n",
- " \"When John and Mary went to the shops,{} gave the bag to\",\n",
- " \"When Tom and James went to the park,{} gave the ball to\",\n",
- " \"When Dan and Sid went to the shops,{} gave an apple to\",\n",
- " \"After Martin and Amy went to the park,{} gave a drink to\",\n",
- "]\n",
- "names = [\n",
- " (\" Mary\", \" John\"),\n",
- " (\" Tom\", \" James\"),\n",
- " (\" Dan\", \" Sid\"),\n",
- " (\" Martin\", \" Amy\"),\n",
- "]\n",
- "# List of prompts\n",
- "prompts = []\n",
- "# List of answers, in the format (correct, incorrect)\n",
- "answers = []\n",
- "# List of the token (ie an integer) corresponding to each answer, in the format (correct_token, incorrect_token)\n",
- "answer_tokens = []\n",
- "for i in range(len(prompt_format)):\n",
- " for j in range(2):\n",
- " answers.append((names[i][j], names[i][1 - j]))\n",
- " answer_tokens.append(\n",
- " (\n",
- " model.to_single_token(answers[-1][0]),\n",
- " model.to_single_token(answers[-1][1]),\n",
- " )\n",
- " )\n",
- " # Insert the *incorrect* answer to the prompt, making the correct answer the indirect object.\n",
- " prompts.append(prompt_format[i].format(answers[-1][1]))\n",
- "answer_tokens = torch.tensor(answer_tokens).to(device)\n",
- "print(prompts)\n",
- "print(answers)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Gotcha**: It's important that all of your prompts have the same number of tokens. If they're different lengths, then the position of the \"final\" logit where you can check logit difference will differ between prompts, and this will break the below code. The easiest solution is just to choose your prompts carefully to have the same number of tokens (you can eg add filler words like The, or newlines to start).\n",
- "\n",
- "There's a range of other ways of solving this, eg you can index more intelligently to get the final logit. A better way is to just use left padding by setting `model.tokenizer.padding_side = 'left'` before tokenizing the inputs and running the model; this way, you can use something like `logits[:, -1, :]` to easily access the final token outputs without complicated indexing. TransformerLens checks the value of `padding_side` of the tokenizer internally, and if the flag is set to be `'left'`, it adjusts the calculation of absolute position embedding and causal masking accordingly.\n",
- "\n",
- "In this demo, though, we stick to using the prompts of the same number of tokens because we want to show some visualisations aggregated along the batch dimension later in the demo."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.164437Z",
- "iopub.status.busy": "2024-08-14T01:17:55.164161Z",
- "iopub.status.idle": "2024-08-14T01:17:55.170671Z",
- "shell.execute_reply": "2024-08-14T01:17:55.170080Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'When', ' John', ' and', ' Mary', ' went', ' to', ' the', ' shops', ',', ' John', ' gave', ' the', ' bag', ' to']\n",
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'When', ' John', ' and', ' Mary', ' went', ' to', ' the', ' shops', ',', ' Mary', ' gave', ' the', ' bag', ' to']\n",
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'When', ' Tom', ' and', ' James', ' went', ' to', ' the', ' park', ',', ' James', ' gave', ' the', ' ball', ' to']\n",
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'When', ' Tom', ' and', ' James', ' went', ' to', ' the', ' park', ',', ' Tom', ' gave', ' the', ' ball', ' to']\n",
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'When', ' Dan', ' and', ' Sid', ' went', ' to', ' the', ' shops', ',', ' Sid', ' gave', ' an', ' apple', ' to']\n",
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'When', ' Dan', ' and', ' Sid', ' went', ' to', ' the', ' shops', ',', ' Dan', ' gave', ' an', ' apple', ' to']\n",
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'After', ' Martin', ' and', ' Amy', ' went', ' to', ' the', ' park', ',', ' Amy', ' gave', ' a', ' drink', ' to']\n",
- "Prompt length: 15\n",
- "Prompt as tokens: ['<|endoftext|>', 'After', ' Martin', ' and', ' Amy', ' went', ' to', ' the', ' park', ',', ' Martin', ' gave', ' a', ' drink', ' to']\n"
- ]
- }
- ],
- "source": [
- "for prompt in prompts:\n",
- " str_tokens = model.to_str_tokens(prompt)\n",
- " print(\"Prompt length:\", len(str_tokens))\n",
- " print(\"Prompt as tokens:\", str_tokens)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We now run the model on these prompts and use `run_with_cache` to get both the logits and a cache of all internal activations for later analysis"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.172721Z",
- "iopub.status.busy": "2024-08-14T01:17:55.172330Z",
- "iopub.status.idle": "2024-08-14T01:17:55.449377Z",
- "shell.execute_reply": "2024-08-14T01:17:55.448808Z"
- }
- },
- "outputs": [],
- "source": [
- "tokens = model.to_tokens(prompts, prepend_bos=True)\n",
- "\n",
- "# Run the model and cache all activations\n",
- "original_logits, cache = model.run_with_cache(tokens)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We'll later be evaluating how model performance differs upon performing various interventions, so it's useful to have a metric to measure model performance. Our metric here will be the **logit difference**, the difference in logit between the indirect object's name and the subject's name (eg, `logit(Mary)-logit(John)`). "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.452194Z",
- "iopub.status.busy": "2024-08-14T01:17:55.451764Z",
- "iopub.status.idle": "2024-08-14T01:17:55.457306Z",
- "shell.execute_reply": "2024-08-14T01:17:55.456880Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Per prompt logit difference: tensor([3.3370, 3.2020, 2.7090, 3.7970, 1.7200, 5.2810, 2.6010, 5.7670])\n",
- "Average logit difference: 3.552\n"
- ]
- }
- ],
- "source": [
- "def logits_to_ave_logit_diff(logits, answer_tokens, per_prompt=False):\n",
- " # Only the final logits are relevant for the answer\n",
- " final_logits = logits[:, -1, :]\n",
- " answer_logits = final_logits.gather(dim=-1, index=answer_tokens)\n",
- " answer_logit_diff = answer_logits[:, 0] - answer_logits[:, 1]\n",
- " if per_prompt:\n",
- " return answer_logit_diff\n",
- " else:\n",
- " return answer_logit_diff.mean()\n",
- "\n",
- "\n",
- "print(\n",
- " \"Per prompt logit difference:\",\n",
- " logits_to_ave_logit_diff(original_logits, answer_tokens, per_prompt=True)\n",
- " .detach()\n",
- " .cpu()\n",
- " .round(decimals=3),\n",
- ")\n",
- "original_average_logit_diff = logits_to_ave_logit_diff(original_logits, answer_tokens)\n",
- "print(\n",
- " \"Average logit difference:\",\n",
- " round(logits_to_ave_logit_diff(original_logits, answer_tokens).item(), 3),\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We see that the average logit difference is 3.5 - for context, this represents putting an $e^{3.5}\\approx 33\\times$ higher probability on the correct answer. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Brainstorm What's Actually Going On (Optional)\n",
- "\n",
- "Before diving into running experiments, it's often useful to spend some time actually reasoning about how the behaviour in question could be implemented in the transformer. **This is optional, and you'll likely get the most out of engaging with this section if you have a decent understanding already of what a transformer is and how it works!**\n",
- "\n",
- "You don't have to do this and forming hypotheses after exploration is also reasonable, but I think it's often easier to explore and interpret results with some grounding in what you might find. In this particular case, I'm cheating somewhat, since I know the answer, but I'm trying to simulate the process of reasoning about it!\n",
- "\n",
- "Note that often your hypothesis will be wrong in some ways and often be completely off. We're doing science here, and the goal is to understand how the model *actually* works, and to form true beliefs! There are two separate traps here at two extremes that it's worth tracking:\n",
- "* Confusion: Having no hypotheses at all, getting a lot of data and not knowing what to do with it, and just floundering around\n",
- "* Dogmatism: Being overconfident in an incorrect hypothesis and being unwilling to let go of it when reality contradicts you, or flinching away from running the experiments that might disconfirm it.\n",
- "\n",
- "**Exercise:** Spend some time thinking through how you might imagine this behaviour being implemented in a transformer. Try to think through this for yourself before reading through my thoughts! \n",
- "\n",
- "(*) My reasoning\n",
- "\n",
- "
Brainstorming:
\n",
- "\n",
- "So, what's hard about the task? Let's focus on the concrete example of the first prompt, \"When John and Mary went to the shops, John gave the bag to\" -> \" Mary\". \n",
- "\n",
- "A good starting point is thinking though whether a tiny model could do this, eg a 1L Attn-Only model. I'm pretty sure the answer is no! Attention is really good at the primitive operations of looking nearby, or copying information. I can believe a tiny model could figure out that at `to` it should look for names and predict that those names came next (eg the skip trigram \" John...to -> John\"). But it's much harder to tell how many of each previous name there are - attending 0.3 to each copy of John will look exactly the same as attending 0.6 to a single John token. So this will be pretty hard to figure out on the \" to\" token!\n",
- "\n",
- "The natural place to break this symmetry is on the second \" John\" token - telling whether there is an earlier copy of the current token should be a much easier task. So I might expect there to be a head which detects duplicate tokens on the second \" John\" token, and then another head which moves that information from the second \" John\" token to the \" to\" token. \n",
- "\n",
- "The model then needs to learn to predict \" Mary\" and not \" John\". I can see two natural ways to do this: \n",
- "1. Detect all preceding names and move this information to \" to\" and then delete the any name corresponding to the duplicate token feature. This feels easier done with a non-linearity, since precisely cancelling out vectors is hard, so I'd imagine an MLP layer deletes the \" John\" direction of the residual stream\n",
- "2. Have a head which attends to all previous names, but where the duplicate token features inhibit it from attending to specific names. So this only attends to Mary. And then the output of this head maps to the logits. \n",
- "\n",
- "(Spoiler: It's the second one).\n",
- "\n",
- "
Experiment Ideas
\n",
- "\n",
- "A test that could distinguish these two is to look at which components of the model add directly to the logits - if it's mostly attention heads which attend to \" Mary\" and to neither \" John\" it's probably hypothesis 2, if it's mostly MLPs it's probably hypothesis 1.\n",
- "\n",
- "And we should be able to identify duplicate token heads by finding ones which attend from \" John\" to \" John\", and whose outputs are then moved to the \" to\" token by V-Composition with another head (Spoiler: It's more complicated than that!)\n",
- "\n",
- "Note that all of the above reasoning is very simplistic and could easily break in a real model! There'll be significant parts of the model that figure out whether to use this circuit at all (we don't want to inhibit duplicated names when, eg, figuring out what goes at the start of the next sentence), and may be parts towards the end of the model that do \"post-processing\" just before the final output. But it's a good starting point for thinking about what's going on."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Direct Logit Attribution"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "*Look up unfamiliar terms in the [mech interp explainer](https://neelnanda.io/glossary)*\n",
- "\n",
- "Further, the easiest part of the model to understand is the output - this is what the model is trained to optimize, and so it can always be directly interpreted! Often the right approach to reverse engineering a circuit is to start at the end, understand how the model produces the right answer, and to then work backwards. The main technique used to do this is called **direct logit attribution**\n",
- "\n",
- "**Background:** The central object of a transformer is the **residual stream**. This is the sum of the outputs of each layer and of the original token and positional embedding. Importantly, this means that any linear function of the residual stream can be perfectly decomposed into the contribution of each layer of the transformer. Further, each attention layer's output can be broken down into the sum of the output of each head (See [A Mathematical Framework for Transformer Circuits](https://transformer-circuits.pub/2021/framework/index.html) for details), and each MLP layer's output can be broken down into the sum of the output of each neuron (and a bias term for each layer). \n",
- "\n",
- "The logits of a model are `logits=Unembed(LayerNorm(final_residual_stream))`. The Unembed is a linear map, and LayerNorm is approximately a linear map, so we can decompose the logits into the sum of the contributions of each component, and look at which components contribute the most to the logit of the correct token! This is called **direct logit attribution**. Here we look at the direct attribution to the logit difference!\n",
- "\n",
- "(*) Background and motivation of the logit difference\n",
- "\n",
- "Logit difference is actually a *really* nice and elegant metric and is a particularly nice aspect of the setup of Indirect Object Identification. In general, there are two natural ways to interpret the model's outputs: the output logits, or the output log probabilities (or probabilities). \n",
- "\n",
- "The logits are much nicer and easier to understand, as noted above. However, the model is trained to optimize the cross-entropy loss (the average of log probability of the correct token). This means it does not directly optimize the logits, and indeed if the model adds an arbitrary constant to every logit, the log probabilities are unchanged. \n",
- "\n",
- "But `log_probs == logits.log_softmax(dim=-1) == logits - logsumexp(logits)`, and so `log_probs(\" Mary\") - log_probs(\" John\") = logits(\" Mary\") - logits(\" John\")` - the ability to add an arbitrary constant cancels out!\n",
- "\n",
- "Further, the metric helps us isolate the precise capability we care about - figuring out *which* name is the Indirect Object. There are many other components of the task - deciding whether to return an article (the) or pronoun (her) or name, realising that the sentence wants a person next at all, etc. By taking the logit difference we control for all of that.\n",
- "\n",
- "Our metric is further refined, because each prompt is repeated twice, for each possible indirect object. This controls for irrelevant behaviour such as the model learning that John is a more frequent token than Mary (this actually happens! The final layernorm bias increases the John logit by 1 relative to the Mary logit)\n",
- "\n",
- "\n",
- "\n",
- "Ignoring LayerNorm\n",
- "\n",
- "LayerNorm is an analogous normalization technique to BatchNorm (that's friendlier to massive parallelization) that transformers use. Every time a transformer layer reads information from the residual stream, it applies a LayerNorm to normalize the vector at each position (translating to set the mean to 0 and scaling to set the variance to 1) and then applying a learned vector of weights and biases to scale and translate the normalized vector. This is *almost* a linear map, apart from the scaling step, because that divides by the norm of the vector and the norm is not a linear function. (The `fold_ln` flag when loading a model factors out all the linear parts).\n",
- "\n",
- "But if we fixed the scale factor, the LayerNorm would be fully linear. And the scale of the residual stream is a global property that's a function of *all* components of the stream, while in practice there is normally just a few directions relevant to any particular component, so in practice this is an acceptable approximation. So when doing direct logit attribution we use the `apply_ln` flag on the `cache` to apply the global layernorm scaling factor to each constant. See [my clean GPT-2 implementation](https://colab.research.google.com/github/TransformerLensOrg/TransformerLens/blob/clean-transformer-demo/Clean_Transformer_Demo.ipynb#scrollTo=Clean_Transformer_Implementation) for more on LayerNorm.\n",
- ""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Getting an output logit is equivalent to projecting onto a direction in the residual stream. We use `model.tokens_to_residual_directions` to map the answer tokens to that direction, and then convert this to a logit difference direction for each batch"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.459506Z",
- "iopub.status.busy": "2024-08-14T01:17:55.459104Z",
- "iopub.status.idle": "2024-08-14T01:17:55.462951Z",
- "shell.execute_reply": "2024-08-14T01:17:55.462384Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Answer residual directions shape: torch.Size([8, 2, 768])\n",
- "Logit difference directions shape: torch.Size([8, 768])\n"
- ]
- }
- ],
- "source": [
- "answer_residual_directions = model.tokens_to_residual_directions(answer_tokens)\n",
- "print(\"Answer residual directions shape:\", answer_residual_directions.shape)\n",
- "logit_diff_directions = (\n",
- " answer_residual_directions[:, 0] - answer_residual_directions[:, 1]\n",
- ")\n",
- "print(\"Logit difference directions shape:\", logit_diff_directions.shape)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To verify that this works, we can apply this to the final residual stream for our cached prompts (after applying LayerNorm scaling) and verify that we get the same answer. \n",
- "\n",
- "Technical details\n",
- "\n",
- "`logits = Unembed(LayerNorm(final_residual_stream))`, so we technically need to account for the centering, and then learned translation and scaling of the layernorm, not just the variance 1 scaling. \n",
- "\n",
- "The centering is accounted for with the preprocessing flag `center_writing_weights` which ensures that every weight matrix writing to the residual stream has mean zero. \n",
- "\n",
- "The learned scaling is folded into the unembedding weights `model.unembed.W_U` via `W_U_fold = layer_norm.weights[:, None] * unembed.W_U`\n",
- "\n",
- "The learned translation is folded to `model.unembed.b_U`, a bias added to the logits (note that GPT-2 is not trained with an existing `b_U`). This roughly represents unigram statistics. But we can ignore this because each prompt occurs twice with names in the opposite order, so this perfectly cancels out. \n",
- "\n",
- "Note that rather than using layernorm scaling we could just study cache[\"ln_final.hook_normalised\"]\n",
- "\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.465088Z",
- "iopub.status.busy": "2024-08-14T01:17:55.464766Z",
- "iopub.status.idle": "2024-08-14T01:17:55.469574Z",
- "shell.execute_reply": "2024-08-14T01:17:55.469016Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Final residual stream shape: torch.Size([8, 15, 768])\n",
- "Calculated average logit diff: 3.552\n",
- "Original logit difference: 3.552\n"
- ]
- }
- ],
- "source": [
- "# cache syntax - resid_post is the residual stream at the end of the layer, -1 gets the final layer. The general syntax is [activation_name, layer_index, sub_layer_type].\n",
- "final_residual_stream = cache[\"resid_post\", -1]\n",
- "print(\"Final residual stream shape:\", final_residual_stream.shape)\n",
- "final_token_residual_stream = final_residual_stream[:, -1, :]\n",
- "# Apply LayerNorm scaling\n",
- "# pos_slice is the subset of the positions we take - here the final token of each prompt\n",
- "scaled_final_token_residual_stream = cache.apply_ln_to_stack(\n",
- " final_token_residual_stream, layer=-1, pos_slice=-1\n",
- ")\n",
- "\n",
- "average_logit_diff = einsum(\n",
- " \"batch d_model, batch d_model -> \",\n",
- " scaled_final_token_residual_stream,\n",
- " logit_diff_directions,\n",
- ") / len(prompts)\n",
- "print(\"Calculated average logit diff:\", round(average_logit_diff.item(), 3))\n",
- "print(\"Original logit difference:\", round(original_average_logit_diff.item(), 3))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Logit Lens"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can now decompose the residual stream! First we apply a technique called the [**logit lens**](https://www.alignmentforum.org/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens) - this looks at the residual stream after each layer and calculates the logit difference from that. This simulates what happens if we delete all subsequence layers. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.471746Z",
- "iopub.status.busy": "2024-08-14T01:17:55.471365Z",
- "iopub.status.idle": "2024-08-14T01:17:55.474738Z",
- "shell.execute_reply": "2024-08-14T01:17:55.474161Z"
- }
- },
- "outputs": [],
- "source": [
- "def residual_stack_to_logit_diff(\n",
- " residual_stack: Float[torch.Tensor, \"components batch d_model\"],\n",
- " cache: ActivationCache,\n",
- ") -> float:\n",
- " scaled_residual_stack = cache.apply_ln_to_stack(\n",
- " residual_stack, layer=-1, pos_slice=-1\n",
- " )\n",
- " return einsum(\n",
- " \"... batch d_model, batch d_model -> ...\",\n",
- " scaled_residual_stack,\n",
- " logit_diff_directions,\n",
- " ) / len(prompts)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Fascinatingly, we see that the model is utterly unable to do the task until layer 7, almost all performance comes from attention layer 9, and performance actually *decreases* from there.\n",
- "\n",
- "**Note:** Hover over each data point to see what residual stream position it's from!\n",
- "\n",
- "Details on `accumulated_resid`\n",
- "**Key:** `n_pre` means the residual stream at the start of layer n, `n_mid` means the residual stream after the attention part of layer n (`n_post` is the same as `n+1_pre` so is not included)\n",
- "\n",
- "* `layer` is the layer for which we input the residual stream (this is used to identify *which* layer norm scaling factor we want)\n",
- "* `incl_mid` is whether to include the residual stream in the middle of a layer, ie after attention & before MLP\n",
- "* `pos_slice` is the subset of the positions used. See `utils.Slice` for details on the syntax.\n",
- "* return_labels is whether to return the labels for each component returned (useful for plotting)\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:55.476818Z",
- "iopub.status.busy": "2024-08-14T01:17:55.476420Z",
- "iopub.status.idle": "2024-08-14T01:17:56.226191Z",
- "shell.execute_reply": "2024-08-14T01:17:56.225573Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- " \n",
- " "
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.plotly.v1+json": {
- "config": {
- "plotlyServerURL": "https://plot.ly"
- },
- "data": [
- {
- "hovertemplate": "%{hovertext}
"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "per_head_residual, labels = cache.stack_head_results(\n",
- " layer=-1, pos_slice=-1, return_labels=True\n",
- ")\n",
- "per_head_logit_diffs = residual_stack_to_logit_diff(per_head_residual, cache)\n",
- "per_head_logit_diffs = einops.rearrange(\n",
- " per_head_logit_diffs,\n",
- " \"(layer head_index) -> layer head_index\",\n",
- " layer=model.cfg.n_layers,\n",
- " head_index=model.cfg.n_heads,\n",
- ")\n",
- "imshow(\n",
- " per_head_logit_diffs,\n",
- " labels={\"x\": \"Head\", \"y\": \"Layer\"},\n",
- " title=\"Logit Difference From Each Head\",\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Attention Analysis"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Attention heads are particularly easy to study because we can look directly at their attention patterns and study from what positions they move information from and two. This is particularly easy here as we're looking at the direct effect on the logits so we need only look at the attention patterns from the final token. \n",
- "\n",
- "We use Alan Cooney's circuitsvis library to visualize the attention patterns! We visualize the top 3 positive and negative heads by direct logit attribution, and show these for the first prompt (as an illustration).\n",
- "\n",
- "Interpreting Attention Patterns \n",
- "An easy mistake to make when looking at attention patterns is thinking that they must convey information about the token looked at (maybe accounting for the context of the token). But actually, all we can confidently say is that it moves information from the *residual stream position* corresponding to that input token. Especially later on in the model, there may be components in the residual stream that are nothing to do with the input token! Eg the period at the end of a sentence may contain summary information for that sentence, and the head may solely move that, rather than caring about whether it ends in \".\", \"!\" or \"?\"\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:56.365420Z",
- "iopub.status.busy": "2024-08-14T01:17:56.365099Z",
- "iopub.status.idle": "2024-08-14T01:17:56.370409Z",
- "shell.execute_reply": "2024-08-14T01:17:56.369827Z"
- }
- },
- "outputs": [],
- "source": [
- "def visualize_attention_patterns(\n",
- " heads: Union[List[int], int, Float[torch.Tensor, \"heads\"]],\n",
- " local_cache: ActivationCache,\n",
- " local_tokens: torch.Tensor,\n",
- " title: Optional[str] = \"\",\n",
- " max_width: Optional[int] = 700,\n",
- ") -> str:\n",
- " # If a single head is given, convert to a list\n",
- " if isinstance(heads, int):\n",
- " heads = [heads]\n",
- "\n",
- " # Create the plotting data\n",
- " labels: List[str] = []\n",
- " patterns: List[Float[torch.Tensor, \"dest_pos src_pos\"]] = []\n",
- "\n",
- " # Assume we have a single batch item\n",
- " batch_index = 0\n",
- "\n",
- " for head in heads:\n",
- " # Set the label\n",
- " layer = head // model.cfg.n_heads\n",
- " head_index = head % model.cfg.n_heads\n",
- " labels.append(f\"L{layer}H{head_index}\")\n",
- "\n",
- " # Get the attention patterns for the head\n",
- " # Attention patterns have shape [batch, head_index, query_pos, key_pos]\n",
- " patterns.append(local_cache[\"attn\", layer][batch_index, head_index])\n",
- "\n",
- " # Convert the tokens to strings (for the axis labels)\n",
- " str_tokens = model.to_str_tokens(local_tokens)\n",
- "\n",
- " # Combine the patterns into a single tensor\n",
- " patterns: Float[torch.Tensor, \"head_index dest_pos src_pos\"] = torch.stack(\n",
- " patterns, dim=0\n",
- " )\n",
- "\n",
- " # Circuitsvis Plot (note we get the code version so we can concatenate with the title)\n",
- " plot = attention_heads(\n",
- " attention=patterns, tokens=str_tokens, attention_head_names=labels\n",
- " ).show_code()\n",
- "\n",
- " # Display the title\n",
- " title_html = f\"
{title}
\"\n",
- "\n",
- " # Return the visualisation as raw code\n",
- " return f\"
{title_html + plot}
\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Inspecting the patterns, we can see that both types of name movers attend to the indirect object - this suggests they're simply copying the name attended to (with the OV circuit) and that the interesting part is the circuit behind the attention pattern that calculates *where* to move information from (the QK circuit)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:56.372626Z",
- "iopub.status.busy": "2024-08-14T01:17:56.372440Z",
- "iopub.status.idle": "2024-08-14T01:17:56.382799Z",
- "shell.execute_reply": "2024-08-14T01:17:56.382212Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "
Top 3 Positive Logit Attribution Heads
\n",
- "
Top 3 Negative Logit Attribution Heads
\n",
- "
"
- ],
- "text/plain": [
- ""
- ]
- },
- "execution_count": 18,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "top_k = 3\n",
- "\n",
- "top_positive_logit_attr_heads = torch.topk(\n",
- " per_head_logit_diffs.flatten(), k=top_k\n",
- ").indices\n",
- "\n",
- "positive_html = visualize_attention_patterns(\n",
- " top_positive_logit_attr_heads,\n",
- " cache,\n",
- " tokens[0],\n",
- " f\"Top {top_k} Positive Logit Attribution Heads\",\n",
- ")\n",
- "\n",
- "top_negative_logit_attr_heads = torch.topk(\n",
- " -per_head_logit_diffs.flatten(), k=top_k\n",
- ").indices\n",
- "\n",
- "negative_html = visualize_attention_patterns(\n",
- " top_negative_logit_attr_heads,\n",
- " cache,\n",
- " tokens[0],\n",
- " title=f\"Top {top_k} Negative Logit Attribution Heads\",\n",
- ")\n",
- "\n",
- "HTML(positive_html + negative_html)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Activation Patching"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**This section explains how to do activation patching conceptually by implementing it from scratch. To use it in practice with TransformerLens, see [this demonstration instead](https://colab.research.google.com/github/TransformerLensOrg/TransformerLens/blob/main/demos/Activation_Patching_in_TL_Demo.ipynb)**.\n",
- "\n",
- "The obvious limitation to the techniques used above is that they only look at the very end of the circuit - the parts that directly affect the logits. Clearly this is not sufficient to understand the circuit! We want to understand how things compose together to produce this final output, and ideally to produce an end-to-end circuit fully explaining this behaviour. \n",
- "\n",
- "The technique we'll use to investigate this is called **activation patching**. This was first introduced in [David Bau and Kevin Meng's excellent ROME paper](https://rome.baulab.info/), there called causal tracing. \n",
- "\n",
- "The setup of activation patching is to take two runs of the model on two different inputs, the clean run and the corrupted run. The clean run outputs the correct answer and the corrupted run does not. The key idea is that we give the model the corrupted input, but then **intervene** on a specific activation and **patch** in the corresponding activation from the clean run (ie replace the corrupted activation with the clean activation), and then continue the run. And we then measure how much the output has updated towards the correct answer. \n",
- "\n",
- "We can then iterate over many possible activations and look at how much they affect the corrupted run. If patching in an activation significantly increases the probability of the correct answer, this allows us to *localise* which activations matter. \n",
- "\n",
- "The ability to localise is a key move in mechanistic interpretability - if the computation is diffuse and spread across the entire model, it is likely much harder to form a clean mechanistic story for what's going on. But if we can identify precisely which parts of the model matter, we can then zoom in and determine what they represent and how they connect up with each other, and ultimately reverse engineer the underlying circuit that they represent. \n",
- "\n",
- "Here's an animation from the ROME paper demonstrating this technique (they studied factual recall, and use stars to represent corruption applied to the subject of the sentence, but the same principles apply):\n",
- "\n",
- "![CT Animation](https://rome.baulab.info/images/small-ct-animation.gif)\n",
- "\n",
- "See also [the explanation in a mech interp explainer](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=qeWBvs-R-taFfcCq-S_hgMqx) and [this piece](https://www.neelnanda.io/mechanistic-interpretability/attribution-patching#how-to-think-about-activation-patching) describing how to think about patching on a conceptual level"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The above was all fairly abstract, so let's zoom in and lay out a concrete example to understand Indirect Object Identification.\n",
- "\n",
- "Here our clean input will be eg \"After John and Mary went to the store, **John** gave a bottle of milk to\" and our corrupted input will be eg \"After John and Mary went to the store, **Mary** gave a bottle of milk to\". These prompts are identical except for the name of the indirect object, and so patching is a causal intervention which will allow us to understand precisely which parts of the network are identifying the indirect object. \n",
- "\n",
- "One natural thing to patch in is the residual stream at a specific layer and specific position. For example, the model is likely initially doing some processing on the second subject token to realise that it's a duplicate, but then uses attention to move that information to the \" to\" token. So patching in the residual stream at the \" to\" token will likely matter a lot in later layers but not at all in early layers.\n",
- "\n",
- "We can zoom in much further and patch in specific activations from specific layers. For example, we think that the output of head L9H9 on the final token is significant for directly connecting to the logits\n",
- "\n",
- "We can patch in specific activations, and can zoom in as far as seems reasonable. For example, if we patch in the output of head L9H9 on the final token, we would predict that it will significantly affect performance. \n",
- "\n",
- "Note that this technique does *not* tell us how the components of the circuit connect up, just what they are. \n",
- "\n",
- "Technical details \n",
- "The choice of clean and corrupted prompt has both pros and cons. By carefully setting up the counterfactual, that only differs in the second subject, we avoid detecting the parts of the model doing irrelevant computation like detecting that the indirect object task is relevant at all or that it should be outputting a name rather than an article or pronoun. Or even context like that John and Mary are names at all. \n",
- "\n",
- "However, it *also* bakes in some details that *are* relevant to the task. Such as finding the location of the second subject, and of the names in the first clause. Or that the name mover heads have learned to copy whatever they look at. \n",
- "\n",
- "Some of these could be patched by also changing up the order of the names in the original sentence - patching in \"After John and Mary went to the store, John gave a bottle of milk to\" vs \"After Mary and John went to the store, John gave a bottle of milk to\".\n",
- "\n",
- "In the ROME paper they take a different tack. Rather than carefully setting up counterfactuals between two different but related inputs, they **corrupt** the clean input by adding Gaussian noise to the token embedding for the subject. This is in some ways much lower effort (you don't need to set up a similar but different prompt) but can also introduce some issues, such as ways this noise might break things. In practice, you should take care about how you choose your counterfactuals and try out several. Try to reason beforehand about what they will and will not tell you, and compare the results between different counterfactuals.\n",
- "\n",
- "I discuss some of these limitations and how the author's solved them with much more refined usage of these techniques in our interview\n",
- ""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Residual Stream"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Lets begin by patching in the residual stream at the start of each layer and for each token position. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We first create a set of corrupted tokens - where we swap each pair of prompts to have the opposite answer."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:56.385070Z",
- "iopub.status.busy": "2024-08-14T01:17:56.384745Z",
- "iopub.status.idle": "2024-08-14T01:17:56.662204Z",
- "shell.execute_reply": "2024-08-14T01:17:56.661620Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Corrupted Average Logit Diff -3.55\n",
- "Clean Average Logit Diff 3.55\n"
- ]
- }
- ],
- "source": [
- "corrupted_prompts = []\n",
- "for i in range(0, len(prompts), 2):\n",
- " corrupted_prompts.append(prompts[i + 1])\n",
- " corrupted_prompts.append(prompts[i])\n",
- "corrupted_tokens = model.to_tokens(corrupted_prompts, prepend_bos=True)\n",
- "corrupted_logits, corrupted_cache = model.run_with_cache(\n",
- " corrupted_tokens, return_type=\"logits\"\n",
- ")\n",
- "corrupted_average_logit_diff = logits_to_ave_logit_diff(corrupted_logits, answer_tokens)\n",
- "print(\"Corrupted Average Logit Diff\", round(corrupted_average_logit_diff.item(), 2))\n",
- "print(\"Clean Average Logit Diff\", round(original_average_logit_diff.item(), 2))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:56.664583Z",
- "iopub.status.busy": "2024-08-14T01:17:56.664201Z",
- "iopub.status.idle": "2024-08-14T01:17:56.668269Z",
- "shell.execute_reply": "2024-08-14T01:17:56.667826Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "['<|endoftext|>When John and Mary went to the shops, Mary gave the bag to',\n",
- " '<|endoftext|>When John and Mary went to the shops, John gave the bag to',\n",
- " '<|endoftext|>When Tom and James went to the park, Tom gave the ball to',\n",
- " '<|endoftext|>When Tom and James went to the park, James gave the ball to',\n",
- " '<|endoftext|>When Dan and Sid went to the shops, Dan gave an apple to',\n",
- " '<|endoftext|>When Dan and Sid went to the shops, Sid gave an apple to',\n",
- " '<|endoftext|>After Martin and Amy went to the park, Martin gave a drink to',\n",
- " '<|endoftext|>After Martin and Amy went to the park, Amy gave a drink to']"
- ]
- },
- "execution_count": 20,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "model.to_string(corrupted_tokens)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We now intervene on the corrupted run and patch in the clean residual stream at a specific layer and position.\n",
- "\n",
- "We do the intervention using TransformerLens's `HookPoint` feature. We can design a hook function that takes in a specific activation and returns an edited copy, and temporarily add it in with `model.run_with_hooks`. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 21,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:17:56.670331Z",
- "iopub.status.busy": "2024-08-14T01:17:56.670013Z",
- "iopub.status.idle": "2024-08-14T01:18:42.982150Z",
- "shell.execute_reply": "2024-08-14T01:18:42.981611Z"
- }
- },
- "outputs": [],
- "source": [
- "def patch_residual_component(\n",
- " corrupted_residual_component: Float[torch.Tensor, \"batch pos d_model\"],\n",
- " hook,\n",
- " pos,\n",
- " clean_cache,\n",
- "):\n",
- " corrupted_residual_component[:, pos, :] = clean_cache[hook.name][:, pos, :]\n",
- " return corrupted_residual_component\n",
- "\n",
- "\n",
- "def normalize_patched_logit_diff(patched_logit_diff):\n",
- " # Subtract corrupted logit diff to measure the improvement, divide by the total improvement from clean to corrupted to normalise\n",
- " # 0 means zero change, negative means actively made worse, 1 means totally recovered clean performance, >1 means actively *improved* on clean performance\n",
- " return (patched_logit_diff - corrupted_average_logit_diff) / (\n",
- " original_average_logit_diff - corrupted_average_logit_diff\n",
- " )\n",
- "\n",
- "\n",
- "patched_residual_stream_diff = torch.zeros(\n",
- " model.cfg.n_layers, tokens.shape[1], device=device, dtype=torch.float32\n",
- ")\n",
- "for layer in range(model.cfg.n_layers):\n",
- " for position in range(tokens.shape[1]):\n",
- " hook_fn = partial(patch_residual_component, pos=position, clean_cache=cache)\n",
- " patched_logits = model.run_with_hooks(\n",
- " corrupted_tokens,\n",
- " fwd_hooks=[(utils.get_act_name(\"resid_pre\", layer), hook_fn)],\n",
- " return_type=\"logits\",\n",
- " )\n",
- " patched_logit_diff = logits_to_ave_logit_diff(patched_logits, answer_tokens)\n",
- "\n",
- " patched_residual_stream_diff[layer, position] = normalize_patched_logit_diff(\n",
- " patched_logit_diff\n",
- " )"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can immediately see that, exactly as predicted, originally all relevant computation happens on the second subject token, and at layers 7 and 8, the information is moved to the final token. Moving the residual stream at the correct position near *exactly* recovers performance!\n",
- "\n",
- "For reference, tokens and their index from the first prompt are on the x-axis. In an abuse of notation, note that the difference here is averaged over *all* 8 prompts, while the labels only come from the *first* prompt. \n",
- "\n",
- "To be easier to interpret, we normalise the logit difference, by subtracting the corrupted logit difference, and dividing by the total improvement from clean to corrupted to normalise\n",
- "0 means zero change, negative means actively made worse, 1 means totally recovered clean performance, >1 means actively *improved* on clean performance"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:18:42.984767Z",
- "iopub.status.busy": "2024-08-14T01:18:42.984370Z",
- "iopub.status.idle": "2024-08-14T01:18:43.017759Z",
- "shell.execute_reply": "2024-08-14T01:18:43.017289Z"
- }
- },
- "outputs": [
- {
- "data": {
- "application/vnd.plotly.v1+json": {
- "config": {
- "plotlyServerURL": "https://plot.ly"
- },
- "data": [
- {
- "coloraxis": "coloraxis",
- "hovertemplate": "Position: %{x} Layer: %{y} color: %{z}",
- "name": "0",
- "type": "heatmap",
- "x": [
- "<|endoftext|>_0",
- "When_1",
- " John_2",
- " and_3",
- " Mary_4",
- " went_5",
- " to_6",
- " the_7",
- " shops_8",
- ",_9",
- " John_10",
- " gave_11",
- " the_12",
- " bag_13",
- " to_14"
- ],
- "xaxis": "x",
- "yaxis": "y",
- "z": [
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.00065016746521,
- -0.00024725322145968676,
- 9.061812306754291e-06,
- -0.00036435198853723705,
- -4.832966806134209e-05
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.0010517835617065,
- -2.6816253011929803e-05,
- -2.0540108380373567e-05,
- -0.0004592325130943209,
- -0.0005939850234426558
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.0002665519714355,
- 0.0008679538150317967,
- 0.0005159862921573222,
- -0.0009933760156854987,
- -0.0008652352844364941
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.9949080944061279,
- 0.005429603159427643,
- 0.0016055518062785268,
- -0.0006179149495437741,
- -0.0016324687749147415
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.9675664305686951,
- 0.03134222328662872,
- 0.0028418514411896467,
- -0.0012303927214816213,
- -0.0009862943552434444
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.9675208926200867,
- 0.031000729650259018,
- 0.001782458508387208,
- -0.0004856795712839812,
- -0.000646778498776257
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.9228320121765137,
- 0.05134553834795952,
- 0.004729225765913725,
- 0.0009345413418486714,
- 0.017047081142663956
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.6565485000610352,
- 0.02385673113167286,
- 0.002357447287067771,
- -1.7318130630883388e-05,
- 0.3186914026737213
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.027302434667944908,
- 0.03142485395073891,
- 0.0018206859240308404,
- 0.0007993190083652735,
- 0.9383869171142578
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- -0.026841893792152405,
- 0.020981015637516975,
- 0.0012513356050476432,
- 0.0003238087520003319,
- 1.0048280954360962
- ],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- -0.005687932018190622,
- 0.014263695105910301,
- 0.0004871227720286697,
- -8.984619489638135e-05,
- 0.9914218783378601
- ]
- ]
- }
- ],
- "layout": {
- "coloraxis": {
- "cmid": 0.0,
- "colorscale": [
- [
- 0.0,
- "rgb(103,0,31)"
- ],
- [
- 0.1,
- "rgb(178,24,43)"
- ],
- [
- 0.2,
- "rgb(214,96,77)"
- ],
- [
- 0.3,
- "rgb(244,165,130)"
- ],
- [
- 0.4,
- "rgb(253,219,199)"
- ],
- [
- 0.5,
- "rgb(247,247,247)"
- ],
- [
- 0.6,
- "rgb(209,229,240)"
- ],
- [
- 0.7,
- "rgb(146,197,222)"
- ],
- [
- 0.8,
- "rgb(67,147,195)"
- ],
- [
- 0.9,
- "rgb(33,102,172)"
- ],
- [
- 1.0,
- "rgb(5,48,97)"
- ]
- ]
- },
- "template": {
- "data": {
- "bar": [
- {
- "error_x": {
- "color": "#2a3f5f"
- },
- "error_y": {
- "color": "#2a3f5f"
- },
- "marker": {
- "line": {
- "color": "#E5ECF6",
- "width": 0.5
- },
- "pattern": {
- "fillmode": "overlay",
- "size": 10,
- "solidity": 0.2
- }
- },
- "type": "bar"
- }
- ],
- "barpolar": [
- {
- "marker": {
- "line": {
- "color": "#E5ECF6",
- "width": 0.5
- },
- "pattern": {
- "fillmode": "overlay",
- "size": 10,
- "solidity": 0.2
- }
- },
- "type": "barpolar"
- }
- ],
- "carpet": [
- {
- "aaxis": {
- "endlinecolor": "#2a3f5f",
- "gridcolor": "white",
- "linecolor": "white",
- "minorgridcolor": "white",
- "startlinecolor": "#2a3f5f"
- },
- "baxis": {
- "endlinecolor": "#2a3f5f",
- "gridcolor": "white",
- "linecolor": "white",
- "minorgridcolor": "white",
- "startlinecolor": "#2a3f5f"
- },
- "type": "carpet"
- }
- ],
- "choropleth": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "type": "choropleth"
- }
- ],
- "contour": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "colorscale": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ],
- "type": "contour"
- }
- ],
- "contourcarpet": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "type": "contourcarpet"
- }
- ],
- "heatmap": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "colorscale": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ],
- "type": "heatmap"
- }
- ],
- "heatmapgl": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "colorscale": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ],
- "type": "heatmapgl"
- }
- ],
- "histogram": [
- {
- "marker": {
- "pattern": {
- "fillmode": "overlay",
- "size": 10,
- "solidity": 0.2
- }
- },
- "type": "histogram"
- }
- ],
- "histogram2d": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "colorscale": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ],
- "type": "histogram2d"
- }
- ],
- "histogram2dcontour": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "colorscale": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ],
- "type": "histogram2dcontour"
- }
- ],
- "mesh3d": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "type": "mesh3d"
- }
- ],
- "parcoords": [
- {
- "line": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "parcoords"
- }
- ],
- "pie": [
- {
- "automargin": true,
- "type": "pie"
- }
- ],
- "scatter": [
- {
- "fillpattern": {
- "fillmode": "overlay",
- "size": 10,
- "solidity": 0.2
- },
- "type": "scatter"
- }
- ],
- "scatter3d": [
- {
- "line": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scatter3d"
- }
- ],
- "scattercarpet": [
- {
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scattercarpet"
- }
- ],
- "scattergeo": [
- {
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scattergeo"
- }
- ],
- "scattergl": [
- {
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scattergl"
- }
- ],
- "scattermapbox": [
- {
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scattermapbox"
- }
- ],
- "scatterpolar": [
- {
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scatterpolar"
- }
- ],
- "scatterpolargl": [
- {
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scatterpolargl"
- }
- ],
- "scatterternary": [
- {
- "marker": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "type": "scatterternary"
- }
- ],
- "surface": [
- {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- },
- "colorscale": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ],
- "type": "surface"
- }
- ],
- "table": [
- {
- "cells": {
- "fill": {
- "color": "#EBF0F8"
- },
- "line": {
- "color": "white"
- }
- },
- "header": {
- "fill": {
- "color": "#C8D4E3"
- },
- "line": {
- "color": "white"
- }
- },
- "type": "table"
- }
- ]
- },
- "layout": {
- "annotationdefaults": {
- "arrowcolor": "#2a3f5f",
- "arrowhead": 0,
- "arrowwidth": 1
- },
- "autotypenumbers": "strict",
- "coloraxis": {
- "colorbar": {
- "outlinewidth": 0,
- "ticks": ""
- }
- },
- "colorscale": {
- "diverging": [
- [
- 0,
- "#8e0152"
- ],
- [
- 0.1,
- "#c51b7d"
- ],
- [
- 0.2,
- "#de77ae"
- ],
- [
- 0.3,
- "#f1b6da"
- ],
- [
- 0.4,
- "#fde0ef"
- ],
- [
- 0.5,
- "#f7f7f7"
- ],
- [
- 0.6,
- "#e6f5d0"
- ],
- [
- 0.7,
- "#b8e186"
- ],
- [
- 0.8,
- "#7fbc41"
- ],
- [
- 0.9,
- "#4d9221"
- ],
- [
- 1,
- "#276419"
- ]
- ],
- "sequential": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ],
- "sequentialminus": [
- [
- 0.0,
- "#0d0887"
- ],
- [
- 0.1111111111111111,
- "#46039f"
- ],
- [
- 0.2222222222222222,
- "#7201a8"
- ],
- [
- 0.3333333333333333,
- "#9c179e"
- ],
- [
- 0.4444444444444444,
- "#bd3786"
- ],
- [
- 0.5555555555555556,
- "#d8576b"
- ],
- [
- 0.6666666666666666,
- "#ed7953"
- ],
- [
- 0.7777777777777778,
- "#fb9f3a"
- ],
- [
- 0.8888888888888888,
- "#fdca26"
- ],
- [
- 1.0,
- "#f0f921"
- ]
- ]
- },
- "colorway": [
- "#636efa",
- "#EF553B",
- "#00cc96",
- "#ab63fa",
- "#FFA15A",
- "#19d3f3",
- "#FF6692",
- "#B6E880",
- "#FF97FF",
- "#FECB52"
- ],
- "font": {
- "color": "#2a3f5f"
- },
- "geo": {
- "bgcolor": "white",
- "lakecolor": "white",
- "landcolor": "#E5ECF6",
- "showlakes": true,
- "showland": true,
- "subunitcolor": "white"
- },
- "hoverlabel": {
- "align": "left"
- },
- "hovermode": "closest",
- "mapbox": {
- "style": "light"
- },
- "paper_bgcolor": "white",
- "plot_bgcolor": "#E5ECF6",
- "polar": {
- "angularaxis": {
- "gridcolor": "white",
- "linecolor": "white",
- "ticks": ""
- },
- "bgcolor": "#E5ECF6",
- "radialaxis": {
- "gridcolor": "white",
- "linecolor": "white",
- "ticks": ""
- }
- },
- "scene": {
- "xaxis": {
- "backgroundcolor": "#E5ECF6",
- "gridcolor": "white",
- "gridwidth": 2,
- "linecolor": "white",
- "showbackground": true,
- "ticks": "",
- "zerolinecolor": "white"
- },
- "yaxis": {
- "backgroundcolor": "#E5ECF6",
- "gridcolor": "white",
- "gridwidth": 2,
- "linecolor": "white",
- "showbackground": true,
- "ticks": "",
- "zerolinecolor": "white"
- },
- "zaxis": {
- "backgroundcolor": "#E5ECF6",
- "gridcolor": "white",
- "gridwidth": 2,
- "linecolor": "white",
- "showbackground": true,
- "ticks": "",
- "zerolinecolor": "white"
- }
- },
- "shapedefaults": {
- "line": {
- "color": "#2a3f5f"
- }
- },
- "ternary": {
- "aaxis": {
- "gridcolor": "white",
- "linecolor": "white",
- "ticks": ""
- },
- "baxis": {
- "gridcolor": "white",
- "linecolor": "white",
- "ticks": ""
- },
- "bgcolor": "#E5ECF6",
- "caxis": {
- "gridcolor": "white",
- "linecolor": "white",
- "ticks": ""
- }
- },
- "title": {
- "x": 0.05
- },
- "xaxis": {
- "automargin": true,
- "gridcolor": "white",
- "linecolor": "white",
- "ticks": "",
- "title": {
- "standoff": 15
- },
- "zerolinecolor": "white",
- "zerolinewidth": 2
- },
- "yaxis": {
- "automargin": true,
- "gridcolor": "white",
- "linecolor": "white",
- "ticks": "",
- "title": {
- "standoff": 15
- },
- "zerolinecolor": "white",
- "zerolinewidth": 2
- }
- }
- },
- "title": {
- "text": "Logit Difference From Patched Residual Stream"
- },
- "xaxis": {
- "anchor": "y",
- "constrain": "domain",
- "domain": [
- 0.0,
- 1.0
- ],
- "scaleanchor": "y",
- "title": {
- "text": "Position"
- }
- },
- "yaxis": {
- "anchor": "x",
- "autorange": "reversed",
- "constrain": "domain",
- "domain": [
- 0.0,
- 1.0
- ],
- "title": {
- "text": "Layer"
- }
- }
- }
- },
- "text/html": [
- "
"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "imshow(\n",
- " patched_head_attn_diff,\n",
- " title=\"Logit Difference From Patched Head Pattern\",\n",
- " labels={\"x\": \"Head\", \"y\": \"Layer\"},\n",
- ")\n",
- "head_labels = [\n",
- " f\"L{l}H{h}\" for l in range(model.cfg.n_layers) for h in range(model.cfg.n_heads)\n",
- "]\n",
- "scatter(\n",
- " x=utils.to_numpy(patched_head_attn_diff.flatten()),\n",
- " y=utils.to_numpy(patched_head_z_diff.flatten()),\n",
- " hover_name=head_labels,\n",
- " xaxis=\"Attention Patch\",\n",
- " yaxis=\"Output Patch\",\n",
- " title=\"Scatter plot of output patching vs attention patching\",\n",
- ")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Consolidating Understanding\n",
- "\n",
- "OK, let's zoom out and reconsolidate. At a high-level, we find that all the action is on the second subject token until layer 7 and then transitions to the final token. And that attention layers matter a lot, MLP layers not so much (apart from MLP0, likely as an extended embedding).\n",
- "\n",
- "We've further localised important behaviour to several categories of heads. We've found 3 categories of heads that matter a lot - early heads (L5H5, L6H9, L3H0) whose output matters on the second subject and whose behaviour is determined by their attention patterns, mid-late heads (L8H6, L8H10, L7H9, L7H3) whose output matters on the final token and whose behaviour is determined by their value vectors, and late heads (L9H9, L10H7, L11H10) whose output matters on the final token and whose behaviour is determined by their attention patterns.\n",
- "\n",
- "A natural speculation is that early heads detect both that the second subject is a repeated token and *which* is repeated (ie the \" John\" token is repeated), middle heads compose with this and move this duplicated token information from the second subject token to the final token, and the late heads compose with this to *inhibit* their attention to the duplicated token, and then attend to the correct indirect object name and copy that directly to the logits."
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Visualizing Attention Patterns\n",
- "\n",
- "We can validate this by looking at the attention patterns of these heads! Let's take the top 10 heads by output patching (in absolute value) and split it into early, middle and late.\n",
- "\n",
- "We see that middle heads attend from the final token to the second subject, and late heads attend from the final token to the indirect object, which is completely consistent with the above speculation! But weirdly, while *one* early head attends from the second subject to its first copy, the other two mysteriously attend to the word *after* the first copy."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 33,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:06.805270Z",
- "iopub.status.busy": "2024-08-14T01:22:06.805100Z",
- "iopub.status.idle": "2024-08-14T01:22:06.817826Z",
- "shell.execute_reply": "2024-08-14T01:22:06.817323Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "
Top Early Heads
\n",
- "
Top Middle Heads
\n",
- "
Top Late Heads
\n",
- "
"
- ],
- "text/plain": [
- ""
- ]
- },
- "execution_count": 33,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "top_k = 10\n",
- "top_heads_by_output_patch = torch.topk(\n",
- " patched_head_z_diff.abs().flatten(), k=top_k\n",
- ").indices\n",
- "first_mid_layer = 7\n",
- "first_late_layer = 9\n",
- "early_heads = top_heads_by_output_patch[\n",
- " top_heads_by_output_patch < model.cfg.n_heads * first_mid_layer\n",
- "]\n",
- "mid_heads = top_heads_by_output_patch[\n",
- " torch.logical_and(\n",
- " model.cfg.n_heads * first_mid_layer <= top_heads_by_output_patch,\n",
- " top_heads_by_output_patch < model.cfg.n_heads * first_late_layer,\n",
- " )\n",
- "]\n",
- "late_heads = top_heads_by_output_patch[\n",
- " model.cfg.n_heads * first_late_layer <= top_heads_by_output_patch\n",
- "]\n",
- "\n",
- "early = visualize_attention_patterns(\n",
- " early_heads, cache, tokens[0], title=f\"Top Early Heads\"\n",
- ")\n",
- "mid = visualize_attention_patterns(\n",
- " mid_heads, cache, tokens[0], title=f\"Top Middle Heads\"\n",
- ")\n",
- "late = visualize_attention_patterns(\n",
- " late_heads, cache, tokens[0], title=f\"Top Late Heads\"\n",
- ")\n",
- "\n",
- "HTML(early + mid + late)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Comparing to the Paper\n",
- "\n",
- "We can now refer to the (far, far more rigorous and detailed) analysis in the paper to compare our results! Here's the diagram they give of their results. \n",
- "\n",
- "![IOI1](https://pbs.twimg.com/media/FghGkTAWAAAmkhm.jpg)\n",
- "\n",
- "(Head 1.2 in their notation is L1H2 in my notation etc. And note - in the [latest version of the paper](https://arxiv.org/pdf/2211.00593.pdf) they add 9.0 as a backup name mover, and remove 11.3)\n",
- "\n",
- "The heads form three categories corresponding to the early, middle and late categories we found and we did fairly well! Definitely not perfect, but with some fairly generic techniques and some a priori reasoning, we found the broad strokes of the circuit and what it looks like. We focused on the most important heads, so we didn't find all relevant heads in each category (especially not the heads in brackets, which are more minor), but this serves as a good base for doing more rigorous and involved analysis, especially for finding the *complete* circuit (ie all of the parts of the model which participate in this behaviour) rather than just a partial and suggestive circuit. Go check out [their paper](https://arxiv.org/abs/2211.00593) or [our interview](https://www.youtube.com/watch?v=gzwj0jWbvbo) to learn more about what they did and what they found!\n",
- "\n",
- "Breaking down their categories:\n",
- "\n",
- "* Early: The duplicate token heads, previous token heads and induction heads. These serve the purpose of detecting that the second subject is duplicated and which earlier name is the duplicate.\n",
- " * We found a direct duplicate token head which behaves exactly as expected, L3H0. Heads L5H0 and L6H9 are induction heads, which explains why they don't attend directly to the earlier copy of John!\n",
- " * Note that the duplicate token heads and induction heads do not compose with each other - both directly add to the S-Inhibition heads. The diagram is somewhat misleading.\n",
- "* Middle: They call these S-Inhibition heads - they copy the information about the duplicate token from the second subject to the to token, and their output is used to *inhibit* the attention paid from the name movers to the first subject copy. We found all these heads, and had a decent guess for what they did.\n",
- " * In either case they attend to the second subject, so the patch that mattered was their value vectors!\n",
- "* Late: They call these name movers, and we found some of them. They attend from the final token to the indirect object name and copy that to the logits, using the S-Inhibition heads to inhibit attention to the first copy of the subject token.\n",
- " * We did find their surprising result of *negative* name movers - name movers that inhibit the correct answer!\n",
- " * They have an entire category of heads we missed called backup name movers - we'll get to these later.\n",
- "\n",
- "So, now, let's dig into the two anomalies we missed - induction heads and backup name mover heads"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Bonus: Exploring Anomalies"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Early Heads are Induction Heads(?!)\n",
- "\n",
- "A really weird observation is that some of the early heads detecting duplicated tokens are induction heads, not just direct duplicate token heads. This is very weird! What's up with that? \n",
- "\n",
- "First off, what's an induction head? An induction head is an important type of attention head that can detect and continue repeated sequences. It is the second head in a two head induction circuit, which looks for previous copies of the current token and attends to the token *after* it, and then copies that to the current position and predicts that it will come next. They're enough of a big deal that [we wrote a whole paper on them](https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html).\n",
- "\n",
- "![Move image demo](https://pbs.twimg.com/media/FNWAzXjVEAEOGRe.jpg)\n",
- "\n",
- "Second, why is it surprising that they come up here? It's surprising because it feels like overkill. The model doesn't care about *what* token comes after the first copy of the subject, just that it's duplicated. And it already has simpler duplicate token heads. My best guess is that it just already had induction heads around and that, in addition to their main function, they *also* only activate on duplicated tokens. So it was useful to repurpose this existing machinery. \n",
- "\n",
- "This suggests that as we look for circuits in larger models life may get more and more complicated, as components in simpler circuits get repurposed and built upon. "
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can verify that these are induction heads by running the model on repeated text and plotting the heads."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 34,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:06.819781Z",
- "iopub.status.busy": "2024-08-14T01:22:06.819614Z",
- "iopub.status.idle": "2024-08-14T01:22:06.971531Z",
- "shell.execute_reply": "2024-08-14T01:22:06.970985Z"
- }
- },
- "outputs": [],
- "source": [
- "example_text = \"Research in mechanistic interpretability seeks to explain behaviors of machine learning models in terms of their internal components.\"\n",
- "example_repeated_text = example_text + example_text\n",
- "example_repeated_tokens = model.to_tokens(example_repeated_text, prepend_bos=True)\n",
- "example_repeated_logits, example_repeated_cache = model.run_with_cache(\n",
- " example_repeated_tokens\n",
- ")\n",
- "induction_head_labels = [81, 65]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 35,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:06.974122Z",
- "iopub.status.busy": "2024-08-14T01:22:06.973736Z",
- "iopub.status.idle": "2024-08-14T01:22:06.983703Z",
- "shell.execute_reply": "2024-08-14T01:22:06.983237Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "
"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "per_head_ablated_residual, labels = ablated_cache.stack_head_results(\n",
- " layer=-1, pos_slice=-1, return_labels=True\n",
- ")\n",
- "per_head_ablated_logit_diffs = residual_stack_to_logit_diff(\n",
- " per_head_ablated_residual, ablated_cache\n",
- ")\n",
- "per_head_ablated_logit_diffs = per_head_ablated_logit_diffs.reshape(\n",
- " model.cfg.n_layers, model.cfg.n_heads\n",
- ")\n",
- "imshow(per_head_ablated_logit_diffs, labels={\"x\": \"Head\", \"y\": \"Layer\"})\n",
- "scatter(\n",
- " y=per_head_logit_diffs.flatten(),\n",
- " x=per_head_ablated_logit_diffs.flatten(),\n",
- " hover_name=head_labels,\n",
- " range_x=(-3, 3),\n",
- " range_y=(-3, 3),\n",
- " xaxis=\"Ablated\",\n",
- " yaxis=\"Original\",\n",
- " title=\"Original vs Post-Ablation Direct Logit Attribution of Heads\",\n",
- ")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "One natural hypothesis is that this is because the final LayerNorm scaling has changed, which can scale up or down the final residual stream. This is slightly true, and we can see that the typical head is a bit off from the x=y line. But the average LN scaling ratio is 1.04, and this should uniformly change *all* heads by the same factor, so this can't be sufficient"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:08.205491Z",
- "iopub.status.busy": "2024-08-14T01:22:08.205314Z",
- "iopub.status.idle": "2024-08-14T01:22:08.210603Z",
- "shell.execute_reply": "2024-08-14T01:22:08.210109Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Average LN scaling ratio: 1.042\n",
- "Ablation LN scale tensor([[18.5200],\n",
- " [17.4700],\n",
- " [17.8200],\n",
- " [17.5100],\n",
- " [17.2600],\n",
- " [18.2500],\n",
- " [16.1800],\n",
- " [17.4300]])\n",
- "Original LN scale tensor([[19.5700],\n",
- " [18.3500],\n",
- " [18.2900],\n",
- " [18.6800],\n",
- " [17.4900],\n",
- " [18.8700],\n",
- " [16.4200],\n",
- " [18.6800]])\n"
- ]
- }
- ],
- "source": [
- "print(\n",
- " \"Average LN scaling ratio:\",\n",
- " round(\n",
- " (\n",
- " cache[\"ln_final.hook_scale\"][:, -1]\n",
- " / ablated_cache[\"ln_final.hook_scale\"][:, -1]\n",
- " )\n",
- " .mean()\n",
- " .item(),\n",
- " 3,\n",
- " ),\n",
- ")\n",
- "print(\n",
- " \"Ablation LN scale\",\n",
- " ablated_cache[\"ln_final.hook_scale\"][:, -1].detach().cpu().round(decimals=2),\n",
- ")\n",
- "print(\n",
- " \"Original LN scale\",\n",
- " cache[\"ln_final.hook_scale\"][:, -1].detach().cpu().round(decimals=2),\n",
- ")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Exercise to the reader:** Can you finish off this analysis? What's going on here? Why are the backup name movers changing their behaviour? Why is one negative name mover becoming significantly less important?"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": ".venv",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.9"
- },
- "vscode": {
- "interpreter": {
- "hash": "eb812820b5094695c8a581672e17220e30dd2c15d704c018326e3cc2e1a566f1"
- }
- },
- "widgets": {
- "application/vnd.jupyter.widget-state+json": {
- "state": {
- "077b053bf73846059a519b7354ea1e0b": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_e32f5abf0da94d3d9c4c8616293e26ec",
- "placeholder": "",
- "style": "IPY_MODEL_beca8ad391964faa82d98b3f6189ef87",
- "tabbable": null,
- "tooltip": null,
- "value": "tokenizer.json: 100%"
- }
- },
- "0caab2c2abee46cdba2b7ced01beca6b": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "0dcffca7265c49df87a0ae71c4698cd0": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "0e3d230c8633497a9c2c08578a326135": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_323ed6e481d14b8e9abbaef1ab67f943",
- "placeholder": "",
- "style": "IPY_MODEL_c231effe025e474580afaf5d4305a5b0",
- "tabbable": null,
- "tooltip": null,
- "value": " 26.0/26.0 [00:00<00:00, 4.69kB/s]"
- }
- },
- "12e179ccdc1e4c13b9bde0ac26091b63": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HBoxModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HBoxModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HBoxView",
- "box_style": "",
- "children": [
- "IPY_MODEL_077b053bf73846059a519b7354ea1e0b",
- "IPY_MODEL_b43b4b5def3248da92a91037f4c98386",
- "IPY_MODEL_97798f96c11a4f2f9d387848a6ef5b95"
- ],
- "layout": "IPY_MODEL_1fa45349d8c1460cbc533148b588c1b4",
- "tabbable": null,
- "tooltip": null
- }
- },
- "13a66e4754df4e7ba5cc07197e70a522": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_fd7619eebe5541b4a416fb6b50db6f24",
- "placeholder": "",
- "style": "IPY_MODEL_f6090935b7e14e7d8bd0d0db357dd302",
- "tabbable": null,
- "tooltip": null,
- "value": " 548M/548M [00:02<00:00, 236MB/s]"
- }
- },
- "187f57078ef442b38f759819e54a5d94": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "FloatProgressModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "FloatProgressModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "ProgressView",
- "bar_style": "success",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_ff06b1ef9c9b486db39aa5a385b39d56",
- "max": 456318.0,
- "min": 0.0,
- "orientation": "horizontal",
- "style": "IPY_MODEL_d3e6670e915246659dd1e0bbbb1689ff",
- "tabbable": null,
- "tooltip": null,
- "value": 456318.0
- }
- },
- "1dc19f8526754226a74249b5f044c2a8": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "FloatProgressModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "FloatProgressModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "ProgressView",
- "bar_style": "success",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_9353e20667a145a692f7ac8d1810f029",
- "max": 548105171.0,
- "min": 0.0,
- "orientation": "horizontal",
- "style": "IPY_MODEL_880381a3e14041a5b18e87395e93f531",
- "tabbable": null,
- "tooltip": null,
- "value": 548105171.0
- }
- },
- "1fa45349d8c1460cbc533148b588c1b4": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "2018e97859ad49cbaee7ed0b8ff2064d": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "280c8cbf80cd4f5a9f89b22a42bf821f": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_770a783ecf8f45558cb127ac0ac66555",
- "placeholder": "",
- "style": "IPY_MODEL_4b182da3c43a427191df1014887454c9",
- "tabbable": null,
- "tooltip": null,
- "value": "model.safetensors: 100%"
- }
- },
- "28179d7b198c460fae2a7226fc2270aa": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "323ed6e481d14b8e9abbaef1ab67f943": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "3425e013b48741d6a16f42bcc7363a76": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "3fe96610bc6341aebe357616c038f384": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_847b917ce5e64b76afc36ade62495c9b",
- "placeholder": "",
- "style": "IPY_MODEL_7fc54a12a17542afa48d8a0228e9f6fe",
- "tabbable": null,
- "tooltip": null,
- "value": " 124/124 [00:00<00:00, 22.2kB/s]"
- }
- },
- "42a34f4dc38e4d79939ffdd5d445e454": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "4b182da3c43a427191df1014887454c9": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "5734961a157342a8b7d8d160769bef66": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "5bec168763f9422e865a52fd632d07d4": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "6a4f6dea119142b8ba9073e83c62246a": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "6b1454e2357146389781c111a33f8c7e": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_9c05fd33311f4eb6af67644244d0b392",
- "placeholder": "",
- "style": "IPY_MODEL_9e18f17e0e3141e3bde3691a1b419f74",
- "tabbable": null,
- "tooltip": null,
- "value": "merges.txt: 100%"
- }
- },
- "6d61aa12183f46d5a70813b289208c75": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_b7de82c11e1d407a9654ca5d92fabcae",
- "placeholder": "",
- "style": "IPY_MODEL_f151474cf52f4871ad3581a4d8a0161e",
- "tabbable": null,
- "tooltip": null,
- "value": "tokenizer_config.json: 100%"
- }
- },
- "7314eb4af4fb44478aff360a01b15b28": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "770a783ecf8f45558cb127ac0ac66555": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "79751ffa6e094cd9a6447889f67adb4b": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HBoxModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HBoxModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HBoxView",
- "box_style": "",
- "children": [
- "IPY_MODEL_6b1454e2357146389781c111a33f8c7e",
- "IPY_MODEL_187f57078ef442b38f759819e54a5d94",
- "IPY_MODEL_8620f48581ca4aab93b1ece3c173f105"
- ],
- "layout": "IPY_MODEL_7314eb4af4fb44478aff360a01b15b28",
- "tabbable": null,
- "tooltip": null
- }
- },
- "7bd8978171af40cfb274f23b1eac5c51": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "7fc54a12a17542afa48d8a0228e9f6fe": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "7fc7bc7b7265481087152a751341caa8": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_0dcffca7265c49df87a0ae71c4698cd0",
- "placeholder": "",
- "style": "IPY_MODEL_0caab2c2abee46cdba2b7ced01beca6b",
- "tabbable": null,
- "tooltip": null,
- "value": " 1.04M/1.04M [00:00<00:00, 29.0MB/s]"
- }
- },
- "847b917ce5e64b76afc36ade62495c9b": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "8620f48581ca4aab93b1ece3c173f105": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_28179d7b198c460fae2a7226fc2270aa",
- "placeholder": "",
- "style": "IPY_MODEL_6a4f6dea119142b8ba9073e83c62246a",
- "tabbable": null,
- "tooltip": null,
- "value": " 456k/456k [00:00<00:00, 24.5MB/s]"
- }
- },
- "880381a3e14041a5b18e87395e93f531": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "ProgressStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "ProgressStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "bar_color": null,
- "description_width": ""
- }
- },
- "8a013ade1ece44068926ba70ee1e8782": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "8cf98f5b28db46d9badbcec1622aa05d": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "9353e20667a145a692f7ac8d1810f029": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "945e0c913801467ba980eeb6cea10aea": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "97798f96c11a4f2f9d387848a6ef5b95": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_3425e013b48741d6a16f42bcc7363a76",
- "placeholder": "",
- "style": "IPY_MODEL_5bec168763f9422e865a52fd632d07d4",
- "tabbable": null,
- "tooltip": null,
- "value": " 1.36M/1.36M [00:00<00:00, 63.3MB/s]"
- }
- },
- "996fa7a72ae9498f884d1f98cba45a69": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "FloatProgressModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "FloatProgressModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "ProgressView",
- "bar_style": "success",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_8a013ade1ece44068926ba70ee1e8782",
- "max": 26.0,
- "min": 0.0,
- "orientation": "horizontal",
- "style": "IPY_MODEL_ef0b32cb18bb43338acc9185a857919c",
- "tabbable": null,
- "tooltip": null,
- "value": 26.0
- }
- },
- "9c05fd33311f4eb6af67644244d0b392": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "9de2df8e0804490db752629f88935f6a": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HBoxModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HBoxModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HBoxView",
- "box_style": "",
- "children": [
- "IPY_MODEL_280c8cbf80cd4f5a9f89b22a42bf821f",
- "IPY_MODEL_1dc19f8526754226a74249b5f044c2a8",
- "IPY_MODEL_13a66e4754df4e7ba5cc07197e70a522"
- ],
- "layout": "IPY_MODEL_8cf98f5b28db46d9badbcec1622aa05d",
- "tabbable": null,
- "tooltip": null
- }
- },
- "9e18f17e0e3141e3bde3691a1b419f74": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "a72d9c5e1228423e914520194face6bb": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HBoxModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HBoxModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HBoxView",
- "box_style": "",
- "children": [
- "IPY_MODEL_e853515d54d84ac4801830a9ab85b693",
- "IPY_MODEL_e1ec2e412ec542a0b358a79a2bc3af4b",
- "IPY_MODEL_7fc7bc7b7265481087152a751341caa8"
- ],
- "layout": "IPY_MODEL_aac4ed89c8154b43883f56d6715e7f10",
- "tabbable": null,
- "tooltip": null
- }
- },
- "aac4ed89c8154b43883f56d6715e7f10": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "b43b4b5def3248da92a91037f4c98386": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "FloatProgressModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "FloatProgressModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "ProgressView",
- "bar_style": "success",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_2018e97859ad49cbaee7ed0b8ff2064d",
- "max": 1355256.0,
- "min": 0.0,
- "orientation": "horizontal",
- "style": "IPY_MODEL_d36655a9f4ef4fbfb2c43781c2661285",
- "tabbable": null,
- "tooltip": null,
- "value": 1355256.0
- }
- },
- "b7de82c11e1d407a9654ca5d92fabcae": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "b9902249d04546eba782688e5a69ba97": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "FloatProgressModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "FloatProgressModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "ProgressView",
- "bar_style": "success",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_5734961a157342a8b7d8d160769bef66",
- "max": 124.0,
- "min": 0.0,
- "orientation": "horizontal",
- "style": "IPY_MODEL_d3bda856f341491bb158d4977dab2d44",
- "tabbable": null,
- "tooltip": null,
- "value": 124.0
- }
- },
- "beca8ad391964faa82d98b3f6189ef87": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "c0f2b2a042574dafac2262692f858162": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HBoxModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HBoxModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HBoxView",
- "box_style": "",
- "children": [
- "IPY_MODEL_f6b879fb6da74b09897a4bff0a2343f8",
- "IPY_MODEL_b9902249d04546eba782688e5a69ba97",
- "IPY_MODEL_3fe96610bc6341aebe357616c038f384"
- ],
- "layout": "IPY_MODEL_c510a95a91fa402fa37e550fe38deba1",
- "tabbable": null,
- "tooltip": null
- }
- },
- "c231effe025e474580afaf5d4305a5b0": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "c510a95a91fa402fa37e550fe38deba1": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "cf1e5a16d96047a0818d0d22d2fe1b03": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "d36655a9f4ef4fbfb2c43781c2661285": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "ProgressStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "ProgressStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "bar_color": null,
- "description_width": ""
- }
- },
- "d3bda856f341491bb158d4977dab2d44": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "ProgressStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "ProgressStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "bar_color": null,
- "description_width": ""
- }
- },
- "d3e6670e915246659dd1e0bbbb1689ff": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "ProgressStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "ProgressStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "bar_color": null,
- "description_width": ""
- }
- },
- "d85ad433e2b64598b6ed677d656d7db7": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "db2a8f026dff4321a69e00990a055259": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "e1ec2e412ec542a0b358a79a2bc3af4b": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "FloatProgressModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "FloatProgressModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "ProgressView",
- "bar_style": "success",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_7bd8978171af40cfb274f23b1eac5c51",
- "max": 1042301.0,
- "min": 0.0,
- "orientation": "horizontal",
- "style": "IPY_MODEL_e58fcaff13ca46f08a53defe12de73e2",
- "tabbable": null,
- "tooltip": null,
- "value": 1042301.0
- }
- },
- "e32f5abf0da94d3d9c4c8616293e26ec": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "e58fcaff13ca46f08a53defe12de73e2": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "ProgressStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "ProgressStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "bar_color": null,
- "description_width": ""
- }
- },
- "e853515d54d84ac4801830a9ab85b693": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_42a34f4dc38e4d79939ffdd5d445e454",
- "placeholder": "",
- "style": "IPY_MODEL_db2a8f026dff4321a69e00990a055259",
- "tabbable": null,
- "tooltip": null,
- "value": "vocab.json: 100%"
- }
- },
- "ecc5187139f249a5814953106dd56bd1": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HBoxModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HBoxModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HBoxView",
- "box_style": "",
- "children": [
- "IPY_MODEL_6d61aa12183f46d5a70813b289208c75",
- "IPY_MODEL_996fa7a72ae9498f884d1f98cba45a69",
- "IPY_MODEL_0e3d230c8633497a9c2c08578a326135"
- ],
- "layout": "IPY_MODEL_945e0c913801467ba980eeb6cea10aea",
- "tabbable": null,
- "tooltip": null
- }
- },
- "ef0b32cb18bb43338acc9185a857919c": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "ProgressStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "ProgressStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "bar_color": null,
- "description_width": ""
- }
- },
- "f151474cf52f4871ad3581a4d8a0161e": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "f6090935b7e14e7d8bd0d0db357dd302": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLStyleModel",
- "state": {
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLStyleModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "StyleView",
- "background": null,
- "description_width": "",
- "font_size": null,
- "text_color": null
- }
- },
- "f6b879fb6da74b09897a4bff0a2343f8": {
- "model_module": "@jupyter-widgets/controls",
- "model_module_version": "2.0.0",
- "model_name": "HTMLModel",
- "state": {
- "_dom_classes": [],
- "_model_module": "@jupyter-widgets/controls",
- "_model_module_version": "2.0.0",
- "_model_name": "HTMLModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/controls",
- "_view_module_version": "2.0.0",
- "_view_name": "HTMLView",
- "description": "",
- "description_allow_html": false,
- "layout": "IPY_MODEL_d85ad433e2b64598b6ed677d656d7db7",
- "placeholder": "",
- "style": "IPY_MODEL_cf1e5a16d96047a0818d0d22d2fe1b03",
- "tabbable": null,
- "tooltip": null,
- "value": "generation_config.json: 100%"
- }
- },
- "fd7619eebe5541b4a416fb6b50db6f24": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- },
- "ff06b1ef9c9b486db39aa5a385b39d56": {
- "model_module": "@jupyter-widgets/base",
- "model_module_version": "2.0.0",
- "model_name": "LayoutModel",
- "state": {
- "_model_module": "@jupyter-widgets/base",
- "_model_module_version": "2.0.0",
- "_model_name": "LayoutModel",
- "_view_count": null,
- "_view_module": "@jupyter-widgets/base",
- "_view_module_version": "2.0.0",
- "_view_name": "LayoutView",
- "align_content": null,
- "align_items": null,
- "align_self": null,
- "border_bottom": null,
- "border_left": null,
- "border_right": null,
- "border_top": null,
- "bottom": null,
- "display": null,
- "flex": null,
- "flex_flow": null,
- "grid_area": null,
- "grid_auto_columns": null,
- "grid_auto_flow": null,
- "grid_auto_rows": null,
- "grid_column": null,
- "grid_gap": null,
- "grid_row": null,
- "grid_template_areas": null,
- "grid_template_columns": null,
- "grid_template_rows": null,
- "height": null,
- "justify_content": null,
- "justify_items": null,
- "left": null,
- "margin": null,
- "max_height": null,
- "max_width": null,
- "min_height": null,
- "min_width": null,
- "object_fit": null,
- "object_position": null,
- "order": null,
- "overflow": null,
- "padding": null,
- "right": null,
- "top": null,
- "visibility": null,
- "width": null
- }
- }
- },
- "version_major": 2,
- "version_minor": 0
- }
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/.doctrees/nbsphinx/generated/demos/Main_Demo.ipynb b/.doctrees/nbsphinx/generated/demos/Main_Demo.ipynb
deleted file mode 100644
index 2b63d7f32..000000000
--- a/.doctrees/nbsphinx/generated/demos/Main_Demo.ipynb
+++ /dev/null
@@ -1,6377 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- " \n",
- ""
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Transformer Lens Main Demo Notebook\n",
- "\n",
- "To use this notebook, go to Runtime > Change Runtime Type and select GPU as the hardware accelerator.\n",
- "\n",
- "This is a reference notebook covering the main features of the [TransformerLens](https://github.com/TransformerLensOrg/TransformerLens) library for mechanistic interpretability. See [Callum McDougall's tutorial](https://transformerlens-intro.streamlit.app/TransformerLens_&_induction_circuits) for a more structured and gentler introduction to the library"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Tips for reading this Colab:**\n",
- "* You can run all this code for yourself! \n",
- "* The graphs are interactive!\n",
- "* Use the table of contents pane in the sidebar to navigate\n",
- "* Collapse irrelevant sections with the dropdown arrows\n",
- "* Search the page using the search in the sidebar, not CTRL+F"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Setup\n",
- "(No need to read)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:14.146237Z",
- "iopub.status.busy": "2024-08-14T01:22:14.146069Z",
- "iopub.status.idle": "2024-08-14T01:22:14.156346Z",
- "shell.execute_reply": "2024-08-14T01:22:14.155790Z"
- }
- },
- "outputs": [],
- "source": [
- "import os\n",
- "DEVELOPMENT_MODE = False\n",
- "# Detect if we're running in Google Colab\n",
- "try:\n",
- " import google.colab\n",
- " IN_COLAB = True\n",
- " print(\"Running as a Colab notebook\")\n",
- "except:\n",
- " IN_COLAB = False\n",
- "\n",
- "# Install if in Colab\n",
- "if IN_COLAB:\n",
- " %pip install transformer_lens\n",
- " %pip install circuitsvis\n",
- " # Install a faster Node version\n",
- " !curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -; sudo apt-get install -y nodejs # noqa\n",
- "\n",
- "# Hot reload in development mode & not running on the CD\n",
- "if not IN_COLAB:\n",
- " from IPython import get_ipython\n",
- " ip = get_ipython()\n",
- " if not ip.extension_manager.loaded:\n",
- " ip.extension_manager.load('autoreload')\n",
- " %autoreload 2\n",
- " \n",
- "IN_GITHUB = os.getenv(\"GITHUB_ACTIONS\") == \"true\"\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:14.158538Z",
- "iopub.status.busy": "2024-08-14T01:22:14.158226Z",
- "iopub.status.idle": "2024-08-14T01:22:14.278664Z",
- "shell.execute_reply": "2024-08-14T01:22:14.278033Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Using renderer: colab\n"
- ]
- }
- ],
- "source": [
- "# Plotly needs a different renderer for VSCode/Notebooks vs Colab argh\n",
- "import plotly.io as pio\n",
- "if IN_COLAB or not DEVELOPMENT_MODE:\n",
- " pio.renderers.default = \"colab\"\n",
- "else:\n",
- " pio.renderers.default = \"notebook_connected\"\n",
- "print(f\"Using renderer: {pio.renderers.default}\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:14.280655Z",
- "iopub.status.busy": "2024-08-14T01:22:14.280477Z",
- "iopub.status.idle": "2024-08-14T01:22:15.603390Z",
- "shell.execute_reply": "2024-08-14T01:22:15.602807Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- " "
- ],
- "text/plain": [
- ""
- ]
- },
- "execution_count": 3,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "import circuitsvis as cv\n",
- "# Testing that the library works\n",
- "cv.examples.hello(\"Neel\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:15.605685Z",
- "iopub.status.busy": "2024-08-14T01:22:15.605280Z",
- "iopub.status.idle": "2024-08-14T01:22:15.899344Z",
- "shell.execute_reply": "2024-08-14T01:22:15.898705Z"
- }
- },
- "outputs": [],
- "source": [
- "# Import stuff\n",
- "import torch\n",
- "import torch.nn as nn\n",
- "import einops\n",
- "from fancy_einsum import einsum\n",
- "import tqdm.auto as tqdm\n",
- "import plotly.express as px\n",
- "\n",
- "from jaxtyping import Float\n",
- "from functools import partial"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:15.901899Z",
- "iopub.status.busy": "2024-08-14T01:22:15.901514Z",
- "iopub.status.idle": "2024-08-14T01:22:17.407760Z",
- "shell.execute_reply": "2024-08-14T01:22:17.407264Z"
- }
- },
- "outputs": [],
- "source": [
- "# import transformer_lens\n",
- "import transformer_lens.utils as utils\n",
- "from transformer_lens.hook_points import (\n",
- " HookPoint,\n",
- ") # Hooking utilities\n",
- "from transformer_lens import HookedTransformer, FactoredMatrix"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We turn automatic differentiation off, to save GPU memory, as this notebook focuses on model inference not model training."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:17.410155Z",
- "iopub.status.busy": "2024-08-14T01:22:17.409802Z",
- "iopub.status.idle": "2024-08-14T01:22:17.413551Z",
- "shell.execute_reply": "2024-08-14T01:22:17.413047Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- ""
- ]
- },
- "execution_count": 6,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "torch.set_grad_enabled(False)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Plotting helper functions:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:17.415594Z",
- "iopub.status.busy": "2024-08-14T01:22:17.415336Z",
- "iopub.status.idle": "2024-08-14T01:22:17.420635Z",
- "shell.execute_reply": "2024-08-14T01:22:17.420199Z"
- }
- },
- "outputs": [],
- "source": [
- "def imshow(tensor, renderer=None, xaxis=\"\", yaxis=\"\", **kwargs):\n",
- " px.imshow(utils.to_numpy(tensor), color_continuous_midpoint=0.0, color_continuous_scale=\"RdBu\", labels={\"x\":xaxis, \"y\":yaxis}, **kwargs).show(renderer)\n",
- "\n",
- "def line(tensor, renderer=None, xaxis=\"\", yaxis=\"\", **kwargs):\n",
- " px.line(utils.to_numpy(tensor), labels={\"x\":xaxis, \"y\":yaxis}, **kwargs).show(renderer)\n",
- "\n",
- "def scatter(x, y, xaxis=\"\", yaxis=\"\", caxis=\"\", renderer=None, **kwargs):\n",
- " x = utils.to_numpy(x)\n",
- " y = utils.to_numpy(y)\n",
- " px.scatter(y=y, x=x, labels={\"x\":xaxis, \"y\":yaxis, \"color\":caxis}, **kwargs).show(renderer)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Introduction"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This is a demo notebook for [TransformerLens](https://github.com/TransformerLensOrg/TransformerLens), **a library I ([Neel Nanda](https://neelnanda.io)) wrote for doing [mechanistic interpretability](https://distill.pub/2020/circuits/zoom-in/) of GPT-2 Style language models.** The goal of mechanistic interpretability is to take a trained model and reverse engineer the algorithms the model learned during training from its weights. It is a fact about the world today that we have computer programs that can essentially speak English at a human level (GPT-3, PaLM, etc), yet we have no idea how they work nor how to write one ourselves. This offends me greatly, and I would like to solve this! Mechanistic interpretability is a very young and small field, and there are a *lot* of open problems - if you would like to help, please try working on one! **If you want to skill up, check out [my guide to getting started](https://neelnanda.io/getting-started), and if you want to jump into an open problem check out my sequence [200 Concrete Open Problems in Mechanistic Interpretability](https://neelnanda.io/concrete-open-problems).**\n",
- "\n",
- "I wrote this library because after I left the Anthropic interpretability team and started doing independent research, I got extremely frustrated by the state of open source tooling. There's a lot of excellent infrastructure like HuggingFace and DeepSpeed to *use* or *train* models, but very little to dig into their internals and reverse engineer how they work. **This library tries to solve that**, and to make it easy to get into the field even if you don't work at an industry org with real infrastructure! The core features were heavily inspired by [Anthropic's excellent Garcon tool](https://transformer-circuits.pub/2021/garcon/index.html). Credit to Nelson Elhage and Chris Olah for building Garcon and showing me the value of good infrastructure for accelerating exploratory research!\n",
- "\n",
- "The core design principle I've followed is to enable exploratory analysis - one of the most fun parts of mechanistic interpretability compared to normal ML is the extremely short feedback loops! The point of this library is to keep the gap between having an experiment idea and seeing the results as small as possible, to make it easy for **research to feel like play** and to enter a flow state. This notebook demonstrates how the library works and how to use it, but if you want to see how well it works for exploratory research, check out [my notebook analysing Indirect Objection Identification](https://neelnanda.io/exploratory-analysis-demo) or [my recording of myself doing research](https://www.youtube.com/watch?v=yo4QvDn-vsU)!"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Loading and Running Models\n",
- "\n",
- "TransformerLens comes loaded with >40 open source GPT-style models. You can load any of them in with `HookedTransformer.from_pretrained(MODEL_NAME)`. For this demo notebook we'll look at GPT-2 Small, an 80M parameter model, see the Available Models section for info on the rest."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:17.422720Z",
- "iopub.status.busy": "2024-08-14T01:22:17.422352Z",
- "iopub.status.idle": "2024-08-14T01:22:17.425068Z",
- "shell.execute_reply": "2024-08-14T01:22:17.424654Z"
- }
- },
- "outputs": [],
- "source": [
- "device = utils.get_device()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:17.427018Z",
- "iopub.status.busy": "2024-08-14T01:22:17.426690Z",
- "iopub.status.idle": "2024-08-14T01:22:18.128653Z",
- "shell.execute_reply": "2024-08-14T01:22:18.128071Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Loaded pretrained model gpt2-small into HookedTransformer\n"
- ]
- }
- ],
- "source": [
- "# NBVAL_IGNORE_OUTPUT\n",
- "model = HookedTransformer.from_pretrained(\"gpt2-small\", device=device)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To try the model out, let's find the loss on this text! Models can be run on a single string or a tensor of tokens (shape: [batch, position], all integers), and the possible return types are: \n",
- "* \"logits\" (shape [batch, position, d_vocab], floats), \n",
- "* \"loss\" (the cross-entropy loss when predicting the next token), \n",
- "* \"both\" (a tuple of (logits, loss)) \n",
- "* None (run the model, but don't calculate the logits - this is faster when we only want to use intermediate activations)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:18.131096Z",
- "iopub.status.busy": "2024-08-14T01:22:18.130672Z",
- "iopub.status.idle": "2024-08-14T01:22:18.443120Z",
- "shell.execute_reply": "2024-08-14T01:22:18.442482Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Model loss: tensor(4.1758)\n"
- ]
- }
- ],
- "source": [
- "model_description_text = \"\"\"## Loading Models\n",
- "\n",
- "HookedTransformer comes loaded with >40 open source GPT-style models. You can load any of them in with `HookedTransformer.from_pretrained(MODEL_NAME)`. See my explainer for documentation of all supported models, and this table for hyper-parameters and the name used to load them. Each model is loaded into the consistent HookedTransformer architecture, designed to be clean, consistent and interpretability-friendly. \n",
- "\n",
- "For this demo notebook we'll look at GPT-2 Small, an 80M parameter model. To try the model the model out, let's find the loss on this paragraph!\"\"\"\n",
- "loss = model(model_description_text, return_type=\"loss\")\n",
- "print(\"Model loss:\", loss)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Caching all Activations\n",
- "\n",
- "The first basic operation when doing mechanistic interpretability is to break open the black box of the model and look at all of the internal activations of a model. This can be done with `logits, cache = model.run_with_cache(tokens)`. Let's try this out on the first line of the abstract of the GPT-2 paper.\n",
- "\n",
- "On `remove_batch_dim`\n",
- "\n",
- "Every activation inside the model begins with a batch dimension. Here, because we only entered a single batch dimension, that dimension is always length 1 and kinda annoying, so passing in the `remove_batch_dim=True` keyword removes it. `gpt2_cache_no_batch_dim = gpt2_cache.remove_batch_dim()` would have achieved the same effect.\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:18.445591Z",
- "iopub.status.busy": "2024-08-14T01:22:18.445173Z",
- "iopub.status.idle": "2024-08-14T01:22:18.704716Z",
- "shell.execute_reply": "2024-08-14T01:22:18.704051Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "cpu\n"
- ]
- }
- ],
- "source": [
- "gpt2_text = \"Natural language processing tasks, such as question answering, machine translation, reading comprehension, and summarization, are typically approached with supervised learning on taskspecific datasets.\"\n",
- "gpt2_tokens = model.to_tokens(gpt2_text)\n",
- "print(gpt2_tokens.device)\n",
- "gpt2_logits, gpt2_cache = model.run_with_cache(gpt2_tokens, remove_batch_dim=True)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Let's visualize the attention pattern of all the heads in layer 0, using [Alan Cooney's CircuitsVis library](https://github.com/alan-cooney/CircuitsVis) (based on [Anthropic's PySvelte library](https://github.com/anthropics/PySvelte)). \n",
- "\n",
- "We look this the attention pattern in `gpt2_cache`, an `ActivationCache` object, by entering in the name of the activation, followed by the layer index (here, the activation is called \"attn\" and the layer index is 0). This has shape [head_index, destination_position, source_position], and we use the `model.to_str_tokens` method to convert the text to a list of tokens as strings, since there is an attention weight between each pair of tokens.\n",
- "\n",
- "This visualization is interactive! Try hovering over a token or head, and click to lock. The grid on the top left and for each head is the attention pattern as a destination position by source position grid. It's lower triangular because GPT-2 has **causal attention**, attention can only look backwards, so information can only move forwards in the network.\n",
- "\n",
- "See the ActivationCache section for more on what `gpt2_cache` can do."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:18.707457Z",
- "iopub.status.busy": "2024-08-14T01:22:18.707110Z",
- "iopub.status.idle": "2024-08-14T01:22:18.711518Z",
- "shell.execute_reply": "2024-08-14T01:22:18.710967Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n",
- "torch.Size([12, 33, 33])\n"
- ]
- }
- ],
- "source": [
- "print(type(gpt2_cache))\n",
- "attention_pattern = gpt2_cache[\"pattern\", 0, \"attn\"]\n",
- "print(attention_pattern.shape)\n",
- "gpt2_str_tokens = model.to_str_tokens(gpt2_text)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:18.713530Z",
- "iopub.status.busy": "2024-08-14T01:22:18.713135Z",
- "iopub.status.idle": "2024-08-14T01:22:18.804930Z",
- "shell.execute_reply": "2024-08-14T01:22:18.804403Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Layer 0 Head Attention Patterns:\n"
- ]
- },
- {
- "data": {
- "text/html": [
- "\n",
- " "
- ],
- "text/plain": [
- ""
- ]
- },
- "execution_count": 13,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "print(\"Layer 0 Head Attention Patterns:\")\n",
- "cv.attention.attention_patterns(tokens=gpt2_str_tokens, attention=attention_pattern)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hooks: Intervening on Activations"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "One of the great things about interpreting neural networks is that we have *full control* over our system. From a computational perspective, we know exactly what operations are going on inside (even if we don't know what they mean!). And we can make precise, surgical edits and see how the model's behaviour and other internals change. This is an extremely powerful tool, because it can let us eg set up careful counterfactuals and causal intervention to easily understand model behaviour. \n",
- "\n",
- "Accordingly, being able to do this is a pretty core operation, and this is one of the main things TransformerLens supports! The key feature here is **hook points**. Every activation inside the transformer is surrounded by a hook point, which allows us to edit or intervene on it. \n",
- "\n",
- "We do this by adding a **hook function** to that activation. The hook function maps `current_activation_value, hook_point` to `new_activation_value`. As the model is run, it computes that activation as normal, and then the hook function is applied to compute a replacement, and that is substituted in for the activation. The hook function can be an arbitrary Python function, so long as it returns a tensor of the correct shape.\n",
- "\n",
- "Relationship to PyTorch hooks\n",
- "\n",
- "[PyTorch hooks](https://blog.paperspace.com/pytorch-hooks-gradient-clipping-debugging/) are a great and underrated, yet incredibly janky, feature. They can act on a layer, and edit the input or output of that layer, or the gradient when applying autodiff. The key difference is that **Hook points** act on *activations* not layers. This means that you can intervene within a layer on each activation, and don't need to care about the precise layer structure of the transformer. And it's immediately clear exactly how the hook's effect is applied. This adjustment was shamelessly inspired by [Garcon's use of ProbePoints](https://transformer-circuits.pub/2021/garcon/index.html).\n",
- "\n",
- "They also come with a range of other quality of life improvements, like the model having a `model.reset_hooks()` method to remove all hooks, or helper methods to temporarily add hooks for a single forward pass - it is *incredibly* easy to shoot yourself in the foot with standard PyTorch hooks!\n",
- ""
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "As a basic example, let's [ablate](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=fh-HJyz1CgUVrXuoiban6bYx) head 7 in layer 0 on the text above. \n",
- "\n",
- "We define a `head_ablation_hook` function. This takes the value tensor for attention layer 0, and sets the component with `head_index==7` to zero and returns it (Note - we return by convention, but since we're editing the activation in-place, we don't strictly *need* to).\n",
- "\n",
- "We then use the `run_with_hooks` helper function to run the model and *temporarily* add in the hook for just this run. We enter in the hook as a tuple of the activation name (also the hook point name - found with `utils.get_act_name`) and the hook function."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:18.807441Z",
- "iopub.status.busy": "2024-08-14T01:22:18.807121Z",
- "iopub.status.idle": "2024-08-14T01:22:19.066611Z",
- "shell.execute_reply": "2024-08-14T01:22:19.065963Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Shape of the value tensor: torch.Size([1, 33, 12, 64])\n",
- "Original Loss: 3.999\n",
- "Ablated Loss: 5.453\n"
- ]
- }
- ],
- "source": [
- "layer_to_ablate = 0\n",
- "head_index_to_ablate = 8\n",
- "\n",
- "# We define a head ablation hook\n",
- "# The type annotations are NOT necessary, they're just a useful guide to the reader\n",
- "# \n",
- "def head_ablation_hook(\n",
- " value: Float[torch.Tensor, \"batch pos head_index d_head\"],\n",
- " hook: HookPoint\n",
- ") -> Float[torch.Tensor, \"batch pos head_index d_head\"]:\n",
- " print(f\"Shape of the value tensor: {value.shape}\")\n",
- " value[:, :, head_index_to_ablate, :] = 0.\n",
- " return value\n",
- "\n",
- "original_loss = model(gpt2_tokens, return_type=\"loss\")\n",
- "ablated_loss = model.run_with_hooks(\n",
- " gpt2_tokens, \n",
- " return_type=\"loss\", \n",
- " fwd_hooks=[(\n",
- " utils.get_act_name(\"v\", layer_to_ablate), \n",
- " head_ablation_hook\n",
- " )]\n",
- " )\n",
- "print(f\"Original Loss: {original_loss.item():.3f}\")\n",
- "print(f\"Ablated Loss: {ablated_loss.item():.3f}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Gotcha:** Hooks are global state - they're added in as part of the model, and stay there until removed. `run_with_hooks` tries to create an abstraction where these are local state, by removing all hooks at the end of the function. But you can easily shoot yourself in the foot if there's, eg, an error in one of your hooks so the function never finishes. If you start getting bugs, try `model.reset_hooks()` to clean things up. Further, if you *do* add hooks of your own that you want to keep, which you can do with `add_perma_hook` on the relevant HookPoint"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Activation Patching on the Indirect Object Identification Task"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "For a somewhat more involved example, let's use hooks to apply **[activation patching](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=qeWBvs-R-taFfcCq-S_hgMqx)** on the **[Indirect Object Identification](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=iWsV3s5Kdd2ca3zNgXr5UPHa)** (IOI) task. \n",
- "\n",
- "The IOI task is the task of identifying that a sentence like \"After John and Mary went to the store, Mary gave a bottle of milk to\" continues with \" John\" rather than \" Mary\" (ie, finding the indirect object), and Redwood Research have [an excellent paper studying the underlying circuit in GPT-2 Small](https://arxiv.org/abs/2211.00593).\n",
- "\n",
- "**[Activation patching](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=qeWBvs-R-taFfcCq-S_hgMqx)** is a technique from [Kevin Meng and David Bau's excellent ROME paper](https://rome.baulab.info/). The goal is to identify which model activations are important for completing a task. We do this by setting up a **clean prompt** and a **corrupted prompt** and a **metric** for performance on the task. We then pick a specific model activation, run the model on the corrupted prompt, but then *intervene* on that activation and patch in its value when run on the clean prompt. We then apply the metric, and see how much this patch has recovered the clean performance. \n",
- "(See [a more detailed demonstration of activation patching here](https://colab.research.google.com/github/TransformerLensOrg/TransformerLens/blob/main/demos/Exploratory_Analysis_Demo.ipynb))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here, our clean prompt is \"After John and Mary went to the store, **Mary** gave a bottle of milk to\", our corrupted prompt is \"After John and Mary went to the store, **John** gave a bottle of milk to\", and our metric is the difference between the correct logit ( John) and the incorrect logit ( Mary) on the final token. \n",
- "\n",
- "We see that the logit difference is significantly positive on the clean prompt, and significantly negative on the corrupted prompt, showing that the model is capable of doing the task!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:19.068984Z",
- "iopub.status.busy": "2024-08-14T01:22:19.068806Z",
- "iopub.status.idle": "2024-08-14T01:22:19.269734Z",
- "shell.execute_reply": "2024-08-14T01:22:19.269118Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Clean logit difference: 4.276\n",
- "Corrupted logit difference: -2.738\n"
- ]
- }
- ],
- "source": [
- "clean_prompt = \"After John and Mary went to the store, Mary gave a bottle of milk to\"\n",
- "corrupted_prompt = \"After John and Mary went to the store, John gave a bottle of milk to\"\n",
- "\n",
- "clean_tokens = model.to_tokens(clean_prompt)\n",
- "corrupted_tokens = model.to_tokens(corrupted_prompt)\n",
- "\n",
- "def logits_to_logit_diff(logits, correct_answer=\" John\", incorrect_answer=\" Mary\"):\n",
- " # model.to_single_token maps a string value of a single token to the token index for that token\n",
- " # If the string is not a single token, it raises an error.\n",
- " correct_index = model.to_single_token(correct_answer)\n",
- " incorrect_index = model.to_single_token(incorrect_answer)\n",
- " return logits[0, -1, correct_index] - logits[0, -1, incorrect_index]\n",
- "\n",
- "# We run on the clean prompt with the cache so we store activations to patch in later.\n",
- "clean_logits, clean_cache = model.run_with_cache(clean_tokens)\n",
- "clean_logit_diff = logits_to_logit_diff(clean_logits)\n",
- "print(f\"Clean logit difference: {clean_logit_diff.item():.3f}\")\n",
- "\n",
- "# We don't need to cache on the corrupted prompt.\n",
- "corrupted_logits = model(corrupted_tokens)\n",
- "corrupted_logit_diff = logits_to_logit_diff(corrupted_logits)\n",
- "print(f\"Corrupted logit difference: {corrupted_logit_diff.item():.3f}\")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We now setup the hook function to do activation patching. Here, we'll patch in the [residual stream](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=DHp9vZ0h9lA9OCrzG2Y3rrzH) at the start of a specific layer and at a specific position. This will let us see how much the model is using the residual stream at that layer and position to represent the key information for the task. \n",
- "\n",
- "We want to iterate over all layers and positions, so we write the hook to take in an position parameter. Hook functions must have the input signature (activation, hook), but we can use `functools.partial` to set the position parameter before passing it to `run_with_hooks`"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:19.272114Z",
- "iopub.status.busy": "2024-08-14T01:22:19.271725Z",
- "iopub.status.idle": "2024-08-14T01:22:38.769236Z",
- "shell.execute_reply": "2024-08-14T01:22:38.768600Z"
- }
- },
- "outputs": [
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "8fda061743fe42b0b72882e8d284a06d",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- " 0%| | 0/12 [00:00, ?it/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "# We define a residual stream patching hook\n",
- "# We choose to act on the residual stream at the start of the layer, so we call it resid_pre\n",
- "# The type annotations are a guide to the reader and are not necessary\n",
- "def residual_stream_patching_hook(\n",
- " resid_pre: Float[torch.Tensor, \"batch pos d_model\"],\n",
- " hook: HookPoint,\n",
- " position: int\n",
- ") -> Float[torch.Tensor, \"batch pos d_model\"]:\n",
- " # Each HookPoint has a name attribute giving the name of the hook.\n",
- " clean_resid_pre = clean_cache[hook.name]\n",
- " resid_pre[:, position, :] = clean_resid_pre[:, position, :]\n",
- " return resid_pre\n",
- "\n",
- "# We make a tensor to store the results for each patching run. We put it on the model's device to avoid needing to move things between the GPU and CPU, which can be slow.\n",
- "num_positions = len(clean_tokens[0])\n",
- "ioi_patching_result = torch.zeros((model.cfg.n_layers, num_positions), device=model.cfg.device)\n",
- "\n",
- "for layer in tqdm.tqdm(range(model.cfg.n_layers)):\n",
- " for position in range(num_positions):\n",
- " # Use functools.partial to create a temporary hook function with the position fixed\n",
- " temp_hook_fn = partial(residual_stream_patching_hook, position=position)\n",
- " # Run the model with the patching hook\n",
- " patched_logits = model.run_with_hooks(corrupted_tokens, fwd_hooks=[\n",
- " (utils.get_act_name(\"resid_pre\", layer), temp_hook_fn)\n",
- " ])\n",
- " # Calculate the logit difference\n",
- " patched_logit_diff = logits_to_logit_diff(patched_logits).detach()\n",
- " # Store the result, normalizing by the clean and corrupted logit difference so it's between 0 and 1 (ish)\n",
- " ioi_patching_result[layer, position] = (patched_logit_diff - corrupted_logit_diff)/(clean_logit_diff - corrupted_logit_diff)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can now visualize the results, and see that this computation is extremely localised within the model. Initially, the second subject (Mary) token is all that matters (naturally, as it's the only different token), and all relevant information remains here until heads in layer 7 and 8 move this to the final token where it's used to predict the indirect object.\n",
- "(Note - the heads are in layer 7 and 8, not 8 and 9, because we patched in the residual stream at the *start* of each layer)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:38.771591Z",
- "iopub.status.busy": "2024-08-14T01:22:38.771263Z",
- "iopub.status.idle": "2024-08-14T01:22:38.921915Z",
- "shell.execute_reply": "2024-08-14T01:22:38.921355Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "# Add the index to the end of the label, because plotly doesn't like duplicate labels\n",
- "token_labels = [f\"{token}_{index}\" for index, token in enumerate(model.to_str_tokens(clean_tokens))]\n",
- "imshow(ioi_patching_result, x=token_labels, xaxis=\"Position\", yaxis=\"Layer\", title=\"Normalized Logit Difference After Patching Residual Stream on the IOI Task\")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hooks: Accessing Activations"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Hooks can also be used to just **access** an activation - to run some function using that activation value, *without* changing the activation value. This can be achieved by just having the hook return nothing, and not editing the activation in place. \n",
- "\n",
- "This is useful for eg extracting activations for a specific task, or for doing some long-running calculation across many inputs, eg finding the text that most activates a specific neuron. (Note - everything this can do *could* be done with `run_with_cache` and post-processing, but this workflow can be more intuitive and memory efficient.)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To demonstrate this, let's look for **[induction heads](https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html)** in GPT-2 Small. \n",
- "\n",
- "Induction circuits are a very important circuit in generative language models, which are used to detect and continue repeated subsequences. They consist of two heads in separate layers that compose together, a **previous token head** which always attends to the previous token, and an **induction head** which attends to the token *after* an earlier copy of the current token. \n",
- "\n",
- "To see why this is important, let's say that the model is trying to predict the next token in a news article about Michael Jordan. The token \" Michael\", in general, could be followed by many surnames. But an induction head will look from that occurrence of \" Michael\" to the token after previous occurrences of \" Michael\", ie \" Jordan\" and can confidently predict that that will come next."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "An interesting fact about induction heads is that they generalise to arbitrary sequences of repeated tokens. We can see this by generating sequences of 50 random tokens, repeated twice, and plotting the average loss at predicting the next token, by position. We see that the model goes from terrible to very good at the halfway point."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:38.924324Z",
- "iopub.status.busy": "2024-08-14T01:22:38.923972Z",
- "iopub.status.idle": "2024-08-14T01:22:40.684312Z",
- "shell.execute_reply": "2024-08-14T01:22:40.683758Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "batch_size = 10\n",
- "seq_len = 50\n",
- "size = (batch_size, seq_len)\n",
- "input_tensor = torch.randint(1000, 10000, size)\n",
- "\n",
- "random_tokens = input_tensor.to(model.cfg.device)\n",
- "repeated_tokens = einops.repeat(random_tokens, \"batch seq_len -> batch (2 seq_len)\")\n",
- "repeated_logits = model(repeated_tokens)\n",
- "correct_log_probs = model.loss_fn(repeated_logits, repeated_tokens, per_token=True)\n",
- "loss_by_position = einops.reduce(correct_log_probs, \"batch position -> position\", \"mean\")\n",
- "line(loss_by_position, xaxis=\"Position\", yaxis=\"Loss\", title=\"Loss by position on random repeated tokens\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The induction heads will be attending from the second occurrence of each token to the token *after* its first occurrence, ie the token `50-1==49` places back. So by looking at the average attention paid 49 tokens back, we can identify induction heads! Let's define a hook to do this!\n",
- "\n",
- "Technical details\n",
- "\n",
- "* We attach the hook to the attention pattern activation. There's one big pattern activation per layer, stacked across all heads, so we need to do some tensor manipulation to get a per-head score. \n",
- "* Hook functions can access global state, so we make a big tensor to store the induction head score for each head, and then we just add the score for each head to the appropriate position in the tensor. \n",
- "* To get a single hook function that works for each layer, we use the `hook.layer()` method to get the layer index (internally this is just inferred from the hook names).\n",
- "* As we want to add this to *every* activation pattern hook point, rather than giving the string for an activation name, this time we give a **name filter**. This is a Boolean function on hook point names, and it adds the hook function to every hook point where the function evaluates as true. \n",
- " * `run_with_hooks` allows us to enter a list of (act_name, hook_function) pairs to all be added at once, so we could also have done this by inputting a list with a hook for each layer.\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:40.686592Z",
- "iopub.status.busy": "2024-08-14T01:22:40.686221Z",
- "iopub.status.idle": "2024-08-14T01:22:41.865930Z",
- "shell.execute_reply": "2024-08-14T01:22:41.865344Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "# We make a tensor to store the induction score for each head. We put it on the model's device to avoid needing to move things between the GPU and CPU, which can be slow.\n",
- "induction_score_store = torch.zeros((model.cfg.n_layers, model.cfg.n_heads), device=model.cfg.device)\n",
- "def induction_score_hook(\n",
- " pattern: Float[torch.Tensor, \"batch head_index dest_pos source_pos\"],\n",
- " hook: HookPoint,\n",
- "):\n",
- " # We take the diagonal of attention paid from each destination position to source positions seq_len-1 tokens back\n",
- " # (This only has entries for tokens with index>=seq_len)\n",
- " induction_stripe = pattern.diagonal(dim1=-2, dim2=-1, offset=1-seq_len)\n",
- " # Get an average score per head\n",
- " induction_score = einops.reduce(induction_stripe, \"batch head_index position -> head_index\", \"mean\")\n",
- " # Store the result.\n",
- " induction_score_store[hook.layer(), :] = induction_score\n",
- "\n",
- "# We make a boolean filter on activation names, that's true only on attention pattern names.\n",
- "pattern_hook_names_filter = lambda name: name.endswith(\"pattern\")\n",
- "\n",
- "model.run_with_hooks(\n",
- " repeated_tokens, \n",
- " return_type=None, # For efficiency, we don't need to calculate the logits\n",
- " fwd_hooks=[(\n",
- " pattern_hook_names_filter,\n",
- " induction_score_hook\n",
- " )]\n",
- ")\n",
- "\n",
- "imshow(induction_score_store, xaxis=\"Head\", yaxis=\"Layer\", title=\"Induction Score by Head\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Head 5 in Layer 5 scores extremely highly on this score, and we can feed in a shorter repeated random sequence, visualize the attention pattern for it and see this directly - including the \"induction stripe\" at `seq_len-1` tokens back.\n",
- "\n",
- "This time we put in a hook on the attention pattern activation to visualize the pattern of the relevant head."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:41.867990Z",
- "iopub.status.busy": "2024-08-14T01:22:41.867815Z",
- "iopub.status.idle": "2024-08-14T01:22:42.071970Z",
- "shell.execute_reply": "2024-08-14T01:22:42.071267Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- " "
- ],
- "text/plain": [
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "if IN_GITHUB:\n",
- " torch.manual_seed(50)\n",
- " \n",
- "induction_head_layer = 5\n",
- "induction_head_index = 5\n",
- "size = (1, 20)\n",
- "input_tensor = torch.randint(1000, 10000, size)\n",
- "\n",
- "single_random_sequence = input_tensor.to(model.cfg.device)\n",
- "repeated_random_sequence = einops.repeat(single_random_sequence, \"batch seq_len -> batch (2 seq_len)\")\n",
- "def visualize_pattern_hook(\n",
- " pattern: Float[torch.Tensor, \"batch head_index dest_pos source_pos\"],\n",
- " hook: HookPoint,\n",
- "):\n",
- " display(\n",
- " cv.attention.attention_patterns(\n",
- " tokens=model.to_str_tokens(repeated_random_sequence), \n",
- " attention=pattern[0, induction_head_index, :, :][None, :, :] # Add a dummy axis, as CircuitsVis expects 3D patterns.\n",
- " )\n",
- " )\n",
- "\n",
- "model.run_with_hooks(\n",
- " repeated_random_sequence, \n",
- " return_type=None, \n",
- " fwd_hooks=[(\n",
- " utils.get_act_name(\"pattern\", induction_head_layer), \n",
- " visualize_pattern_hook\n",
- " )]\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Available Models"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "TransformerLens comes with over 40 open source models available, all of which can be loaded into a consistent(-ish) architecture by just changing the name in `from_pretrained`. The open source models available are [documented here](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=jHj79Pj58cgJKdq4t-ygK-4h), and a set of interpretability friendly models I've trained are [documented here](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=NCJ6zH_Okw_mUYAwGnMKsj2m), including a set of toy language models (tiny one to four layer models) and a set of [SoLU models](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=FZ5W6GGcy6OitPEaO733JLqf) up to GPT-2 Medium size (300M parameters). You can see [a table of the official alias and hyper-parameters of available models here](https://github.com/TransformerLensOrg/TransformerLens/blob/main/transformer_lens/model_properties_table.md).\n",
- "\n",
- "**Note:** TransformerLens does not currently support multi-GPU models (which you want for models above eg 7B parameters), but this feature is coming soon!"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Notably, this means that analysis can be near immediately re-run on a different model by just changing the name - to see this, let's load in DistilGPT-2 (a distilled version of GPT-2, with half as many layers) and copy the code from above to see the induction heads in that model."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 21,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:42.074862Z",
- "iopub.status.busy": "2024-08-14T01:22:42.074418Z",
- "iopub.status.idle": "2024-08-14T01:22:44.576494Z",
- "shell.execute_reply": "2024-08-14T01:22:44.575903Z"
- }
- },
- "outputs": [
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "5eee5a4ba0c84b0296d19d6fce7b0b31",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "model.safetensors: 0%| | 0.00/353M [00:00, ?B/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "25a2a165b92d4488bff3e42c64925ced",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "generation_config.json: 0%| | 0.00/124 [00:00, ?B/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "23d45b17ce6b492fbbc9624b00d4d285",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "tokenizer_config.json: 0%| | 0.00/26.0 [00:00, ?B/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "88d2ca21449141c18c49923662fc6545",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "vocab.json: 0%| | 0.00/1.04M [00:00, ?B/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "ed92285797e64e348575c73deeb82b7c",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "merges.txt: 0%| | 0.00/456k [00:00, ?B/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "045c92fdaa614f998bb2aec9b5a70da0",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "tokenizer.json: 0%| | 0.00/1.36M [00:00, ?B/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Loaded pretrained model distilgpt2 into HookedTransformer\n"
- ]
- }
- ],
- "source": [
- "# NBVAL_IGNORE_OUTPUT\n",
- "distilgpt2 = HookedTransformer.from_pretrained(\"distilgpt2\", device=device)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:44.578887Z",
- "iopub.status.busy": "2024-08-14T01:22:44.578506Z",
- "iopub.status.idle": "2024-08-14T01:22:45.194469Z",
- "shell.execute_reply": "2024-08-14T01:22:45.193924Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "\n",
- "# We make a tensor to store the induction score for each head. We put it on the model's device to avoid needing to move things between the GPU and CPU, which can be slow.\n",
- "distilgpt2_induction_score_store = torch.zeros((distilgpt2.cfg.n_layers, distilgpt2.cfg.n_heads), device=distilgpt2.cfg.device)\n",
- "def induction_score_hook(\n",
- " pattern: Float[torch.Tensor, \"batch head_index dest_pos source_pos\"],\n",
- " hook: HookPoint,\n",
- "):\n",
- " # We take the diagonal of attention paid from each destination position to source positions seq_len-1 tokens back\n",
- " # (This only has entries for tokens with index>=seq_len)\n",
- " induction_stripe = pattern.diagonal(dim1=-2, dim2=-1, offset=1-seq_len)\n",
- " # Get an average score per head\n",
- " induction_score = einops.reduce(induction_stripe, \"batch head_index position -> head_index\", \"mean\")\n",
- " # Store the result.\n",
- " distilgpt2_induction_score_store[hook.layer(), :] = induction_score\n",
- "\n",
- "# We make a boolean filter on activation names, that's true only on attention pattern names.\n",
- "pattern_hook_names_filter = lambda name: name.endswith(\"pattern\")\n",
- "\n",
- "distilgpt2.run_with_hooks(\n",
- " repeated_tokens, \n",
- " return_type=None, # For efficiency, we don't need to calculate the logits\n",
- " fwd_hooks=[(\n",
- " pattern_hook_names_filter,\n",
- " induction_score_hook\n",
- " )]\n",
- ")\n",
- "\n",
- "imshow(distilgpt2_induction_score_store, xaxis=\"Head\", yaxis=\"Layer\", title=\"Induction Score by Head in Distil GPT-2\")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "### An overview of the important open source models in the library\n",
- "\n",
- "* **GPT-2** - the classic generative pre-trained models from OpenAI\n",
- " * Sizes Small (85M), Medium (300M), Large (700M) and XL (1.5B).\n",
- " * Trained on ~22B tokens of internet text. ([Open source replication](https://huggingface.co/datasets/openwebtext))\n",
- "* **GPT-Neo** - Eleuther's replication of GPT-2\n",
- " * Sizes 125M, 1.3B, 2.7B\n",
- " * Trained on 300B(ish?) tokens of [the Pile](https://pile.eleuther.ai/) a large and diverse dataset including a bunch of code (and weird stuff)\n",
- "* **[OPT](https://ai.facebook.com/blog/democratizing-access-to-large-scale-language-models-with-opt-175b/)** - Meta AI's series of open source models\n",
- " * Trained on 180B tokens of diverse text.\n",
- " * 125M, 1.3B, 2.7B, 6.7B, 13B, 30B, 66B\n",
- "* **GPT-J** - Eleuther's 6B parameter model, trained on the Pile\n",
- "* **GPT-NeoX** - Eleuther's 20B parameter model, trained on the Pile\n",
- "* **StableLM** - Stability AI's 3B and 7B models, with and without chat and instruction fine-tuning\n",
- "* **Stanford CRFM models** - a replication of GPT-2 Small and GPT-2 Medium, trained on 5 different random seeds.\n",
- " * Notably, 600 checkpoints were taken during training per model, and these are available in the library with eg `HookedTransformer.from_pretrained(\"stanford-gpt2-small-a\", checkpoint_index=265)`.\n",
- "- **BERT** - Google's bidirectional encoder-only transformer.\n",
- " - Size Base (108M), trained on English Wikipedia and BooksCorpus.\n",
- " \n",
- ""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "### An overview of some interpretability-friendly models I've trained and included\n",
- "\n",
- "(Feel free to [reach out](mailto:neelnanda27@gmail.com) if you want more details on any of these models)\n",
- "\n",
- "Each of these models has about ~200 checkpoints taken during training that can also be loaded from TransformerLens, with the `checkpoint_index` argument to `from_pretrained`.\n",
- "\n",
- "Note that all models are trained with a Beginning of Sequence token, and will likely break if given inputs without that! \n",
- "\n",
- "* **Toy Models**: Inspired by [A Mathematical Framework](https://transformer-circuits.pub/2021/framework/index.html), I've trained 12 tiny language models, of 1-4L and each of width 512. I think that interpreting these is likely to be far more tractable than larger models, and both serve as good practice and will likely contain motifs and circuits that generalise to far larger models (like induction heads):\n",
- " * Attention-Only models (ie without MLPs): attn-only-1l, attn-only-2l, attn-only-3l, attn-only-4l\n",
- " * GELU models (ie with MLP, and the standard GELU activations): gelu-1l, gelu-2l, gelu-3l, gelu-4l\n",
- " * SoLU models (ie with MLP, and [Anthropic's SoLU activation](https://transformer-circuits.pub/2022/solu/index.html), designed to make MLP neurons more interpretable): solu-1l, solu-2l, solu-3l, solu-4l\n",
- " * All models are trained on 22B tokens of data, 80% from C4 (web text) and 20% from Python Code\n",
- " * Models of the same layer size were trained with the same weight initialization and data shuffle, to more directly compare the effect of different activation functions.\n",
- "* **SoLU** models: A larger scan of models trained with [Anthropic's SoLU activation](https://transformer-circuits.pub/2022/solu/index.html), in the hopes that it makes the MLP neuron interpretability easier. \n",
- " * A scan up to GPT-2 Medium size, trained on 30B tokens of the same data as toy models, 80% from C4 and 20% from Python code. \n",
- " * solu-6l (40M), solu-8l (100M), solu-10l (200M), solu-12l (340M)\n",
- " * An older scan up to GPT-2 Medium size, trained on 15B tokens of [the Pile](https://pile.eleuther.ai/)\n",
- " * solu-1l-pile (13M), solu-2l-pile (13M), solu-4l-pile (13M), solu-6l-pile (40M), solu-8l-pile (100M), solu-10l-pile (200M), solu-12l-pile (340M)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Other Resources:\n",
- "\n",
- "* [Concrete Steps to Get Started in Mechanistic Interpretability](https://neelnanda.io/getting-started): A guide I wrote for how to get involved in mechanistic interpretability, and how to learn the basic skills\n",
- "* [A Comprehensive Mechanistic Interpretability Explainer](https://neelnanda.io/glossary): An overview of concepts in the field and surrounding ideas in ML and transformers, with long digressions to give context and build intuitions.\n",
- "* [Concrete Open Problems in Mechanistic Interpretability](https://neelnanda.io/concrete-open-problems), a doc I wrote giving a long list of open problems in mechanistic interpretability, and thoughts on how to get started on trying to work on them. \n",
- " * There's a lot of low-hanging fruit in the field, and I expect that many people reading this could use TransformerLens to usefully make progress on some of these!\n",
- "* Other demos:\n",
- " * **[Exploratory Analysis Demo](https://neelnanda.io/exploratory-analysis-demo)**, a demonstration of my standard toolkit for how to use TransformerLens to explore a mysterious behaviour in a language model.\n",
- " * [Interpretability in the Wild](https://github.com/redwoodresearch/Easy-Transformer) a codebase from Arthur Conmy and Alex Variengien at Redwood research using this library to do a detailed and rigorous reverse engineering of the Indirect Object Identification circuit, to accompany their paper\n",
- " * Note - this was based on an earlier version of this library, called EasyTransformer. It's pretty similar, but several breaking changes have been made since. \n",
- " * A [recorded walkthrough](https://www.youtube.com/watch?v=yo4QvDn-vsU) of me doing research with TransformerLens on whether a tiny model can re-derive positional information, with [an accompanying Colab](https://colab.research.google.com/github/TransformerLensOrg/TransformerLens/blob/main/No_Position_Experiment.ipynb)\n",
- "* [Neuroscope](https://neuroscope.io), a website showing the text in the dataset that most activates each neuron in some selected models. Good to explore to get a sense for what kind of features the model tends to represent, and as a \"wiki\" to get some info\n",
- " * A tutorial on how to make an [Interactive Neuroscope](https://github.com/TransformerLensOrg/TransformerLens/blob/main/Hacky-Interactive-Lexoscope.ipynb), where you type in text and see the neuron activations over the text update live."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Transformer architecture\n",
- "\n",
- "HookedTransformer is a somewhat adapted GPT-2 architecture, but is computationally identical. The most significant changes are to the internal structure of the attention heads: \n",
- "* The weights (W_K, W_Q, W_V) mapping the residual stream to queries, keys and values are 3 separate matrices, rather than big concatenated one.\n",
- "* The weight matrices (W_K, W_Q, W_V, W_O) and activations (keys, queries, values, z (values mixed by attention pattern)) have separate head_index and d_head axes, rather than flattening them into one big axis.\n",
- " * The activations all have shape `[batch, position, head_index, d_head]`\n",
- " * W_K, W_Q, W_V have shape `[head_index, d_model, d_head]` and W_O has shape `[head_index, d_head, d_model]`\n",
- "\n",
- "The actual code is a bit of a mess, as there's a variety of Boolean flags to make it consistent with the various different model families in TransformerLens - to understand it and the internal structure, I instead recommend reading the code in [CleanTransformerDemo](https://colab.research.google.com/github/TransformerLensOrg/TransformerLens/blob/clean-transformer-demo/Clean_Transformer_Demo.ipynb)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Parameter Names\n",
- "\n",
- "Here is a list of the parameters and shapes in the model. By convention, all weight matrices multiply on the right (ie `new_activation = old_activation @ weights + bias`). \n",
- "\n",
- "Reminder of the key hyper-params:\n",
- "* `n_layers`: 12. The number of transformer blocks in the model (a block contains an attention layer and an MLP layer)\n",
- "* `n_heads`: 12. The number of attention heads per attention layer\n",
- "* `d_model`: 768. The residual stream width.\n",
- "* `d_head`: 64. The internal dimension of an attention head activation.\n",
- "* `d_mlp`: 3072. The internal dimension of the MLP layers (ie the number of neurons).\n",
- "* `d_vocab`: 50267. The number of tokens in the vocabulary.\n",
- "* `n_ctx`: 1024. The maximum number of tokens in an input prompt.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Transformer Block parameters:** \n",
- "Replace 0 with the relevant layer index."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 23,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.196770Z",
- "iopub.status.busy": "2024-08-14T01:22:45.196428Z",
- "iopub.status.idle": "2024-08-14T01:22:45.200135Z",
- "shell.execute_reply": "2024-08-14T01:22:45.199613Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "blocks.0.attn.W_Q torch.Size([12, 768, 64])\n",
- "blocks.0.attn.W_O torch.Size([12, 64, 768])\n",
- "blocks.0.attn.b_Q torch.Size([12, 64])\n",
- "blocks.0.attn.b_O torch.Size([768])\n",
- "blocks.0.attn.W_K torch.Size([12, 768, 64])\n",
- "blocks.0.attn.W_V torch.Size([12, 768, 64])\n",
- "blocks.0.attn.b_K torch.Size([12, 64])\n",
- "blocks.0.attn.b_V torch.Size([12, 64])\n",
- "blocks.0.mlp.W_in torch.Size([768, 3072])\n",
- "blocks.0.mlp.b_in torch.Size([3072])\n",
- "blocks.0.mlp.W_out torch.Size([3072, 768])\n",
- "blocks.0.mlp.b_out torch.Size([768])\n"
- ]
- }
- ],
- "source": [
- "for name, param in model.named_parameters():\n",
- " if name.startswith(\"blocks.0.\"):\n",
- " print(name, param.shape)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Embedding & Unembedding parameters:**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 24,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.202113Z",
- "iopub.status.busy": "2024-08-14T01:22:45.201797Z",
- "iopub.status.idle": "2024-08-14T01:22:45.205467Z",
- "shell.execute_reply": "2024-08-14T01:22:45.204861Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "embed.W_E torch.Size([50257, 768])\n",
- "pos_embed.W_pos torch.Size([1024, 768])\n",
- "unembed.W_U torch.Size([768, 50257])\n",
- "unembed.b_U torch.Size([50257])\n"
- ]
- }
- ],
- "source": [
- "for name, param in model.named_parameters():\n",
- " if not name.startswith(\"blocks\"):\n",
- " print(name, param.shape)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Activation + Hook Names\n",
- "\n",
- "Lets get out a list of the activation/hook names in the model and their shapes. In practice, I recommend using the `utils.get_act_name` function to get the names, but this is a useful fallback, and necessary to eg write a name filter function.\n",
- "\n",
- "Let's do this by entering in a short, 10 token prompt, and add a hook function to each activations to print its name and shape. To avoid spam, let's just add this to activations in the first block or not in a block.\n",
- "\n",
- "Note 1: Each LayerNorm has a hook for the scale factor (ie the standard deviation of the input activations for each token position & batch element) and for the normalized output (ie the input activation with mean 0 and standard deviation 1, but *before* applying scaling or translating with learned weights). LayerNorm is applied every time a layer reads from the residual stream: `ln1` is the LayerNorm before the attention layer in a block, `ln2` the one before the MLP layer, and `ln_final` is the LayerNorm before the unembed. \n",
- "\n",
- "Note 2: *Every* activation apart from the attention pattern and attention scores has shape beginning with `[batch, position]`. The attention pattern and scores have shape `[batch, head_index, dest_position, source_position]` (the numbers are the same, unless we're using caching)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 25,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.207757Z",
- "iopub.status.busy": "2024-08-14T01:22:45.207351Z",
- "iopub.status.idle": "2024-08-14T01:22:45.276279Z",
- "shell.execute_reply": "2024-08-14T01:22:45.275657Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Num tokens: 10\n",
- "hook_embed torch.Size([1, 10, 768])\n",
- "hook_pos_embed torch.Size([1, 10, 768])\n",
- "blocks.0.hook_resid_pre torch.Size([1, 10, 768])\n",
- "blocks.0.ln1.hook_scale torch.Size([1, 10, 1])\n",
- "blocks.0.ln1.hook_normalized torch.Size([1, 10, 768])\n",
- "blocks.0.ln1.hook_scale torch.Size([1, 10, 1])\n",
- "blocks.0.ln1.hook_normalized torch.Size([1, 10, 768])\n",
- "blocks.0.ln1.hook_scale torch.Size([1, 10, 1])\n",
- "blocks.0.ln1.hook_normalized torch.Size([1, 10, 768])\n",
- "blocks.0.attn.hook_q torch.Size([1, 10, 12, 64])\n",
- "blocks.0.attn.hook_k torch.Size([1, 10, 12, 64])\n",
- "blocks.0.attn.hook_v torch.Size([1, 10, 12, 64])\n",
- "blocks.0.attn.hook_attn_scores torch.Size([1, 12, 10, 10])\n",
- "blocks.0.attn.hook_pattern torch.Size([1, 12, 10, 10])\n",
- "blocks.0.attn.hook_z torch.Size([1, 10, 12, 64])\n",
- "blocks.0.hook_attn_out torch.Size([1, 10, 768])\n",
- "blocks.0.hook_resid_mid torch.Size([1, 10, 768])\n",
- "blocks.0.ln2.hook_scale torch.Size([1, 10, 1])\n",
- "blocks.0.ln2.hook_normalized torch.Size([1, 10, 768])\n",
- "blocks.0.mlp.hook_pre torch.Size([1, 10, 3072])\n",
- "blocks.0.mlp.hook_post torch.Size([1, 10, 3072])\n",
- "blocks.0.hook_mlp_out torch.Size([1, 10, 768])\n",
- "blocks.0.hook_resid_post torch.Size([1, 10, 768])\n",
- "ln_final.hook_scale torch.Size([1, 10, 1])\n",
- "ln_final.hook_normalized torch.Size([1, 10, 768])\n"
- ]
- }
- ],
- "source": [
- "test_prompt = \"The quick brown fox jumped over the lazy dog\"\n",
- "print(\"Num tokens:\", len(model.to_tokens(test_prompt)[0]))\n",
- "\n",
- "def print_name_shape_hook_function(activation, hook):\n",
- " print(hook.name, activation.shape)\n",
- "\n",
- "not_in_late_block_filter = lambda name: name.startswith(\"blocks.0.\") or not name.startswith(\"blocks\")\n",
- "\n",
- "model.run_with_hooks(\n",
- " test_prompt,\n",
- " return_type=None,\n",
- " fwd_hooks=[(not_in_late_block_filter, print_name_shape_hook_function)],\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Folding LayerNorm (For the Curious)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "(For the curious - this is an important technical detail that's worth understanding, especially if you have preconceptions about how transformers work, but not necessary to use TransformerLens)\n",
- "\n",
- "LayerNorm is a normalization technique used by transformers, analogous to BatchNorm but more friendly to massive parallelisation. No one *really* knows why it works, but it seems to improve model numerical stability. Unlike BatchNorm, LayerNorm actually changes the functional form of the model, which makes it a massive pain for interpretability! \n",
- "\n",
- "Folding LayerNorm is a technique to make it lower overhead to deal with, and the flags `center_writing_weights` and `fold_ln` in `HookedTransformer.from_pretrained` apply this automatically (they default to True). These simplify the internal structure without changing the weights.\n",
- "\n",
- "Intuitively, LayerNorm acts on each residual stream vector (ie for each batch element and token position) independently, sets their mean to 0 (centering) and standard deviation to 1 (normalizing) (*across* the residual stream dimension - very weird!), and then applies a learned elementwise scaling and translation to each vector.\n",
- "\n",
- "Mathematically, centering is a linear map, normalizing is *not* a linear map, and scaling and translation are linear maps. \n",
- "* **Centering:** LayerNorm is applied every time a layer reads from the residual stream, so the mean of any residual stream vector can never matter - `center_writing_weights` set every weight matrix writing to the residual to have zero mean. \n",
- "* **Normalizing:** Normalizing is not a linear map, and cannot be factored out. The `hook_scale` hook point lets you access and control for this.\n",
- "* **Scaling and Translation:** Scaling and translation are linear maps, and are always followed by another linear map. The composition of two linear maps is another linear map, so we can *fold* the scaling and translation weights into the weights of the subsequent layer, and simplify things without changing the underlying computation. \n",
- "\n",
- "[See the docs for more details](https://github.com/TransformerLensOrg/TransformerLens/blob/main/further_comments.md#what-is-layernorm-folding-fold_ln)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "A fun consequence of LayerNorm folding is that it creates a bias across the unembed, a `d_vocab` length vector that is added to the output logits - GPT-2 is not trained with this, but it *is* trained with a final LayerNorm that contains a bias. \n",
- "\n",
- "Turns out, this LayerNorm bias learns structure of the data that we can only see after folding! In particular, it essentially learns **unigram statistics** - rare tokens get suppressed, common tokens get boosted, by pretty dramatic degrees! Let's list the top and bottom 20 - at the top we see common punctuation and words like \" the\" and \" and\", at the bottom we see weird-ass tokens like \" RandomRedditor\":"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 26,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.278803Z",
- "iopub.status.busy": "2024-08-14T01:22:45.278445Z",
- "iopub.status.idle": "2024-08-14T01:22:45.285917Z",
- "shell.execute_reply": "2024-08-14T01:22:45.285362Z"
- }
- },
- "outputs": [],
- "source": [
- "unembed_bias = model.unembed.b_U\n",
- "bias_values, bias_indices = unembed_bias.sort(descending=True)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 27,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.288211Z",
- "iopub.status.busy": "2024-08-14T01:22:45.287808Z",
- "iopub.status.idle": "2024-08-14T01:22:45.294747Z",
- "shell.execute_reply": "2024-08-14T01:22:45.294254Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Top 20 values\n",
- "7.03 ','\n",
- "6.98 ' the'\n",
- "6.68 ' and'\n",
- "6.49 '.'\n",
- "6.48 '\\n'\n",
- "6.47 ' a'\n",
- "6.41 ' in'\n",
- "6.25 ' to'\n",
- "6.16 ' of'\n",
- "6.04 '-'\n",
- "6.03 ' ('\n",
- "5.88 ' \"'\n",
- "5.80 ' for'\n",
- "5.72 ' that'\n",
- "5.64 ' on'\n",
- "5.59 ' is'\n",
- "5.52 ' as'\n",
- "5.49 ' at'\n",
- "5.45 ' with'\n",
- "5.44 ' or'\n",
- "...\n",
- "Bottom 20 values\n",
- "-3.82 ' サーティ'\n",
- "-3.83 '\\x18'\n",
- "-3.83 '\\x14'\n",
- "-3.83 ' RandomRedditor'\n",
- "-3.83 '龍�'\n",
- "-3.83 '�'\n",
- "-3.83 '\\x1b'\n",
- "-3.83 '�'\n",
- "-3.83 '\\x05'\n",
- "-3.83 '\\x00'\n",
- "-3.83 '\\x06'\n",
- "-3.83 '\\x07'\n",
- "-3.83 '\\x0c'\n",
- "-3.83 '\\x02'\n",
- "-3.83 'oreAndOnline'\n",
- "-3.84 '\\x11'\n",
- "-3.84 '�'\n",
- "-3.84 '\\x10'\n",
- "-3.84 '�'\n",
- "-3.84 '�'\n"
- ]
- }
- ],
- "source": [
- "top_k = 20\n",
- "print(f\"Top {top_k} values\")\n",
- "for i in range(top_k):\n",
- " print(f\"{bias_values[i].item():.2f} {repr(model.to_string(bias_indices[i]))}\")\n",
- "\n",
- "print(\"...\")\n",
- "print(f\"Bottom {top_k} values\")\n",
- "for i in range(top_k, 0, -1):\n",
- " print(f\"{bias_values[-i].item():.2f} {repr(model.to_string(bias_indices[-i]))}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This can have real consequences for interpretability - for example, this bias favours \" John\" over \" Mary\" by about 1.2, about 1/3 of the effect size of the Indirect Object Identification Circuit! All other things being the same, this makes the John token 3.6x times more likely than the Mary token."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 28,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.296751Z",
- "iopub.status.busy": "2024-08-14T01:22:45.296432Z",
- "iopub.status.idle": "2024-08-14T01:22:45.300783Z",
- "shell.execute_reply": "2024-08-14T01:22:45.300258Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "John bias: 2.8995\n",
- "Mary bias: 1.6034\n",
- "Prob ratio bias: 3.6550x\n"
- ]
- }
- ],
- "source": [
- "john_bias = model.unembed.b_U[model.to_single_token(' John')]\n",
- "mary_bias = model.unembed.b_U[model.to_single_token(' Mary')]\n",
- "\n",
- "print(f\"John bias: {john_bias.item():.4f}\")\n",
- "print(f\"Mary bias: {mary_bias.item():.4f}\")\n",
- "print(f\"Prob ratio bias: {torch.exp(john_bias - mary_bias).item():.4f}x\")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Features\n",
- "\n",
- "An overview of some other important features of the library. I recommend checking out the [Exploratory Analysis Demo](https://colab.research.google.com/github/TransformerLensOrg/Easy-Transformer/blob/main/Exploratory_Analysis_Demo.ipynb) for some other important features not mentioned here, and for a demo of what using the library in practice looks like."
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Dealing with tokens\n",
- "\n",
- "**Tokenization** is one of the most annoying features of studying language models. We want language models to be able to take in arbitrary text as input, but the transformer architecture needs the inputs to be elements of a fixed, finite vocabulary. The solution to this is **tokens**, a fixed vocabulary of \"sub-words\", that any natural language can be broken down into with a **tokenizer**. This is invertible, and we can recover the original text, called **de-tokenization**. \n",
- "\n",
- "TransformerLens comes with a range of utility functions to deal with tokenization. Different models can have different tokenizers, so these are all methods on the model.\n",
- "\n",
- "get_token_position, to_tokens, to_string, to_str_tokens, prepend_bos, to_single_token"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The first thing you need to figure out is *how* things are tokenized. `model.to_str_tokens` splits a string into the tokens *as a list of substrings*, and so lets you explore what the text looks like. To demonstrate this, let's use it on this paragraph.\n",
- "\n",
- "Some observations - there are a lot of arbitrary-ish details in here!\n",
- "* The tokenizer splits on spaces, so no token contains two words.\n",
- "* Tokens include the preceding space, and whether the first token is a capital letter. `how` and ` how` are different tokens!\n",
- "* Common words are single tokens, even if fairly long (` paragraph`) while uncommon words are split into multiple tokens (` token|ized`).\n",
- "* Tokens *mostly* split on punctuation characters (eg `*` and `.`), but eg `'s` is a single token."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 29,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.302816Z",
- "iopub.status.busy": "2024-08-14T01:22:45.302653Z",
- "iopub.status.idle": "2024-08-14T01:22:45.306355Z",
- "shell.execute_reply": "2024-08-14T01:22:45.305923Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "['<|endoftext|>', 'The', ' first', ' thing', ' you', ' need', ' to', ' figure', ' out', ' is', ' *', 'how', '*', ' things', ' are', ' token', 'ized', '.', ' `', 'model', '.', 'to', '_', 'str', '_', 't', 'ok', 'ens', '`', ' splits', ' a', ' string', ' into', ' the', ' tokens', ' *', 'as', ' a', ' list', ' of', ' sub', 'strings', '*,', ' and', ' so', ' lets', ' you', ' explore', ' what', ' the', ' text', ' looks', ' like', '.', ' To', ' demonstrate', ' this', ',', ' let', \"'s\", ' use', ' it', ' on', ' this', ' paragraph', '.']\n"
- ]
- }
- ],
- "source": [
- "example_text = \"The first thing you need to figure out is *how* things are tokenized. `model.to_str_tokens` splits a string into the tokens *as a list of substrings*, and so lets you explore what the text looks like. To demonstrate this, let's use it on this paragraph.\"\n",
- "example_text_str_tokens = model.to_str_tokens(example_text)\n",
- "print(example_text_str_tokens)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The transformer needs to take in a sequence of integers, not strings, so we need to convert these tokens into integers. `model.to_tokens` does this, and returns a tensor of integers on the model's device (shape `[batch, position]`). It maps a string to a batch of size 1."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 30,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.308240Z",
- "iopub.status.busy": "2024-08-14T01:22:45.308075Z",
- "iopub.status.idle": "2024-08-14T01:22:45.311716Z",
- "shell.execute_reply": "2024-08-14T01:22:45.311262Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "tensor([[50256, 464, 717, 1517, 345, 761, 284, 3785, 503, 318,\n",
- " 1635, 4919, 9, 1243, 389, 11241, 1143, 13, 4600, 19849,\n",
- " 13, 1462, 62, 2536, 62, 83, 482, 641, 63, 30778,\n",
- " 257, 4731, 656, 262, 16326, 1635, 292, 257, 1351, 286,\n",
- " 850, 37336, 25666, 290, 523, 8781, 345, 7301, 644, 262,\n",
- " 2420, 3073, 588, 13, 1675, 10176, 428, 11, 1309, 338,\n",
- " 779, 340, 319, 428, 7322, 13]])\n"
- ]
- }
- ],
- "source": [
- "example_text_tokens = model.to_tokens(example_text)\n",
- "print(example_text_tokens)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "`to_tokens` can also take in a list of strings, and return a batch of size `len(strings)`. If the strings are different numbers of tokens, it adds a PAD token to the end of the shorter strings to make them the same length.\n",
- "\n",
- "(Note: In GPT-2, 50256 signifies both the beginning of sequence, end of sequence and padding token - see the `prepend_bos` section for details)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 31,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.313558Z",
- "iopub.status.busy": "2024-08-14T01:22:45.313399Z",
- "iopub.status.idle": "2024-08-14T01:22:45.317076Z",
- "shell.execute_reply": "2024-08-14T01:22:45.316520Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "tensor([[50256, 464, 3797, 3332, 319, 262, 2603, 13, 50256, 50256],\n",
- " [50256, 464, 3797, 3332, 319, 262, 2603, 1107, 1327, 13]])\n"
- ]
- }
- ],
- "source": [
- "example_multi_text = [\"The cat sat on the mat.\", \"The cat sat on the mat really hard.\"]\n",
- "example_multi_text_tokens = model.to_tokens(example_multi_text)\n",
- "print(example_multi_text_tokens)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "`model.to_single_token` is a convenience function that takes in a string corresponding to a *single* token and returns the corresponding integer. This is useful for eg looking up the logit corresponding to a single token. \n",
- "\n",
- "For example, let's input `The cat sat on the mat.` to GPT-2, and look at the log prob predicting that the next token is ` The`. \n",
- "\n",
- "Technical notes\n",
- "\n",
- "Note that if we input a string to the model, it's implicitly converted to a string with `to_tokens`. \n",
- "\n",
- "Note further that the log probs have shape `[batch, position, d_vocab]==[1, 8, 50257]`, with a vector of log probs predicting the next token for *every* token position. GPT-2 uses causal attention which means heads can only look backwards (equivalently, information can only move forwards in the model.), so the log probs at position k are only a function of the first k tokens, and it can't just cheat and look at the k+1 th token. This structure lets it generate text more efficiently, and lets it treat every *token* as a training example, rather than every *sequence*.\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 32,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.319292Z",
- "iopub.status.busy": "2024-08-14T01:22:45.318900Z",
- "iopub.status.idle": "2024-08-14T01:22:45.403340Z",
- "shell.execute_reply": "2024-08-14T01:22:45.402745Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Probability tensor shape [batch, position, d_vocab] == torch.Size([1, 8, 50257])\n",
- "| The| probability: 11.98%\n"
- ]
- }
- ],
- "source": [
- "cat_text = \"The cat sat on the mat.\"\n",
- "cat_logits = model(cat_text)\n",
- "cat_probs = cat_logits.softmax(dim=-1)\n",
- "print(f\"Probability tensor shape [batch, position, d_vocab] == {cat_probs.shape}\")\n",
- "\n",
- "capital_the_token_index = model.to_single_token(\" The\")\n",
- "print(f\"| The| probability: {cat_probs[0, -1, capital_the_token_index].item():.2%}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "`model.to_string` is the inverse of `to_tokens` and maps a tensor of integers to a string or list of strings. It also works on integers and lists of integers.\n",
- "\n",
- "For example, let's look up token 256 (due to technical details of tokenization, this will be the most common pair of ASCII characters!), and also verify that our tokens above map back to a string."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 33,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.405726Z",
- "iopub.status.busy": "2024-08-14T01:22:45.405384Z",
- "iopub.status.idle": "2024-08-14T01:22:45.408904Z",
- "shell.execute_reply": "2024-08-14T01:22:45.408377Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Token 256 - the most common pair of ASCII characters: | t|\n",
- "De-Tokenizing the example tokens: <|endoftext|>The first thing you need to figure out is *how* things are tokenized. `model.to_str_tokens` splits a string into the tokens *as a list of substrings*, and so lets you explore what the text looks like. To demonstrate this, let's use it on this paragraph.\n"
- ]
- }
- ],
- "source": [
- "print(f\"Token 256 - the most common pair of ASCII characters: |{model.to_string(256)}|\")\n",
- "# Squeeze means to remove dimensions of length 1. \n",
- "# Here, that removes the dummy batch dimension so it's a rank 1 tensor and returns a string\n",
- "# Rank 2 tensors map to a list of strings\n",
- "print(f\"De-Tokenizing the example tokens: {model.to_string(example_text_tokens.squeeze())}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "A related annoyance of tokenization is that it's hard to figure out how many tokens a string will break into. `model.get_token_position(single_token, tokens)` returns the position of `single_token` in `tokens`. `tokens` can be either a string or a tensor of tokens. \n",
- "\n",
- "Note that position is zero-indexed, it's two (ie third) because there's a beginning of sequence token automatically prepended (see the next section for details)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 34,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.410754Z",
- "iopub.status.busy": "2024-08-14T01:22:45.410603Z",
- "iopub.status.idle": "2024-08-14T01:22:45.415001Z",
- "shell.execute_reply": "2024-08-14T01:22:45.414420Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "With BOS: 2\n",
- "Without BOS: 1\n"
- ]
- }
- ],
- "source": [
- "print(\"With BOS:\", model.get_token_position(\" cat\", \"The cat sat on the mat\"))\n",
- "print(\"Without BOS:\", model.get_token_position(\" cat\", \"The cat sat on the mat\", prepend_bos=False))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If there are multiple copies of the token, we can set `mode=\"first\"` to find the first occurrence's position and `mode=\"last\"` to find the last"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 35,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.416826Z",
- "iopub.status.busy": "2024-08-14T01:22:45.416664Z",
- "iopub.status.idle": "2024-08-14T01:22:45.420770Z",
- "shell.execute_reply": "2024-08-14T01:22:45.420317Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "First occurrence 2\n",
- "Final occurrence 13\n"
- ]
- }
- ],
- "source": [
- "print(\"First occurrence\", model.get_token_position(\n",
- " \" cat\", \n",
- " \"The cat sat on the mat. The mat sat on the cat.\", \n",
- " mode=\"first\"))\n",
- "print(\"Final occurrence\", model.get_token_position(\n",
- " \" cat\", \n",
- " \"The cat sat on the mat. The mat sat on the cat.\", \n",
- " mode=\"last\"))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In general, tokenization is a pain, and full of gotchas. I highly recommend just playing around with different inputs and their tokenization and getting a feel for it. As another \"fun\" example, let's look at the tokenization of arithmetic expressions - tokens do *not* contain consistent numbers of digits. (This makes it even more impressive that GPT-3 can do arithmetic!)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.422561Z",
- "iopub.status.busy": "2024-08-14T01:22:45.422384Z",
- "iopub.status.idle": "2024-08-14T01:22:45.426069Z",
- "shell.execute_reply": "2024-08-14T01:22:45.425629Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "['<|endoftext|>', '23', '42', '+', '2017', '=', '214', '45']\n",
- "['<|endoftext|>', '1000', '+', '1', '000000', '=', '9999', '99']\n"
- ]
- }
- ],
- "source": [
- "print(model.to_str_tokens(\"2342+2017=21445\"))\n",
- "print(model.to_str_tokens(\"1000+1000000=999999\"))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "I also *highly* recommend investigating prompts with easy tokenization when starting out - ideally key words should form a single token, be in the same position in different prompts, have the same total length, etc. Eg study Indirect Object Identification with common English names like ` Tim` rather than ` Ne|el`. Transformers need to spend some parameters in early layers converting multi-token words to a single feature, and then de-converting this in the late layers, and unless this is what you're explicitly investigating, this will make the behaviour you're investigating be messier."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Gotcha: `prepend_bos`\n",
- "\n",
- "Key Takeaway: **If you get weird off-by-one errors, check whether there's an unexpected `prepend_bos`!**"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "A weirdness you may have noticed in the above is that `to_tokens` and `to_str_tokens` added a weird `<|endoftext|>` to the start of each prompt. TransformerLens does this by default, and it can easily trip up new users. Notably, **this includes `model.forward`** (which is what's implicitly used when you do eg `model(\"Hello World\")`). This is called a **Beginning of Sequence (BOS)** token, and it's a special token used to mark the beginning of the sequence. Confusingly, in GPT-2, the End of Sequence (EOS), Beginning of Sequence (BOS) and Padding (PAD) tokens are all the same, `<|endoftext|>` with index `50256`.\n",
- "\n",
- "**Gotcha:** You only want to prepend a BOS token at the *start* of a prompt. If you, eg, want to input a question followed by an answer, and want to tokenize these separately, you do *not* want to prepend_bos on the answer."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 37,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.428077Z",
- "iopub.status.busy": "2024-08-14T01:22:45.427776Z",
- "iopub.status.idle": "2024-08-14T01:22:45.625416Z",
- "shell.execute_reply": "2024-08-14T01:22:45.624878Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Logits shape by default (with BOS) torch.Size([1, 3, 50257])\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Logits shape with BOS torch.Size([1, 3, 50257])\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Logits shape without BOS - only 2 positions! torch.Size([1, 2, 50257])\n"
- ]
- }
- ],
- "source": [
- "print(\"Logits shape by default (with BOS)\", model(\"Hello World\").shape)\n",
- "print(\"Logits shape with BOS\", model(\"Hello World\", prepend_bos=True).shape)\n",
- "print(\"Logits shape without BOS - only 2 positions!\", model(\"Hello World\", prepend_bos=False).shape)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "`prepend_bos` is a bit of a hack, and I've gone back and forth on what the correct default here is. The reason I do this is that transformers tend to treat the first token weirdly - this doesn't really matter in training (where all inputs are >1000 tokens), but this can be a big issue when investigating short prompts! The reason for this is that attention patterns are a probability distribution and so need to add up to one, so to simulate being \"off\" they normally look at the first token. Giving them a BOS token lets the heads rest by looking at that, preserving the information in the first \"real\" token.\n",
- "\n",
- "Further, *some* models are trained to need a BOS token (OPT and my interpretability-friendly models are, GPT-2 and GPT-Neo are not). But despite GPT-2 not being trained with this, empirically it seems to make interpretability easier.\n",
- "\n",
- "(However, if you want to change the default behaviour to *not* prepending a BOS token, pass `default_prepend_bos=False` when you instantiate the model, e.g., `model = HookedTransformer.from_pretrained('gpt2', default_prepend_bos=False)`.)\n",
- "\n",
- "For example, the model can get much worse at Indirect Object Identification without a BOS (and with a name as the first token):"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 38,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.627711Z",
- "iopub.status.busy": "2024-08-14T01:22:45.627519Z",
- "iopub.status.idle": "2024-08-14T01:22:45.824080Z",
- "shell.execute_reply": "2024-08-14T01:22:45.823479Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Logit difference with BOS: 6.754\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Logit difference without BOS: 2.782\n"
- ]
- }
- ],
- "source": [
- "ioi_logits_with_bos = model(\"Claire and Mary went to the shops, then Mary gave a bottle of milk to\", prepend_bos=True)\n",
- "mary_logit_with_bos = ioi_logits_with_bos[0, -1, model.to_single_token(\" Mary\")].item()\n",
- "claire_logit_with_bos = ioi_logits_with_bos[0, -1, model.to_single_token(\" Claire\")].item()\n",
- "print(f\"Logit difference with BOS: {(claire_logit_with_bos - mary_logit_with_bos):.3f}\")\n",
- "\n",
- "ioi_logits_without_bos = model(\"Claire and Mary went to the shops, then Mary gave a bottle of milk to\", prepend_bos=False)\n",
- "mary_logit_without_bos = ioi_logits_without_bos[0, -1, model.to_single_token(\" Mary\")].item()\n",
- "claire_logit_without_bos = ioi_logits_without_bos[0, -1, model.to_single_token(\" Claire\")].item()\n",
- "print(f\"Logit difference without BOS: {(claire_logit_without_bos - mary_logit_without_bos):.3f}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Though, note that this also illustrates another gotcha - when `Claire` is at the start of a sentence (no preceding space), it's actually *two* tokens, not one, which probably confuses the relevant circuit. (Note - in this test we put `prepend_bos=False`, because we want to analyse the tokenization of a specific string, not to give an input to the model!)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 39,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.826422Z",
- "iopub.status.busy": "2024-08-14T01:22:45.826044Z",
- "iopub.status.idle": "2024-08-14T01:22:45.830146Z",
- "shell.execute_reply": "2024-08-14T01:22:45.829692Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "| Claire| -> [' Claire']\n",
- "|Claire| -> ['Cl', 'aire']\n"
- ]
- }
- ],
- "source": [
- "print(f\"| Claire| -> {model.to_str_tokens(' Claire', prepend_bos=False)}\")\n",
- "print(f\"|Claire| -> {model.to_str_tokens('Claire', prepend_bos=False)}\")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Factored Matrix Class\n",
- "\n",
- "In transformer interpretability, we often need to analyse low rank factorized matrices - a matrix $M = AB$, where M is `[large, large]`, but A is `[large, small]` and B is `[small, large]`. This is a common structure in transformers, and the `FactoredMatrix` class is a convenient way to work with these. It implements efficient algorithms for various operations on these, such as computing the trace, eigenvalues, Frobenius norm, singular value decomposition, and products with other matrices. It can (approximately) act as a drop-in replacement for the original matrix, and supports leading batch dimensions to the factored matrix. \n",
- "\n",
- "Why are low-rank factorized matrices useful for transformer interpretability?\n",
- "\n",
- "As argued in [A Mathematical Framework](https://transformer-circuits.pub/2021/framework/index.html), an unexpected fact about transformer attention heads is that rather than being best understood as keys, queries and values (and the requisite weight matrices), they're actually best understood as two low rank factorized matrices. \n",
- "* **Where to move information from:** $W_QK = W_Q W_K^T$, used for determining the attention pattern - what source positions to move information from and what destination positions to move them to.\n",
- " * Intuitively, residual stream -> query and residual stream -> key are linear maps, *and* `attention_score = query @ key.T` is a linear map, so the whole thing can be factored into one big bilinear form `residual @ W_QK @ residual.T`\n",
- "* **What information to move:** $W_OV = W_V W_O$, used to determine what information to copy from the source position to the destination position (weighted by the attention pattern weight from that destination to that source). \n",
- " * Intuitively, the residual stream is a `[position, d_model]` tensor (ignoring batch). The attention pattern acts on the *position* dimension (where to move information from and to) and the value and output weights act on the *d_model* dimension - ie *what* information is contained at that source position. So we can factor it all into `attention_pattern @ residual @ W_V @ W_O`, and so only need to care about `W_OV = W_V @ W_O`\n",
- "* Note - the internal head dimension is smaller than the residual stream dimension, so the factorization is low rank. (here, `d_model=768` and `d_head=64`)\n",
- ""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Basic Examples"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can use the basic class directly - let's make a factored matrix directly and look at the basic operations:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.832169Z",
- "iopub.status.busy": "2024-08-14T01:22:45.831859Z",
- "iopub.status.idle": "2024-08-14T01:22:45.837487Z",
- "shell.execute_reply": "2024-08-14T01:22:45.837020Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Norms:\n",
- "tensor(9.9105)\n",
- "tensor(9.9105)\n",
- "Right dimension: 5, Left dimension: 5, Hidden dimension: 2\n"
- ]
- }
- ],
- "source": [
- "if IN_GITHUB:\n",
- " torch.manual_seed(50)\n",
- "A = torch.randn(5, 2)\n",
- "B = torch.randn(2, 5)\n",
- "\n",
- "AB = A @ B\n",
- "AB_factor = FactoredMatrix(A, B)\n",
- "print(\"Norms:\")\n",
- "print(AB.norm())\n",
- "print(AB_factor.norm())\n",
- "\n",
- "print(f\"Right dimension: {AB_factor.rdim}, Left dimension: {AB_factor.ldim}, Hidden dimension: {AB_factor.mdim}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can also look at the eigenvalues and singular values of the matrix. Note that, because the matrix is rank 2 but 5 by 5, the final 3 eigenvalues and singular values are zero - the factored class omits the zeros."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 41,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.839415Z",
- "iopub.status.busy": "2024-08-14T01:22:45.839254Z",
- "iopub.status.idle": "2024-08-14T01:22:45.844358Z",
- "shell.execute_reply": "2024-08-14T01:22:45.843929Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Eigenvalues:\n",
- "tensor([-6.2877e+00+0.j, 1.8626e-09+0.j, 2.3121e+00+0.j, -8.9038e-08+0.j,\n",
- " -4.1527e-07+0.j])\n",
- "tensor([-6.2877+0.j, 2.3121+0.j])\n",
- "\n",
- "Singular Values:\n",
- "tensor([8.3126e+00, 5.3963e+00, 2.2029e-07, 5.7690e-08, 1.2164e-08])\n",
- "tensor([8.3126, 5.3963])\n"
- ]
- }
- ],
- "source": [
- "# NBVAL_IGNORE_OUTPUT\n",
- "print(\"Eigenvalues:\")\n",
- "print(torch.linalg.eig(AB).eigenvalues)\n",
- "print(AB_factor.eigenvalues)\n",
- "print()\n",
- "print(\"Singular Values:\")\n",
- "print(torch.linalg.svd(AB).S)\n",
- "print(AB_factor.S)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can multiply with other matrices - it automatically chooses the smallest possible dimension to factor along (here it's 2, rather than 5)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 42,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.846168Z",
- "iopub.status.busy": "2024-08-14T01:22:45.846006Z",
- "iopub.status.idle": "2024-08-14T01:22:45.851408Z",
- "shell.execute_reply": "2024-08-14T01:22:45.850914Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Unfactored: torch.Size([5, 300]) tensor(160.0830)\n",
- "Factored: torch.Size([5, 300]) tensor(160.0830)\n",
- "Right dimension: 300, Left dimension: 5, Hidden dimension: 2\n"
- ]
- }
- ],
- "source": [
- "if IN_GITHUB:\n",
- " torch.manual_seed(50)\n",
- " \n",
- "C = torch.randn(5, 300)\n",
- "\n",
- "ABC = AB @ C\n",
- "ABC_factor = AB_factor @ C\n",
- "print(\"Unfactored:\", ABC.shape, ABC.norm().round(decimals=3))\n",
- "print(\"Factored:\", ABC_factor.shape, ABC_factor.norm().round(decimals=3))\n",
- "print(f\"Right dimension: {ABC_factor.rdim}, Left dimension: {ABC_factor.ldim}, Hidden dimension: {ABC_factor.mdim}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If we want to collapse this back to an unfactored matrix, we can use the AB property to get the product:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 43,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.853449Z",
- "iopub.status.busy": "2024-08-14T01:22:45.853094Z",
- "iopub.status.idle": "2024-08-14T01:22:45.856844Z",
- "shell.execute_reply": "2024-08-14T01:22:45.856352Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "tensor(True)\n"
- ]
- }
- ],
- "source": [
- "AB_unfactored = AB_factor.AB\n",
- "print(torch.isclose(AB_unfactored, AB).all())"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Medium Example: Eigenvalue Copying Scores\n",
- "\n",
- "(This is a more involved example of how to use the factored matrix class, skip it if you aren't following)\n",
- "\n",
- "For a more involved example, let's look at the eigenvalue copying score from [A Mathematical Framework](https://transformer-circuits.pub/2021/framework/index.html) of the OV circuit for various heads. The OV Circuit for a head (the factorised matrix $W_OV = W_V W_O$) is a linear map that determines what information is moved from the source position to the destination position. Because this is low rank, it can be thought of as *reading in* some low rank subspace of the source residual stream and *writing to* some low rank subspace of the destination residual stream (with maybe some processing happening in the middle).\n",
- "\n",
- "A common operation for this will just be to *copy*, ie to have the same reading and writing subspace, and to do minimal processing in the middle. Empirically, this tends to coincide with the OV Circuit having (approximately) positive real eigenvalues. I mostly assert this as an empirical fact, but intuitively, operations that involve mapping eigenvectors to different directions (eg rotations) tend to have complex eigenvalues. And operations that preserve eigenvector direction but negate it tend to have negative real eigenvalues. And \"what happens to the eigenvectors\" is a decent proxy for what happens to an arbitrary vector.\n",
- "\n",
- "We can get a score for \"how positive real the OV circuit eigenvalues are\" with $\\frac{\\sum \\lambda_i}{\\sum |\\lambda_i|}$, where $\\lambda_i$ are the eigenvalues of the OV circuit. This is a bit of a hack, but it seems to work well in practice."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Let's use FactoredMatrix to compute this for every head in the model! We use the helper `model.OV` to get the concatenated OV circuits for all heads across all layers in the model. This has the shape `[n_layers, n_heads, d_model, d_model]`, where `n_layers` and `n_heads` are batch dimensions and the final two dimensions are factorised as `[n_layers, n_heads, d_model, d_head]` and `[n_layers, n_heads, d_head, d_model]` matrices.\n",
- "\n",
- "We can then get the eigenvalues for this, where there are separate eigenvalues for each element of the batch (a `[n_layers, n_heads, d_head]` tensor of complex numbers), and calculate the copying score."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 44,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.858706Z",
- "iopub.status.busy": "2024-08-14T01:22:45.858532Z",
- "iopub.status.idle": "2024-08-14T01:22:45.865619Z",
- "shell.execute_reply": "2024-08-14T01:22:45.865086Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "FactoredMatrix: Shape(torch.Size([12, 12, 768, 768])), Hidden Dim(64)\n"
- ]
- }
- ],
- "source": [
- "OV_circuit_all_heads = model.OV\n",
- "print(OV_circuit_all_heads)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 45,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.867910Z",
- "iopub.status.busy": "2024-08-14T01:22:45.867538Z",
- "iopub.status.idle": "2024-08-14T01:22:45.984265Z",
- "shell.execute_reply": "2024-08-14T01:22:45.983688Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "torch.Size([12, 12, 64])\n",
- "torch.complex64\n"
- ]
- }
- ],
- "source": [
- "OV_circuit_all_heads_eigenvalues = OV_circuit_all_heads.eigenvalues \n",
- "print(OV_circuit_all_heads_eigenvalues.shape)\n",
- "print(OV_circuit_all_heads_eigenvalues.dtype)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 46,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:45.986670Z",
- "iopub.status.busy": "2024-08-14T01:22:45.986315Z",
- "iopub.status.idle": "2024-08-14T01:22:46.015978Z",
- "shell.execute_reply": "2024-08-14T01:22:46.015516Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "OV_copying_score = OV_circuit_all_heads_eigenvalues.sum(dim=-1).real / OV_circuit_all_heads_eigenvalues.abs().sum(dim=-1)\n",
- "imshow(utils.to_numpy(OV_copying_score), xaxis=\"Head\", yaxis=\"Layer\", title=\"OV Copying Score for each head in GPT-2 Small\", zmax=1.0, zmin=-1.0)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Head 11 in Layer 11 (L11H11) has a high copying score, and if we plot the eigenvalues they look approximately as expected."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 47,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:46.017994Z",
- "iopub.status.busy": "2024-08-14T01:22:46.017678Z",
- "iopub.status.idle": "2024-08-14T01:22:46.047073Z",
- "shell.execute_reply": "2024-08-14T01:22:46.046495Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "scatter(x=OV_circuit_all_heads_eigenvalues[-1, -1, :].real, y=OV_circuit_all_heads_eigenvalues[-1, -1, :].imag, title=\"Eigenvalues of Head L11H11 of GPT-2 Small\", xaxis=\"Real\", yaxis=\"Imaginary\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can even look at the full OV circuit, from the input tokens to output tokens: $W_E W_V W_O W_U$. This is a `[d_vocab, d_vocab]==[50257, 50257]` matrix, so absolutely enormous, even for a single head. But with the FactoredMatrix class, we can compute the full eigenvalue copying score of every head in a few seconds."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 48,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:46.049026Z",
- "iopub.status.busy": "2024-08-14T01:22:46.048718Z",
- "iopub.status.idle": "2024-08-14T01:22:56.219077Z",
- "shell.execute_reply": "2024-08-14T01:22:56.218446Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "FactoredMatrix: Shape(torch.Size([12, 12, 50257, 50257])), Hidden Dim(64)\n"
- ]
- }
- ],
- "source": [
- "full_OV_circuit = model.embed.W_E @ OV_circuit_all_heads @ model.unembed.W_U\n",
- "print(full_OV_circuit)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 49,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:56.221470Z",
- "iopub.status.busy": "2024-08-14T01:22:56.221139Z",
- "iopub.status.idle": "2024-08-14T01:22:56.749033Z",
- "shell.execute_reply": "2024-08-14T01:22:56.748441Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "torch.Size([12, 12, 64])\n",
- "torch.complex64\n"
- ]
- }
- ],
- "source": [
- "full_OV_circuit_eigenvalues = full_OV_circuit.eigenvalues\n",
- "print(full_OV_circuit_eigenvalues.shape)\n",
- "print(full_OV_circuit_eigenvalues.dtype)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 50,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:56.751540Z",
- "iopub.status.busy": "2024-08-14T01:22:56.751212Z",
- "iopub.status.idle": "2024-08-14T01:22:56.781404Z",
- "shell.execute_reply": "2024-08-14T01:22:56.780834Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "full_OV_copying_score = full_OV_circuit_eigenvalues.sum(dim=-1).real / full_OV_circuit_eigenvalues.abs().sum(dim=-1)\n",
- "imshow(utils.to_numpy(full_OV_copying_score), xaxis=\"Head\", yaxis=\"Layer\", title=\"OV Copying Score for each head in GPT-2 Small\", zmax=1.0, zmin=-1.0)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Interestingly, these are highly (but not perfectly!) correlated. I'm not sure what to read from this, or what's up with the weird outlier heads!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 51,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:56.783673Z",
- "iopub.status.busy": "2024-08-14T01:22:56.783141Z",
- "iopub.status.idle": "2024-08-14T01:22:56.812591Z",
- "shell.execute_reply": "2024-08-14T01:22:56.812045Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "scatter(x=full_OV_copying_score.flatten(), y=OV_copying_score.flatten(), hover_name=[f\"L{layer}H{head}\" for layer in range(12) for head in range(12)], title=\"OV Copying Score for each head in GPT-2 Small\", xaxis=\"Full OV Copying Score\", yaxis=\"OV Copying Score\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 52,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:56.814563Z",
- "iopub.status.busy": "2024-08-14T01:22:56.814234Z",
- "iopub.status.idle": "2024-08-14T01:22:56.817824Z",
- "shell.execute_reply": "2024-08-14T01:22:56.817368Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Token 256 - the most common pair of ASCII characters: | t|\n",
- "De-Tokenizing the example tokens: <|endoftext|>The first thing you need to figure out is *how* things are tokenized. `model.to_str_tokens` splits a string into the tokens *as a list of substrings*, and so lets you explore what the text looks like. To demonstrate this, let's use it on this paragraph.\n"
- ]
- }
- ],
- "source": [
- "print(f\"Token 256 - the most common pair of ASCII characters: |{model.to_string(256)}|\")\n",
- "# Squeeze means to remove dimensions of length 1. \n",
- "# Here, that removes the dummy batch dimension so it's a rank 1 tensor and returns a string\n",
- "# Rank 2 tensors map to a list of strings\n",
- "print(f\"De-Tokenizing the example tokens: {model.to_string(example_text_tokens.squeeze())}\")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Generating Text"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "TransformerLens also has basic text generation functionality, which can be useful for generally exploring what the model is capable of (thanks to Ansh Radhakrishnan for adding this!). This is pretty rough functionality, and where possible I recommend using more established libraries like HuggingFace for this."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 53,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:56.819864Z",
- "iopub.status.busy": "2024-08-14T01:22:56.819469Z",
- "iopub.status.idle": "2024-08-14T01:22:59.019481Z",
- "shell.execute_reply": "2024-08-14T01:22:59.018763Z"
- }
- },
- "outputs": [
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "2ecdd6424250402cb35d39c3d9ffe3e3",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- " 0%| | 0/50 [00:00, ?it/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "text/plain": [
- "'(CNN) President Barack Obama caught in embarrassing new scandal\\n\\nThe president, in an interview with the Financial Times, said that he did not know when he was caught on video talking about his wife, Chelsea, but he did know that she was a \"young woman\" and that he had been using her'"
- ]
- },
- "execution_count": 53,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# NBVAL_IGNORE_OUTPUT\n",
- "model.generate(\"(CNN) President Barack Obama caught in embarrassing new scandal\\n\", max_new_tokens=50, temperature=0.7, prepend_bos=True)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hook Points\n",
- "\n",
- "The key part of TransformerLens that lets us access and edit intermediate activations are the HookPoints around every model activation. Importantly, this technique will work for *any* model architecture, not just transformers, so long as you're able to edit the model code to add in HookPoints! This is essentially a lightweight library bundled with TransformerLens that should let you take an arbitrary model and make it easier to study. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This is implemented by having a HookPoint layer. Each transformer component has a HookPoint for every activation, which wraps around that activation. The HookPoint acts as an identity function, but has a variety of helper functions that allows us to put PyTorch hooks in to edit and access the relevant activation. \n",
- "\n",
- "There is also a `HookedRootModule` class - this is a utility class that the root module should inherit from (root module = the model we run) - it has several utility functions for using hooks well, notably `reset_hooks`, `run_with_cache` and `run_with_hooks`. \n",
- "\n",
- "The default interface is the `run_with_hooks` function on the root module, which lets us run a forwards pass on the model, and pass on a list of hooks paired with layer names to run on that pass. \n",
- "\n",
- "The syntax for a hook is `function(activation, hook)` where `activation` is the activation the hook is wrapped around, and `hook` is the `HookPoint` class the function is attached to. If the function returns a new activation or edits the activation in-place, that replaces the old one, if it returns None then the activation remains as is.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Toy Example"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Here's a simple example of defining a small network with HookPoints:\n",
- "\n",
- "We define a basic network with two layers that each take a scalar input $x$, square it, and add a constant:\n",
- "$x_0=x$, $x_1=x_0^2+3$, $x_2=x_1^2-4$.\n",
- "\n",
- "We wrap the input, each layer's output, and the intermediate value of each layer (the square) in a hook point.\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 54,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:59.021744Z",
- "iopub.status.busy": "2024-08-14T01:22:59.021569Z",
- "iopub.status.idle": "2024-08-14T01:22:59.027042Z",
- "shell.execute_reply": "2024-08-14T01:22:59.026503Z"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "from transformer_lens.hook_points import HookedRootModule, HookPoint\n",
- "\n",
- "\n",
- "class SquareThenAdd(nn.Module):\n",
- " def __init__(self, offset):\n",
- " super().__init__()\n",
- " self.offset = nn.Parameter(torch.tensor(offset))\n",
- " self.hook_square = HookPoint()\n",
- "\n",
- " def forward(self, x):\n",
- " # The hook_square doesn't change the value, but lets us access it\n",
- " square = self.hook_square(x * x)\n",
- " return self.offset + square\n",
- "\n",
- "\n",
- "class TwoLayerModel(HookedRootModule):\n",
- " def __init__(self):\n",
- " super().__init__()\n",
- " self.layer1 = SquareThenAdd(3.0)\n",
- " self.layer2 = SquareThenAdd(-4.0)\n",
- " self.hook_in = HookPoint()\n",
- " self.hook_mid = HookPoint()\n",
- " self.hook_out = HookPoint()\n",
- "\n",
- " # We need to call the setup function of HookedRootModule to build an\n",
- " # internal dictionary of modules and hooks, and to give each hook a name\n",
- " super().setup()\n",
- "\n",
- " def forward(self, x):\n",
- " # We wrap the input and each layer's output in a hook - they leave the\n",
- " # value unchanged (unless there's a hook added to explicitly change it),\n",
- " # but allow us to access it.\n",
- " x_in = self.hook_in(x)\n",
- " x_mid = self.hook_mid(self.layer1(x_in))\n",
- " x_out = self.hook_out(self.layer2(x_mid))\n",
- " return x_out\n",
- "\n",
- "\n",
- "model = TwoLayerModel()\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "We can add a cache, to save the activation at each hook point\n",
- "\n",
- "(There's a custom `run_with_cache` function on the root module as a convenience, which is a wrapper around model.forward that return model_out, cache_object - we could also manually add hooks with `run_with_hooks` that store activations in a global caching dictionary. This is often useful if we only want to store, eg, subsets or functions of some activations.)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 55,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:59.029217Z",
- "iopub.status.busy": "2024-08-14T01:22:59.028828Z",
- "iopub.status.idle": "2024-08-14T01:22:59.033182Z",
- "shell.execute_reply": "2024-08-14T01:22:59.032725Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Model output: 780.0\n",
- "Value cached at hook hook_in 5.0\n",
- "Value cached at hook layer1.hook_square 25.0\n",
- "Value cached at hook hook_mid 28.0\n",
- "Value cached at hook layer2.hook_square 784.0\n",
- "Value cached at hook hook_out 780.0\n"
- ]
- }
- ],
- "source": [
- "\n",
- "out, cache = model.run_with_cache(torch.tensor(5.0))\n",
- "print(\"Model output:\", out.item())\n",
- "for key in cache:\n",
- " print(f\"Value cached at hook {key}\", cache[key].item())\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "We can also use hooks to intervene on activations - eg, we can set the intermediate value in layer 2 to zero to change the output to -5\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 56,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:59.035230Z",
- "iopub.status.busy": "2024-08-14T01:22:59.034861Z",
- "iopub.status.idle": "2024-08-14T01:22:59.038817Z",
- "shell.execute_reply": "2024-08-14T01:22:59.038234Z"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "layer2.hook_square\n",
- "Output after intervening on layer2.hook_scaled -4.0\n"
- ]
- }
- ],
- "source": [
- "\n",
- "def set_to_zero_hook(tensor, hook):\n",
- " print(hook.name)\n",
- " return torch.tensor(0.0)\n",
- "\n",
- "\n",
- "print(\n",
- " \"Output after intervening on layer2.hook_scaled\",\n",
- " model.run_with_hooks(\n",
- " torch.tensor(5.0), fwd_hooks=[(\"layer2.hook_square\", set_to_zero_hook)]\n",
- " ).item(),\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Loading Pre-Trained Checkpoints\n",
- "\n",
- "There are a lot of interesting questions combining mechanistic interpretability and training dynamics - analysing model capabilities and the underlying circuits that make them possible, and how these change as we train the model. \n",
- "\n",
- "TransformerLens supports these by having several model families with checkpoints throughout training. `HookedTransformer.from_pretrained` can load a checkpoint of a model with the `checkpoint_index` (the label 0 to `num_checkpoints-1`) or `checkpoint_value` (the step or token number, depending on how the checkpoints were labelled)."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Available models:\n",
- "* All of my interpretability-friendly models have checkpoints available, including:\n",
- " * The toy models - `attn-only`, `solu`, `gelu` 1L to 4L\n",
- " * These have ~200 checkpoints, taken on a piecewise linear schedule (more checkpoints near the start of training), up to 22B tokens. Labelled by number of tokens seen.\n",
- " * The SoLU models trained on 80% Web Text and 20% Python Code (`solu-6l` to `solu-12l`)\n",
- " * Same checkpoint schedule as the toy models, this time up to 30B tokens\n",
- " * The SoLU models trained on the pile (`solu-1l-pile` to `solu-12l-pile`)\n",
- " * These have ~100 checkpoints, taken on a linear schedule, up to 15B tokens. Labelled by number of steps.\n",
- " * The 12L training crashed around 11B tokens, so is truncated.\n",
- "* The Stanford Centre for Research of Foundation Models trained 5 GPT-2 Small sized and 5 GPT-2 Medium sized models (`stanford-gpt2-small-a` to `e` and `stanford-gpt2-medium-a` to `e`)\n",
- " * 600 checkpoints, taken on a piecewise linear schedule, labelled by the number of steps."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The checkpoint structure and labels is somewhat messy and ad-hoc, so I mostly recommend using the `checkpoint_index` syntax (where you can just count from 0 to the number of checkpoints) rather than `checkpoint_value` syntax (where you need to know the checkpoint schedule, and whether it was labelled with the number of tokens or steps). The helper function `get_checkpoint_labels` tells you the checkpoint schedule for a given model - ie what point was each checkpoint taken at, and what type of label was used.\n",
- "\n",
- "Here are graphs of the schedules for several checkpointed models: (note that the first 3 use a log scale, latter 2 use a linear scale)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 57,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:59.040769Z",
- "iopub.status.busy": "2024-08-14T01:22:59.040605Z",
- "iopub.status.idle": "2024-08-14T01:22:59.390140Z",
- "shell.execute_reply": "2024-08-14T01:22:59.389605Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "
\n",
- "\n",
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "from transformer_lens.loading_from_pretrained import get_checkpoint_labels\n",
- "for model_name in [\"attn-only-2l\", \"solu-12l\", \"stanford-gpt2-small-a\"]:\n",
- " checkpoint_labels, checkpoint_label_type = get_checkpoint_labels(model_name)\n",
- " line(checkpoint_labels, xaxis=\"Checkpoint Index\", yaxis=f\"Checkpoint Value ({checkpoint_label_type})\", title=f\"Checkpoint Values for {model_name} (Log scale)\", log_y=True, markers=True)\n",
- "for model_name in [\"solu-1l-pile\", \"solu-6l-pile\"]:\n",
- " checkpoint_labels, checkpoint_label_type = get_checkpoint_labels(model_name)\n",
- " line(checkpoint_labels, xaxis=\"Checkpoint Index\", yaxis=f\"Checkpoint Value ({checkpoint_label_type})\", title=f\"Checkpoint Values for {model_name} (Linear scale)\", log_y=False, markers=True)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Example: Induction Head Phase Transition"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "One of the more interesting results analysing circuit formation during training is the [induction head phase transition](https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html). They find a pretty dramatic shift in models during training - there's a brief period where models go from not having induction heads to having them, which leads to the models suddenly becoming much better at in-context learning (using far back tokens to predict the next token, eg over 500 words back). This is enough of a big deal that it leads to a visible *bump* in the loss curve, where the model's rate of improvement briefly increases. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "As a brief demonstration of the existence of the phase transition, let's load some checkpoints of a two layer model, and see whether they have induction heads. An easy test, as we used above, is to give the model a repeated sequence of random tokens, and to check how good its loss is on the second half. `evals.induction_loss` is a rough util that runs this test on a model.\n",
- "(Note - this is deliberately a rough, non-rigorous test for the purposes of demonstration, eg `evals.induction_loss` by default just runs it on 4 sequences of 384 tokens repeated twice. These results totally don't do the paper justice - go check it out if you want to see the full results!)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the interests of time and memory, let's look at a handful of checkpoints (chosen to be around the phase change), indices `[10, 25, 35, 60, -1]`. These are roughly 22M, 200M, 500M, 1.6B and 21.8B tokens through training, respectively. (I generally recommend looking things up based on indices, rather than checkpoint value!). "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 58,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:59.392374Z",
- "iopub.status.busy": "2024-08-14T01:22:59.392204Z",
- "iopub.status.idle": "2024-08-14T01:22:59.395497Z",
- "shell.execute_reply": "2024-08-14T01:22:59.394971Z"
- }
- },
- "outputs": [],
- "source": [
- "from transformer_lens import evals\n",
- "# We use the two layer model with SoLU activations, chosen fairly arbitrarily as being both small (so fast to download and keep in memory) and pretty good at the induction task.\n",
- "model_name = \"solu-2l\"\n",
- "# We can load a model from a checkpoint by specifying the checkpoint_index, -1 means the final checkpoint\n",
- "checkpoint_indices = [10, 25, 35, 60, -1]\n",
- "checkpointed_models = []\n",
- "tokens_trained_on = []\n",
- "induction_losses = []"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We load the models, cache them in a list, and "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 59,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:59.397838Z",
- "iopub.status.busy": "2024-08-14T01:22:59.397492Z",
- "iopub.status.idle": "2024-08-14T01:22:59.401089Z",
- "shell.execute_reply": "2024-08-14T01:22:59.400558Z"
- }
- },
- "outputs": [],
- "source": [
- "if not IN_GITHUB:\n",
- " for index in checkpoint_indices:\n",
- " # Load the model from the relevant checkpoint by index\n",
- " model_for_this_checkpoint = HookedTransformer.from_pretrained(model_name, checkpoint_index=index, device=device)\n",
- " checkpointed_models.append(model_for_this_checkpoint)\n",
- "\n",
- " tokens_seen_for_this_checkpoint = model_for_this_checkpoint.cfg.checkpoint_value\n",
- " tokens_trained_on.append(tokens_seen_for_this_checkpoint)\n",
- "\n",
- " induction_loss_for_this_checkpoint = evals.induction_loss(model_for_this_checkpoint, device=device).item()\n",
- " induction_losses.append(induction_loss_for_this_checkpoint)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can plot this, and see there's a sharp shift from ~200-500M tokens trained on (note the log scale on the x axis). Interestingly, this is notably earlier than the phase transition in the paper, I'm not sure what's up with that.\n",
- "\n",
- "(To contextualise the numbers, the tokens in the random sequence are uniformly chosen from the first 20,000 tokens (out of ~48,000 total), so random performance is at least $\\ln(20000)\\approx 10$. A naive strategy like \"randomly choose a token that's already appeared in the first half of the sequence (384 elements)\" would get $\\ln(384)\\approx 5.95$, so the model is doing pretty well here.)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 60,
- "metadata": {
- "execution": {
- "iopub.execute_input": "2024-08-14T01:22:59.403335Z",
- "iopub.status.busy": "2024-08-14T01:22:59.402893Z",
- "iopub.status.idle": "2024-08-14T01:22:59.436066Z",
- "shell.execute_reply": "2024-08-14T01:22:59.435556Z"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "\n",
- "