Transformers as Statisticians: Provable In-Context Learning with In-Context Algorithm Selection
Yu Bai, Fan Chen, Huan Wang, Caiming Xiong, Song Mei
Introduction
Large neural sequence models have demonstrated remarkable in-context learning (ICL) capabilities , where models can make accurate predictions on new tasks when prompted with training examples from the same task, in a zero-shot fashion without any parameter update to the model. A prevalent example is large language models based on the transformer architecture , which can perform a diverse range of tasks in context when trained on enormous text . Recent models in this paradigm such as GPT-4 achieve surprisingly impressive ICL performance that makes them akin to a general-purpose agent in many aspects . Such strong capabilities call for better understandings, which a recent line of work tackles from various aspects .
Recent pioneering work of Garg et al. proposes an interpretable and theoretically amenable setting for understanding ICL in transformers. They perform ICL experiments where input tokens are real-valued (input, label) pairs generated from standard statistical models such as linear models (and the sparse version), neural networks, and decision trees. Garg et al. find that transformers can learn to perform ICL with prediction power (and fitted functions) matching standard machine learning algorithms for these settings, such as least squares for linear models, and Lasso for sparse linear models. Subsequent work further studies the internal mechanisms , expressive power , and generalization of transformers in this setting. However, these works only showcase simple mechanisms such as regularized regression or gradient descent , which are arguably only a small subset of what transformers are capable of in practice; or expressing universal function classes not specific to ICL . This motivates the following question:
How do transformers learn in context beyond implementing simple algorithms?
This paper makes steps on this question by making two main contributions: (1) We unveil a general mechanism—in-context algorithm selection—by which a single transformer can adaptively select different “base” ICL algorithms to use on different ICL instances, without any explicit prompting of the right algorithm to use in the input sequence. For example, a transformer may choose to perform ridge regression with regularization on ICL instance 1, and on ICL instance 2 (Fig. 2); or perform regression on ICL instance 1 and classification on ICL instance 2 (Fig. 5). This adaptivity allows transformers to achieve much stronger ICL performance than the base ICL algorithms. We both prove this in theory, and demonstrate this phenomenon empirically on standard transformer architectures. (2) Along the way, equally importantly, we present a first comprehensive theory for ICL in transformers by establishing end-to-end quantitative guarantees for the expressive power, in-context prediction performance, and sample complexity of pretraining. These results add upon the recent line of work on the statistical learning theory of transformers , and lay out a foundation for the intriguing special case where the learning targets are themselves ICL algorithms.
We prove that transformers can implement a broad class of standard machine learning algorithms in context, such as least squares and ridge regression (Section 3.1), convex risk minimization for learning generalized linear models (such as logistic regression; Section 3.2), Lasso (Section 3.3), and gradient descent for two-layer neural networks (Section 3.4 & Appendix G). Our constructions admit mild bounds on the number of layers, heads, and weight norms, and achieve near-optimal prediction power on many in-context data distributions.
Technically, the above transformer constructions build on a new efficient implementation of in-context gradient descent (Section 3.5), which could be broaderly applicable. For a broad class of smooth convex empirical risks over the in-context training data, we construct an -layer transformer that approximates steps of gradient descent. Notably, the approximation error accumulates only linearly in , utilizing a stability-like property of smooth convex optimization.
We prove that transformers can perform in-context algorithm selection (Section 4). We construct two algorithm selection mechanisms: Post-ICL validation (Section 4.1), and Pre-ICL testing (Section 4.2). For both mechanisms, we provide general constructions as well as concrete examples. Fig. 1 provides a pictorial illustration of the two mechanisms.
As a concrete application, using the post-ICL validation mechanism, we construct a transformer that can perform nearly Bayes-optimal ICL on noisy linear models with mixed noise levels (Section 4.1.1), a more complex task than those considered in existing work.
We provide the first line of results for pretraining transformers to perform the various ICL tasks above, from polynomially many training sequences (Section 5).
Experimentally, we find that learned transformers indeed exhibit strong in-context algorithm selection capabilities in the settings considered in our theory (Section 6). For example, Fig. 2 shows that a single transformer can approach the individual Bayes risks (the optimal risk among all possible algorithms) simultaneously on two noisy linear models with different noise levels.
We humbly remark that the typical toolkit of a statistician contains much more beyond those covered in this work, including and not limited to inference, uncertainty quantification, and theoretical analysis. This work merely aims to show the algorithm selection capability of transformers, akin to what a statistician can do.
1 Related work
The in-context learning (ICL) capability of large language models (LLMs) has gained significant attention since demonstrated on GPT-3 Brown et al. . A number of subsequent empirical studies have contributed to a better understanding of the capabilities and limitations of ICL in LLM systems, which include but are not limited to . For an overview of ICL, see the survey by Dong et al. which highlights some key findings and advancements in this direction.
A line of recent work investigates why and how LLMs perform ICL . In particular, Xie et al. propose a Bayesian inference framework explaining how ICL works despite formatting differences between training and inference distributions. Garg et al. show empirically that transformers could be trained from scratch to perform ICL of linear models, sparse linear models, two-layer neural networks, and decision trees. Li et al. analyze the generalization error of trained ICL transformers from a stability viewpoint. They also experimentally show that transformers could perform “in-context model selection” (conceptually similar to in-context algorithm selection considered in this work) in specific tasks and presented related theoretical hypotheses. However, they do not provide concrete mechanisms or constructions for in-context model selection. A recent work shows that pretrained transformers can perform Bayesian inference in latent variable models, which may also be interpreted as a mechanism for ICL. Our experimental findings extend these results by unveiling and demonstrating the in-context algorithm selection capabilities of transformers.
Closely related to our theoretical results are , which show (among many things) that transformers can perform ICL by simulating gradient descent. However, these results do not provide quantitative error bounds for simulating multi-step gradient descent, and only handle linear regression models or their simple variants. Among these works, Akyürek et al. showed that transformers can implement learning algorithms for linear models based on gradient descent and closed-form ridge regression; it also presented preliminary evidence that learned transformers perform ICL similar to Bayes-optimal ridge regression. Our work builds upon and substantially extends this line of work by (1) providing a more efficient construction for in-context gradient descent; (2) providing an end-to-end theory with additional results for pretraining and statistical power; (3) analyzing a broader spectrum of ICL algorithms, including least squares, ridge regression, Lasso, convex risk minimization for generalized linear models, and gradient descent on two-layer neural networks; and (4) constructing more complex ICL procedures using in-context algorithm selection.
When in-context data are generated from a prior, the Bayes risk is a theoretical lower bound for the risk of any possible ICL algorithm, including transformers. Xie et al. , Akyürek et al. observe that learned transformers behave closely to the Bayes predictor on a variety of tasks such as hidden Markov models and noisy linear regression with a fixed noise level . Using the in-context algorithm selection mechanism (more precisely the post-ICL validation mechanism), we show that transformers can perform nearly-Bayes optimal ICL in noisy linear models with mixed noise levels (a strictly more challenging task than considered in ), with both concrete theoretical guarantees (Section 4.1.1) and empirical evidence (Fig. 2 & 4).
The transformer architecture, introduced by , has revolutionized natural language processing and been adopted in most of the recently developed large language models such as BERT and GPT . Broaderly, transformers have demonstrated remarkable performance in many other fields of artificial intelligence such as computer vision, speech, graph processing, reinforcement learning, and biological applications . Towards a better theoretical understanding, recent work has studied the capabilities , limitations , and internal workings of transformers.
We remark that the transformer architecture used in our theoretical constructions differs from the standard one by replacing the softmax activation (in the attention layers) with a (normalized) ReLU function. Transformers with ReLU activations is experimentally studied in the recent work of Shen et al. , who find that they perform as well as the standard softmax activation in many NLP tasks.
Training models (such as transformers) to perform ICL can be viewed as an approach for the broader problem of learning-to-learn or meta-learning . A number of other approaches has been studied extensively for this problem, including (and not limited to) training a meta-learner on how to update the parameters of a downstream learner , learning parameter initializations that quickly adapt to downstream tasks , learning latent embeddings that allow for effective similarity search . Most relevant to the ICL setting are approaches that directly take as input examples from a downstream task and a query input and produce the corresponding output . For a comprehensive overview, see the survey .
Theoretical aspects of meta-learning have received significant recent interest . In particular, analyzed the benefit of multi-task learning through a representation learning perspective, and studied the statistical properties of learning the parameter initialization for downstream tasks.
We build on various existing techniques from the statistics and learning theory literature to establish our approximation and generalization guarantees for transformers. For the approximation component, we rely on a technical result of Bach on the approximation power of ReLU networks. We use this result to show that transformers can approximate gradient descent (GD) on a broad range of loss functions, substantially extending the results of who primarily consider the square loss. The recent work of Giannou et al. also approximates GD with general loss functions by transformers, though using a different technique of forcing the softmax activations to act as sigmoids. Our analyses of Lasso and generalized linear models build on . Our generalization bound for transformers (used in our pretraining results) build on a chaining argument .
Preliminaries
Above, Eq. 1 uses a normalized ReLU activation in place of the standard softmax activation, which is for technical convenience and does not affect the essence of our studyFor each query index , the attention weights is also a set of non-negative weights that sum to (similar as a softmax probability distribution) in typical scenarios..
We consider a transformer architecture with transformer layers, each consisting of a self-attention layer followed by an MLP layer.
We additionally define the following norm of a transformer :
In (2), the choices of the operator norm and max/sums are for convenience only and not essential, as our results (e.g. for pretraining) depend only logarithmically on .
2 In-context learning
We emphasize that the setting above considers predicting only at the last token , which is without much loss of generality. Our constructions may be generalized to predicting at every token, by using a decoder architecture and a corresponding input format (cf. Appendix B). Our theory focuses on predicting at the last token only, which simplifies the setting. Our experiments test both settings.
Basic in-context learning algorithms
We begin by constructing transformers that approximately implement a variety of standard machine learning algorithms in context, with mild size bounds and near-optimal prediction power on many standard in-context data distributions.
Consider the standard ridge regression estimator over the in-context training examples with regularization (reducing to least squares at and ):
We show that transformers can approximately implement Eq. ICRidge (proof in Section D.1).
For any , with , , and , there exists an -layer attention-only transformer with
(with ) such that the following holds. On any input data such that the problem Eq. ICRidge is well-conditioned and has a bounded solution:
approximately implements Eq. ICRidge: The prediction satisfies
Further, the second-to-last layer approximates : we have for all (see Section D.1 for the definition of ).
Theorem 4 presents the first quantitative construction for end-to-end in-context ridge regression up to arbitrary precision, and improves upon Akyürek et al. whose construction does not give (or directly imply) an explicit error bound like Eq. 6. Further, the bounds on the number of layers and heads in Eq. 4 are mild (constant heads and logarithmically many layers).
Combining Theorem 4 with standard analyses of linear regression yields the following corollaries (proofs in Section D.3 & D.4).
For any , there exists an -layer transformer , such that on any satisfying standard statistical assumptions for least squares (Assumption), its ICL prediction achieves
Assumption requires only generic tail properties such as sub-Gaussianity, and not realizability (i.e., follows a true linear model); above denote the covariance condition number and the noise level therein. The excess risk is known to be rate-optimal for linear regression , and Corollary 5 achieves this in context with a transformer with only logarithmically many layers.
Next, consider Bayesian linear models where each in-context data distribution is drawn from a Gaussian prior , and is sampled as , . It is a standard result that the Bayes estimator of given is given by ridge regression Eq. ICRidge: with . We show that transformers achieve nearly-Bayes risk for this problem, and we use
to denote the Bayes risk of this problem under prior .
2 In-context learning of generalized linear models
As a natural generalization of linear regression, we now show that transformers can recover learn generalized linear models (GLMs) (which includes logistic regression for linear classification as an important special case), by implementing the corresponding convex risk minimization algorithm in context, and achieve near-optimal excess risk under standard statistical assumptions.
The following result (proof in Section E.1) shows that, as long as the empirical risk satisfies strong convexity and bounded solution conditions (similar as in Theorem 4), transformers can approximately implement the ERM predictor , with given by Eq. ICGLM.
For any with , , and , there exists an attention-only transformer with
(where , , and is a constant that depends only on and the -smoothness of within ), such that the following holds. On any input data such that
approximately implements Eq. ICGLM: We have , where
In Theorem 7, the number of heads scales as as opposed to as in ridge regression (Theorem 4), due to the fact that the gradient of the loss is in general a smooth function that can be only approximately expressed as a sum-of-relus (cf. Definition 12 & Lemma A.0) rather than exactly expressed as in the case for the square loss.
achieves small excess risk under the population loss, i.e. for the linear prediction ,
Above, hides constants that depend polynomially on the parameters in Assumption. Similar as in Corollary 5, the excess risk obtained here matches the optimal (fast) rate for typical learning problems with parameters and samples .
Applying Theorem 8 to logistic regression, we have the following result as a direct corollary. Below, the Gaussian input assumption is for convenience only and can be genearalized to e.g. sub-Gaussian input.
Consider any in-context data distribution satisfying
For the link function and , we can choose so that Assumption holds. In that case, when , there exists a transformer with layers, such that for any considered above,
The estimation outputted by achieves excess risk bound Eq. 8.
(Realizable setting) Consider the logistic in-context data distribution
Then, for any distribution with , the prediction of additionally achieves the square loss excess risk Eq. 9.
3 In-context Lasso
We show that transformers can also approximate in-context Lasso with a mild number of layers, and can perform sparse linear regression in standard sparse linear models (proofs in Appendix F).
For any , , , and , there exists a -layer transformer with
For any , there exists a -layer transformer such that the following holds: For any and , suppose that is an -sparse linear model: , for any and , then with probability at least (over the randomness of ), the transformer output achieves
The excess risk obtained in Theorem 11 is optimal up to log factors . We remark that Theorem 11 is not a direct corollary of Theorem 10; Rather, the bound on the number of layers in Theorem 11 requires a sharper convergence analysis of the Eq. ICLasso problem under sparse linear models (Section F.2), similar to .
4 Gradient descent on two-layer neural networks
Thus far, we have focused on convex risks with (generalized) linear predictors of the form . To move beyond both restrictions, as a primary example, we show that transformers can approximate in-context gradient descent on two-layer neural networks (NNs).
5 Mechanism: In-context gradient descent
Technically, the constructions in Section 3.1-3.3 rely on a new efficient construction for transformers to implement in-context gradient descent and its variants, which we present as follows. We begin by presenting the result for implementing (vanilla) gradient descent on convex empirical risks.
such that .
Definition 12 is known to contain broad class of functions. For example, any mildly smooth -variate function is approximable by a sum of relus for any , with mild bounds on (Proposition A.0, building on results of Bach ). Also, any function that is a -sum of relus itself (which includes all piecewise linear functions) is by definition -approximable by sum of relus.
We show that steps of Eq. ICGD can be approximately implemented by an -layer transformer.
Fix any , , , and . Suppose that
approximately implements Eq. ICGD with initialization :
(Prediction space) The final output approximates the prediction of steps of Eq. ICGD: We have , where so that
Further, the transformer admits norm bound .
The proof can be found in Section C.3. Theorem 13 substantially generalizes that of von Oswald et al. (which only does GD on square losses with a linear self-attention), and is simpler than the ones in Akyürek et al. and Giannou et al. . See Fig. 3 for a pictorial illustration of the basic component of the construction, which implements a single step of gradient descent using a single attention layer (Proposition C.0).
Technically, we utilize the stability of convex gradient descent as in the following lemma (proof in Section C.4) to obtain the linear error accumulation in Theorem 13; the error accumulation will become exponential in in the non-convex case in general; see Lemma G.0(b).
In-context algorithm selection
We now show that transformers can perform various kinds of in-context algorithm selection, which allows them to implement more complex ICL procedures by adaptively selecting different “base” algorithms on different input sequences. We construct two general mechanisms: Post-ICL validation, and Pre-ICL testing; See Fig. 1 for a pictorial illustration.
denote the validation loss of any predictor .
We show that (proof in Section H.1) a 3-layer transformer can output a predictor that achieves nearly the smallest validation loss, and thus nearly optimal expected loss if concentrates around the expected loss . Below, the input sequence uses a generalized positional encoding in Eq. 3, where for , for , and .
As an example, we use Proposition 15 to construct a transformer to perform in-context ridge regression with regularization selection according to the unregularized validation loss (proof in Section H.2). Let be fixed regularization strengths.
There exists a transformer with layers and heads such that the following holds: On any well-conditioned (cf. Eq. 5) for all , it outputs , where
Above, denotes the solution to Eq. ICRidge on the training split , and , where are the bounds in the well-conditioned assumption Eq. 5.
1.1 Nearly Bayes-optimal ICL on noisy linear models with mixed noise levels
We build on Theorem 16 to show that transformers can perform nearly Bayes-optimal ICL when data come from noisy linear models with a mixture of different noise levels .
Concretely, consider the following data generating model, where we first sample from , , and then sample data as
For any fixed , consider the Bayes risk for predicting under this model:
By standard Bayesian calculations, the above Bayes risk is attained when is a certain mixture of ridge regressions with regularization ; however, the mixing weights depend on in a highly non-trivial fashion (see Section I.2 for a derivation). By using the post-ICL validation mechanism in Theorem 16, we construct a transformer that achieves nearly the Bayes risk.
For sufficiently large , there exists a transformer with layers and heads such that on the above model, it outputs a prediction that is nearly Bayes-optimal:
In particular, Theorem 17 applies in the proportional setting where are large and , in which case , and thus the transformer achieves vanishing excess risk relative to the Bayes risk at large . This substantially strengthens the results of Akyürek et al. , who empirically find that transformers can achieve nearly Bayes risk under any fixed noise level. By contrast, Theorem 17 shows that a single transformer can achieve nearly Bayes risk even under a mixture of noise levels, with quantitative guarantees. Also, our proof in fact gives a stronger guarantee: The transformer approaches the individual Bayes risks on all noise levels simultaneously (in addition to the overall Bayes risk for as in Theorem 17). We demonstrate this empirically in Section 6 (cf. Fig. 4 & 2).
As another example of the post-ICL validation mechanism, we construct a transformer that can learn a generalized linear model with adaptively chosen link function for the particular ICL instance; see Theorem I.0.
2 Pre-ICL testing mechanism
In our second mechanism, pre-ICL testing, the transformer runs a distribution testing procedure on the input sequence to determine the right ICL algorithm to use. While the test (and thus the mechanism itself) could in principle be general, we focus on cases where the test amounts to computing some simple summary statistics of the input sequence.
To showcase pre-ICL testing, we consider the toy problem of selecting between in-context regression and in-context classification, by running the following binary type check on the input labels .
There exists a single attention layer with 6 heads that implements exactly.
Using this test, we construct a transformer that performs logistic regression when labels are binary, and linear regression with high probability if the label admits a continuous distribution.
There exists a transformer with layers such that the following holds: On any such that , it outputs that -approximates the prediction of in-context logistic regression.
By contrast, for any distribution whose marginal distribution of is not concentrated around , with high probability (over ), -approximates the prediction of in-context least squares.
The proofs can be found in Section H.3. We additionally show that transformers can implement more complex tests such as a linear correlation test, which can be useful in certain scenarios such as “confident linear regression” (predict only when the signal-to-noise ratio is high); see Section H.4.
Analysis of pretraining
Thus far, we have established the existence of transformers for performing various ICL tasks with good in-context statistical performance. We now analyze the sample complexity of pretraining these transformers from a finite number of training ICL instances.
Above, is the standard clipping operator onto , and the transformer architecture as in Definition 3 with clipping operators after each layer: let ,
The clipping operator is used to control the Lipschitz constant of with respect to , and we typically choose a sufficiently large clipping radius so that it does not modify the behavior of the transformer on any input sequence of our concern.
We draw ICL instances from a (meta-)distribution denoted as , which first sample an in-context data distribution , then sample iid examples and form . Our pretraining loss is the average ICL loss on pretraining instances , and we consider the corresponding test ICL loss on a new test instance:
Our pretraining algorithm is to solve a standard constrained empirical risk minimization (ERM) problem over transformers with layers, heads, and norm bound (recall the definition of the norm in Eq. 2):
By standard uniform concentration analysis via chaining arguments (Proposition A.0; see also [84, Chapter 5] for similar arguments), we have the following excess loss guarantee for Eq. TF-ERM. The proof can be found in Section J.2.
With probability at least (over the pretraining instances ), the solution to Eq. TF-ERM satisfies
where is a log factor.
2 Examples of pretraining for in-context regression problems
In Theorem 20, the comparator is simply the smallest expected ICL loss for ICL instances drawn from , among all transformers within the norm ball . Using our constructions in Section 3 & 4, we show that this comparator loss is small on various (meta-)distribution ’s, by which we obtain end-to-end guarantees for pretraining transformers with small ICL loss at test time. Here we showcase this argument on several representative regression problems.
Suppose is almost surely well-posed for in-context linear regression (Assumption) with the canonical parameters. Then, for , with probability at least (over the training instances ), the solution of Eq. TF-ERM with layers, heads, (attention-only), and achieves small excess ICL risk over :
where only hides polylogarithmic factors in .
To our best knowledge, Theorem 21 offers the first end-to-end result for pretraining a transformer to perform in-context linear regression with explicit excess loss bounds. The term originates from the generalization of pretraining (Theorem 20), where as the term agrees with the standard fast rate for the excess loss of linear regression . Further, as long as , the excess risk achieves the optimal rate (up to log factors).
By similar arguments as in the proof of Theorem 21, we can directly turn most of our other expressivity results into results on the pretrained transformers. Here we present three such additional examples (proofs in Section J.4-J.6). The first example is for the sparse linear regression problem considered in Theorem 11.
Suppose each is almost surely an instance of the sparse linear model specified in Theorem 11 with parameters and . Suppose and let .
Then with probability at least (over the training instances ), the solution of Eq. TF-ERM with layers, heads, , and achieves small excess ICL risk:
where only hides polylogarithmic factors in .
Our next example is for the problem of noisy linear regression with mixed noise levels considered in Theorem 17 and Theorem I.0. There, the constructed transformer uses the post-ICL validation mechanism to perform ridge regression with an adaptive regulariation strength depending on the particular input sequence.
Suppose is the data generating model (noisy linear model with mixed noise levels) considered in Theorem I.0, with . Let .
Then, with probability at least (over the training instances ), the solution of Eq. TF-ERM with input dimension , layers, heads, , and achieves small excess ICL risk:
where only hides polylogarithmic factors in .
Our final example is for in-context logistic regression. For simplicity we consider the realizable case.
Suppose for , is almost surely a realizable logistic model (i.e. with as in Corollary 9). Suppose that and .
Then, with probability at least (over the training instances ), the solution of Eq. TF-ERM with layers, heads, , and achieves small excess ICL risk:
where only hides polylogarithmic factors in .
All results above are established by the expressivity results in Section 3 & 4 for transformers to implement various ICL procedures (such as least squares, Lasso, GLM, and ridge regression with in-context algorithm selection), combined with the generalization bound (Theorem 20). However, the transformer itself was not specified to encode any actual structure about the problem at hand in any result above, other than having sufficiently large number of layers, number of heads, and weight norms, which illustrates the flexibility of the transformer architecture.
Experiments
We test our theory by studying the ICL and in-context algorithm selection capabilities of transformers, using the encoder-based architecture in our theoretical constructions (Definition 3). Additional experimental details can be found in Section K.1.
We train a 12-layer transformer, with two modes for the training sequence (instance) distribution . In the “base” mode, similar to , we sample the training instances from one of the following base distributions (tasks), where we first sample by sampling , and then sample as , and from one of the following models studied in Section 3:
Linear model: ;
Noisy linear model: , where is a fixed noise level, and .
Sparse linear model: with , where is a fixed sparsity level, and in this case we sample from a special prior supported on -sparse vectors;
Linear classification model: .
These base tasks have been empirically investigated by Garg et al. , though we remark that our architecture (used in our theory) differs from theirs in several aspects, such as encoder-based architecture instead of decoder-based, and ReLU activation instead of softmax. All experiments use . We choose and for noisy linear regression, and for sparse linear regression, and for linear regression and linear classification.
In the “mixture” mode, is the uniform mixture of two or more base distributions. We consider two representative mixture modes studied in Section 4:
Linear model + linear classification model;
Noisy linear model with four noise levels .
Transformers trained with the mixture mode will be evaluated on multiple base distributions simultaneously. When the base distributions are sufficiently diverse, a transformer performing well on all of them will likely be performing some level of in-context algorithm selection. We evaluate transformers against standard machine learning algorithms in context (for each task respectively) as baselines.
Fig. 4 shows the ICL performance of transformers on five base tasks, within each the transformer is trained on the same task. Transformers match the best baseline algorithm in four out of the five cases, except for the sparse regression task where the Transformer still outperforms least squares and matches Lasso with some choices of (thus utilizing sparsity to some extent). This demonstrates the strong ICL capability of the transformer architecture considered in our theory.
Fig. 4 & 4 examine the in-context algorithm selection capability of transformers, on noisy linear regression with two different noise levels (Fig. 4), and regression + classification (Fig. 4). In both figures, the transformer trained in the mixture mode (TF_alg_select) approaches the best baseline algorithm on both tasks simultaneously. By contrast, transformers trained in the base mode for one of the tasks perform well on that task but behave suboptimally on the other task as expected. The existence of TF_alg_select showcases a single transformer that performs well on multiple tasks simultaneously (and thus has to perform in-context algorithm selection to some extent), supporting our theoretical results in Section 4.
2 Decoder-based architecture & details for Figure 2
ICL capabilities have also been demonstrated in the literature for decoder-based architectures . There, the transformer can do in-context predictions at every token using past tokens as training examples. Here we show that such architectures is also able to perform in-context algorithm selection at every token; For results for this architecture on “base” ICL tasks (such as those considered in Fig. 4), we refer the readers to Garg et al. .
Our setup is the same as the two “mixture” modes (linear model + linear classification model, and noisy linear models with two different noise levels) as in Section 6.1, except that the architecture is GPT-2 following Garg et al. , and the input format is changed to Eq. 15 (so that the input sequence has tokens) without positional encodings. For every , we extract the prediction using a linear read-out function applied on output token , and the (learnable) linear read-out function is the same across all tokens, similar as in Section 6.1. The rest of the setup (optimization, training, and evaluation) is the same as in Section 6.1 & K.1. Note that we also train on the objective Eq. 48 for all tokens averaged, instead of for the last test token as in Section 6.1.
Fig. 2 shows the results for noisy linear models with two different noise levels, and Fig. 5 shows the results for linear model + linear classification model. We observe that at every token, In both cases, TF_alg_select nearly matches the strongest baseline for both tasks simultaneously, whereas transformers trained on a single task perform suboptimally on the other task. Further, this phenomenon consistently shows up at every token. For example, in Fig. 2 & 2, TF_alg_select matches ridge regression with the optimal on all tokens (). In Fig. 5 & 5, TF_alg_select matches least squares on the regression task and logistic regression on the classification task on all tokens . This demonstrates the in-context algorithm selection capabilities of standard decoder-based transformer architectures.
Conclusion
This work shows that transformers can perform complex in-context learning procedures with strong in-context algorithm selection capabilties, by both explicit theoretical constructions and experiments. We believe our work opens up many exciting directions, such as (1) more mechanisms for in-context algorithm selection; (2) Bayes-optimal ICL on other problems by either the post-ICL validation mechanism or new approaches; (3) understanding the internal workings of transformers performing in-context algorithm selection; (4) other mechanisms for implementing complex ICL procedures beyond in-context algorithm selection; (5) further statistical analyses, e.g. of pretraining.
Acknowledgment
The authors would like to thank Tengyu Ma and Jason D. Lee for the many insightful discussions. S. Mei is supported in part by NSF DMS-2210827 and NSF CCF-2315725.
References
Appendix A Technical tools
A.1 Concentration inequalities
Let . Then we have
The following lemma is a standard result of covariance concentration, see e.g. [82, Theorem 4.6.1].
Suppose that are independent -dimensional -sub-Gaussian random vectors. Then as long as , with probability at least we have
A.2 Approximation theory
The following result for expressing smooth functions as a random feature model with relu activation is adapted from Bach [4, Proposition 5].
where is -Lipschitz (in ) in the first argument, and is a signed measure over with finite total measure . Then for any , there exists , with , such that
where denotes the -covering number of in .
Let denote the sign of the density . We have
Note that is the density of a probability distribution over . Thus for any , as long as , we can sample , and obtain by Hoeffding’s inequality that with probability at least ,
Let for shorthand. By union bound, as long as , we have with probability at least that for every in the covering set corresponding to ,
Taking (for which ), by the probabilistic method, there exists a deterministic set and such that the above holds.
Next, note that both (by Eq. 13) and the function are -Lipschitz. Therefore, for any , taking to be the point in the covereing set with , we have
such that .
A.3 Optimization
The following convergence result for minimizing a smooth and strongly convex function is standard from the convex optimization literature, see e.g. Bubeck [13, Theorem 3.10].
The following convergence result of proximal gradient descent (PGD) on convex composite minimization problem is also standard, see e.g. .
A.4 Uniform convergence
The following result is shown in [84, Section 5.6].
Suppose that is a zero-mean random process indexed by such that for some metric on the space . Then it holds that
where is the diameter of the metric space , and the generalized Dudley entropy integral is given by
where is the -covering number of .
As a corollary of Theorem A.0, we have the following result.
Suppose that is a zero-mean random process given by
The index set is equipped with a distance and diameter . Further, assume that for some constant , for any ball of radius in , the covering number admits upper bound for all .
Then with probability at least , it holds that
where is a universal constant, and we denote .
Furthermore, if we replace the in assumption (b) and (c) by , then with probability at least , it holds that
Fix a to be specified later. We pick a -covering of so that . Then, by the standard uniform covering of independent sub-Gaussian random variables, we have with probability at least ,
Assume that . For each , we consider is the ball centered at of radius in . Then has diameter and admits covering number bound . Hence, we can apply Theorem A.0 with the process , then
Therefore, we can let in the above inequality and taking the union bound over , and hence with probability at least , it holds that for all ,
Notice that for each there exists such that , and hence
Thus, with probability at least , it holds
Taking completes the proof of case.
We next consider the case. The idea is the same as the case, but in this case we need to consider the following Orlicz-norm:
Then Bernstein’s inequality of random variables yields
for some universal constant . Therefore, we can repeat the argument above to deduce that with probability at least , it holds
Taking completes the proof. ∎
A.5 Useful properties of transformers
The following result can be obtained immediately by “joining” the attention heads and MLP layers of two single-layer transformers.
Further, has at most heads, hidden dimension in its MLP layer, and norm bound .
When ( and have the same number of layers), the result follows directly by applying Proposition A.0 repeatedly for all layers and the definition of the norm Eq. 2.
If (without loss of generality) , we can augment to layers by adding layers with zero attention heads, and zero MLP hidden dimension (note that this does not change , , and ). Due to the residual structure, the transformer maintains the output throughout layer , and it reduces to the case . ∎
Appendix B Extension to decoder-based architecture
Decoder TFs are the same as encoder TFs, except that the attention layers are replaced by masked attention layers with a specific decoder-based (causal) attention mask.
Notice that standard masked attention definitions use the pre-activation additive masks (with mask value ) . The post-activation multiplicative masks we use is equivalent to the pre-activation additive masks, and the modified presentation is for notational convenience. We also use a normalized ReLU activation in place of the standard softmax activation to be consistent with Definition 1. Note that the normalization is to ensure that the attention weights is a set of non-negative weights that sum to . The motivation of masked attention layer is to ensure that, when processing a sequence of tokens, the computations at any token do not see any later token.
We next define the decoder-based transformers with transformer layers, each consisting of a masked attention layer (c.f. Definition B.0) followed by an MLP layer (c.f. Definition 2). This definition is similar to the definition of encoder-based transformers (c.f., Definition 3), except that we replace the attention layers by masked attention layers.
We also use Eq. 2 to define the norm of .
B.2 In-context learning with decoder-based transformers
Eq. 15 is different from out input format Eq. 3 for encoder-based TFs. The main difference is that are in different tokens in (15), whereas are in the same token in (3). The reason for the former (i.e., different tokens in decoder) is that we want to avoid every token seeing the information of , since we will evaluate the loss at every token. The reason for the latter (i.e., the same token in encoder) is for presentation convenience: since we only evaluate the loss at the last token, it is not necessary to alternate between and to avoid information leakage.
B.3 Results
We discuss how our theoretical results upon encoder TFs can be converted to those of the decoder TFs. Taking the implementation of (ICGD) (a key mechanism that enables most basic ICL algorithms such as ridge regression; cf. Section 3.5) as an example, this conversion is enabled by the following facts: (a) the input format (15) of decoders can be converted to the input format (3) of encoders by a 2-layer decoder TF; (b) the encoder TF that implements (ICGD) with input format (3), by a slight parameter modification, can be converted to a decoder TF that implements the (ICGD) algorithm with a converted input format.
Despite the difference between the input format (15) and (3), we show that there exists a 2-layer decoder TF that can convert the input format (15) to format (3). The proof can be found in Section B.4.
There exists a 2-layer decoder TF with heads per layer, hidden dimension and such that upon taking input of format (15), it outputs with
In particular, format Eq. 16 contains format Eq. 3 as a submatrix, by restricting to the rows and columns.
The construction in Theorem 13 can be generalized to using the input format Eq. 16 along with a decoder TF, by using the scratch pad within the last token to record the gradient descent iterates. Further, if we slightly change the normalization in from to , then the same construction performs Eq. ICGD (with training examples ) at every token (corresponding to predicting at ). Building on this extension, all our constructions in Section 3 and Section 4.2 can be generalized to decoder TFs.
B.4 Proof of Proposition B.0
In the following, we construct the desired as follows.
for all . By the structure of , these matrices indeed exist, and further it is straightforward to check that they have norm bounds
Notice that only when , we then compute for that
for all . By the structure of , these matrices indeed exist, and further it is straightforward to check that they have norm bounds
where the last equality follows from the fact that
Finally, we only need to take a MLP layer with hidden dimension 2 that maps
Combining the two steps above, we complete the proof of Proposition B.0. ∎
Appendix C Proofs for Section 3.5 and additional results
The definition above captures the proximal operator for a broad class of regularizers, such as the (commonly-used) and regularizer listed in the following proposition, for all of which one can directly check that they can be exactly implemented by an MLP as stated below.
For , is -approximable by MLP.
For , is -approximable by MLP.
Fix any , , , and . Suppose that
convex, and the proximal operator is -approximable by MLP with .
approximately implements Eq. ICGD:
(Prediction space) The final output approximates the prediction of steps of Eq. ICGD: We have , where so that
Further, the weight matrices have norm bounds .
The proof of Theorem C.0 is essentially similar to the proof of Theorem 13, using the following generalized version of Lemma 14.
The proof of the above lemma is done by utilizing the non-expansiveness of the PGD operator and otherwise following the same arguments as for Lemma 14.
C.2 Approximating a single GD step
Then, for any , there exists an attention layer with heads such that, for any input sequence that takes form with , it gives output for all , where
Further, .
for all . As the input has structure , these matrices indeed exist, and further it is straightforward to check that they have norm bounds
Consequently, .
where the last equality follows from the bound
so that the above relu equals if . Therefore,
Thus letting the attention layer , we have
C.3 Proof of Theorem 13
We first prove part (a), which requires constructing the first layers of . Note that by our precondition .
We now prove part (b), which requires constructing the last attention layer . Recall for all . We construct a 2-head attention layer such that for every ,
Note that the weight matrices have norm bound
Above, (i) uses the identity . Further by part (a) we have
This proves part (b), and also finishes the proof Theorem 13 where the overall -layer attention-only transformer is given by with
C.4 Proof of Lemma 14
As is a convex, smooth function on , the mapping is non-expansive in : Indeed, for any we have
Above, (i) uses the property for smooth convex functions [60, Theorem 2.1.5]; (ii) uses the precondition that .
The lemma then follows directly by induction on . The base case of follows directly by assumption that . Suppose the claim holds for iterate . For iterate , we have
Above, (i) uses the non-expansiveness, and (ii) uses the inductive hypothesis. Similarly, by our assumption ,
Further, the transformer admits norm bound
Appendix D Proofs for Section 3.1
Fix , with , and , and consider any in-context data such that the precondition of Theorem 4 holds. Let
Consider the gradient descent algorithm on the ridge loss
with initialization, learning rate, and number of steps
By standard convergence results for strongly convex and smooth functions (Proposition A.0), we have for all that
Combining Eq. 18 and Eq. 19, we obtain that
Further, we have for all , where (cf. Corollary C.0), so that as shown above. This finishes the proof. ∎
D.2 Statistical analysis of in-context least squares
denote the expected risk of over a new test example .
and almost surely;
The whitened vector is -sub-Gaussian for some .
Further, we say is well-posed with canonical parameters if
where and only hides absolute constants.
The following result bounds the excess risk of least squares under Assumption with a clipping operation on the predictor; the clipping allows the result to only depend on the second moment of the noise (cf. Assumption(5)) instead of e.g. its sub-Gaussianity, and also makes the result convenient to be directly translated to a result for transformers.
Suppose distribution satisfies Assumption. Then as long as , we have the following:
The (clipped) least squares predictor achieves small expected excess risk (fast rate) over the best linear predictor: For any clipping radius ,
We have , where
We first show . Let , and let the whitened covariance and noise variables be denoted as
Also let denote the “noise” variables. Note that
Setting ensures that the right-hand side above is at most , on which event we have
i.e. holds. This shows that .
Next, we show Eq. 21. Using , we decompose the risk as
Above, (i) follows by conditioning on and using Assumption(5). Combining with Eq. 25, we obtain
Therefore, using an argument similar to Chebyshev’s inequality,
D.3 Proof of Corollary 5
The proof follows by first checking the well-conditionedness of the data (cf. Eq. 5) with high probability, then invoking Theorem 4 (for approximation least squares) and Proposition D.0 (for the statistical power of least squares).
First, as satisfies Assumption, by Proposition D.0, as long as , we have with probability at least that event holds. On this event, we have
and thus the dataset is well-conditioned (in the sense of Eq. 5) with parameters , , and defined as above. Note that the condition number of is upper bounded by , where is the upper bound on the condition number of as in Assumption(c).
Note that by the above choice of .
such that on (so that is well-conditioned), we have (choosing the clipping radius in to be ):
We now bound the excess risk of the above transformer. Combining Proposition D.0 and Eq. 29, we have
Above, (i) uses the approximation guarantee Eq. 29 as well as Proposition D.0(a) (with clipping radius ). This proves the desired excess risk guarantee.
Finally, under the canonical choice of parameters Eq. 20, the bounds for simplify to
and the requirement for simplifies to (as ). This proves the claim about the required and . ∎
D.4 Proof of Corollary 6
Fix parameters to be specified later and a large universal constant . Let us set
and we define . Under the event , the problem (ICRidge) is well-conditioned and (by Lemma D.0).
Therefore, Theorem 4 implies that for , there exists a -layer transformer with prediction (clipped by ), such that under the good event , we have and .
In the following, we show that is indeed the desired transformer (when and is suitably chosen). Notice that we have
and we analyze these two parts separately.
where the inequality is because under the good event . Notice that by our construction, under the good event , depends only on the dataset We need this, as on , the transformer output at this location could in principle depend additionally on , as Eq. 17 may not hold due to the potential unbounededness of its input. A similar fact will also appear in later proofs (for generalized linear models and Lasso).. Therefore, we have as long as the event holds for . Thus, under ,
Combining the inequalities above, we have
Therefore, it suffices to take for some small constant , then as long as
our choice of and is feasible. Note that , and hence under such choice of , we have and . This is the desired result. ∎
Under the event , we have \big{\|}{\mathbf{w}}_{\rm ridge}^{\lambda}\big{\|}_{2}\leq\mathcal{O}\left(B_{w}^{\star}+\sigma\right).
By the definition of and recall that , we have .
Therefore, we only need to prove the following fact: for any and , we have
Appendix E Proofs for Section 3.2
We begin by stating our assumptions on the well-posedness of the generalized linear models.
We assume that there is some such that for any , .
We also assume that for each , is independently sampled from such that the following holds.
Under the law , We have , and .
For , it holds .
Let us fix parameters and (that we specify later in proof).
Define and
By Proposition A.0, is with
Therefore, we can invoke Theorem 13 to obtain that, as long as , there exists a -layer attention-only transformer with heads per layer, such that for any input of format (3) and satisfies (7), its last layer outputs , such that
Furthermore, we can show that (similar to the proof of Theorem 13 (b)), there exists a single attention layer with heads such that it outputs , where .
In the following, we show that for suitably chosen , is the desired transformer. First notice that its output satisfies
Therefore, for any fixed , we can take
so that the we construct above ensures for any input that satisfies (7). The upper bound on follows immediately from Theorem 13. ∎
E.2 Proof of Theorem 8
We summarize some basic and useful facts about GLM in the following theorem. Its proof is presented in Section E.3 - E.6.
Under Assumption Assumption, the following statements hold with universal constant and constant that depend only on the parameters .
(a) As long as , the following event happens with probability at least :
(b) For any , we have with probability at least that
where we denote .
(c) Condition on (a) holds and , the event happens with probability at least .
(d) For any , it holds that
(e) (Realizable setting) As long as , it holds that
Under the event and our choice of , the problem (ICGLM) is well-conditioned (i.e. (7) holds).
Theorem 7 implies that there exists a transformer such that for any input of the form (3), outputs , such that the output is given by and , and the following holds on the good event :
, where is a predictor such that for all .
depends only on (by the proof of Theorem 7 and Theorem 13), such that \big{\|}\nabla\widehat{L}_{N}(\widetilde{{\mathbf{w}}})\big{\|}_{2}\leq\frac{\beta\varepsilon}{L_{g}B_{w}}.
In the following, we show that constructed above fulfills both (a) & (b) of Theorem 8. The bounds on number of layers and heads and follows from plugging our choice of in our proof of Theorem 7.
Proof of Theorem 8 (a). Notice that under the good event , we have depends only on . Then we have
Thus, we can consider , and then
and by Theorem E.0 (b) and taking integration over , we have
Taking completes the proof. ∎
Proof of Theorem 8 (b). Similar to the proof of Corollary 6, we have
where the inequality follows from on event . For the first part, we have
where we use the fact that the conditional distribution of agrees with . Thus,
Taking completes the proof. ∎
Suppose that , , and is a (possibly random) vector such that . Then
E.3 Proof of Theorem E.0 (a)
We begin with the upper bound on . By Lemma A.0, as long as , the following event
In the following, we analyze the quantity . We have to invoke the following covering argument (see e.g. [82, Section 4.1.1]).
Therefore, we can define (which is a -Lipschitz function), and we have
By our definition of , we have (for any fixed )
(a) With norm , with constant ;
(b) Let , then and hence in for any random ;
(c) For , we have . Hence, because , the random variable is , and the random variable is .
Therefore, we can apply Proposition A.0 to obtain that with probability , it holds
where we denote . Setting and taking the union bound over , we obtain that with probability at least ,
where we use . Therefore, we plug in the definition of and to deduce that, if we set
Under Assumption, for , it holds
Because , , and a simple calculation yields
E.4 Proof of Theorem E.0 (b)
(a) With norm , with constant ;
(b) For , we let , then for any by our assumption on ;
(c) For , we have . Hence, because , the random variable is sub-Gaussian in . Thus, is sub-exponential in .
Therefore, we can apply Proposition A.0 to obtain that with probability , it holds
where we denote . Setting and taking the union bound over , we obtain that with probability at least ,
E.5 Proof of Theorem E.0 (c)
In the following, we condition on (a) holds, i.e. is -strongly-convex and smooth over with and . We define
Then by standard convex analysis, we have
so that as long as , the event holds with probability at least . This is the desired result. ∎
E.6 Proof of Theorem E.0 (d) & (e)
We first prove Theorem E.0 (d). Notice that
Therefore, is -strongly-convex over . Therefore, because is the global minimum of , it holds that for all ,
On the other hand, by the -strong-convexity of over , it holds that
Appendix F Proofs for Section 3.3
Fix , and , and consider any in-context data such that the precondition of Theorem 10 holds. Recall that
Consider the proximal gradient descent algorithm on the ridge loss
By the standard convergence result for proximal gradient descent (Proposition A.0), we have for all that
F.2 Sharper convergence analysis of proximal gradient descent for Lasso
Throughout the rest of this section, we consider fixed , for , fixed (and to be determined), fixed , and fixed . We write , and .
We say the Eq. ICLasso problem is well-conditioned with sparsity if the following conditions hold:
Further, .
It holds that (i.e. ).
The proof can be found in Section F.4. Combining Theorem F.0 with the construction in Theorem 10, we directly obtain the following result as a corollary.
For any , , , , there exists a -layer transformer with
F.3 Basic properties for Lasso
Suppose that Assumption2 holds. Then it holds that
where the second inequality follows from and our assumption that , and the last inequality is due to . Therefore, we have
We follow the notation in the proof of Lemma F.0. By (33), we have
where the last inequality uses AM-GM inequality and Cauchy inequality. Notice that , we now derive that
where we write . Then by the convexity of , we have
F.4 Proof of Theorem F.0
By Lemma F.0, we have , which implies
We denote . Using the assumption that is -RSC, we obtain that
Thus, as long as , we have
where the last inequality follows from Lemma F.0 and the definition of .
Then for all , we have (the second below uses Proposition A.0(2))
where the last inequality follows from Proposition A.0(2). Further, by Proposition A.0(3), we have
Hence, we can conclude that for all such that
F.5 Proof of Theorem 11
In this section, we present the proof of Theorem 11 based on Theorem F.0. We begin by recalling the following RSC property of a Gaussian random matrix [84, Theorem 7.16], a classical result in the high-dimensional statistics literature.
where is the maximum of diagonal entries of .
Fix a parameter (which we will specify in proof) and a large universal constant . Let us set
Similar to the proof of Corollary 6 (Section D.4), we consider the following good events (where )
and we define .
Furthermore, we choose that correspond to the choice , and we also assume . Then, Assumption holds on the event .
Therefore, we can apply Theorem F.0 with , which implies that there exists a -layer transformer such that its prediction , so that under the good event we have , where
In the following, we show that is indeed the desired transformer (similarly to the proof in Section D.4). Consider the conditional prediction error
and we analyze these two parts separately under the good event of .
where the inequality is because under the good event . Notice that by our construction, under the good event , depends only on the dataset (because it is the -th iterate of PGD on (ICLasso) problem). Applying Proposition F.0 to and using the definition of and our choice of , we obtain that (under )
Notice that under good event , the bad event holds if and only if holds, and hence
where the last inequality is because the marginal distribution of is simply . Combining these yields
Therefore, choosing is enough for our purpose, and under such choice of ,
Combining the inequalities above, we can conclude that under ,
We also remark that in the construction above,
which would be useful for bounding .
Appendix G Gradient descent on two-layer neural networks
We now move beyond the convex setting by showing that transformers can implement gradient descent on two-layer neural networks in context.
where is a bounded domain. For the sake of simplicity, in the following discussion we assume that can be exactly implemented by a MLP layer (e.g. for some ).
Fix any , , , and . Suppose that
Then there exists a -layer transformer with
where denotes the smoothness of within .
denote the gradient mapping at with step size , a standard measure of stationarity in constrained optimization . Note that when (so that the projection does not take effect).
As long as , for all ,
G.1 Proof of Theorem G.0
We only need to prove the following single-step version of Theorem G.0.
Before we present the formal (and technical) proof of Proposition G.0, we first provide some intuitions. To begin with, we first note that
Based on the observations above, we now present the proof of Proposition G.0.
We write be the length of the vector . We also define
The function is for , , where depends only on and the -smoothness of . Therefore, there exists
such that .
The function is for , , where depends only on and the -smoothness of . Therefore, there exists
such that .
In the following, we proceed to construct the desired transformer step by step.
Step 1: construction of . We consider the matrices so that for all , we have
As the input has structure , these matrices indeed exist, and further it is straightforward to check that they have norm bounds
Step 2: construction of . We pick matrices so that maps
By the definition of the function , for each ,
Step 3: construction of . We consider the matrices so that for all , we have
We further consider the matrices so that for all , we have
By the structure of the input , these matrices indeed exist, and further it is straightforward to check that they have norm bounds
Furthermore, a simple calculation shows that
where the summation is taken over all possibilities of the tuple , i.e. over the union of and .
By our definition, we have for all . Therefore, for each , ,
where is the upper bound of . Similarly, for each , , we have
As for the case , we have and for each by defintion. Combining these estimations and using (37) and (38), we can conclude that
Thus, letting the attention layer , we have
Step 4: construction of . We only need to pick so that it maps
By our assumption on the map , this is easy.
Combining the four steps above and taking completes the proof. ∎
G.2 Proof of Lemma G.0
Above, (i) uses the inequality ; (ii) uses the fact that projection to a convex set is a non-expansion; (iii) uses the definition of the gradient mapping.
By the -smoothness of within , we have
Dividing both sides by yields part (a).
Next, we prove part (b). Let . We prove by induction that
Appendix H Proofs for Section 4
We begin by restating Proposition 15 into the following version, which contains additional size bounds on .
To prove Theorem H.0, we first state and prove the following two propositions.
There exists a 1-layer transformer with heads and such that for all such that , maps
where is a functional such that .
where the last equality follows from the bound , so that the above relu equals if . Therefore, for each and ,
Thus letting the attention layer , we have
There exists a 3-layer transformer with
We construct a which is a composition of 2 MLP layers followed by an attention layer .
Step 1: construction of . We consider matrix that maps
Step 2: construction of . We consider matrix that maps
where . Clearly, , and if and only if .
Step 3: construction of . We define
Clearly, , and . Further,
Therefore, it remains to construct that implements based on . Notice that
for all , where we understand and is the -dimensional vector with all entries being 1. By the structure of , these matrices indeed exist, and further it is straightforward to check that they have norm bounds
Now, for every , , we have
where the last equality follows from . Therefore,
where the last equality is due to (42). Thus letting the attention layer , we have
for any input of the form described in Theorem H.0, and is a functional such that .
Next, by the proof of Proposition H.0, there exists that maps
where and only when . Using the fact that , we deduce that is supported on .
Therefore, is the desired transformer, with
H.2 Proof of Theorem 16
We first restate Theorem 16 into the following version which provides additional size bounds for . For the simplicity of presentation, throughout this subsection and Appendix I, we denote , , to be the input matrix corresponding to the training split only, and , .
For any sequence of regularizations , with , , , and , suppose in input format Eq. 3 we have . Then there exists an -layer transformer with
such that the following holds. On any input data such that the problem Eq. ICRidge is well-conditioned and has a bounded solution:
approximately implements ridge selection: its prediction
For each , approximates the ridge estimator , i.e. \big{\|}\widehat{{\mathbf{w}}}_{k}-{\mathbf{w}}_{\rm ridge}^{\lambda_{k}}(\mathcal{D}_{{\sf train}})\big{\|}_{2}\leq\varepsilon.
so that
In particular, if we set , then it holds thatThis is because is -Lipschitz w.r.t. .
where we denote .
To prove Theorem H.0, we first show that, for the squared validation loss, there exists a 3-layer transformer that performs predictor selection based on the exactly evaluated for each . (Proof in Section H.2.1.)
Then there exists a 3-layer transformer with
such that for any input that takes form
Proof of Theorem H.0 First, by the proofTechnically, an adapted version where the underlying ICGD mechanism operates on the training split (with ) with size instead of on all training examples, which only changes by at most a constant factor, and does not change the number of layers and heads. of Theorem 4 and Proposition A.0, for each , there exists a layer transformer such that maps
so that if (43) holds, we have \big{\|}\widehat{{\mathbf{w}}}_{k}-{\mathbf{w}}_{\rm ridge}^{\lambda_{k}}\big{\|}_{2}\leq\varepsilon and .
Next, by Theorem H.0, there exists a 3-layer transformer that outputs
where , so that
Similar to the proof of Proposition 15, Theorem H.0 is a direct corollary by combining Proposition H.0 with Proposition H.0.
There exists an attention layer with heads and such that maps
As the input has structure , these matrices indeed exist, and further it is straightforward to check that they have norm bounds
where the second equality follows from the bound , so that the relus equals if . Thus letting the attention layer , we have
H.3 Proofs for Section 4.2
with , . We can thus construct an attention layer with heads such that
Further, we have . This is the desired result. ∎
By composing the above attention layer with one additional layer (with 2 heads) that implement the following function
on the output , we directly obtain the following corollary.
at every token , where we recall the definition of in Lemma 18.
H.3.2 Formal statement and proof of Proposition 19
for all . A sufficient condition is that the density is upper bounded by within .
Throughout this section, let denote the sigmoid activation, and let denote the solution to the in-context logistic regression problem, i.e. Eq. ICGLM with .
For any , , with , and any , there exists a -layer attention-only transformer with
(with , and depending only on ) such that the following holds. Suppose the input format is Eq. 3 with dimension .
On any classification instance (such that ) that is well-conditioned for logistic regression in the sense of Eq. 7, it outputs that -approximates the prediction of in-context logistic regression:
On the contrary, for regression problems, i.e. any in-context distribution whose marginal is -not-concentrated around , with probability at least over (where depends only on ), -approximates the prediction of in-context least squares if the data is well-conditioned:
where denotes the in-context least squares estimator, i.e. Eq. ICRidge with .
The result follows by combining the binary test in Corollary H.0 with Theorem 4 and Theorem 7. By those results, there exists three attention-only transformers , with (below for )
that outputs prediction , (at the -th token) and (at every token) respectively, which satisfy
when the corresponding well-conditionednesses are satisfied. In particular, we can make well-defined on non-binary data, by multiplying onto the ’s (which can be implemented by slightly modifying without changing the order of the number of layers, heads, and norms) so that on any data where .
By joining and using Proposition A.0, concatenating with before, and concatenating with one additional attention layer with 2 heads after to implement
we obtain a single transformer with
which outputs Eq. 45 as its prediction (at the location for ).
It remains to show that Eq. 45 reduces to either one of or . When the data are binary (), we have and , in which case Eq. 45 becomes exactly . By contrast, when data is sampled from a distribution that is -not-concentrated around , we have for any fixed that, letting and , by Hoeffding’s inequality,
where is an absolute constant. On the event (which happens with probability at least ), Eq. 45 becomes exactly . This finishes the proof. ∎
H.4 Linear correlation test and application
For any fixed parameters , consider the linear correlation test over data defined as
We show that can be exactly implemented by a 3-layer transformer.
There exists a 3-layer attention-only transformer with at most heads per layer and such that on input sequence of the form Eq. 3 with , the transformer exactly implements : it outputs such that for all .
We begin by noting the following basic facts:
Identity function can be implemented exactly by two ReLUs: .
We construct the transformer as follows.
Layer 1: Use 2 heads to implement , where , , and (where we recall and note that corresponds exactly to the location for in , cf. Eq. 3). By manipulating the output dimension in , write the result into blank memory space with dimension at every token .
Layer 2: Use a single head to compute : , , and . By manipulating the output dimension in , write the result into blank memory space with dimension 1 at every token . After layer 2, we have .
Layer 3: Use 2 heads to implement two ReLU functions with bias: . The two query (or key) matrices contain values and . In our problem we take
so that the above ReLU function implements exactly. Write the result into a blank memory space with dimension 1. We finish the proof by noting that . ∎
We consider the following well-posedness assumption for the linear correlation test . Note that, similar as Assumption, the assumption does not require the data to be generated from any true linear model, but rather only requires some properties about the best linear fit , as well as sub-Gaussianity conditions.
and almost surely;
The whitened vector is -sub-Gaussian for some .
The label is -sub-Gaussian.
The residual is -sub-Gaussian with probability one (over ).
The following results states that achieves high power as long as the sample size is high enough, and the signal is either sufficiently high or sufficiently low.
Suppose distribution satisfies Assumption with parameters . Then, for the linear correlation test with parameters with and any , we have
If , then with probability at least over , we have .
If , then with probability at least over , we have .
The proof is finished by recalling the definition of in Eq. 46, so that if , and if . ∎
By directly composing the linear correlation test in Lemma H.0 with the transformer construction in Corollary 5 (using an argument similar as the proof of Proposition H.0), and using the power of the linear correlation test Proposition H.0, we immediately obtain the following result, which outputs a prediction from (approximately) least squares if , and abstains from predicting if . This can be viewed as a form of “confident linear regression”, where the model predicts only if it thinks the linear signal is strong enough.
For any , , , , with , there exists a -layer attention-only transformer with
(with ) such that the following holds. Let . Suppose the input format is Eq. 3 with dimension . Let ICL instance be drawn from any distribution satisfying Assumption. Then the transformer outputs a 2-dimensional prediction (within the test token )
If , then with probability at least over , we have , and if is in addition well-conditioned for least squares (in the sense of Eq. 5 with ).
If , then with probability at least over , we have and .
Appendix I Proof of Theorem 17: Noisy linear model with mixed noise levels
Suppose that and we write . Suppose in input format Eq. 3 we have . Then there exists a transformer with
such that for any , it holds that
if we choose .
The core of the proof of Theorem I.0 is to show that any estimator that achieves small validation loss must achieve small population loss.
Throughout the rest of this section, recall that we define , , , and .
Fix parameters and a large universal constant . Let us set
Then, we define good events similarly to the proof of Corollary 6 (Section D.4):
For the ridge and parameters , we consider the transformer constructed in Theorem H.0, with a clipped prediction .
and we analyze these two parts separately.
Recall that by our construction, when holds, we have and the statements of Theorem H.0 hold for . Thus, we have
Let us consider the following risk functional
Then, under the good event of ,
By our construction, under the good event , we have
where \big{\|}\widehat{{\mathbf{w}}}_{l}(\mathcal{D}_{{\sf train}}))-{\mathbf{w}}^{\lambda_{l}}_{\rm ridge}(\mathcal{D}_{{\sf train}})\big{\|}_{2}\leq\varepsilon for each . Clearly,
We next deal with the term . Note that for the good event of , we have
Therefore, we can choose so that as
It is worth noting that such choice of is feasible as long as . Under such choice, we obtain
Similar to the proof of Corollary 6, we have
I.2 Derivation of the exact Bayes predictor
Let be observations from the data generating model considered in Section 4.1.1. On observing , the Bayes predictor of is given by its posterior mean:
(Note that the sample covariance within is not normalized by , which is not to be confused with remaining parts within the paper.) Therefore, the posterior mean Eq. 47 is exactly a weighted combination of ridge regression estimators, each with regularization .
Note that such mixing weights involve the determinant of the matrix , which depends on the data in a non-trivial fashion; Any transformer has to approximate these weights if their mechanism is to directly approximate the exact Bayesian predictor Eq. 47.
I.3 Useful lemmas
We denote , then by definition (with ). Thus, a simple calculation yields
where in the above inequality we denote and use the following fact:
Case 1. We first suppose that . Then by definition , and hence
Combining these two cases finishes the proof. ∎
Condition on the event , we have
where we denote .
We only need to work with a fixed pair of such that holds. Hence, in the following we only consider the randomness of conditional on such a .
Note that under , we have for all , and hence . We then have ’s are (conditional) i.i.d random variables in . Then, by Bernstein’s inequality, we have
where is a universal constant. Applying the union bound, we obtain
Taking integration completes the proof. ∎
I.4 Generalized linear models with adaptive link function selection
For any and any distribution that is a generalized linear model of the link function and some parameter , if Assumption Assumption holds for each pair , then
For each , we consider optimizing the following training loss:
Fix a large universal constant . Let us set
Then, we define good events similarly to the proof of Corollary 6 (Section D.4):
Similar to the proof of Theorem 8 (Section E.2), we know the good event holds with high probability: .
Similar to the proof of Theorem H.0, we can show that there exists a transformer with prediction (clipped by ), such that (for any ) the following holds under :
For each , is a predictor such that for all (where is chosen as in Section E.2).
, where is an aggregated predictor given by , such that is a distribution supported on such that
Similar to the proof of Theorem 8, for , we have
For the first term, repeating the argument in the proof of Theorem 8 directly yields that for ,
For the second term, similar to Lemma I.0, we can show that conditional on such that holds, it holds
Combining these inequalities and suitably choosing complete the proof. ∎
Appendix J Proofs for Section 5
For any , let denote the column-wise -norm of . For any radius , we denote be the ball of radius under norm .
For a single MLP layer , we introduce its norm (as in (2))
For any fixed hidden dimension , we consider
Then for , , the function is -Lipschitz w.r.t. and -Lipschitz w.r.t. .
Now, for , we consider
Clearly . For any , we have
where the second inequality uses the definition of operator norm, the third inequality follows from the triangle inequality, the forth inequality is because , and is 1-Lipschitz. This completes the proof the Lipschitzness w.r.t. .
Similarly, we consider , and
where the last inequality uses and the AM-GM inequality. This completes the proof the Lipschitzness w.r.t. . ∎
For a fixed number of heads and hidden dimension , we consider
Then for the function given by
is -Lipschitz w.r.t and -Lipschitz w.r.t. , where and .
For any , , and , we have
where the second inequality follows from Lemma J.0 and Lemma J.0 and the fact that for all .
Furthermore, for , we have
which also follows from Lemma J.0 and Lemma J.0. ∎
For a fixed number of heads and hidden dimension , we consider
Then the function is -Lipschitz w.r.t for any fixed .
For , we have
where the second inequality follows from Corollary J.0, and the last inequality is because . ∎
J.2 Proof of Theorem 20
In this section, we prove a slightly more general result by considering the general ICL loss
where are i.i.d copies of . It remains to apply Proposition A.0 to the random process . We verify the preconditions:
(a) By [84, Example 5.8], it holds that , where is any ball of radius under norm .
Therefore, we can apply the uniform concentration result in Proposition A.0 to obtain that, with probability at least ,
J.3 Proof of Theorem 21
By Corollary 5, there exists a transformer such that for every satisfying Assumption with canonical parameters (and thus in expectation over ) and every , it outputs prediction such that
We can thus apply Theorem 20 to obtain that the solution to Eq. TF-ERM with the above choice of and (attention-only) satisfies the following with probability at least :
Above, . This finishes the proof. ∎
J.4 Proof of Theorem 22
We invoke Theorem 11 (using the construction in Theorem 10 with a different choice of ) with the following parameters:
where hides polylogarithmic factors in .
By inspecting the proof, the same result holds if we change to the clipped version if we choose , so that on the good event considered therein, all intermediate outputs within has and thus the clipping does not modify the transformer output on the good event. On the bad event , using the same argument as in the proof of Theorem 11, we have
Combining the above two bounds and further taking expectation over gives
We can thus apply Theorem 20 to obtain that the solution to Eq. TF-ERM with the above choice of satisfies the following with probability at least :
Above, . This finishes the proof. ∎
J.5 Proof of Theorem 23
We invoke Theorem 17 and Theorem I.0, which shows that (recalling the input dimension ) there exists a transformer with the following size bounds:
such that it outputs that satisfies
By inspecting the proof, the same result holds if we change to the clipped version if we choose , so that on the good event considered therein, all intermediate outputs within has and thus the clipping does not modify the transformer output on the good event. Using this clipping radius, we obtain
We can thus apply Theorem 20 to obtain that the solution to Eq. TF-ERM with the above choice of satisfies the following with probability at least :
Above, . This finishes the proof. ∎
J.6 Proof of Theorem 24
The proof follows from similar arguments as of Theorem 22 and Theorem 23, where we plug in the size bounds (number of layers, heads, and weight norms) from Theorem 8 and Corollary 9. ∎
Appendix K Experimental details
We train a 12-layer encoder-only transformer, where each layer consists of an attention layer as in Definition 1 with heads, hidden dimension , and ReLU activation (normalized by the sequence length), as well as an MLP layer as in Definition 2 hidden dimension . We add Layer Normalization after each attention and MLP layer to help optimization, as in standard implementations . We append linear read-in layer and linear read-out layer before and after the transformer respectively, both applying a same affine transform to all tokens in the sequence and are trainable. The read-in layer maps any input vector to a -dimensional hidden state, and the read-out layer maps a -dimensional hidden state to a 1-dimensional scalar.
For the sparse linear regression experiment, we find that minimizing the training objective Eq. 48 alone was not enough, e.g. for the learned transformer to achieve better loss than the least squares algorithm (which achieves much higher test loss than the Lasso; cf. Fig. 4). To help optimization, we augment Eq. 48 with another loss that encourages the second-to-last hidden states to recover the true (sparse) coefficient :
Specifically, the above loss encourages the first tokens within the second-to-last layer to be close to . We choose (recall that the total number of tokens is and sequence length is for this experiment). We minimize the loss with for 2M steps for this task.
All evaluations are done on the trained transformer with 6400 test instances. We use the square loss for regression tasks, and the classification error (accuracy) between the true label and the predicted label . We report the means in all experiments, as well as their standard deviations (using one-std error bars) in Fig. 2, 2, 5, 5. In Fig. 2, 4, 4 5, all standard deviations are sufficiently small (not significantly exceeding the width of the markers), thus we did not show error bars in those plots.
We implement various baseline machine learning algorithms to compare with the learned transformers. A superset of the algorithms is shown in Fig. 4:
Least squares, Logistic regression: Standard algorithms for linear regression and linear classification, respectively. Note that least squares is also a valid algorithm for classification.
Averaging: The simple algorithm which computes the linear predictor and predicts ;
Ridge: Standard ridge regression as in Eq. ICRidge. We specifically consider two ’s (denoted as lam_1 and lam_2): . These are the Bayes-optimal regularization strengths for the noise levels respectively under the noisy linear model (cf. Corollary 6), using the formula , with .
Lasso: Standard Lasso as in Eq. ICLasso with .
In Fig. 2, the ridge_analytical curve plots the expected risk of ridge regression under the noisy linear model over 20 geometrically spaced values of ’s in between , using analytical formulae (with Monte Carlo simulations). The Bayes_err_{1,2} indicate the expected risks of on task 1 (with noise ) and on task 2 (with noise ), respectively.
K.2 Computational resource
All our experiments are performed on 8 Nvidia Tesla A100 GPUs (40GB memory). The total GPU time is approximately 5 days (on 8 GPUs), with the largest individual training run taking about a single day on a single GPU.