Implicit In-context Learning

## Abstract

Abstract In-context Learning (ICL) empowers large language models (LLMs) to adapt to unseen tasks during inference by prefixing a few demonstration examples prior to test queries. Despite its versatility, ICL incurs substantial computational and memory overheads compared to zero-shot learning and is susceptible to the selection and order of demonstration examples. In this work, we introduce Implicit In-context Learning (I2CL), an innovative paradigm that addresses the challenges associated with traditional ICL by absorbing demonstration examples within the activation space. I2CL first generates a condensed vector representation, namely a context vector, from the demonstration examples. It then integrates the context vector during inference by injecting a linear combination of the context vector and query activations into the model’s residual streams. Empirical evaluation on nine real-world tasks across three model architectures demonstrates that I2CL achieves few-shot performance with zero-shot cost and exhibits robustness against the variation of demonstration examples. Furthermore, I2CL facilitates a novel representation of “task-ids”, enhancing task similarity detection and enabling effective transfer learning. We provide a comprehensive analysis of I2CL, offering deeper insights into its mechanisms and broader implications for ICL. The source code is available at: https://github.com/LzVv123456/I2CL .

## 1 Introduction

In-context Learning (ICL) has emerged as a prominent capability of large language models (LLMs) [Brown et al., ]. It enables swift adaptation to new tasks during inference by prefixing a few demonstration examples prior to a test query [Wei et al., , Dong et al., ].
ICL, characterized by its adaptability and flexibility, has prompted extensive research efforts aimed at optimizing these demonstration examples, or prompts [Rubin et al., , Sorensen et al., , Wu et al., , Min et al., , inter alia], as well as mitigating their sensitivity to formatting, order, and recency bias [Zhao et al., , Lu et al., , Hao et al., , inter alia].

Despite these advancements, the predominant focus on manipulating demonstration examples within the token space—where tokens are prepended to the query—presents notable limitations. This approach not only escalates computation and memory demands with each additional token but also remains susceptible to the selection and the order of demonstration examples. Such constraints pose significant challenges in scenarios with limited computational and memory resources or variable demonstration profiles, affecting ICL’s scalability and practical utility in real-world applications.

In this study, we explore the usage of demonstration examples within the activation space to surmount these obstacles. Utilizing a decoder-only architecture, we observe that the primary burdens of ICL arise from the computationally intensive multi-head mechanism, which fuses information between demonstration and query tokens, and the memory-intensive key-value caching scheme necessary for retaining demonstration contexts(^1^11Without applying key-value cache, one needs to repetitively forward the same demonstration examples.). These observations lead us to explore two pivotal questions: Is there a memory-efficient representation of demonstration examples? And, can we integrate information in a more computationally economical manner?

Figure: Figure 1: (Upper-left is better) Comparison of accuracy, inference time and cached memory of different methods on Llama2-7b.

Our findings suggest that both objectives are attainable by first condensing demonstration examples into a compact vector representation and then reintegrating their functionalities within the model’s activation space. Specifically, instead of concatenating demonstration examples into a text sequence before the test query, we independently extract a demonstration vector from each example. These vectors are then aggregated in a permutation-invariant manner to form a unified context vector. During inference, we inject a linear combination of this context vector and the query activations back into the model’s residual streams. We term this scheme Implicit In-context Learning (I2CL), underscoring the absence of an explicit causal relation between the demonstration examples and the test query in the token space.

I2CL offers several merits over standard ICL methods. By condensing demonstration examples into a unified context vector, I2CL requires to cache only a fixed amount of activation vectors, regardless of the length of demonstration tokens. I2CL also maintains a zero-shot inference speed by merging information between demonstration examples and queries through simple linear operations. We evaluate I2CL across three open-source LLMs on nine real-world text classification tasks, where it significantly surpasses the zero-shot and other comparable baselines and achieves results on par with few-shot learning (Figure 1). Importantly, I2CL demonstrates robustness against the variability of demonstration examples. It also facilitates a natural representation of ‘task-ids”, which can effectively indicate task similarity and support transfer learning. The main contributions of this work are summarized as follows:

- 1.
We introduce I2CL, a simple and novel framework that effectively integrates a minimal set of demonstration examples within the activation space. By decomposing conventional ICL into two stages: context vectorization and context-vector injection, I2CL attains few-shot performances at zero-shot costs.
- 2.
We empirically confirm the robustness of I2CL against variations in demonstration examples and its ability to produce a natural representation of task-ids. Leveraging these task-ids, we further propose a transfer learning strategy that can enhance performance on new tasks based on existing
ones.
- 3.
We conduct an extensive analysis to thoroughly examine the scheme of I2CL, thereby shedding light on its internal mechanisms and contributing to a deeper understanding of ICL. We also provide a deliberated discussion on the limitations and future directions of I2CL.

## 2 Related Work

Understanding In-context Learning Besides enhancing ICL, the exploration of ICL’s internal mechanisms has attracted significant research attention. Akyürek et al. [] draw parallels between ICL and gradient descent in linear regression tasks, suggesting a fundamental alignment with classical optimization methods. Complementary perspectives from Von Oswald et al. [] and Dai et al. [] conceptualize ICL as a form of meta-optimization, further enriching our understanding of its operational basis. Concurrently, Xie et al. [] interpret ICL through the lens of implicit Bayesian inference, proposing a probabilistic foundation for the learning process. Wei et al. [] and Olsson et al. [] respectively attribute ICL’s capabilities to the establishment of input-label correspondences and the identification of so-called induction heads, highlighting the intricate interplay between data representation and model interpretability. Despite these advancements, a comprehensive understanding of ICL’s working mechanism remains elusive. Our work, I2CL, contributes additional insights to this domain by substantiating a novel two-stage scheme, which suggests a potential division of the underlying functionality of ICL. Most recently, Label-as-Anchors [Wang et al., ] inspects ICL from an information flow perspective and leverages anchor tokens to perform context compression. Similarly, I2CL also enhances the efficiency of ICL, but distinguishes itself by circumventing the need for caching latents of anchor tokens or employing multi-head attention, thereby reducing the inference cost to that of the zero-shot learning.

Activation/representation Engineering An emerging research field, termed activation/representation engineering, also relates to our study. Recent endeavors by Merullo et al. [], Turner et al. [], Zou et al. [] have unveiled the phenomenon of steering vectors, which can be derived from a positive and negative text pair and used to steer the content generation of LLMs. Steering vectors can also be learned via gradient descent [Subramani et al., ]. Liu et al. [] applies these insights to bolster LLM safety while Li et al. [] explores their utility in eliciting more truthful responses from LLMs. To better understand the inner mechanism of activation engineering, the linear representation hypothesis has been studied and discussed in Li et al. [], Hernandez et al. [], Park et al. []. Our work, I2CL, further corroborates this hypothesis, aligning with and expanding upon the pioneering works by Mikolov et al. [], Meng et al. [], Hernandez et al. []. Central to this discourse, the idea of task/function vector [Hendel et al., , Todd et al., ] resonates with the core premise of I2CL. Both methodologies extract task/function vectors from the demonstration examples and them to improve zero-shot performance. I2CL stands out not only due to its superior performance, but also through its simplicity, namely, its avoidance of the need for task- or architecture-specific hyperparameter tuning, such as selecting attention heads through causal mediation or determining target layers via extra validation sets. Conceptually, we ask an even simpler question: In practice, is there a more economical method to absorb a tiny amount of demonstration examples than by prefixing them in context?

## 3 Methodology

### 3.1 Preliminaries

Residual Stream We adopt the mathematical interpretation from Elhage et al. [], viewing the hidden states across layers and at each token position as a residual stream. This perspective views each attention head and multi-layer perceptron (MLP) module as engaging with residual streams, facilitating both the addition and deletion of information within them. At any given layer $l$ and token position $t$, the residual stream ${\bm{r}}_{l}^{t}$ is defined recursively:

$$ ${\bm{r}}_{l}^{t}={\bm{r}}_{l-1}^{t}+{\bm{a}}_{l}^{t}+{\bm{m}}_{l}^{t},$ (1) $$

where ${\bm{a}}_{l}^{t}$ denotes the integrated output of the multi-head attention (MHA) module, and ${\bm{m}}^{t}_{l}$ signifies the MLP’s output, contingent also on ${\bm{a}}_{l}^{t}$. In this framework, MHA promotes the information fusion across residual streams, whereas the MLP functions akin to an associative memory [Geva et al., , Dai et al., ] that retrieves information encapsulated within its weights.

In-context Learning Given an unseen task, ICL assumes the existence of a set of $N$ demonstration examples ${\mathbb{D}}=\{d_{1},d_{2},\dots,d_{N}\}$, each comprising an instructional pair $d_{i}=(x_{i},y_{i})$ that includes an input sentence(^2^22Input $x_{i}$ also includes formatting texts like: “Question:”, “Answer Type:”.) and its corresponding label. ICL operates by first concatenating the demonstration set ${\mathbb{D}}$ with the test query $x_{q}$, forming an input prompt $p=[{\mathbb{D}},x_{q}]$. The objective is then to predict the correct response $y_{q}$ from a finite set of discrete labels ${\mathbb{C}}$ via $y_{q}=\operatorname*{arg\,max}_{y\in{\mathbb{C}}}P(y\mid p)$.

### 3.2 Context Vectorization

To overcome the inefficiencies associated with key-value caching system, we isolate the reasoning process of demonstration examples from that of the query, and introduce an independent vectorization of each demonstration pair $d_{i}$. These vectors are subsequently merged in the activation space. Specifically, we define a function $V$, capable of generating a vector representation for each demonstration example: ${\bm{d}}_{i}=V(d_{i})$. Then, a function $F$ is applied to aggregate these demonstration vectors into a unified context vector ${\bm{v}}=F(\{{\bm{d}}_{i}\}_{i=1}^{N})$. Note that $F$ is designed to be permutation invariant, ensuring a unique vector representation for a given set of demonstration examples.

In our implementation, $V$ consists of a pre-trained tokenizer and a frozen LLM parameterized by its pre-trained weights. The demonstration vectors are extracted from the output activations of both MHA and MLP modules at the end residual stream across all layers:

$$ ${\bm{d}}_{i}=\{{\bm{a}}^{e}_{i,l},{\bm{m}}^{e}_{i,l}\}^{L}_{l=1}~{}.$ (2) $$

Here, $e$ denotes the end position within a token sequence responsible for next-token prediction, and $L$ represents the total number of layers. For the aggregation function, we compute an element-wise arithmetic mean of each vector component across the demonstration examples:

$$ ${\bm{v}}=\{\bar{{\bm{a}}}_{l}^{e},\bar{{\bm{m}}}_{l}^{e}\}_{l=1}^{L}$ (3) $$

where $\bar{{\bm{a}}}_{l}^{e}=\frac{1}{N}\sum_{i=1}^{N}{{\bm{a}}^{e}_{i,l}}$ and $\bar{{\bm{m}}}_{l}^{e}=\frac{1}{N}\sum_{i=1}^{N}{{\bm{m}}^{e}_{i,l}}$.

The rationale of above designs is twofold. First, we argue that the end residual stream encapsulates the essential information from each example. This is supported by the dynamics of next-token prediction and empirical findings from recent studies [Hendel et al., , Zou et al., , Todd et al., ]. Second, inspired by the linear representation hypothesis [Park et al., ], we premise various demonstration vectors can undergo linear transformations at different levels of abstraction.

Figure: Figure 2: A schematic overview of I2CL, including a single layer for the illustrative purpose. I2CL begins by extracting the output activations of the MHA and MLP modules at the end residual stream of each demonstration example. These activation vectors are then fused in a permutation-invariant manner to form layer-wise context vectors. At inference, a linear combination of context vectors and activations from the test query is added to all residual streams.

### 3.3 Context Injection

Having established a unique vector representation, ${\bm{v}}$, for the demonstration examples, I2CL seeks to enhance zero-shot performance by integrating this context information with that of the query. While typical implementations leverage the multi-head attention module for this purpose, I2CL utilizes a simpler, yet effective, linear operation to augment the query activations with context vectors.

Consider ${\bm{r}}_{l}^{t}$, the residual stream at the $t$-th token and $l$-th layer of a test query. Instead of merely adding the output activations from the MHA and MLP to their corresponding residual streams, we inject a linear combination of these activations with context vectors:

$$ ${\bm{r}}_{l}^{t}={\bm{r}}_{l-1}^{t}+(\lambda_{l}^{a}\bar{{\bm{a}}}^{e}_{l}+ \beta_{l}^{a}{\bm{a}}_{l}^{t})+(\lambda_{l}^{m}\bar{{\bm{m}}}^{e}_{l}+\beta_{l }^{m}{\bm{m}}_{l}^{t}),\quad l\in[1,L],t\in[1,T].$ (4) $$

Here, $\lambda^{a},\beta^{a},\lambda^{m},\beta^{m}$ are four layer-wise scalars used to adjust the proportion to which the context vectors and query activations are blended. They also affect the amplitude of vectors. By default, we apply this information fusion process to all residual streams of a given query, implemented using the forward hook function. Letting $\lambda=0$ and $\beta=1$ (omitting subscripts) will replicate the original zero-shot inference.

Above context injection method incurs minimal computational overhead, involving only two scalar multiplications and an element-wise addition, a process more efficient than the attention mechanism. As a result, the inference speed of I2CL matches that of standard zero-shot learning. Since a constant number of activations is necessary for caching, I2CL also retains approximately the same memory usage as zero-shot. We refer to Figure 2 for a schematic illustration of the context vectorization and injection procedures.

### 3.4 Noisy Self-calibration

To achieve generic and nuanced control over the information fusion process, we propose estimating the linear coefficients ${\bm{c}}=\{\lambda_{l}^{a},\beta_{l}^{a},\lambda_{l}^{m},\beta_{l}^{m}\}_{l=1}
^{L}$ using a gradient-based method applied to the demonstration examples. It is worth recapitulating that I2CL does not require any additional data beyond the provided demonstration examples. Concretely, we initialize $\lambda=0.1,\beta=1.0$ to promote a modest initial addition of information, and update these coefficients by minimizing the perplexity of label tokens, represented by the following loss function:

$$ $\mathcal{L}=-\frac{1}{|{\mathbb{D}}|}\sum_{(x,y)\in{\mathbb{D}}}\log P(y\mid x ,{\bm{v}},{\bm{c}}),$ (5) $$

where $P(\cdot)$ denotes the induced probability distribution over the entire vocabulary at the end token position from the last layer. To bolster the robustness and adaptability of the linear coefficients to potential downstream variations, we introduce random Gaussian noises $\bm{\eta}\sim\mathcal{N}(\bm{0},\bm{I})$ into the residual streams during the calibration phase:

$$ $\displaystyle{\bm{o}}_{l}^{t}={\bm{r}}_{l-1}^{t}+(\lambda_{l}^{a}\bar{{\bm{a}} }^{e}_{l}+\beta_{l}^{a}{\bm{a}}_{l}^{t}),$ (6) $\displaystyle{\bm{o}}_{l}^{t}={\bm{o}}_{l}^{t}+\gamma||{\bm{o}}_{l}^{t}||_{2} \times\bm{\eta},$ $\displaystyle{\bm{r}}_{l}^{t}={\bm{o}}_{l}^{t}+(\lambda_{l}^{m}\bar{{\bm{m}}}^ {e}_{l}+\beta_{l}^{m}{\bm{m}}_{l}^{t}),$ $\displaystyle{\bm{r}}_{l}^{t}={\bm{r}}_{l}^{t}+\gamma||{\bm{r}}_{l}^{t}||_{2} \times\bm{\eta},$ $$

where $\gamma$ is a scalar employed to modulate the intensity of the noise, and $||\cdot||_{2}$ denotes the $L^{2}$ norm. The ${\bm{o}}$ represents the intermediate state of a residual stream.

Given that only a few linear coefficients (totaling $4L$) are updated, this process is remarkably efficient, consuming 1-2 minutes on a single A100 GPU (40G). Importantly, calibrated linear coefficients are demonstration agnostic—they require calibration only once per task and exhibit excellent generalization ability to unseen demonstration examples (see Section 4.3).

## 4 Experiments

In empirical section, we begin by detailing the architectures, tasks, and configurations used in our study, followed by a comparative analysis of I2CL against other relevant techniques. We then delve into the formation of context vectors and the characteristics of the calibrated linear coefficients, demonstrating the robustness of I2CL, as well as identifying the function of calibrated coefficients as task-ids. This section concludes with an extensive ablation study to highlight our rationales.

Models We evaluate I2CL using three open-source decoder-only architectures: GPT2-XL [Radford et al., ], GPT-J-6B [Wang and Komatsuzaki, ], and Llama2-7b [Touvron et al., ]. We selected these models based on their suitability for our computational resources and their range in size from relatively small (1.5B) to large (7B). The primary results, reported in subsequent sections, are based on Llama2-7b, with additional results for other architectures detailed in Appendix C.1. We observed consistent trends across all models.

Tasks Initially, we use the four tasks from Wang et al. [], including sentiment analysis: SST-2 [Socher et al., ], emotion classification: EmoC [Chatterjee et al., ], question classification: TREC [Voorhees and Tice, ], and topic classification: AGNews [Zhang et al., ]. We further enrich our experiments with five additional datasets, encompassing 5-way sentiment analysis: SST-5 [Socher et al., ], movie review classification: MR [Pang and Lee, ], 14-way topic classification: DBPedia [Zhang et al., ], subjectivity status categorization: Subj [Pang and Lee, ], and hate speech detection: hate_speech18 [de Gibert et al., ]. We leverage the HuggingFace version of the data [Lhoest et al., ] and uniformly sample 500 data points from the development set for evaluation.

Experimental Setup Our experimental setup remains consistent across all tasks unless otherwise specified. For each task, we randomly sample five demonstration examples per class(^4^44One exception is DBPedia, where we use only one example per class due to the limitation of GPU memory.) following the practice described in Wang et al. [] to avoid majority label bias [Zhao et al., ] and provide a strong few-shot performance. No instruction is used to describe the task. Input sequences are formed using simple manually designed templates (included in Appendix A). For evaluation, we report the macro-average accuracy across nine tasks, computed under five random seeds. For the calibration process, we optimize linear coefficients for $100$ epochs on the same demonstration set using the AdamW [Loshchilov and Hutter, ] optimizer. The learning rate starts at $1\times 10^{-2}$ and anneals to $1\times 10^{-5}$ according to a cosine scheduler. This calibration configuration is applied uniformly across all architectures and tasks without tailoring.

### 4.1 Benchmarking I2CL

Table: Table 1: Comparison between I2CL and other methods on Llama2-7b. Mean accuracy and standard deviation across five random seeds are reported for each task. The best results are highlighted in bold, and the second-best results are shown in blue. In addition to a practical gauge of the inference speed and memory usage (see Fig 1), we include an examination of cached parameters. Here, $M$, $D$, and $L$ denote the number of demonstration tokens, model dimension, and architecture layers, respectively. $P$ indicates the number of extra learnable tokens in the Soft-prompt method, and $1/K$ represents the compression rate in the Label-anchor method.

I2CL Achieves Few-shot Performance at Zero-shot Cost I2CL is designed to enhance zero-shot performance, aspiring to match or exceed those of few-shot outcomes. As shown in Table 1, I2CL significantly outperforms the zero-shot counterpart by 17% in absolute accuracy and is marginally behind (by around 1%) the few-shot learning. An interesting outcome arises from the Subj task, where the instructions (*i.e*., demonstration examples) do not function effectively with ICL, yet are well adhered to under I2CL. Critically, I2CL caches only a fixed number of vectors, independent of the context token length, and retains the speed of zero-shot learning. These results demonstrate I2CL’s potential as a more economical alternative to traditional ICL.

Comparison with Other Methods To further validate the effectiveness of I2CL, we compare it with other comparable techniques. (1) Noise vector: We substitute the context vector with random noise in order to assess its necessity. (2) Soft-prompt: Another approach of using demonstration examples is to treat them as training data and apply the soft-prompt technique. To this end, we compare I2CL with representative Prompt-tuning [Lester et al., ] method to demonstrate the superior data efficiency of I2CL. (3) Label-anchor: We also compare I2CL with the context compression technique presented in Wang et al. [] under the same setup. Following the original methodology, we include formatting tokens as anchors. (4) Task-vector: We compare I2CL to the task vector [Hendel et al., ] method, which also improves zero-shot performance. Adhering to their setup, we use a hold-out validation set to identify the optimal replacement layer for each task. We refer to Appendix B for reproduction details. As displayed in Table 1, replacing the context vector with random noise significantly degrades performance, yielding subpar results compared to zero-shot. The soft-prompt technique is beneficial for only a few tasks under data scarcity, and it can also impair the performance. The label-anchor method exhibits a decent upgrade over the zero-shot baseline, achieving results most close to I2CL. However, its inference cost remains dependent on the length of demonstration tokens, with reductions proportional to their compression rate. Alike I2CL, the task-vector method also enjoys zero-shot inference expense; Nevertheless, its performance is sensitive to the downstream task and is slightly worse on average than the label-anchor method. It also requires an additional hyperparameter selection step, *i.e*., choosing the target replacement layer using a hold-out validation set. I2CL achieves the best performance on all tasks and surpasses its rivals by a considerable margin.

Figure: Figure 3: Left: Evaluation of I2CL and few-shot learning under deficient demonstrations. The symbol $*$ denotes the results under deficient demonstration examples. “Unseen demo” refers to the evaluation of calibrated coefficients on unseen demonstrations. Middle: Analysis of the influencing factors of context vectors. “Random-labe” indicates random input-label mappings. “Random-order” refers to the random permutation of words. “W/o format” signifies excluding the template tokens in the creation of context vectors. Right: t-SNE plot of context vectors. Each circle denotes a context vector generated using a group of randomly sampled demonstration examples.

### 4.2 On the Formation of the Context Vector

Context vector plays a fundamental role in the design of I2CL. Here, we conduct an in-depth analysis to investigate its properties and the factors affecting its functionality.

Deficient Demonstrations $\bm{\neq}$ Deficient I2CL It is well-known that ICL is sensitive to the choice of demonstration examples [Dong et al., ], even the order [Zhao et al., , Lu et al., ]. In this context, we investigate whether deficient demonstration examples necessarily lead to degraded I2CL performance. We sample $20$ different groups of demonstration examples and keep the group with the poorest ICL performance on a hold-out validation set. Using this poorest group, we then perform both ICL and I2CL on an evaluation set. Referencing Figure 3 (left), the deficient demonstration group leads to a severely downgraded ICL performance ($-7\%$), while I2CL performance is barely affected ($-0.5\%$). This result suggests that less attention can be paid to the selection of demonstration examples when using I2CL. We hypothesize that this resiliency is due to the emergence of more abstract and generic concepts within the context vector, making them robust against token space variations. To corroborate this hypothesis, we visualize the context vectors using the t-SNE technique [van der Maaten and Hinton, ] in Figure 3 (right). Context vectors under different demonstration groups are close to each other and different tasks hold distinct context vectors.

Influencing Factors of the Context Vector Generation We have shown that context vectors are robust against the selection of demonstration examples. Here, we explore various factors that may impact the context vector’s functionality. Inspired by counter-intuitive findings reported in [Zhang et al., , Min et al., ], we experiment with two variations of demonstration examples. Random-label: pairing each input sentence with a random label from the task, rather than the ground-truth label. Random-token: randomly permuting all words within a demonstration example. Another ineligible factor involves the inclusion of formatting tokens. W/o-format: removing formatting words from a demonstration example, retaining only the input sentence and its corresponding label, *e.g*., “Review: This is a great movie. Label: positive. As revealed in Figure 3 (middle), input-label mapping relations have minimal impact on context vector formation, mirroring the observations made in ICL. However, these mapping relations are crucial for calibration purposes; using random input-label mapping during calibration undermines the functionality of I2CL. Unlike the phenomenon observed in [Zhang et al., ], word sequence holds essential statistics under a casual architecture. Randomly permuting input sequences yields degenerated context vectors and a clearly downgraded I2CL performance. Lastly, formatting tokens contribute substantially—removing them leads to a noticeable performance drop.

### 4.3 Analysis of Calibrated Linear Coefficients

With a grasp on the formation of context vectors, we now delve into the properties of calibrated linear coefficients to enhance our understanding of the internal mechanisms of I2CL.

Linear Coefficients are Generalizable Given the demonstration-dependent context vectorization and calibration process, it is natural to consider I2CL as a test-time optimization framework. However, we show that the coefficients are generalizable and require calibration once per task. In this context, we evaluate a set of calibrated coefficients on five new context vectors generated using five unseen groups of demonstrations. As exhibited in Figure 3 (left), the calibrated linear coefficients generalize well to unseen demonstrations. We attribute this generalization capability to two factors: (1) the inherent robustness of the context vector against token space variations, as demonstrated in Section 4.2, and (2) the sufficiency of calibrated linear coefficients, independent of context vectors and query activation, to uniquely represent a task. We substantiate the second premise in the following subsection.

Figure: Figure 4: Left: t-SNE visualization of calibrated linear coefficients. Each circle denotes a runtime with a random seed. Middle: This image displays the transfer results among various tasks. Each row represents a source task and each column denotes a target task. Red and blue colors signify positive and negative transfer outcomes, respectively. Right: This plot shows the calibrated linear coefficients for SST-2. $\lambda^{a},\beta^{a},\lambda^{m},\beta^{m}$ are the layer-wise coefficients described in Equation 4.

Calibrated Coefficients Embed Task Semantics Here, we investigate whether calibrated coefficients alone are adequate to serve as "task id". In pursuit of this goal, we concatenate calibrated coefficients across layers to form a 1D vector, which we then visualize using t-SNE. As illustrated in Figure 4 (left), the calibrated linear coefficients are tightly clustered for instances associated with the same task and separate otherwise, providing complementary evidence for their good generalization capability. One exception comes from the proximity between MR and SST-2. This phenomenon is not unexpected, as both tasks originate from the same underlying distribution (*i.e*., rotten tomatoes movie reviews), suggesting that similarities among calibrated coefficients may indicate potential transferability among tasks. To explore this further, we transfer the context vectors and calibrated linear coefficients from a source task to various target tasks. We then measure the differences between the transferred results and their respective zero-shot outcomes to identify both positive and negative transfers. Figure 4 (middle) shows that performance on MR can be effectively enhanced by transferring context vectors and calibrated coefficients from SST-2, and vice versa. Similarly, both SST-2 and MR benefit from transfers from SST-5, likely due to their shared focus on sentiment analysis. An intriguing aspect of our findings is the asymmetric nature of transferability among different tasks; a successful transfer in one direction does not necessarily guarantee success in the opposite direction (e.g., transfer between HateSpeech18 and SST-2).

Enhance New Task with Existing Anchors I2CL posits two pivotal features distinct from typical ICL: (1) An interface that facilitates vector arithmetic; (2) A set of linear coefficients that act as “task-ids”, laying a foundation for effective transfer learning [Zhuang et al., ]. Let ${\bm{c}}_{1},\ldots,{\bm{c}}_{N}$ represent calibrated coefficients for existing tasks, and ${\bm{c}}_{\text{new}}$ for the new task. Associated with these coefficients, respectively, are context vectors ${\bm{v}}_{1},\ldots,{\bm{v}}_{N}$, and ${\bm{v}}_{\text{new}}$.

Table: Table 2: Transfer learning result. Only tasks having more than one similar task (according to $h$) in our task curation are exhibited.

We compute the cosine similarity between ${\bm{c}}_{\text{new}}$ and each ${\bm{c}}_{i}$ for $i=1,\ldots,N$ and retain indices $I=\{i\mid\text{cos}({\bm{c}}_{\text{new}},{\bm{c}}_{i})>h\}$ according to a pre-defined threshold $h$. The cosine similarities for the indices in $I$ are then converted into a probability distribution using the softmax function:

$$ $P(i)=\frac{\exp(\text{cos}({\bm{c}}_{\text{new}},{\bm{c}}_{i})/\tau)}{\sum_{j \in I}\exp(\text{cos}({\bm{c}}_{\text{new}},{\bm{c}}_{j})/\tau)},\quad\forall i \in I,$ (7) $$

where $\tau$ is the temperature. Finally, we reinitialize ${\bm{v}}_{\text{new}}$ and ${\bm{c}}_{\text{new}}$ using the weighted average of retained context vectors and coefficients: ${\bm{v}}_{\text{avg}}=\sum_{i\in I}P(i){\bm{v}}_{i},{\bm{c}}_{\text{avg}}=\sum
_{i\in I}P(i){\bm{c}}_{i}$, and perform another around of calibration. We refer to Appendix B for detailed algorithms and implementation. Empirical results in Table 2 demonstrate a clear benefit of the proposed transfer learning method.

Injection Dynamics Thus far, we have demonstrated that a few static scalars, conditioned on appropriate context vectors, can successfully execute a wide range of NLP tasks. Herein, we delve into how context vectors are injected. Using the SST-2 as an example, we examine the coefficient values across different layers (additional plots in Appendix D). One reasonable speculation postulates a gradual addition of context vectors to the residual streams. Nevertheless, observations from Figure 4 (right) reveal a more nuanced control over the information injection process. Instead of monotonically adding ($+$) more information to the residual streams, I2CL also allows the deletion ($-$) of information at certain layers, with coefficient values fluctuating across different layers.

Table: Table 3: Target modules.

### 4.4 Ablation Study

In this section, we conduct a comprehensive ablation study on the module, layer, and token position of injection, as well as the noise scale. We also explore various vectorization and injection formulas to highlight the rationale behind our designs.

Target Module I2CL extracts and injects activations at both the MHA and MLP modules. To identify the contribution of each module, we test using either MHA or MLP independently and also consider leveraging the hidden state at each layer. As shown in Table 8, extracting and injecting context vectors at either MHA or MLP proves beneficial, with MLP showing a clear advantage. We hypothesize this is due to the additional engagement of information stored in the MLP weights. However, targeting the hidden state does not lead to improvement, likely due to the accumulation effect that complicates harnessing the scales of hidden states.

Target Layer I2CL encompasses all layers in a large language model (LLM), eliminating the need for a layer selection process, which is often a designated hyperparameter. This model-agnostic approach not only simplifies the setup but also enhances performances, as evidenced in Table 8. We divide the model into three sub-parts—early, middle, and late—each containing one-third of the total layers. We then apply I2CL only within the target layer range. The middle and late layers prove more effective than the early layers, and injecting across all layers provides a clear performance boost, highlighting the importance of fusing information at all levels of abstraction.

Injection Position By default, I2CL injects context vectors into all residual streams during inference. To justify this choice, we test injections only at random, first, and last residual streams. As shown in Table 8, and aligning with common intuition, injecting at the end residual stream yields the largest improvement compared to other positions, although it still shows a significant gap compared to injecting at all residual streams.

Noise Scale Here, we evaluate the impact of noise strength during the calibration phase. As demonstrated in Table 8, an appropriate noise scale leads to a clear performance gain. Conversely, an improper noise scale will disrupt information propagation during inference, resulting in deteriorated outcomes. Through empirical testing, we identify $\tau=0.001$ as a suitable scale and have applied it across all tasks.

Vectorization Method For context vectorization, we treat each demonstration example separately and post-merge them using an element-wise algorithmic average. A straightforward alternative is to concatenate all demonstration examples as in typical ICL, and extract the context vector from the end residual stream. Furthermore, we evaluate another post-fusion strategy that applies PCA to extract the first principal component vector as the context vector. According to Table 8, the concatenation method significantly underperforms the post-fusion counterparts. The PCA variant achieves a negligible improvement; therefore, we employ the average operator by default for its simplicity.

Injection Formula I2CL utilizes a linear combination to blend context vectors with query activations. Let ${\bm{v}}$ denote the context vector and ${\bm{a}}$ indicates activation; we use $\lambda{\bm{c}}+\beta{\bm{a}}$. One simplification is to view the injection process as solely adding the context vector to the activation: $\lambda{\bm{v}}+{\bm{a}}$ with $\lambda>0$. Another common formula involves constraining the sum of linear coefficients to one and allowing a separate scale factor: $(\lambda{\bm{v}}+(1-\lambda){\bm{a}})\times\beta,\beta>0$. According to Table 8, a linear combination with no constraints achieves the best overall performance. Therefore, we conjecture that it is critical to allow not only information addition but also deletion, *i.e*., permitting a negative sign for the linear coefficient, and to scale each vector independently. Observations in Figure 4 (right) support our conjecture.

## 5 Discussion

A Hypothetical Two-Stage Interpretation of ICL  The effectiveness of I2CL suggests a conceptual two-stage internal mechanism within ICL. In the first stage, the information from each demonstration example is encapsulated within its respective end residual stream. In the second stage, this encapsulated information is accessed and integrated into the residual streams of the query. Commonly, both stages are seamlessly executed by non-linear multi-head attention modules within transformer layers. I2CL reveals that the end residual stream of a sequence functions as an effective anchor to condense context information, and by leveraging activation vectors from it, we can effectively approximate an attention-based information fusion scheme using only linear operations. We hypothesize that this phenomenon arises due to the emergence of certain linear representations during the pre-training stage. These linear properties enable a vector interface that facilitates the formation and transportation of functions through simple linear operations. While we do not claim the above interpretation as a rigorous internal mechanism of ICL, it aligns with our empirical observations and we hope it can inspire future work aimed at a deeper understanding of the ICL.

Potential Design Although the end residual stream contains a rich repository of information for the given token sequence, other token positions may also possess valuable attributes, as noted in recent studies [Hendel et al., , Todd et al., , Liu et al., ]. Recent research also highlights the importance of formatting tokens during information propagation [Wang et al., , Bai et al., ]. We believe our approach could benefit from a more sophisticated design of demonstration vectorization. Additionally, while we currently use a single scalar to gauge the strength of aggregated multi-head attention, allowing finer granularity—such as separate strength scalars for different attention heads—might enhance our system’s performance, albeit at the cost of increased parameters.

Limitations and Future Work Our research is subject to several limitations. Firstly, we confine the scope of our initial exploration to standard classification tasks, leaving more sophisticated tasks for future research. It would be intriguing to extend I2CL to the realm of open-ended generation tasks and those involving multi-hop reasoning processes. Secondly, I2CL necessitates access to and caching of intermediate activations from language models, which may not be feasible with state-of-the-art commercial models (e.g., GPT-4, Gemini, Claude3). Lastly, we have evaluated I2CL on relatively modest-sized models, and scaling our evaluations to models with hundreds of billions of parameters could yield additional insights.

## 6 Conclusion

In this study, we introduce Implicit In-context Learning (I2CL), a simple and novel framework that integrates a minimal set of demonstration examples within the activation space of LLMs. Diverge from ICL, I2CL eliminates the need for caching the latents of demonstration tokens and replaces the non-linear information fusion process with linear operations. Therefore, I2CL reduces both computational and memory expenses during inference to that of zero-shot level. Moreover, I2CL is validated to be robust against token space variations, and it facilitates a novel representation of “task-ids”, enhancing task similarity detection and enabling effective transfer learning. Empirical evidence on nine real-world tasks across three different models demonstrates I2CL as a more efficient and robust alternative to ICL. Through a set of in-depth analyses, we shed light on the internal mechanics of I2CL and provide further insights into the working scheme of ICL.

## Acknowledgments

We extend our sincere gratitude to Prof. Diyi Yang for her constructive suggestions on the empirical design of this study. Her expertise and insights were invaluable to this research.

## Appendix A Templates

**Table 9: Templates and label spaces for tasks used in our experiments. {Sentence} and {Label} are placeholders for the input sentence and label of a demonstration example, respectively. We show only the template for a single demonstration example to save space, and we connect multiple demonstration examples by a new line character: ‘\n’.**
| Dataset | Template | Label Space |
| --- | --- | --- |
| SST-2 | Review: {Sentence} | negative / positive |
|  | Sentiment: {Label} |  |
| SST-5 | Sentence: {Sentence} | terrible / negative / neutral / positive / great |
|  | Sentiment: {Label} |  |
| MR | Review: {Sentence} | negative / positive |
|  | Sentiment: {Label} |  |
| Subj | Sentence: {Sentence} | objective / subjective |
|  | Label: {Label} |  |
| DBPedia | Input: {Sentence}<br>Label: {Label} | company / school / artist / athlete / politics / transportation / building / nature / village / animal / plant / album / film / book |
| AGNews | News: {Sentence} | World / Sports / Business / Technology |
|  | Type: {Label} |  |
| TREC | Question: {Sentence}<br>Answer Type: {Label} | Abbreviation / Entity / Person / Location / Number |
| HateSpeech18 | Text: {Sentence}<br>Label: {Label} | neutral / hate |
| EmoC | Dialogue: {Sentence}<br>Emotion: {Label} | others / happy / sad / angry |

Extra Details For the task HateSpeech18, we preprocess the data to retain only the first two classes—{0: neutral} and {1: hate}. We exclude the other two classes due to their extremely limited number of samples.

## Appendix B Reproduction Details

The code is publicly available at: [https://github.com/LzVv123456/I2CL](https://github.com/LzVv123456/I2CL)

### B.1 Implementation of Comparable Methods.

Noise Vector We replace context vectors with random noise vectors while keeping all other settings identical to I2CL.

Soft Prompt For the implementation of soft-prompt method [Lester et al., ], we allow one extra learnable token ($P=1$) per layer, and apply soft prompt across all layers. We also attempt to use more learnable tokens, resulting in poorer performance due to overfitting. For optimization, we conduct a simple grid search on SST-2 to determine an optimal learning rate of $0.1$, which we then apply across all tasks. All other configurations remain as specified in the experimental section.

Label Anchor We utilize the official code from the Label-anchor paper Wang et al. [], aligning the architecture, datasets, and template setups for a fair comparison. Template tokens and the newline separator ‘\n’ serve as anchors, following their established practice. Detailed information can be found at [https://github.com/lancopku/label-words-are-anchors](https://github.com/lancopku/label-words-are-anchors).

Task Vector We replicate the task vector method originally studied by Hendel et al. [], which was evaluated using a set of toy datasets, within our experimental framework. To generate the task vector, we append a random extra query after the concatenated demonstration examples (five per class) to simulate the dummy query they utilized. We then extract the hidden state from the token position responsible for the next token prediction to serve as the task vector. A hold-out dataset with $32$ extra examples is used to select the best layer for extraction and replacement for each task, following the original practice.

### B.2 Implementation of Transfer Learning

Algorithm 1 details the transfer learning method of I2CL. In implementation, we set $h=0.8$ and $\tau=0.5$.

Figure: Algorithm 1 Transfer Learning of I2CL

## Appendix C Additional Experiments

### C.1 Results of Other Architectures

Here, we show results of I2CL under architecture GPT-J and GPT2-XL in Table 10 and Table 11, respectively.

Table: Table 10: Comparison between I2CL and other methods on GPT-J-6B.

Table: Table 11: Comparison between I2CL and other comparable methods on GPT2-XL. AGnews and DBPedia are not evaluated due to the limitation of GPT2-XL’s context window size.

### C.2 Trend of I2CL Under Varying Shots

In our standard empirical setup, we select five examples per class to create the demonstration group. This approach prompts an important question about how I2CL behaves under different shot configurations. To investigate this, we varied the number of shots per class from $1$ to $10$ and compared the performance of I2CL with that of ICL. As illustrated in Figure 5, I2CL and ICL perform similarly when the number of demonstration examples is limited. However, while the performance of ICL plateaued at approximately five shots per class, our model continues to show the capacity to benefit from an increased number of demonstration examples.

Figure: Figure 5: Data scaling trend of ICL and I2CL on Llama2-7B.

## Appendix D Additional Visualization

Additional Plots of Calibrated Linear Coefficients Here, we present the calibrated coefficients for all tasks we used, illustrating variations and patterns across different configurations.

Figure: Figure 6: Calibrated coefficients for SST-2.

## Peer Reviews

confidence: 3
contribution: 3
initial_rating: 6
presentation: 3
questions: 1. The experiments are mainly based on Llama-2. Have you explored the potential of I2CL in larger language models? It would be helpful to understand whether the efficiency gains scale up with model size.
2. Just a question (not require you perform experiments in the revision period) and may help clarify the potential of I2CL, which is how to convert your method to vision area. Current visual in-context learning [Zhang et al.] requires extra training process to select best in-context samples. Do you think if I2Cl has the potential to transfer to visual modality? 
3. It looks like context vectors are well seperated as shown in figure 4. How might the task-id approach handle more nuanced variations within a single task type? i.e., does such context vector carry some information regarding classification labels?


Zhang, Y., Zhou, K. and Liu, Z., 2023. What makes good examples for visual in-context learning?. Advances in Neural Information Processing Systems, 36, pp.17773-17794.
soundness: 3
strengths: 1. I2CL presents a unique approach to reducing ICL’s computational load, which is an important advancement, especially for applications with resource constraints.

2. The concept of "task-ids" is a novel contribution that could facilitate transfer learning.
summary: The paper I2CL proposes a method to achieve few-shot performance at zero-shot inference costs by generating a condensed "context vector" from demonstration examples, which is then injected directly into the model’s residual streams. Many experiments demonstrate the method’s efficacy.
The paper is well-structured and with sufficient experiments.
Managing similar cost with few-shot but keeping comparative performance sounds novel for me.
weaknesses: 1. I2CL’s dependence on accessing intermediate activations may limit its use in closed or black-box models where such access is restricted. Addressing this limitation or proposing adaptations for such environments would broaden its utility.

2. Expand the evaluation to include more diverse tasks, such as open-ended generation or multi-step reasoning. Demonstrating I2CL’s efficacy in these tasks would make the paper’s findings more universally applicable.

---

confidence: 4
contribution: 3
initial_rating: 8
presentation: 3
questions: - Could you please include a comparison with PEFT-based few-shot fine-tuning strategies to highlight how your approach performs relative to these methods?
soundness: 3
strengths: - Proposes a method for performing in-context learning at the cost of zero-shot learning and their method (I2CL) performs comparable to in-context learning.
- The idea of performing activation merging is an interesting direction to make model learn new skills at a very negligible cost.
- I2CL scales very well with adding more samples in-contrast to in-context learning.
- The paper provides comparison of their method with diverse methods such as task vector, label anchors etc to show improvements and at the same time provide ablation studies showing the robustness of learned coefficients and the robustness of I2CL to ordering and choice of samples.
- Paper is well written and easy to understand.
summary: This paper introduces a mechanism (I2CL) to mitigate major criticism of in-context learning which is the inference cost associated with it as we need to pre-append all the demonstration examples always while performing inference. The proposed method involves two step first involving generating a context vector based on each demonstration by feeding it through the LLM and caching the activation across each layer and second where we linearly combine these activations with query activations during inference using pre-learned weights (or coefficients). These coefficients are learned only using the few-shot examples available to us for in-context learning. They show that this method can achieve comparable performance to in-context learning and at the cost of zero-shot learning. The paper also provides various ablations on how generalizable learned coefficients are to un-seen samples and the robustness of I2CL in comparison to in-context learning in different scenarios such as ordering of samples, choice of samples etc.
weaknesses: - Learning of weights to infuse demonstration samples might require some compute and hence comparing this method to few-shot parameter efficient fine-tuning method would also be helpful. As there are two computational cost associated here one where you extract out the context vector and other where you train the coefficients to find optimal coefficients to combine samples.
- Caching large context vector (for larger models) might not be feasible which might make it harder to apply this method to very large models.

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 4
questions: Please refer to the weakness.
soundness: 3
strengths: 1. This paper is clear and eazy to follow. The plot and table are eazy to understand
2. The proposed method is simple, and it achieves improvement on the inference speed and memory cost, compared to vallina ICL
3. The proposed algorithm is less sensitive to the order of demonstration examples.
4. The experiment part is comprehensive. The method is compared to various baselines. The authors also studied careful ablation studies to understand  the method.
5. The observation that the calibrated  linear coefficients can function as effective task-ids is interesing
summary: This paper introduces presents a method to reduce the computational and memory overheads of in-context learning. The proposed method, called implicit in-context learning (I2CL), extracts a context vector from demonstration examples and inject the context vector for the inference of query example. Experiments on 8 text-classification datasets show that I2CL successfully reduces the computation and memory cost of ICL, while performs only slightly worse than vallina ICL. The authors also show that I2CL is less sensitive to the order of demonstration examples.
weaknesses: 1. The major claim of this paper is that I2CL achieves ICL performance at zero-shot cost in terms of both memory usage and inference speed, which raises my concern on the fairness of the comparison. Does the optimization of noisy self-calibration (Sec 2.4) included in the comparision? The calibration process requires inference of LLMs on each demonstration examples multiple times and optimize the linear coefficient with Adam. In comparison, ICL only requires forward pass of LLM on one-time. In table 1, only #cached param are considered as memory cost, and the cost of noisy calibration is missing. Also, is noisy self-calibration counted as inference time (the author metioned the optimization takes 1-2 minutes on a single A100?
2. In terms of the performance, I2CL is 1% worse than ICL on average. On simple task such as SST2 and MR, the performance of I2CL is not satisfying. Is there any specific reason that cause the degraded performance? 
3. Only one very simple prompt is used in this paper. Have the author tried other prompts? From my own experience, SUBJ would be a very simple dataset for Llama-2 few-shot setting given some basic prompts.
4. On the scaling plot of figure 3: what dataset is the figure using? And as shown [1], the performance of ICL is expected to increasing as the number of demonstration increases. Could the author explain why the performance of ICL starts to decrease after 5-shots?

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: 1. The proposed method performs worse than the prompt-compression-based method on some tasks but outperforms it on others. I'm curious about which task characteristics contribute to these differences in performance.
soundness: 4
strengths: 1. The proposed method is simple, interesting and effective.
2. Experimental results demonstrate the method's superiority.
3.  The paper is well-structured and easy to comprehend.
summary: This paper proposes an innovative paradigm that reduces the inference cost of ICL to that of zero-shot learning with minimal information loss. The results reveal that the method is quite effective with certain extra benefits including enhancing task similarity detection and fostering effective transfer learning.
weaknesses: 1.  The paper relies solely on experimental evidence to validate the superiority of the proposed method, lacking a clear explanation of why it outperforms prior approaches. Additionally, there is a lack of detailed analysis, making it feel more like a technical report.
2.  More ablation studies are needed to provide deeper insights.

Meta-review: This work proposes a new implicit in-context learning that extracts a context vector from demonstration examples and injects the context vector into the model’s residual stream to reduce the inference cost of ICL to that of zero-shot learning  All reviewers consistently recommended accepting this work. AC agrees that this work is interesting and deserves to be published on ICLR 2O25. The reviewers did raise some valuable concerns that should be addressed in the final camera-ready version of the paper. The authors are encouraged to make the necessary changes in the final version.

Decision: Accept (Poster)