W HAT LEARNING ALGORITHM IS IN - CONTEXT LEARNING ? I NVESTIGATIONS WITH LINEAR MODELS
Anonymous authors
Paper under double-blind review
A BSTRACT
Neural sequence models, especially transformers, exhibit a remarkable capacity for in-context learning .
They can construct new predictors from sequences of labeled examples ( x, f ( x )) presented in the input without further parameter updates.
We investigate the hypothesis that transformer-based in-context learners implement standard learning algorithms implicitly , by encoding smaller models in their activations, and updating these implicit models as new examples appear in the context.
Using linear regression as a prototypical problem, we offer three sources of evidence for this hypothesis.
First, we prove by construction that transformers can implement learning algorithms for linear models based on gradient descent and closed-form ridge regression.
Second, we show that trained in-context learners closely match the predictors computed by gradient descent, ridge regression, and exact least-squares regression, transitioning between different predictors as transformer depth and dataset noise vary, and converging to Bayesian estimators for large widths and depths.
Third, we present preliminary evidence that in-context learners share algorithmic features with these predictors: learners’ late layers nonlinearly encode weight vectors and moment matrices.
These results suggest that in-context learning is understandable in algorithmic terms, and that (at least in the linear case) learners may rediscoverc standard estimation algorithms.
Code and reference implementations will be released at [anon].
I NTRODUCTION
One of the most surprising behaviors observed in large neural sequence models is in-context learning (ICL; Brown et al., 2020).
When trained appropriately, models can map from sequences of ( x, f ( x )) pairs to accurate predictions
f ( x (cid:48) ) on novel inputs x (cid:48) .
This behavior occurs both in models trained on collections of few-shot learning problems (Chen et al., 2021; Min et al., 2021) and surprisingly in large language models trained on open-domain text (Brown et al., 2020; Zhang et al., 2022; Chowdhery et al., 2022).
ICL requires a learner to implicitly construct a map from in-context examples to predictors without any updates to the learner’s parameters themselves.
How can a neural network with ﬁxed parameters to learn a new function from a new dataset on the ﬂy?
This paper investigates the hypothesis that some instances of ICL can be understood as implicit implementation of known learning algorithms: in-context learners encode an implicit, contextdependent model in their hidden activations, and train this model on in-context examples in the course of computing these internal activations.
As in recent investigations of empirical properties of ICL (Garg et al., 2022; Xie et al., 2022), we study the behavior of transformer-based predictors (Vaswani et al., 2017) on a restricted class of learning problems, here linear regression.
Unlike in past work, our goal is not simply to understand what functions ICL can learn, but how it learns these functions: the speciﬁc inductive biases and algorithmic properties of transformer-based ICL.
In Section 3, we investigate theoretically what learning algorithms transformer decoders can implement.
We prove by construction that they require only a modest number of layers and hidden units to train linear models: with O ( d ) hidden size and constant depth, a transformer can implement a single step of gradient descent, and O ( d 2 ) hidden size and constant depth, a transformer can update an ridge regression solution to include a single new observation. Intuitively, n steps of these algorithms can be implemented with n times more layers.
In Section 4, we investigate empirical properties of trained in-context learners.
We begin by constructing linear regression problems in which learner behavior is under-determined by training data (so different valid learning rules will give different predictions on held-out data).
We that model predictions are closely matched by existing predictors (including those studied in Section 3), and that they transition between different predictors as model depth and training set noise vary, behaving like Bayesian predictors at large hidden sizes and depths.
Finally, in Section 5, we present preliminary experiments showing how model predictions are computed algorithmically.
We show that important intermediate quantities computed by learning algorithms for linear models, including parameter vectors and moment matrices, can be decoded from in-context learners’ hidden activations.
A complete characterization of which learning algorithms are (or could be) implemented by deep networks has the potential to improve both our theoretical understanding of their capabilities and limitations, and our empirical understanding of how best to train them.
This paper offers ﬁrst steps toward such a characterization: some in-context learning appears to involve familiar algorithms, discovered and implemented by transformers from sequence modeling tasks alone .
P RELIMINARIES
Training a machine learning model involves many decisions, including the choice of model architecture, loss function and learning rule.
Since the earliest days of the ﬁeld, research has sought to understand whether these modeling decisions can be automated using the tools of machine learning itself.
Such “meta-learning” approaches typically treat learning as a bi-level optimization problem (Schmidhuber et al., 1996; Andrychowicz et al., 2016;
Finn et al., 2017): they deﬁne “inner” and “outer” models and learning procedures, then train an outer model to set parameters for an inner procedure (e.g. initializer or step size) to maximize inner model performance across tasks.
Recently, a more ﬂexible family of approaches has gained popularity.
In in-context learning (ICL), meta-learning is reduced to ordinary supervised learning: a large sequence model (typically implemented as a transformer network) is trained to map from sequences [ x 1 , f ( x 1 ) , x 2 , f ( x 2 ) , ..., x n ] to predictions f ( x n ) (Brown et al., 2020; Olsson et al., 2022; Laskin et al., 2022).
ICL does not specify an explicit inner learning procedure; instead, this procedure exists only implicitly through the parameters of the sequence model.
ICL has shown impressive results on synthetic tasks and naturalistic language, vision problems (Garg et al., 2022; Min et al., 2021;
Zhou et al., 2022).
While past work has characterized what kinds of functions ICL can learn, how it learns these functions has remained unclear.
What learning algorithms (if any) are implementable by deep network models?
Which algorithms are actually discovered in the course of training?
This paper takes ﬁrst steps toward answering these questions, focusing on a widely used model architecture (the transformer) and an extremely well-understood class of learning problems (linear regression).
2. T HE T RANSFORMER A RCHITECTURE
Transformers (Vaswani et al., 2017) are neural network models that map a sequence of input vectors x
= [ x 1 , . .
, x n ] to a sequence of output vectors y =
[ y 1 , . . .
, y n ] .
Each layer in a transformer maps a matrix H ( l ) (interpreted as a sequence of vectors) to a sequence H ( l +1) .
To do so, a transformer layer processes each column h ( l ) i of H ( l ) in parallel.
Here, we are interested in autoregressive (or “decoder-only”) transformer models in which each layer ﬁrst computes a self-attention :
[Equation]
where each b is the response of an “attention head” deﬁned by:
[Equation]
then applies a feed-forward transformation:
[Equation]
Here σ denotes a nonlinearity, e.g. a Gaussian error linear unit (GeLU; Hendrycks & Gimpel, 2016):
[Equation]
and λ denotes layer normalization (Ba et al., 2016):
[Equation]
where the expectation and variance are computed across the entries of x .
To map from x to y , a transformer applies a sequence of such layers, each with its own parameters.
We use θ to denote a model’s full set of parameters (the complete collection of W matrices across layers).
The three main factors governing the computational capacity of a transformer are its depth (the number of layers), its hidden size (the dimension of the vectors h ), and the number of heads (denoted m above).
2. T RAINING FOR I N -C ONTEXT L EARNING
We study transformer models directly trained on an ICL objective (Some past work has found that
ICL also “emerges” in models trained on general text datasets; Brown et al., 2020.).
To train a transformer T with parameters θ to perform ICL, we ﬁrst deﬁne a class of functions F , a distribution p ( f ) supported on F , a distribution p ( x ) over the domain of functions in F , and a loss function L .
We then choose θ to optimize:
[Equation]
We refer to the resulting T θ as an in-context learner .
2. L INEAR R EGRESSION
Our experiments focus on linear regression problems.
In these problems, F is the space of linear functions f ( x ) =
w (cid:62) x where w , x ∈ R d , and the loss function is the squared error L ( y, y (cid:48) )
= ( y − y (cid:48) ) 2 .
Linear regression is a model problem in machine learning and statistical estimation, with diverse algorithmic solutions.
It thus offers an ideal test-bed for understanding ICL.
Given a dataset with inputs X =
[ x 1 , . . .
, x n ] and y =
[ y 1 , . . .
, y n ] , the (regularized) linear regression objective:
[Equation]
minimized by
[Equation]
With λ = 0 , this objective is known as ordinary least squares regression (OLS); with λ > 0 , it is known as ridge regression (Hoerl & Kennard, 1970).
(As discussed further in Section 4, ridge regression can also be assigned a Bayesian interpretation.)
To present a linear regression problem to a transformer, we encode both x and f ( x ) as d + 1 -dimensional vectors:
˜ x i = [0 , x i ] , ˜ y
i =
[ y i , 0 d ] , where 0 d denotes the d -dimensional zero vector.
W HAT LEARNING ALGORITHMS CAN A TRANSFORMER IMPLEMENT ?
For a transformer-based model to solve Eq.
(9) by implementing an explicit learning algorithm, that learning algorithm must be implementable via Eq.
(1) and Eq.
(4) with some ﬁxed choice of transformer parameters θ .
In this section, we prove constructively that such parameterizations exist, giving concrete implementations of two standard learning algorithms.
These proofs yield upper bounds on how many layers and hidden units sufﬁce to implement (though not necessarily learn) each algorithm. Proofs are given in Appendices A and B.
3. P RELIMINARIES
It will be useful to ﬁrst establish a few computational primitives with simple transformer implementations.
Consider the following four functions from R H × T → R H × T : mov ( H ; s, t, i, j, i (cid:48) , j (cid:48) ) : selects the entries of the s th column of H between rows i and j , and copies them into the t th column ( t ≥ s ) of H between rows i (cid:48) and j (cid:48) , yielding the matrix: (cid:34) |
H : i − 1 ,t |
H : , : t −
H i (cid:48) : j (cid:48) ,s
H : , : t +1 |
H j +1 ,t | (cid:35) .
mul ( H ; a, b, c, ( i, j ) , ( i (cid:48) , j (cid:48) ) , ( i (cid:48)(cid:48) , j (cid:48)(cid:48) )) : in each column h of H , interprets the entries between i and j as an a × b matrix A 1 , and the entries between i (cid:48) and j (cid:48) as a b × c matrix A 2 , multiplies these matrices together, and stores the result between rows i (cid:48)(cid:48) and j (cid:48)(cid:48) , yielding a matrix in which each column has the form [ h : i (cid:48)(cid:48) − 1 , A 1 A 2 , h j (cid:48)(cid:48) +1 ] (cid:62) .
div ( H ; ( i, j ) , i (cid:48) , ( i (cid:48)(cid:48) , j (cid:48)(cid:48) )) : in each column h of H , divides the entries between i and j by the absolute value of the entry at i (cid:48) , and stores the result between rows i (cid:48)(cid:48) and j (cid:48)(cid:48) , yielding a matrix in which every column has the form [ h : i (cid:48)(cid:48) − 1 , h i : j / | h i (cid:48)
| , h j (cid:48)(cid:48) +1: ] (cid:62) .
aff ( H ; ( i, j ) , ( i (cid:48) , j (cid:48) ) , ( i (cid:48)(cid:48) , j (cid:48)(cid:48) ) , W 1 , W 2 , b ) : in each column h of H , applies an afﬁne transformation to the entries between i and j and i (cid:48) and j (cid:48) , then stores the result between rows i (cid:48)(cid:48) and j (cid:48)(cid:48) , yielding a matrix in which every column has the form [ h : i (cid:48)(cid:48) − 1 , W 1 h i : j + W 2 h i (cid:48) : j (cid:48)
+ b, h j (cid:48)(cid:48)
+1: ] (cid:62) .
Lemma 1.
Each of mov , mul , div and aff can be implemented by a single transformer decoder layer: in Eq.
(1) and Eq.
(4) , there exist matrices W Q , W K , W V , W F , W 1 and W 2 such that, given a matrix H as input, the layer’s output has the form of the corresponding function output above.
With these operations, we can implement building blocks of two important learning algorithms.
3. G RADIENT DESCENT
Rather than directly solving linear regression problems by evaluating Eq.
(10), a standard approach to learning exploits a generic loss minimization framework, and optimizes the ridge-regression objective in Eq.
(9) via gradient descent on parameters w .
This involves repeatedly computing updates:
[Equation]
11) for different examples ( x i , y i ) , and ﬁnally predicting w (cid:48)(cid:62) x n on a new input x n .
A step of this gradient descent procedure can be implemented by a transformer:
Theorem 1.
A transformer can compute Eq.
(11) (i.e. the prediction resulting from single step of gradient descent on an in-context example) with constant number of layers and O ( d ) hidden space, where d = | x | is the problem dimension.
Speciﬁcally, there exist transformer parameters θ such that, given an input matrix of the form:
[Equation]
the transformer’s output matrix H ( D ) contains an entry equal to w (cid:48)(cid:62) x n as in Eq.
3. C LOSED - FORM REGRESSION
Another way to solve the linear regression problem is to directly compute the closed-form solution
Eq.
This is somewhat challenging computationally, as it requires inverting the regularized covariance matrix X (cid:62) X + λI .
However, one can exploit the Sherman–Morrison formula (Sherman & Morrison, 1950) to reduce the inverse to a sequence of rank-one updates performed example-byexample.
For any invertible square A ,
[Equation]
Because the covariance matrix X (cid:62) X in Eq.
(10) can be expressed as a sum of rank-one terms each involving a single training example x i , this can be used to construct an iterative algorithm for computing the closed-form ridge-regression solution.
Theorem 2.
A transformer can predict according to a single Sherman–Morrison update:
[Equation]
with constant layers and O ( d 2 ) hidden space.
More precisely, there exists a set of transformer parameters θ such that, given an input matrix of the form in Eq.
(12) , the transformer’s output matrix H ( D ) contains an entry equal to w (cid:48)(cid:62) x n for w (cid:48) as deﬁned above.
Discussion.
There are various existing universality results for transformers (Yun et al., 2019; Wei et al., 2021), and for neural networks more generally (Hornik et al., 1989).
These generally require very high precision, very deep models, or the use of an external “tape”, none of which appear to be important for in-context learning in the real world.
Results in this section establish sharper upper bounds on the necessary capacity required to implement learning algorithms speciﬁcally, bringing theory into the range where it can explain existing empirical ﬁndings.
We emphasize that Theoremand Theorem 2 each show the implementation of a single step of larger iterative algorithm; these results can be straightforwardly generalized to the multi-step case by “stacking” groups of transformer layers.
As described next, it is these iterative algorithms that capture the behavior of real learners.
W HAT COMPUTATION DOES AN IN - CONTEXT LEARNER PERFORM ?
The previous section showed that the building blocks for two speciﬁc procedures—gradient descent on the least-squares objective and closed-form computation of its minimizer—are implementable by transformer networks.
These constructions show that, in principle, ﬁxed transformer parameterizations are expressive enough to simulate these learning algorithms.
When trained on real datasets, however, in-context learners might implement other learning algorithms (or fail to implement any).
In this section, we investigate the empirical properties of trained in-context learners in terms of their behavior .
In the framework of Marr’s (2010) “levels of analyis”, we aim to explain ICL at the computational level by identifying the kind of solution to regression problems that transformer-based ICL computes.
4. B EHAVIORAL M ETRICS
Determining which learning algorithms best characterize ICL predictions requires ﬁrst quantifying the degree to which two predictors agree.
We use two metrics to do so:
Squared prediction difference. Given any learning algorithm A that maps from a set of input– output pairs D =
[ x 1 , y 1 , . . .
, x n , y n ] to a predictor f ( x ) =
A ( D )( x ) , we deﬁne the squared prediction difference (SPD):
[Equation]
14) where D is sampled as in Eq.
SPD measures agreement at the output level, regardless of the algorithm used to compute this output.
Implicit linear weight difference. When ground-truth predictors all belong to a known, parametric function class (as with the linear functions here), we may also investigate the extent to which different learners agree on the parameters themselves.
Given an algorithm A , we sample a context dataset D as above, and an additional collection of unlabeled test inputs D X (cid:48)
= { x (cid:48) i } .
We then compute A ’s prediction on each x (cid:48)
i , yielding a predictor-speciﬁc dataset D A = { ( x (cid:48) i , ˆ y i ) } =
[Equation]
x i , A ( D )( x
[Equation]
i ) (cid:1)(cid:9) encapsulating the function learned by A .
Next we compute the implied parameters:
[Equation]
[Figure] D ( [Figure] We can then quantify agreement between two predictors A 1 and A 2 by computing the distance between their implied weights in expectation over datasets:
[Equation]
4. E XPERIMENTAL S ETUP
We train a Transformer decoder autoregresively on the objective in Eq.
For all experiments, we perform a hyperparameter search over depth L ∈ { 1 , 2 , 4 , 8 , 12 , 16 } , hidden size
W ∈ { 16 , 32 , 64 , 256 , 512 , 1024 } and heads M ∈ { 1 , 2 , 4 , 8 } .
Other hyper-parameters are noted in Appendix D. For our main experiments, we found that L = 16 , H = 512 , M = 4 minimized loss on a validation set.
We follow the training guidelines in Garg et al.
(2022), and trained models for 500 , 000 iterations, with each in-context dataset consisting of 40 ( x , y ) pairs.
For the main experiments we generate data according to p ( w ) =
N (0 , I ) and p ( x ) = N (0 , I ) .
4. R ESULTS
ICL matches ordinary least squares predictions on noiseless datasets.
We begin by comparing a ( L = 16 , H = 512 , M = 4) transformer against a variety of reference predictors:
• k -nearest neighbors :
In the uniform variant, models predict ˆ y i = 13 (cid:80)
j y j , where j is the top-3 closest data point to x i where j < i .
In the weighted variant, a weighted average ˆ y i ∝ 13 (cid:80) j | x i − x j | − 2 y j is calculated, normalized by the total weights of the y j s. • One-pass stochastic gradient descent : ˆ y i =
w (cid:62) i x i where w i is obtained by stochastic gradient descent on the previous examples with batch-size equals to 1: w i = w i − 1 − α ( x (cid:62) i − 1 w (cid:62)
i − 1 x i − 1 − x (cid:62) i − 1 y i − 1 + 2 λw i − 1 ) . • One-step batch gradient descent : ˆ y i = w (cid:62) i x i where w i is obtained by one of step gradient descent on the batch of previous examples: w i = w 0 − α
( X (cid:62) w (cid:62) X − X (cid:62) Y + 2 λw 0 ) .
• Ridge regression : We compute ˆ y i =
w (cid:48)(cid:62) x i where w (cid:48)(cid:62) =
( X (cid:62) X + λI ) − 1 X (cid:62) Y .
We denote the case of λ = 0 as OLS .
The agreement between the transformer-based ICL and these predictors is shown in Fig.
As can be seen, there are clear differences in ﬁt to predictors: for almost any number of examples, normalized
SPD and ILWD are small between the transformer and OLS predictor (with squared error less than 0.01), while other predictors (especially nearest neighbors) agree considerably less well.
When the number of examples is less than the input dimension d = 8 , the linear regression problem is under-determined, in the sense that multiple linear models can exactly ﬁt the in-context training
[Figure]
Brightness is proportional with dataset.
In these cases, OLS regression selects the minimum-norm weight vector, and (as shown in
Fig. 1), the in-context learner’s predictions are reliably consistent with this minimum-norm predictor.
Why, when presented with an ambiguous dataset [Figure] should ICL behave like this particular predictor?
One possibility is that, because the weights used to generate the training data are sampled from a
Gaussian centered at zero, ICL learns to output the minimum Bayes risk solution when predicting under uncertainty.
Building on these initial ﬁndings, our next set of experiments investigates whether
ICL is behaviorally equivalent to Bayesian inference more generally.
ICL matches the minimum Bayes risk predictor on noisy datasets.
To more closely examine the behavior of ICL algorithms under uncertainty, we add noise to the training data: now we present the in-context dataset as a sequence: [ x 1 , f ( x 1 ) + (cid:15) 1 , . . .
, x n , f ( x n ) + (cid:15) n ] where each (cid:15) i ∼ N (0 , σ 2 ) .
Recall that ground-truth weight vectors are themselves sampled from a Gaussian distribution; together, this choice of prior and noise mean that the learner cannot be certain about the target function with any number of examples.
Standard Bayesian statistics gives that the optimal predictor for minimizing the loss in Eq.
(8) is: ˆ y =
E
[ y | x, D ] 2 .
For linear regression with Gaussian priors and Gaussian noise, the Bayesian estimator in Section 4.3 has a closed-form expression:
[Equation]
Note that this predictor has the same form as the ridge predictor from Section 2.3, with the regularization parameter set to σ 2 τ 2 .
In the presence of noisy labels, does ICL match this Bayesian predictor?
We explore this by varying both the dataset noise σ 2 and the prior variance τ 2 (sampling w ∼ N (0 , τ 2 )) .
For these experiments, the SPD values between the in-context learner and various regularized linear models is shown in Fig.
As predicted, as variance increases, the value of the ridge parameter that best explains ICL behavior also increases.
For all values of σ 2 , τ 2 , the ridge parameter that gives the best ﬁt to the transformer behavior is also the one that minimizes Bayes risk.
These experiments clarify the ﬁnding above, showing that ICL in this setting behaviorally matches minimum-Bayes-risk prediction.
ICL exhibits algorithmic phase transitions as model depth increases.
The two experiments above evaluated extremely high-capacity models in which (given ﬁndings in Section 3) computational constraints are not likely to play a role in the choice of algorithm implemented by ICL.
But what about smaller models—does the size of an in-context learner play a role in determining the learning algorithm it implements?
To answer this question, we run two ﬁnal behavioral experiments: one in which we vary the hidden size (while optimizing the depth and number of heads as in
Section 4.2), then vary the depth of the transformer (while optimizing the hidden size and number of heads).
These experiments are conducted without dataset noise.
Results are shown in Fig.
When we vary the depth, learners occupy three distinct regimes: very shallow models (1L) are best approximated by a single step of gradient descent (though not well-
[Figure]
deeper models (2L-4L) are best approximated by ridge regression, while the deepest (+8L) models match OLS as observed in Fig.
Similar phase shifts occurs when we vary hidden size in 16D problem. Interestingly, we can read hidden size requirements to be close to ridge-regression-like solutions as H ≥ 16 and H ≥ 32 for 8D and 16D problems respectively, suggesting that ICL discovers more efﬁcient ways to use available hidden state than our theoretical constructions requiring O ( d 2 ) .
Together, these results show that ICL does not necessarily involve minimum-risk prediction.
However, even in models too computationally constrained to perform Bayesian inference, alternative interpretable computations can emerge.
D OES ICL ENCODE MEANINGFUL INTERMEDIATE QUANTITIES ?
Section 4 showed that transformers are a good ﬁt to standard learning algorithms (including those constructed in Section 3) at the computational level.
But these experiments leave open the question of how these computations are implemented at the algorithmic level.
How do transformers arrive at the solutions in Section 4, and what quantities do they compute along the way?
Research on extracting precise algorithmic descriptions of learned models is still in its infancy (Cammarata et al., 2020; Mu & Andreas, 2020).
However, we can gain insight into ICL by inspecting learners’ intermediate states: asking what information is encoded in these states, and where .
To do so, we identify two intermediate quantities that we expect to be computed by gradient descent and ridge-regression variants: the moment vector X (cid:62) Y and the (min-norm) least-square estimated weight vector w lstsq , each calculated after feeding n examplars.
We take a trained in-context learner, freeze its weights, then train an auxiliary probing model (Alain & Bengio, 2016) to attempt to recover the target quantities from the learner’s hidden representations.
Speciﬁcally, the probe model takes as input hidden states at a layer h ( l ) , then outputs the prediction for target variable.
We deﬁne a probe with position-attention that computes (Appendix E):
[Equation] [Equation]
[Figure]
We train this probe to minimize the squared error between the predictions and targets v : L ( v , ˆ v ) = | v − ˆ v | 2 .
The probe performs two functions simultaneously: its prediction error on held-out representations determines the extent to which the target quantity is encoded , while its attention mask, α identiﬁes the location in which the target quantity is encoded .
For the FF term, we can insert the function approximator of our choosing; by changing this term we can determine the manner in which the target quantity is encoded —e.g. if FF is a linear model and the probe achieves low error, then we may infer that the target is encoded linearly.
For each target, we train a separate probe for the value of the target on each preﬁx of the dataset : i.e. one probe to decode the value of w computed from a single training example, a second probe to decode the value for two examples, etc.
Results are shown in Fig.
For both targets, a 2layer MLP probe outperforms a linear probe, meaning that these targets are encoded nonlinearly (unlike the constructions in Section 3).
However, probing also reveals similarities.
Both targets are decoded accurately deep in the network (but inaccurately in the input layer, indicating that probe success is non-trivial.)
Probes attend to the correct timestamps when decoding them.
As in both constructions, X (cid:62) Y appears to be computed ﬁrst, becoming predictable by the probe relatively early in the computation (layer 7); while w becomes predictable later (around layer 12).
For comparison, we additionally report results on a control task in which the transformer predicts y s generated with a ﬁxed weight vector w = 1 (so no ICL is required). Probes applied to these models perform signiﬁcantly worse at recovering moment matrices (see Appendix E for details).
C ONCLUSION
We have presented a set of experiments characterizing the computations underlying in-context learning of linear functions in transformer sequence models.
We showed that these models are capable in theory of implementing multiple linear regression algorithms, that they empirically implement this range of algorithms (transitioning between algorithms depending on model capacity and dataset noise), and ﬁnally that they can be probed for intermediate quantities computed by these algorithms.
While our experiments have focused on the linear case, these ﬁndings immediately extend to many learning problems over richer function classes—e.g. to a network whose initial layers perform a non-linear feature computation.
Even more generally, the experimental methodology here could be applied to larger-scale examples of ICL, especially language models, to determine whether their behaviors are also described by interpretable learning algorithms.
While much work remains to be done, our results offer initial evidence that the apparently mysterious phenomenon of in-context learning can be understood with the standard ML toolkit, and that the solutions to learning problems discovered by machine learning researchers may be discovered by gradient descent as well.
A T HEOREM
The operations for 1-step SGD with single exemplar can be expressed as following chain (please see proofs for the Transformer implementation of these operations (Lemma 1) in Appendix C):
• mov (; 1 , 0 , (1 , 1 + d ) , (1 , 1 + d ))
(move
x ) • aff (; (1 , 1 + d ) , () , (1 + d, 2 + d ) , W 1 = w )
w
x ) • aff (;
(1 + d, 2 + d ) , (0 , 1) , (2 + d, 3 + d ) , W
=
I, W 2 = − I ) ( w (cid:62) x − y )
• mul (; d, 1 , 1 , (1 , 1 + d ) , (2 + d, 3 + d ) , (3 + d, 3 + 2 d ))
( x ( w (cid:62) x − y ) )
• aff
() , () , (3 + 2 d, 3 + 3 d ) , b = w , )
(write w )
• aff (; (3+ d, 3+2 d ) , (3+2 d, 3+3 d ) , (3+3 d, 3+4 d ) , W 1 =
I, W 2 = − 2 λ ) ( x ( w (cid:62) x − y ) − 2 λ w ) • aff (;
(3 + 2 d, 3 + 3 d ) , (3 + 3 d, 3 + 4 d ) , (3 + 2 d, 3 + 3 d ) , W 1 =
I, W 2 = − α, )
( w (cid:48)
) • mov (; 2 , 1 , (3 + 2 d, 3 + 3 d ) , (3 + 2 d, 3 + 3 d ))
(move w (cid:48)
) • mul (; 1 , d, 1 , (3 + 2 d, 3 + 3 d ) , (1 , 1 + d ) , (3 + 3 d, 4 + 3 d ))
( w (cid:48)(cid:62) x 2 )
This will map:    y x x   (cid:55)→   
[Equation]
  
We can verify the chain of operator step-by-step.
In each step, we show only the non-zero rows.
• mov (; 1 , 0 , (1 , 1 + d ) , (1 , 1 + d )) (move x )
(cid:20)
[Table]
y
[Table]
x
[Table]
x [Table] (cid:21) (cid:55)→
[Table]
x
[Table]
x
[Table]
(cid:21) • aff (; (1 , 1 + d ) , () , (1 + d, 2 + d ) , W [Table]
= w )
[Table]
) (cid:20)y
[Table]
[Table]
(cid:21)
[Table]
[Table]
• mul (; d, 1 , 1 , (1 , 1 + d ) , (2 + d, 3 + d ) , (
[Table]
+ d,
[Table]
+ 2 d ))
( x
[Table]
w
[Table]
− y )
[Table]
  y xxxw
[Table]
x
[Table]
w
[Table]
w
[Table]
x
[Table]
w
[Table]
x
[Table]
w [Table] x 1 − yw (cid:62) x [Table]


[Table]
  y
[Table]
x
[Table]
x
[Table]
x
[Table]
w
[Table]
w [Table] w [Table]
w [Table] w [Table]
−
[Table]
w
[Table]
x [Table] w [Table]
x
[Table]
w
[Table] x [Table] − y )
x
[Table]
w [Table]  • aff (; () , () , (3 + 2 d, 3 + 3 d ) , b = w , ) (write w )   y xxxw [Table]
x [Table] w [Table]
w
[Table]
w
[Table]
w
[Table]
y w [Table] x [Table]
w
[Table]
x
[Table]
x [Table] w [Table]
y )
[Table]

[Table]
w
[Table]
y w
[Table]
w
[Table]
− y )
[Table]
w
[Table]
w w w 
 • aff
3+ d, 3+2 d ) , 3+2 d, 3+3 d ) , (3+3 d, 3+4 d ) , W 1 =
I, W 2 = − 2 λ ) ( x ( w (cid:62) x − y ) − 2 λ w )   y xxxw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) x 1 − y w (cid:62) xx 1 w (cid:62) xx 1 ( w (cid:62) x 1 − y )
x 2 w (cid:62) xw w w 
 (cid:55)→   y xxxw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) x 1 − y w (cid:62) xx
1 w (cid:62) xx 1 ( w (cid:62) x 1 − y )
x 2 w (cid:62) xw w w x 1 w (cid:62) x 1 − 2 λw x 1 ( w (cid:62) x 1 − y ) − 2 λw x 2 w (cid:62) x 1 − 2 λw 
 • aff
(3 + 2 d 3 + 3 d ) (3 +
d
3 + 4 d ) , (3 + d, 3 + 3 d ) , W 1 =
I, W 2 = − α, ) ( w (cid:48) )
  y xxxw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) x 1 − y w (cid:62) xx
1 w (cid:62) xx 1 ( w (cid:62) x 1 − y )
x 2 w (cid:62) xw w w x 1 w (cid:62) x 1 − 2 λw x 1 ( w (cid:62) x 1 − y ) − 2 λw x 2 w (cid:62) x 1 − 2 λw   (cid:55)→   y xxxw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) xw (cid:62) x
1 − y w (cid:62) xx 1 w (cid:62) xx 1 ( w (cid:62) x 1 − y ) x
2 w (cid:62) xw − αx 1 w (cid:62) x 1 − 2 λw w (cid:48) w − α ( x 2 w (cid:62) x 1 − 2 λw ) x 1 w (cid:62) x 1 − 2 λw x 1 ( w (cid:62) x 1 − y ) − 2 λw x 2 w (cid:62) x 1 − 2 λw  
[Table]
w
[Table]
   • mul (
[Table]
1 , d, 1 , (3 + 2 d [Table] 3 + 3 d ) , (
[Table]
1 + d ) , ( [Table] [Table] d )) ( w
[Table]
  y [Table] x
[Table]
x [Table] w
[Table]
w
[Table]
w
[Table]
w
[Table]
w
[Table]
w
[Table] 

[Table]
  
[Table]
w
[Table] w [Table] w
[Table]
w
[Table]
x
[Table]
w
[Table]
x
[Table]
( w
[Table]
y )
[Table]
w
[Table]
w
[Table]
w
[Table]
w
[Table]
w
[Table]
x
[Table]
w
[Table]
x
[Table]
w
[Table]
[Equation]

 
We obtain the updated prediction in the last hidden unit of the third time-step.
Generalizing to multiple steps of SGD.
Since w (cid:48) is written in the hidden states, we may repeat this iteration to obtain ˆ y 3 = w (cid:48)(cid:48)(cid:62) x 3 where w (cid:48)(cid:48) is the one step update w (cid:48) − α ( x 2 w (cid:48)(cid:62) x 2 − y 2 x 2 + 2 λ w , requiring a total of O ( n ) layers for a single pass through the dataset where n is the number of examplers.
As an empirical demonstration of this procedure, the accompanying code release contains a reference implementation of SGD deﬁned in terms of the base primitive provided in an anymous links https://icl1.s3.us-east-2.amazonaws.com/theory/ { primitives,sgd,ridge } .py
(to preserve the anonymity we did not provide the library dependencies).
This implementation predicts ˆ y n = w (cid:62) n x n , where w n is the weight vector resulting from n − 1 consecutive SGD updates on previous examples.
It can be veriﬁed there that the procedure requires O ( n + d ) hidden space.
Note that, it is not O ( nd ) because we can reuse spaces for the next iteration for the intermediate variables, an example of this performed in ( w (cid:48) )
step above highlighted with blue color.
B T HEOREM
We provide a similar construction to Theorem 1 (please see proofs for the Transformer implementation of these operations in Appendix C, speciﬁcally for div see Appendix C.6)
• mov (; 1 , 0 , (1 , 1 + d ) , (1 , 1 + d ))
[Table]
• mul (; d, 1 , 1 , (1 , 1 + d ) , (0 , 1) , (1 + d, 1 + 2 d ))
[Table]
• aff (; () , () , (1 + 2 d, 1 + 2 d + d 2 ) , b = Iλ )
[Table]
• mul (; d, d, 1 , (1 + 2 d, 1 + 2 d + d 2 ) , (1 , 1 + d ) , (1 + 2 d + d 2 , 1 + 3 d + d 2 ))
[Table]
• mul (; 1 , d, d, (1 , 1 + d ) , (1 + 2 d, 1 + 2 d + d 2 ) , (1 + 3 d + d 2 , 1 + 4 d + d 2 ))
[Table]
• mul (; d, 1 , d, (1 + 2 d + d 2 , 1 + 3 d + d 2 ) , (1 + 3 d + d 2 , 1 + 4 d + d 2 ) , (1 + 4 d + d 2 , 1 + 4 d
+ 2 d 2 ))
( A − 1 0 uv A − 1 0 =
Iλ x 1 x (cid:62) 1 Iλ ) • mul (; 1 , d, 1 , (1+3 d + d 2 , 1+4 d + d 2 ) , (1 , 1+ d ) , (1+4 d +2 d 2 , 2+4 d +2 d 2 ))
( v (cid:62)
[Table]
{+1 0 u = x (cid:62) 
+}
Iλ x 1 ) • aff (; (1+4 d +2 d
[Table]
+
[Table]
+
[Table]
2 ) , () , (1+
[Table]
+
[Table]
2 , 2+
[Table] [Table]
[Table]
) • div (; (1 + 4 d + d 2 , 1 + 4 d + 2 d 2 ) , 1 + 4 d + 2 d 2 , (2 + 4 d + 2 d 2 , 2 + 4 d + 3 d 2 )) (right term) • aff (;
(1+2 d, 1+2 d + d 2 ) , (2+4 d +2 d 2 , 2+4 d +3 d 2 ) , (1+2 d, 1+2 d + d 2 ) , W 1 =
I, W 2 = − I )
( A − 1 1 ) • mul (;
d, d, 1 , (1 + 2 d, 1 + 2 d + d 2 ) , (1 , 1 + d ) , (2 + 4 d + 3 d 2 , 2 + 5 d + 3 d 2 ))
[Table]
) • mul (; d, 1 , 1 , (2 + 4 d + 3 d 2 , 2 + 5 d + 3 d 2 ) , (0 , 1) , (2 + 4 d + 3 d 2 , 2 + 5 d + 3 d 2 ))
[Table]
x
[Table]
y 1 ) • mov (; 2 , 1 , (2 + 4 d + 3 d 2 , 2 + 5 d + 3 d 2 ) , (2 + 4 d + 3 d 2 , 2 + 5 d + 3 d 2 ))
[Table]
• mul (; d, 1 , 1(2 + 4 d + 3 d 2 , 2 + 5 d + 3 d 2 ) , (1 , 1 + d ) , (2 + 5 d + 3 d 2 , 3 + 5 d + 3 d 2 ))
[Table]
(cid:48)(cid:62) x 2 )
Note that, in contrast to Appendix A, we need O ( d 2 ) space to implement matrix multiplications. Therefore over-all required hidden size is O ( d 2 )
As Theorem 1, generalizing it to multiple iterations will at least require O ( n ) layers, as we repeat the process for the next examplar.
C L EMMA
All of the operators mentioned in this lemma share a common computational structure, and can in fact be implemented as special cases of a “base primitive” we call RAW (for Read-Arithmetic-Write).
This operator may also be useful for future work aimed at implementing other algorithms.
The structure of our proof of Lemma 1 is as follows:
Motivation of the base primitive RAW .
Formal deﬁnition of RAW .
Deﬁnition of dot , aff , mov in terms of RAW . 4.
Implementation of RAW in terms of transformer parameters.
Brief discussion of how to parallelize RAW , making it possible to implement mul .
Seperate proof for div by utilizing layer norm.
C. RAW O PERATOR : I NTUITION
At a high level, all of the primitives in Lemma 1 involve a similar sequence of operations: 1) Operators read some hidden units from the current or previous timestep: dot and aff read from two subsets of indices in the current hidden state h t , while mov reads from a previous hidden state h t (cid:48) .
This selection is straightforwardly implemented using the attention component of a transformer layer.
We may notate this reading operation as follows:
[Equation]
Here r denotes a list of indice to read from, and K denotes a map from current timesteps to target timesteps .
For convenience, we use Numpy-like notation to denote indexing into a vector with another vector:
Deﬁnition C.1 (Bracket) .
x [ . ] is Python index notation where the resulting vector, x (cid:48) =
x [ r ] :
[Equation]
The ﬁrst step of our proof below shows that the attention output a ( l ) can compute the expression above.
2) Operators perform element-wise arithmetic between the quantity read in step 1 and another set of entries from the current timestep: This step takes different forms for aff and mul ( mov ignores values at the current timestep altogether).
[Equation]
The second step of the proof below computes these operations inside the MLP component of the transformer layer.
3) Operators reduce, then write to the current hidden state Once the underlying element-wise operation calculated, the operator needs to write these values to the some indices in current hidden state, deﬁned by a list of indices w .
Writing might be preceded by a reduction state (e.g. for computing dot products), which can be expressed generically as a linear operator W o .
The ﬁnal form of the computation is thus:
[Equation]

[Equation]
Here, ← means that the other indices i / ∈ w are copied from h l − 1 .
C. RAW O PERATOR D EFINITION
We denote this “master operator” as RAW :
Deﬁnition C.2.
RAW ( h ; (cid:13) (cid:63), s , r , w , W o , W a , W, K ) is a function R H × T
(cid:55)→ R H × T .
It is parameterized by an elementwise operator (cid:13) (cid:63) ∈ { + , (cid:12)} , three matrices W ∈ R
d ×| s | , W a ∈ R d ×| r | , W o ∈ R | w |× d , three index sets s , r , and w , and a timestep map K : Z
+ (cid:55)→ ( Z + ∗ ) .
Given an input matrix h , it outputs a matrix with entries:
[Equation]
We additionally require that j ∈ K ( i ) = ⇒ j < i (since self-attention is causal.)
(For simplicity, we did not include a possible bias term in linear projections W o , W a , W , we can always assume the accompanying bias parameters b 0 , b a , b when needed)
C. R EDUCING L EMMA 1 OPERATORS TO RAW OPERATOR
Given this operator, we can deﬁne each primitive in Lemma 1 using a single RAW operator, except the mul and div .
Instead of the matrix multiplication operator mul , we will ﬁrst show the dot product dot (a special case of mul ), then later in the proof, we will argue that we can parallelize these dot products in Appendix C.5 to obtain mul .
We will show how to implement div separately in Appendix C.6.
Lemma 2.
We can deﬁne mov , aff operator, and the dot product case of mul in Lemma 1 by using a single RAW operator dot ( h ; ( i, j ) , ( i (cid:48) , j (cid:48) ) , ( i (cid:48)(cid:48) , j (cid:48)(cid:48) ))
=
mul ( h ; 1 , | i − j | , 1 , ( i, j ) , ( i (cid:48) , j (cid:48) ) , ( i (cid:48)(cid:48) , i (cid:48)(cid:48) + 1))
=
RAW (
[Equation]
(cid:12) ,
[Equation]
, W
[Equation]
I
[Equation]
W
[Equation]
1 (cid:62)
[Equation]
[Equation]
( i (cid:48)
[Equation]
(cid:48) ) , w
[Equation]
( i (cid:48)(cid:48) , i (cid:48)(cid:48) + 1) , K
[Equation]
( t
[Equation]
t } ) ∀ t } ) aff
( h ; ( i, j ) , ( i (cid:48) , j (cid:48) )
[Equation]
( i (cid:48)(cid:48) , j (cid:48)(cid:48) ) , W 1 , W 2 , b ) =
RAW ( h
[Equation]
+ , W
[Equation]
W 1 , W a = W
[Equation]
W o =
I
[Equation]
{+b 
+}
=
b, s =
( i, j ) , r
[Equation]
( i (cid:48) , j (cid:48) ) , w
[Equation]
( i (cid:48)(cid:48) , i (cid:48)(cid:48) + 1) , K = { ( t,
[Equation]
t } ) ∀ t } ) mov ( h
[Equation]
s, t
[Equation]
( i, j ) , ( i (cid:48) , j (cid:48) ))
=
RAW ( h
[Equation]
+ , W = 0 , W a =
I, W
o
=
I, s = () , r
= ( i (cid:48) , j (cid:48) ) , w = ( i, j ) ,
K = { ( t, { s } ) } )
Proof.
Follows immediately by substituting parameters into Eq.
C. I MPLEMENTING RAW
It remains only to show:
Lemma 3.
A single transformer layer can implement the RAW operator: there exist settings of transformer parameters such that, given an arbitrary hidden matrix h as input, the transformer computes h (cid:48)
(Eq. (24) ) as output.
Our proof proceeds in stages.
We begin by providing specifying initial embedding and positional embedding layers, constructing inputs to the main transformer layer with necessary positional information and scratch space.
Next, we prove three useful procedures for bypassing (or exploiting) non-linearities in the feed-forward component of the transformer.
Finally, we provide values for remaining parameters, showing that we can implement the Elementwise and Reduction steps described above.
C.4. E MBEDDING LAYERS
Embedding Layer for Initialization: Rather than inserting the input matrix h directly into the transformer layer, we assume (as is standard) the existence of a linear embedding layer.
We can set this layer to pad the input, providing extra scratch space that will be used by later steps of our implementation.
We deﬁne the embedding matrix W e as:
[Equation] [Equation]
Then, the embedded inputs will be
[Equation]
[Equation]
[Equation]
Position Embeddings for Attention Manipulation: Implementing RAW ultimately requires controlling which position attends to which position in each layer.
For example, we may wish to have layers in which each position attends to the previous position only, or in which even positions attends to other even positions.
We can utilize position embeddings, p i , to control attention weights.
In a standard transformer, the position embedding matrix is a constant matrix that is added to the inputs of the transformer after embedding layer (before the ﬁrst layer), so the actual input to to the transformer is:
[Equation]
We will use these position embeddings to encode the timestep map K. To do this, we will use 2 p units per layer ( p will be deﬁned momentarily).
p units will be used to encode attention keys k i , and the other p will be used to encode queries
q i .
We deﬁne the position embedding matrix as follows:
[Equation]
With K encoded in positional embeddings, the transformer matrices W Q and W K are easy to deﬁne: they just need to retrieve the corresponding embedding values:
[Equation]
[Equation]  (31) The constructions used in this paper rely on two speciﬁc timestep maps K , each of which can be implemented compactly in terms of k and q :
Case 1: Attend to previous token.
This can be constructed by setting
[Equation]
where N is a sufﬁciently large number.
In this case, the output of the attention mechanism will be:
[Equation]
Case 2: Attend to a single token.
For simpler patterns, such as attention to a speciﬁc token:
[Equation]
only 1 hidden unit is required.
We set:
[Equation]
from which it can be veriﬁed (using the same procedure as in Case 1) that the desired attention pattern is produced.
Intricacy: How can K be empty?
We can also cause K ( i ) to attend to an empty set by assuming the softmax has extra (“imaginary”) timestep obtained by prepending a 0 to attention vector pot-hoc
(Chen et al., 2020).
Cumulatively, the parameter matrices deﬁned in this subsection implement the Read with Attention component of the RAW operator.
C.4. H ANDLING & U TILIZING N ONLINEARITIES
The mul operator requires elementwise multiplication of quantities stored in hidden states.
While transformers are often thought of as only straightforwardly implementing afﬁne transformations on hidden vectors, their nonlinearities in fact allow elementwise multiplication to a high degree of approximation.
We begin by observing the following property of the GeLU activation function in the MLP layers of the Transformer network:
Lemma 4.
The GeLU nonlinearity can be used to perform multiplication: speciﬁcally,
[Equation]
Proof.
A standard implementation of the GeLU nonlinearity is deﬁned as follows:
[Equation]
Thus
[Equation]
[Equation]
For small x and y , the third-order term vanishes.
By scaling inputs down by a constant before the GeLU layer, and scaling them up afterwards, models may use the GeLU operator to perform elementwise multiplication.
We can generalize this proof to other smooth functions as we discussed further in [TODO REF].
Previous work also shows, in practice, Transformers with ReLU activation utilize non-linearities to get the multiplication in other settings.
When implementing the aff operator, we have the opposite problem: we would like the output of addition to be transmitted without nonlinearities to the output of the transformer layer.
Fortunately, for large inputs, the GeLU nonlinearity is very close to linear; to bypass it it sufﬁces to add to inputs a large N :
Lemma 5.
The GeLU nonlinearity can be bypassed: speciﬁcally,
[Equation]
Proof.
[Equation]
For all verions of the RAW operator, it is additionally necessary to bypass the LayerNorm operation.
The following formula will be helpful for this:
Lemma 6.
Let N be a large number and λ the LayerNorm function.
Then the following approximation holds:
[Equation]
Proof.
[Equation]
Then,
[Equation]
By adding a large number N to two padding locations and sum the part of the hidden state that we are interested to pass through LayerNorm, we make x to the output of LayerNorm pass through.
This addition can be done in the transformer’s feed-forward computation (with parameter W F ) prior to layer norm.
This multiplication of (cid:113) 2 L N can be done in ﬁrst layer of MLP back, then linear layer can output/use x .
For convenience, we will henceforth omit the LayerNorm operation when it is not needed.
We may make each of these operations as precise as desired (or allowed by system precision).
With them deﬁned, we are ready to specify the ﬁnal components of the RAW operator.
C.4. P ARAMETERIZING RAW
We want to show a layer of Transformer deﬁned in above, hence parameterized by θ = { W f , W 1 , W 2 , ( W Q , W K , W v ) m } , can well-approximate the RAW operator deﬁned in Eq.
We will provide step by step constructions and deﬁne the parameters in θ .
Begin by recalling the transformer layer deﬁnition:
[Equation]
Attention Output We will only use m = 2 attention heads for this construction.
We show in
Eq.
(30) that we can control attentions to uniformly attend with a pattern by setting key and query matrices.
Assume that the ﬁrst head parameters W Q 1 , W K 1 have been set in the described way to obtain the pattern function K .
Now we will set remaining attention parameters W V 1 , W Q 2 , W K 2 , W V 2 and show hat we can make the a i + h ( l ) i term in Eq.
(4) to contain the corresponding term in Eq.
(23), in some unused indices t such that:
[Equation]
Then the term on the RAW operator can be obtained by the ﬁrst head’s output.
In order to achieve that, we will set W a as a part of actual attention value network such that W V 1 is sparse matrixeverywhere expect:
[Equation]
Now our ﬁrst heads stores the right term in Eq.
(51) in the indicies t .
However, when we add the residual term h ( l ) i , this will change.
To remove the residual term, we will use another head to output h ( l ) i , by setting W Q 2 , W K 2 such that K ( i )
=
i , and W V 2 (similar to Eq.
[Equation]
Then, W f ∈ R H × 2 H is zero otherwise:
[Equation]
We already deﬁned ( W Q , W K , W V ) 1 , 2 and W f and obtained the ﬁrst term in the Eq.
(23) in ( a i + h ( l ) i ) t (cid:48) ∈ t .
Arithmetic term Now we want to calculate the term inside the parenthesis Eq.
We will calculate it through the MLP layer and store in m i and substract the ﬁrst term.
Let’s denote the input to the MLP as x i
= ( a i + h ( l ) i ) , the output of the ﬁrst layer
u i , the output of the non-linearity as a i , and the ﬁnal output as m i .
The entries of m i will be:
[Equation]
We will deﬁne the MLP layer to operate the attention term calculated above with a part of the current hidden state by deﬁning W 1 and W 2 .
Let’s assume we bypass the LayerNorm by using Lemma 6.
Let’s show this seperately for + and (cid:12) operators.
RAW (+ , . )
If the operator, (cid:13) (cid:63) =
+ , ﬁrst layer of the MLP will calculate the second term in
Eq.
(23) and overwrite the space where the attention output term Eq.
(51) is written, and add a large positive bias term N to by pass GeLU as explained in Lemma 4.
We will use an available space ˆ t in the x i same size as t .
[Equation]
This can be done by setting W 1 (weight term of the ﬁrst layer of the MLP) to zero except the below indices:
[Equation]
and the bias vector b 1 to
[Equation]
Note the second term is added to make unused indices t ∪ w ∪ ˆ t become zero after the gelu , which outputs zero for large negative values.
Since we added a large positive term, we make sure gelu behaved like a linear layer.
Thus we have,
[Equation]
[Equation]
[Equation]
Now, we need to set W 2 , to simulate W o ∈ R | w |×| t | ,
[Equation]
[Equation] [Equation]
[Equation]
Therefore, m i [ w ] =
W o x i [ t ] + W 0 W h li
[ s ] − x i [ w ] equals to what we promised in Eq.
(58) for + case.
If we sum this with the residual x i term back Eq.
(51), so the output of this layer can be written as:
[Equation]
RAW ( (cid:12) , . )
If the operator, (cid:13) (cid:63) = (cid:12) , we need to use three extra hidden units the same size as | t | , let’s name the extra indices as t a , t b , t c , and output w space.
The ( u i ) will get below entries to be able to use [], where N is a large number:
[Equation]
All of this operations are linear, can be done W 1 zero except the below entries:
[Equation]
and b 1 to:
[Equation]
The resulting v with the approximations become:
[Equation]
Now
[Equation]
we can use the GeLU trick in Lemma
[Equation]
by setting W
[Equation]
[Equation]
[Equation]
[Equation]
We then set b 2 :
[Equation]
[Equation]
With this, m i [ w ] =
W o x i [ t ] ∗ W 0 W h l − 1 i [ s ] − x i [ w ] , and ( h i ) ( l +1) t (cid:48) ∈ w = W o   
[Equation]
| (cid:88) k ∈ K
( i ) h
( l ) k
[ r ] 
 (cid:12)
[Equation]
h ( l ) i [ s ] 
 (124) (
[Equation]
[Equation] (cid:48) [Equation] We have used 4 | t | space for internal computation of this operation, and ﬁnally used | w | space to write the ﬁnal result.
We show RAW operator is implementable by setting the parameters of a
Transformer.
C. P ARALLELIZING THE RAW OPERATOR
Lemma 7. With the conditions that K is constant, the operators are independent (i.e ( r i ∪ s i ∪ w i ) ∩ w j (cid:54) =
i = ∅ ), and there is (cid:80) k (4 | t k | + | w k | ) available space in the hidden state, then a Transformer layer can apply k such RAW operation in parallel by setting different regions of W 1 , W 2 , W f and ( W V ) k matrices. Proof.
From the construction above, it is straightforward to modify the deﬁnition of the RAW operator to perform k operations as all the indices of matrices that we use in Appendix C.4.3 do not overlap with the given conditions in the lemma.
This makes it possible to construct a Transformer layer not only to implement vector-vector dot products, but general matrix-matrix products, as required by mul .
With this, we show that we can implement mul by using single layer of a Transformer.
C. L AYER N ORM FOR D IVISION
Let say we have the input [ c, y , 0 ] (cid:62) calculated before the attention output in Eq.
and we want to divide y to c .
This trick is very similar to the on in Lemma 6.
We can use the following formula:
Lemma 8.
using LayerNorm for division.
Let N, M to be large numbers, λ LayerNorm function, the following approximation holds:
[Equation]
Proof.
[Equation]
Then, [Equation]
[Equation]
To get the input to the format used in this Lemma, we can easily use W f to convert the head outputs.
Then, after the layer norm, we can use W 1 to pull the y c back and write it to the attention output.
By this way, we can approximate scalar division in one layer.
Lemma 1 By Lemmas 2, 3, 3, 7 and 8; we constructed the operators in Lemma 1 using single layer of a Transformer, thus proved Lemma
[Figure]
D D ETAILS OF T RANSFORMER A RHITECTURE AND T RAINING
We perform these experiments using the Jax framework on P100 GPUs.
The major hyperparameters used in these experiments are presented in Table 1.
The code repository used for reproducing these experiments will be open sourced at the time of publication.
Most of the hyperparameters adapted from previous work Garg et al.
(2022) to be compatible,
and we adapted the Transformer architecture details.
We use Adam optimizer with cosine learning rate scheduler with warmup where number of warmup steps set to be 1/5 of total iterations. We use larned absolute position embeddings. [Figure]
[Table]
In the phase shift plots in Fig.
3, we keep the value in the x-axis constant and used the best setting over the parameters: { number of layers, hidden size, number of heads and learning rate } .
E D ETAILS OF P ROBE
We will use the terms probe model and task model to distinguish probe from ICL.
Our probe is deﬁned as: [Equation]
[Equation]
The position scores s v ∈ R T are learned parameters where T is the max input sequence length ( T = 80 in our experiments).
The softmax of position scores attention weights α for each position and for each target variable.
This enables us to learn input-independent, optimal target locations for each target (displayed on the right side of Fig. 4).
We then average hidden states by using these [Figure] attention weights. A linear projection, W v ∈ R T × H (cid:48) , is applied before averaging.
FF is either a linear layer or a 2-layer MLP (hidden size=512) with a GeLU activation function.
For each layer, we train a different probe with different parameters using stochastic gradient descent.
H (cid:48) equals to the 512.
The probe is trained using an Adam optimizer with a learning rate of 0.001 (chosen from among { 0 . 01 , 0 . 001 , 0 . 0001 } on validation data). Control Experiments In Fig. 4, dashed lines show probing results with a task model trained on a control task , in which w is always the all-ones 1 . This problem structurally resembles our main experiment setup, but does not require in-context learning.
During probing, we feed this model data generated by w sampled form normal distribution as in the original task model.
We observe that the control probe has a signiﬁcantly higher error rate, showing that the probing accuracy obtained with actual task model is non-trivial.
We present detailed error values of the control probe in Fig.
F L INEARITY OF ICL
In Fig.
1b, we compare implicit linear weight of the ICL against the linear algorithms using ILWD measure.
Note that this measure do not assume predictors to be linear: when the predictors are not linear, ILWD measures the difference between closest linear predictors (in Eq.
(15) sense) to each algorithm.
To gain more insight to ICL’s algorithm, we can measure how linear ICL in different regimes of the linear problem (underdetermined, determined) by using R 2 (coefﬁcient of determination) measure.
So, instead of asking what’s the best linear ﬁt in Eq.
(15), we can ask how good is the linear ﬁt, which is the R 2 of the estimator.
Interestingly, even though our model matches min-norm least square solution in both metrics in Section 4.3, we show that ICL is becoming gradually linear in the under-determined regime Fig.
This is an important result, enables us to say the in-context learner’s hypothesis class is not purely linear.
G M ULTIPLICATIVE INTERACTIONS WITH O THER N ON - LINEARITIES
We can show that for a real-valued and smooth non-linearity f ( x ) , we can apply the same trick in in the paper body.
In particular, we can write Taylor expansion as:
[Equation]
which converges for some sufﬁciently small neighborhood: X ∈ [ − (cid:15), (cid:15) ] .
First, assume that the second order term a 2 dominates higher-order terms in this domain such that:
[Equation]
where x ∈ X .
It’s is easy to verify that the following is true:
[Equation]
So, given the expansion for GeLU in Eq.
(35), we can use this generic formula to obtain the multiplication approximation:
[Equation]
We plot this approximation against x 2 for [0 . 1 , − 0 .
1] range in Fig.
7a.
In the case of a 2 is zero, we cannot get any second order term, and in the case of a 2 is negligible
O ( x 3 + y 3 ) will dominate the Eq.
(133), so we cannot obtain a good approximation of xy .
In this case, we can resort to numerical derivatives and utilize the a 3 term:
[Equation]
If a 3 is not negligible, a 3 x 2 (cid:28) a i> 3 x i in the same domain, we can use numerical derivatives to get a multiplication term:
[Equation]
For example, tanh has no second order term in its Taylor expansion:
[Equation]
Using above formula we can obtain the following expression:
[Equation]
Similar to our construction in Eq.
(108), we can construct a Transformer layer that calculates these quantities (noting that δ is a small, input-independent scalar).
We plot this approximation against x 2 for [0 . 1 , − 0 .
1] range in Fig.
7b.
Note that, if we use this approximation in our constructions we will need more hidden space as there are 6 different tanh term as opposed to 3 GeLU term in Eq.
Non-smooth non-linearities ReLU is another commonly used non-linearity that is not differentiable.
With ReLU, we can only hope to get piece-wise linear approximations.
For example, we can try to approximate x 2 with the following function:
[Equation]
We plot this approximation against x 2 for [0 . 1 , − 0 .
1] range in Fig.
7c.
H E MPIRICAL S CALING A NALYSIS WITH D IMENSIONALITY
In Figs. 3a and 3b, we showed that ICL needs different hidden sizes to enter the “Ridge regression phase” (orange background) or “OLS phase” (green background) depending on the dimensionality d of inputs x .
However, we cannot reliably read the actual relations between size requirements and the dimension of the problem from only two dimensions.
To better understand size requirements, we ask the following empirical question for each dimension: how many layer/hidden size/heads are needed to better ﬁt the least-squares solution than the Ridge( λ = (cid:15) ) regression solution (the green phase in Figs. 3a and 3b)?
To answer this important question, we experimented with d = { 1 , 2 , 4 , 8 , 12 , 16 , 20 } and run an experiment sweep for each dimension over:
[Figure]
• number of layers (L): { 1 , 2 , 4 , 8 , 12 , 16 } , • hidden size (H): { 16 , 32 , 64 , 256 , 512 , 1024 } , • number of heads (M): { 1 , 2 , 4 , 8 } , • learning rate: { 1e-4, 2.5e-4 } .
For each feature that affects computational capacity of transformer ( L , H , M ), we optimize other features and ﬁnd the minimum value for the feature that satisﬁes SPD(OLS( λ = (cid:15) ) , ICL) <
SPD(Ridge( λ = (cid:15) ) , ICL) .
We plot our experiment with (cid:15) = 0 .
1 in Appendix H.
We ﬁnd that single head is enough for all problem dimensions, while other parameters exhibit a step-functionlike dependence on input size.
Please note that other hyperparameters discussed in Appendix D (e.g weight initialization) were not optimized for each dimension independently.
[Figure]