In-Context Learning Creates Task Vectors
Roee Hendel, Mor Geva, Amir Globerson
Introduction
Large language models have improved dramatically over the last several years. One striking property of these models is that they can learn new rules from very few demonstrations. For instance, a model can be prompted with the input “Apple Red, Lime Green, Corn ” and produce the output “Yellow”. The model has thus learned a mapping based on just two examples, which it can apply correctly to new examples. This capability, referred to as In-Context Learning (ICL), has been used extensively, yielding impressive empirical results Brown et al. (2020); Liu et al. (2023); Dong et al. (2022).
It is unclear whether ICL operates in such a way because the prediction is performed via , where is typically an auto-regressive transformer and is a concatenation of the tokens in and . Thus, in the general case, it can be an arbitrary function that operates on and to produce the output. This can include “non-parametric” methods such as nearest-neighbor. Recent work has begun to explore this question. For example, it was shown that when training a transformer from scratch to perform linear regression in context, the emerging learning algorithm is similar to Stochastic Gradient Descent Akyürek et al. (2022); von Oswald et al. (2022). However, for LLMs performing more complex natural language tasks, it is not at all clear what the hypothesis space may be.
In this work, we show that on a wide range of tasks, ICL in LLMs can be viewed as working on a very natural hypothesis space. We argue that, given a training set , the transformer maps it into a “task vector” that essentially represents the mapping/rule described in .The term “task vector” was coined by Ilharco et al. (2023) for directions in weight space that correspond to a particular task. Although our vectors are in “activations space” they share a similar motivation and thus we overload the term. Namely, given the transformer and a vector , we can construct a new function that implements the task. The function is very similar to the original transformer applied to without demonstrations but instead modulated by (see Fig. 2).
Our view is also related to soft prompts Lester et al. (2021), since both approaches modulate the function of the transformer towards a particular task. However, in ICL, task vectors are calculated in the forward pass rather than being fine-tuned.
Our contributions include proposing a hypothesis-class based mechanistic view of ICL, and conducting experiments to validate our view on a range of publicly available LLMs and a diverse set of tasks. Our results further the understanding of ICL and may have practical implications for the efficient adaptation of LLMs to perform specific tasks.
A Hypothesis Class View of ICL
Motivated by the hypothesis class view of learning theory, our goal is to understand if ICL maps the set of demonstrations to a function on the query and how this mapping occurs. Specifically, we seek to see if ICL converts into - the “parameters” of a function within a certain hypothesis space. Our empirical findings suggest this view is applicable, shedding light on the structure of the hypothesis space on which ICL can be viewed to operate.
We use to denote a decoder-only transformer LLM, to denote the set of demonstrations (i.e. training examples) used as input to ICL, and to denote the query that ICL is asked to provide an output for. We use to denote the output of ICL on the concatenation of and .
To demonstrate that ICL operates within a hypothesis space, we aim to show that its underlying mechanism can be broken down into two parts:
A “Learning Algorithm” (denoted by ) that maps into a “task vector” , independent of the query . Given that attention layers can access both and , this independence is not trivial.
A “Rule Application” (denoted by ) which maps the query to the output, based on , without direct dependence on . Again, this independence is not trivial.
Thus, we consider the following mapping from a set of demonstrations and a query to the predicted output: .
If we can break down the forward pass of the LLM into the above two components, we can view ICL as operating on the following hypothesis class: . In the next section we propose an implementation of such a class.
2 A Proposed Hypothesis Class
There are many possible realizations of the above framework, that correspond to different choices of and . We next describe the realization we focus on, which naturally follows from the transformer architecture. We consider an ICL setting as in Fig. 1, where the input ends with a query (i.e., Corn) followed by an “” symbol. As mentioned above, we view learning as composed of two steps: calculating a parameter vector based on the training sample , and applying the rule defined by this parameter vector to the query . A presumably simple way for a transformer to do this is for the first layers of the representations to calculate and then for the remaining layers to take and as input and produce an output. See Fig. 1. Recall that and are accessible to the transformer at any layer, presenting a challenge with our view.
In the following sections, we address this challenge and present experiments validating our view. Namely, we show that we can isolate our proposed and in the forward pass of LLMs performing ICL. We also show that the vectors are interpretable and correspond to learned tasks.
Validity of the Hypothesis Class View
We first show that separating the forward pass into the two distinct components and , defined in §2.2, maintains the high accuracy of ICL.
We face some challenges in a regular forward pass: first, the initial layers that correspond to , updating the representations of to create , can attend to the query . Thus, they may depend on , creating an unwanted dependence of on . Second, the remaining layers that correspond to , may directly access , instead of using only and .
We propose the following procedure to tackle these challenges: to solve the first problem, we introduce a “dummy query” and calculate the representations of using that query. We use the representation of after the first layers, calculated using , as the vector (as demonstrated on the left side of Fig. 2). An alternative was to block attention to , but it led to poor performance. To solve the second problem of calculating without allowing direct dependence on , we perform a forward pass of the transformer only on and ,Ignoring positional embeddings, this is equivalent to blocking the attention to in these layers. and “patch” the we previously extracted at the th layer of the (right side of Fig. 2).Note that the second token can actually be anything, because it is overridden by patching. We use for simplicity.
2 Tasks and Models
We consider a diverse set of 18 tasks across 4 categories: algorithmic, translation, linguistic, and factual knowledge. For simplicity, we limit ourselves to single-token outputs. A representative subset of the tasks is described in Tab. 1. A complete detailed table, as well as more information regarding the data, are provided in § A.1.
Models
We use multiple open LLMs: LLaMA 7B, 13B, and 30B Touvron et al. (2023), GPT-J 6B Wang and Komatsuzaki (2021), and Pythia 2.8B, 6.9B, and 12B Biderman et al. (2023).
3 Finding L𝐿L
The mechanism we described in §2.2 has a free parameter - the layer where ends and begins. We use the proposed implementation for different choices of and evaluate the accuracy on a development set to find the best layer.
Fig. 3 shows the accuracy on the development set, for different choices of . We focus here on the LLaMA models and include the rest in § A.2. Interestingly, all models exhibit a performance peak at a similar intermediate layer, irrespective of their parameters and layer count differences.
4 Accuracy of Hypothesis Based Prediction
We next compare the accuracy of the mechanism to that of a regular forward pass performing ICL. For each model and task, we evaluate the following three procedures:
Regular An application of the LLM to the demonstrations and query . Namely , as in regular ICL.
Hypothesis Our proposed procedure from § 3.1 where generates using a dummy , and is applied to by running the transformer on with patched at layer of .
Baseline A forward pass of the LLM only on , without demonstrations . That is, . This is the same as the application of from our separated procedure, but without patching .
Fig. 4 shows the average accuracy across all tasks of these 3 procedures, for each model. Full results are reported in Tab. LABEL:table:main_results in § A.2. Across all models, our procedure maintains around 80-90% of the accuracy of regular ICL, while the baseline reaches only 10-20%. This shows that our proposed separation to and provides a good empirical approximation of the process underlying ICL.
Robustness of Task Vectors
In our setting, is derived from and a dummy query . It is natural to examine the robustness of to variations in these inputs. Intuitively, if it represents the task, it should remain stable across different and values.
To test this, we use LLaMA 7B to generate 50 task vectors per task with varied and and conduct two analyses.
A t-SNE dimensionality reduction (Fig. 5) reveals that the task vectors form distinct clusters, each containing task vectors of a single task. Fig. 9 further shows proximity between tasks of the same category, strengthening the idea that they encapsulate task understanding.
Variability of 𝜽𝜽\boldsymbol{\theta}
Fig. 8 shows histograms of distances within and across tasks. It can be seen that vectors within the same task are closer than those between different tasks, indicating that is stable within tasks and not highly influenced by or .
Dominance of 𝜽𝜽\boldsymbol{\theta} Patching
In §3 we prevented from directly accessing . However, in a regular forward pass during ICL, the last token can attend to . Here we verify that even in this case, mainly uses the task vector , without directly accessing the demonstrations . To this end, we use a pair of tasks, and , sharing the input space but differing on the output. We first use a “Regular” forward pass, where we provide the model with demonstrations for task (denoted ), to verify the model can perform this task using ICL. Then, we do a “Conflicting” forward pass, still providing , while injecting . For more details, refer to Fig. 6 in §A.1.
In Tab.2, the “Regular” forward pass shows high accuracy on task (90%+), as anticipated. However, the “Conflicting” forward pass yields high accuracy on task , corresponding to the injected task vector . This implies that the model mainly relies on , largely disregarding the demonstrations for task . We note that the accuracy on task is slightly low, likely consistent with the performance dip seen in Fig. LABEL:table:main_results, and potentially further affected by the presence of .
Interpreting 𝜽𝜽\boldsymbol{\theta}
The learned vector intuitively captures information about the task demonstrated by . Here we provide evidence supporting this interpretation. Since is an intermediate hidden state of the transformer, we can employ a vocabulary projection method nostalgebraist (2020); Dar et al. (2022). Namely, we examine the top tokens in the distribution over the vocabulary induced by the hidden state.
Tab. 3 shows the top tokens for three tasks for LLaMA 13B (more models and tasks are provided in Tab. 7 in §A). In multiple cases, we observe tokens that directly describe the task. Importantly, these terms never explicitly appeared in the context. For example in the task of translation from French to English, we observe tokens such as “English” and “translate”. This supports our view that carries significant, non-trivial semantic information about the task.
Related Work
A key question with ICL is how it emerges as a capability from pre-training the LLMs. Levine et al. (2022) provides results in this direction that highlight the importance of training data structure. Xie et al. use probabilistic analysis and model pre-training data using Hidden Markov Models to theoretically explain the emergence of ICL, while Chan et al. (2022) empirically explore the effect of several distributional properties of the pre-training data.
Meta-Learning in Transformers
Studies by Akyürek et al. (2022); von Oswald et al. (2022); Garg et al. focus on the meta-learning capabilities of transformers. They typically train models from scratch on elementary tasks such as linear regression, drawing theoretical parallels with algorithms like Gradient Descent and demonstrating how transformers could implement them. A key assumption of these works is a known parameter space within which gradient descent operates. Our work focuses on identifying such a parameter space for LLMs.
ICL in LLMs
Olsson et al. (2022) identify “induction heads” in transformers as a likely main mechanism of ICL. Dai et al. (2022) provide empirical evidence for the connection of ICL to Gradient Descent in LLMs, focusing on classification tasks. Concurrent work by Merullo et al. (2023) also explores a phenomenon similar to the task vectors we study here, where a single vector can encode learned functions. Our findings are complementary to theirs, and future work could explore the relationship between the two more closely.
Conclusions
Through this exploration of ICL in LLMs, we have shed light on a new perspective of ICL learning mechanisms. We have revealed a simple and elegant structure: ICL functions by compressing a given training set into a single task vector, which then guides the transformer to generate appropriate outputs given queries. Our work provides a stepping stone towards understanding how LLMs perform ICL. In light of our findings, future work could focus on understanding how the task vector is constructed as well as how it is used to calculate the output.
Limitations
We study relatively simple tasks, whereas ICL can learn to perform more complex tasks, such as solving arithmetic reasoning problems. It remains to be seen if and how the mechanisms we observe here will translate to these cases. E.g., our approach focuses on cases where a single task vector suffices, while more complex ICL cases may require more elaborate parameterization. We also focus on tasks where the output is a single token, while some other tasks require multi-token outputs.
Finally, as noted above, we do not provide a mechanistic explanation for how the task vector is formed or how it is used. Namely, we do not explain how the transformer performs these calculations using its parameters.
Acknowledgements
This project is funded by the European Research Council (ERC) under the European Unions Horizon 2020 research and innovation program (grant ERC HOLI 819080).
References
Appendix A Appendix
Here we provide additional details and results.
Our study covers 18 tasks in 4 categories: Algorithmic, Translation, Linguistic and Knowledge. A detailed description of all tasks is provided in Tab. 5.
Model Details
More details on the models used in the study are provided in Tab. 4.
Task Data
Here we detail the sources of the data for each task. The accompanying GitHub repository contains the data itself as well as the code used to create it.
Translation: For each language pair, the most frequent words in the source language are first retrieved from https://github.com/frekwencja/most-common-words-multilingual and are then translated to the destination language using the open-source package nltk.
Linguistic: The data for the tenses tasks is parsed from https://github.com/Drulac/English-Verbs-Conjugates. The data for the plural-singular task is taken from https://github.com/sindresorhus/irregular-plurals. Finally, the data for the antonyms task is taken from https://github.com/SuzanaK/english_synonyms_antonyms_list.
Knowledge Data for the knowledge tasks is taken from the counterfactual dataset introduced in Meng et al. (2022).
Conflicting Tasks Experiment
In Fig. 6, we provide more details and a visualization of the experiment described in §5.
A.2 Additional Results
Fig. 7 shows results similar to Fig. 3, but for different models. It is interesting to observe that the curves are similar across different-sized models.
Detailed results for Fig. 4.
Fig. 4 presented results for our hypothesis-based approach, averaged across tasks. Table. LABEL:table:main_results provides these results for all the specific tasks considered.
Dependence of 𝒜𝒜\mathcal{A} on x𝑥x
Fig. 9 and Fig. 8 provide more results on the geometry of the vectors (see main text for discussion).
Inspecting Task Vectors
Tab. 7 is an expanded version of Tab. 3, providing more vocabulary projections of for additional tasks and on multiple LLMs.