Manuscript Offprint
arXiv:2610.07754Adversarially Trained Linear Transformers Are Optimal Robust In-Context Learners for Gaussian Mixtures
ABSTRACT
Adversarial training is one of the most reliable defenses against adversarial attacks, but its high computational cost must generally be paid anew for each task. Robust foundation models offer a promising alternative: adversarially pretrain a model once and then transfer its robustness to downstream tasks through lightweight adaptation. However, a fundamental question remains open: can robustness acquired during pretraining transfer to unseen tasks without further adversarial training? In this study, we answer this question affirmatively. A single model adversarially pretrained at scale can achieve optimal robustness on new tasks without additional task-specific training. Specifically, we show that, for a family of Gaussian-mixture classification tasks, a sufficiently deep linear transformer adversarially trained across tasks can asymptotically attain the robust Bayes error on previously unseen tasks through in-context learning from clean demonstrations. By contrast, a standardly trained model cannot. We further analyze convergence under gradient flow, an accuracy–robustness trade-off, and demonstration complexity.
1 INTRODUCTION
Adversarial examples, inputs that are slightly perturbed to cause machine learning models to make incorrect predictions, expose a fundamental vulnerability of deep learning systems (Szegedy et al., 2014). Adversarial training is one of the most reliable defenses against adversarial attacks (Goodfellow et al., 2015; Madry et al., 2018). It improves robustness by minimizing the loss under worst-case perturbations. However, the resulting min-max optimization makes adversarial training substantially more expensive than standard training. While many cheaper defenses have been proposed, some offer only apparent robustness that disappears under stronger attacks (Carlini & Wagner, 2017a;b; Athalye et al., 2018; Croce & Hein, 2020; Tramer et al., 2020). Consequently, obtaining reliable robustness generally requires paying the cost of adversarial training anew for each task.
Meanwhile, foundation models have transformed how models are developed and deployed. Rather than training a separate model for each task, practitioners pretrain a single model at scale and adapt it to downstream tasks using lightweight methods. This paradigm suggests a compelling possibility: robust foundation models. Adversarial training would be performed only once during pretraining, and the resulting robustness could then be transferred to downstream tasks at little additional cost. Although adversarial pretraining incurs an initial cost, model developers (typically large organizations) could recoup it by licensing the model. The fundamental question here is: Can an adversarially pretrained model adapt to unseen downstream tasks while retaining robustness, without further adversarial training?
Kumano et al. (2026) provided the first theoretical evidence that such transfer might be possible. They showed that an adversarially pretrained single-layer transformer with linear attention can adapt robustly to unseen classification tasks through in-context learning. In-context learning is a particularly lightweight adaptation method that enables transformers to learn from demonstrations in the prompt without updating their parameters (Brown et al., 2020). This result suggests that robustness acquired during pretraining can transfer to new tasks without additional training. However, their analysis is limited to a restricted data model and a single-layer architecture. Moreover, they provided only bounds on the expected robust margin. Thus, it does not provide direct guarantees on robust accuracy or evaluate robust optimality. Consequently, our central question remains open in broader settings.
In this study, we provide a stronger affirmative answer to this question under substantially more general conditions. We consider multilayer linear transformers adversarially pretrained on a family of Gaussian-mixture classification tasks. We focus on the robust zero-one error of these transformers on tasks not encountered during pretraining. In particular, we investigate whether this error approaches the robust Bayes error, which is the minimum robust error attainable by any classifier, even one with full knowledge of the task distribution.
Specifically, we show that, through in-context learning from clean demonstrations, a sufficiently deep linear transformer can asymptotically attain the robust Bayes error on every task in this Gaussian family, including tasks unseen during pretraining. In other words, using only standard samples and without task-specific adversarial training or access to adversarial examples, a single linear transformer can asymptotically serve as an optimal robust predictor for each task. We should note that the transformer's parameters remain fixed and shared across all downstream tasks. Nevertheless, the transformer can adapt to each task and implement its optimal robust prediction rule.
Moreover, we show that a standardly pretrained transformer cannot achieve optimal robustness, even with infinite pretraining tasks and in-context demonstrations. This result indicates that optimal robust in-context learning cannot be attributed solely to model capacity or task diversity; rather, it stems from an inherent advantage of adversarial pretraining.
We further investigate several properties of robust in-context learning. Whereas the discussion above focuses on empirical-risk minimizers, we also prove that gradient flow in a two-layer architecture converges to a predictor that attains robust Bayes optimality. We also identify two fundamental challenges in developing robust transformers. The first is an inherent accuracy–robustness trade-off: adversarial pretraining can degrade clean accuracy even in the infinite-data limit. The second is greater demonstration complexity: even at the same Bayes excess risk, robust prediction requires more demonstrations than standard prediction.
In summary, we prove the following:
• A sufficiently deep linear transformer asymptotically achieves optimal robustness across a family of Gaussian-mixture classification tasks through in-context learning from clean demonstrations.
• Adversarial pretraining makes the transformer an optimal robust in-context learner, whereas standard pretraining does not, even with unlimited data.
• Under mild conditions, (i) gradient flow leads the transformer to become such an in-context learner, (ii) an accuracy–robustness trade-off arises, and (iii) robust in-context prediction requires more demonstrations than standard prediction.
In-context learning. In-context learning enables a transformer to learn a task from demonstrations in the prompt, without updating its parameters (Brown et al., 2020). Existing theoretical work on in-context learning has largely focused on the algorithms that transformers can implement in context. For example, appropriately parameterized transformers can implement one gradient descent step per layer in context, so that propagation through multiple layers corresponds to multiple gradient descent steps (Ahn et al., 2023; Bai et al., 2023; Cheng et al., 2024; Gatmiry et al., 2024; Mahankali et al., 2024; Zhang et al., 2024). In-context learning can also simulate second-order optimization (Fu et al., 2024; Giannou et al., 2024), reinforcement learning algorithms (Lee et al., 2023; Lin et al., 2024), and Bayesian inference (Xie et al., 2022; Zhang et al., 2025). Unlike these studies, we do not seek to identify the algorithms that in-context learning can simulate. Instead, we study the ability of in-context learning to transfer robustness acquired in adversarial pretraining to downstream tasks.
Adversarial robustness of in-context learning. The adversarial robustness of in-context learning remains relatively underexplored from a theoretical perspective. Anwar et al. (2025) studied context hijacking and showed that modifying in-context tokens can cause a transformer to output an arbitrary value for a clean query. Li et al. (2025) showed that deeper transformers are more robust to context hijacking. Fu et al. (2025) showed that adversarial training with short adversarial suffixes in the context and clean queries can improve robustness to longer adversarial suffixes at test time. Fu & Wang (2026) used the theory of in-context learning to analyze continuous adversarial training (Xhonneux et al., 2024). Both our work and that of Kumano et al. (2026) differ from these studies in terms of problem setting and objective. Specifically, we ask whether a transformer can learn in context from clean demonstrations to make robust predictions on adversarially perturbed queries. Following our theoretical results, we provide a detailed comparison with Kumano et al. (2026) in Section 3.5.
3 THEORETICAL RESULTS
Notation. For each , define . We denote the -th element of a vector by and the entry in row and column of a matrix by . For , let , and denote the -dimensional zero vector, the zero matrix, and the identity matrix, respectively. For , define the real orthogonal group in dimension by . We write for the Euclidean norm and for the Frobenius norm. Let be nonnegative random variables and be positive deterministic values; we write if, for every , there exists such that for all .
3.1 PROBLEM SETTING
Overview. We consider pretraining an -layer linear transformer on tasks. For each , the -th task consists of in-context demonstrations and a test pair . Given the clean demonstrations , the transformer uses in-context learning to predict the binary label of the adversarially perturbed query . The adversary chooses subject to . We train the transformer parameters by minimizing the empirical risk . We then evaluate the resulting predictor on a freshly sampled test task using the taskwise zero-one error , where denotes the task-specific variable. Our main interest is the excess error , where denotes the corresponding taskwise Bayes error.
Task structure. Let denote the number of pretraining tasks and the number of in-context demonstrations per task, respectively. For each , the -th task consists of demonstrations and a test pair . Let denote an orthogonal matrix whose columns form a task-specific orthonormal basis. For each , let denote the coefficient vector for the -th sample of the -th task, and define the corresponding input vector as
Task distribution. The matrices are independently drawn according to the normalized Haar measure on . In other words, the columns of each form an orthonormal basis chosen uniformly at random. The labels are independently drawn from the uniform distribution on . The coefficient vectors are independently drawn from the multivariate normal distribution with mean and covariance . These three collections are mutually independent. The parameters and are common across tasks.
Dimension of the Krylov subspace. Let denote the dimension of , the order-d Krylov subspace generated by and . More precisely, define
Equivalently, is the largest integer such that the vectors are linearly independent. Consequently, . Moreover, equals the number of distinct eigenvalues of for which has a nonzero projection onto the corresponding eigenspace. If , so that the Gaussian coordinates are mutually independent and have unit variance, then . If is the all-ones vector and is diagonal, then equals the number of distinct diagonal entries of . In general, characterizes the representational complexity of the Bayes classifier for the Gaussian data . Without adversarial perturbations, this classifier is . Its weight vector belongs to , and is the smallest Krylov order required to represent this vector.
Input sequence. Given the clean in-context demonstrations and a possibly perturbed query , we define the input sequence for a linear transformer as
The bottom-right entry serves as a placeholder for the query prediction.
Linear transformer. In this study, we focus on transformers with linear self-attention, which are commonly used in recent theoretical work (Ahn et al., 2023; Mahankali et al., 2024; Gatmiry et al., 2024; Cheng et al., 2024; Zhang et al., 2024; Kumano et al., 2026). Let denote the number of layers. For each , we recursively define
where are, respectively, the trainable value and key-query matrices in layer . As in prior work on in-context learning (Ahn et al., 2023; Gatmiry et al., 2024; Cheng et al., 2024; Kumano et al., 2026), we use the masking matrix to prevent the tokens from attending to the query token. The resulting scalar predictor and the collection of trainable parameters are defined as
Training objective. Let be a loss function. Based on prior work (Bai et al., 2023; Ahn et al., 2023; Mahankali et al., 2024; Zhang et al., 2024; Kumano et al., 2026), we define the empirical risk over pretraining tasks, each with demonstrations, as follows:
Minimizing corresponds to standard training, whereas minimizing for corresponds to adversarial training. Training the transformer on multiple tasks with a single shared set of parameters encourages it to adaptively infer the task-specific structure from the demonstrations and generalize across tasks, rather than specialize in any particular task.
Taskwise zero-one error. For each fixed , let be a fresh test pair independently drawn from the same task-conditional distribution as the pretraining samples. We define the taskwise robust zero-one error of a predictor by
Setting yields the taskwise standard zero-one error .
Taskwise Bayes error. Let denote the class of all measurable functions . For each , we define the taskwise robust Bayes error by . Setting yields the taskwise standard Bayes error .
Assumptions. The assumptions used in this study are as follows:
Assumption 3.1
(a) The mean vector is nonzero, and the covariance matrix is symmetric and positive definite; and .
(b) The perturbation radius is smaller than the norm of the mean vector ; .
(c) The number of layers L is at least the dimension r of the Krylov subspace; .
(d) The loss function is twice differentiable and satisfies and for every , and .
Condition (a) rules out degenerate classification problems. Condition (b) prevents an adversary from completely canceling the mean signal. The role of Condition (c) is explained in the next section. Condition (d) ensures that the empirical risk minimization problem is well-posed. The logistic loss is an example satisfying Condition (d).
3.2 A SINGLE LINEAR TRANSFORMER CAN REPRESENT ROBUST BAYES CLASSIFIERS ACROSS TASKS
In this section, we first show that, given sufficient depth, a single linear transformer can asymptotically achieve the taskwise robust Bayes error through in-context learning. At this stage, we do not address whether the required parameters can be learned by empirical risk minimization.
Theorem 3.2 (A single linear transformer can be Bayes optimal across tasks). Suppose that (a) to (c) in Assumption 3.1 hold. Then, there exists a parameter such that, for every ,
The implied constant may depend on , , , and .
The proof is given in Section B. The theorem establishes that a single linear transformer with a shared parameter asymptotically attains the robust Bayes error for every task as the number of demonstrations grows. In other words, without any task-specific parameter updates, the same linear transformer can adapt to every task through in-context learning and match the performance of the corresponding task-specific robust Bayes classifier. This uniform guarantee demonstrates the expressive capacity of linear transformers for in-context adaptation across tasks. Moreover, the excess error decays at a rate of . The rate is consistent with empirical observations of strong few-shot performance in in-context learning. Recall that r reflects the complexity of the Gaussian mixture model and the resulting difficulty of representing its robust Bayes classifier. Accordingly, the condition suggests that more complex data models call for deeper linear transformers to achieve Bayes optimality.
We next provide intuition about how a linear transformer can attain the Bayes error and why the depth condition arises.
Lemma 3.3 (Proof sketch of Theorem 3.2). Suppose that (a) and (b) in Assumption 3.1 hold. Suppose also that ; write . Let be the unique solution of
(Bayes classifier) For every ,
(Krylov order of the optimal direction) Let . Then,
(Effective weights of a linear transformer) There exists a parameter family whose corresponding effective weights satisfy, for every , , and ,
(Span of the effective weights) For the same parameter family,
The proof is given in Section B. Although this lemma does not constitute a complete proof of Theorem 3.2, it provides a roadmap for the proof.
Bayes classifier. The first part of the lemma gives the Bayes classifier for generated according to Eq. (1). The form of this function provides two insights into this classifier.
First, the optimal weight is the solution to the following regularized mean–variance problem:
The regularization parameter is determined by the perturbation level : it is zero when and increases monotonically with . This regularization controls the sensitivity to adversarial perturbations, since . The taskwise Bayes classifier minimizing is a linear classifier obtained from a perturbation-dependent -regularized optimization problem.
Second, the classifier makes predictions while accounting for both variance and the effects of adversarial attacks. Substituting gives
For simplicity, suppose that for . Then the -th term in the inner product, for , can be expressed as . When the perturbation level is small and hence is small, this term can be approximated by . Thus, components with large variance have less influence on the prediction, whereas components with small variance have greater influence. In contrast, when is large, . The classifier relies more directly on strong features in the data without accounting for their variances.
Krylov order of the optimal direction. The second part of the lemma shows that the optimal direction belongs to the order-r Krylov subspace generated by and . This vector cannot belong to the order- Krylov subspace. The proof uses the Cayley–Hamilton theorem. This result suggests that, to attain the taskwise Bayes error for arbitrary and , a linear transformer must be expressive enough to internally represent weight vectors in the order-r Krylov subspace.
Effective weights of a linear transformer. The third part of the lemma shows that a suitable parameter family makes a linear transformer behave as a context-dependent linear classifier. We restrict and for as follows, and, under , the context matrix is as follows:
The outputs after the first, second, and third layers are
Consequently, the three-layer model's output on a query x and its effective weight are
The same construction shows inductively that, with suitable parameters, a linear transformer of any depth can act as a context-dependent linear classifier whose effective weight is independent of U.
Span of the effective weights. The fourth part of the lemma states that, as varies, the effective weights associated with this parameter family span the order-L Krylov subspace. The equations above illustrate this mechanism: stacking L layers yields effective weights that are linear combinations of
Closely related characterizations of the Bayes classifier were previously established by Bhagoji et al. (2019); Dan et al. (2020), and we therefore do not claim this characterization as a novel contribution. Here, it serves only as an intermediate result in the proof of Theorem 3.2.
. As shown in the second part, the optimal direction lies in the order-r Krylov subspace. Hence, when , the optimal direction lies in the span of the effective weights. These results explain how linear transformers achieve Bayes optimality and why the depth condition is required. Note that, even when , this lemma alone does not establish that an effective weight can exactly match the optimal direction . See Section B for the complete proof.
3.3 ADVERSARIAL TRAINING ENABLES LINEAR TRANSFORMERS TO ACHIEVE ROBUST BAYES OPTIMALITY ACROSS TASKS; STANDARD TRAINING DOES NOT
The preceding section establishes that sufficiently deep linear transformers have the expressive capacity to asymptotically attain robust Bayes optimality across tasks. However, this existence result does not show whether such parameters can be learned by a training procedure. We address this question by analyzing empirical risk minimization under adversarial and standard training.
Theorem 3.4 (Adversarial training yields robust linear transformers). Suppose that Assumption 3.1 holds. For sufficiently large B > 0, choose any empirical risk minimizer
Then, for every ,
The implied constant may depend on d, B, L, , , , and .
The proof is given in Section C. This theorem complements the representability result in Theorem 3.2 by showing that adversarial training can produce a transformer that asymptotically achieves robust Bayes optimality across tasks. For , a test-task basis U differs almost surely from every pretraining basis under the Haar measure on , even when there are countably infinitely many pretraining tasks. Thus, the theorem establishes robust generalization to previously unseen tasks, which cannot be attributed to exact memorization of the pretraining bases. Moreover, the excess-error bound decomposes into a term depending on T and a term depending on N, rather than taking a joint form such as . This decomposition isolates the contributions of cross-task learning from pretraining and within-task inference from in-context demonstrations. The bound converges to zero only as both the number of pretraining tasks and the number of in-context demonstrations grow; increasing either one alone might be insufficient for the convergence to Bayes optimality.
We next contrast this result with standard training.
Theorem 3.5 (Standard training does not yield robust linear transformers). Suppose that Assumption 3.1 holds. Suppose also that ; write and . For sufficiently large , choose any population risk minimizer
Then, there exists a constant such that, for every ,
The constant C may depend on d, , , and .
The proof is given in Section C. In contrast to Theorem 3.4, this theorem establishes an impossibility result for standard training: when and , standard training cannot produce a linear transformer whose predictions attain robust Bayes optimality. This impossibility is not due to a finite amount of training data; it persists in the population limit, even when both the number of pretraining tasks and the number of demonstrations per task tend to infinity. These results reveal a fundamental difference between standard and adversarial training and suggest that, at least for linear transformers, adversarial training is necessary to obtain adversarially robust in-context learners.

Figure 1: Robust zero-one errors for , , and . Means and sample standard deviations are shown over three runs in the left panel and five runs in the other panels.
3.4 OTHER THEORETICAL RESULTS
Gradient flow to Bayes optimality. The preceding sections show that global minimizers of the adversarial empirical risk asymptotically achieve taskwise Bayes optimality. However, practical optimization algorithms such as gradient descent are not guaranteed to find a global minimizer. To bridge this gap, Theorem D.1 analyzes the case and , in which only the final key-query matrix is trained. We show that gradient flow yields predictors whose robust errors converge to the corresponding Bayes errors.
Accuracy–robustness trade-off. Robustness often comes at the cost of clean accuracy. In particular, adversarially trained models may be less accurate on unperturbed samples than their standardly trained counterparts (Su et al., 2018; Tsipras et al., 2019; Ilyas et al., 2019). In Theorem E.1, we establish that the same trade-off arises in our setting. Moreover, the trade-off persists even with infinitely many pretraining tasks and infinitely many demonstrations per task. This result highlights a fundamental challenge in developing robust foundation models.
Demonstration complexity. Achieving a target level of robust accuracy often requires more training samples than achieving the corresponding level of standard accuracy (Schmidt et al., 2018; Dan et al., 2020). In Theorem F.1, we establish an analogous gap in the number of in-context demonstrations. Attaining the same fixed excess error relative to the respective Bayes errors requires only one demonstration for standard prediction but demonstrations for robust prediction. This result reveals another fundamental challenge in developing robust foundation models.
3.5 COMPARISON WITH PRIOR WORK
Compared to Kumano et al. (2026), we substantially relax their assumptions on the data distribution and the model architecture while establishing stronger robustness guarantees for linear transformers.
Data distribution. Their data model restricts feature scales to two discrete levels, such as , where represent large and small values, respectively. This is a major limitation they acknowledge. Our framework allows arbitrary feature scales. They also consider only the standard basis, which roughly corresponds to fixing U to a particular value in our framework. In contrast, our theory applies to any orthonormal basis. Although they allow a broader class of coefficient distributions than our Gaussian family, they impose strong constraints on the covariance structure, whereas we do not. Overall, our framework broadens the class of admissible data models.
Architecture. Theoretically, their analysis is limited to single-layer linear transformers, whereas ours applies to multilayer linear transformers. Their experiments are also limited to single-layer linear transformers trained on relatively small datasets, including MNIST (Deng, 2012), Fashion-MNIST (Xiao et al., 2017), and CIFAR-10 (Krizhevsky, 2009). By contrast, we conduct experiments with multilayer transformers equipped with softmax attention on larger datasets, including CIFAR-100 (Krizhevsky, 2009), Tiny ImageNet (Le & Yang, 2015), and Caltech-256 (Griffin et al., 2007), thereby evaluating the effectiveness of robust foundation models in more realistic settings.
Robustness guarantees. Although differences in assumptions make direct comparisons difficult, our results provide more direct and comprehensive robustness guarantees. First, they establish only
Table 1: Clean/robust accuracy (%) of six-layer transformers with softmax attention on real-world data, reported as mean sample standard deviation across five independent runs.
| Training | CIFAR-100 | Tiny ImageNet | Caltech-256 |
|---|---|---|---|
| Standard | |||
| Adversarial |
bounds on the expected robust margin . Because the expected robust margin does not generally determine robust accuracy, these bounds alone do not provide a direct guarantee of robustness. By contrast, we prove that the robust zero-one error converges to the taskwise robust Bayes error, thereby directly guaranteeing transformer robustness. Second, their analysis does not determine whether linear transformers are robust or vulnerable in certain data regimes. As they acknowledge, their single-layer restriction limits model capacity and prevents their analysis from capturing the full robustness potential of linear transformers. By considering a multilayer model, we show that linear transformers asymptotically achieve taskwise robust Bayes optimality when they are sufficiently deep relative to the data complexity (i.e., ). Overall, our analysis provides more definitive guarantees and more fully characterizes the robustness of linear transformers.
4 EXPERIMENTAL RESULTS
Detailed experimental settings and additional results are provided in Section A.
Synthetic datasets. We first empirically validate our theoretical results using synthetic datasets generated according to Eq. (1). We set , , and . We train the linear transformer in Eq. (5) by minimizing the logistic loss with Adam. Each model is evaluated on 40,000 test tasks with 200 queries per task. The left panel of Fig. 1 compares robust zero-one errors for and . Under adversarial training, the robust zero-one error decreases with depth, and the depth-10 model essentially attains the robust Bayes error, supporting Theorems 3.2 and 3.4. The near-optimal performance of the depth-2 model does not contradict the theorem because is a sufficient but not necessary condition. In contrast, despite having sufficient depth and being trained on abundant data, the depth-10 model obtained by standard training remains far from optimal, consistent with Theorem 3.5. The center and right panels show that the depth-10 adversarially trained model approaches the robust Bayes error as and increase, respectively, supporting Theorem 3.4.
Real-world datasets. We then evaluate six-layer transformers with softmax attention on binary classification tasks from CIFAR-100, Tiny ImageNet, and Caltech-256. The pretraining, validation, and test classes are mutually disjoint. Clean and robust test accuracies are shown in Tab. 1. Adversarial training substantially improves robust accuracy, albeit at the cost of lower clean accuracy.
5 CONCLUSION AND LIMITATIONS
We showed that adversarial pretraining can enable a sufficiently deep linear transformer to adapt to unseen Gaussian-mixture classification tasks through in-context learning from clean demonstrations and asymptotically attain the taskwise robust Bayes error. By contrast, standard pretraining does not, even in the population limit. We further established convergence under gradient flow and identified two challenges in robust in-context learning. These results provide theoretical evidence that robustness acquired once during pretraining can transfer to downstream tasks without additional adversarial training, supporting the feasibility of robust foundation models.
Our analysis is restricted to Gaussian-mixture tasks that share a common latent mean and covariance, so the unseen tasks considered in our theory still belong to a structured task family. Although such cross-task sharing is common in theoretical analyses of in-context learning (Ahn et al., 2023; Mahankali et al., 2024; Kumano et al., 2026), extending our guarantees to settings with task-dependent means or covariances and to non-Gaussian inputs is an important direction for future theoretical work. Moreover, the practical utility of robust foundation models remains unknown at the scale of modern foundation-model pretraining. We hope that our theoretical results will motivate large-scale empirical studies by large organizations with the computational resources required to conduct them.
AI USE STATEMENT
In this work, we used generative AI tools to formulate mathematical claims, provide critical ingredients for proving mathematical claims, assist in the writing of proofs, implement methods, and assist with translation. We have not used generative AI tools to generate synthetic data sets, help develop theoretical models or conceptual frameworks, propose or refine hypotheses, design or provide feedback on research methodology or experiments, and interpret results. Dataset cleaning and reformatting, and support for qualitative or thematic data analysis are not applicable to this work. Additionally, we used generative AI tools to create or edit software code, draft parts of a research paper, summarize or analyze existing literature, brainstorm, source or search for information, edit a research paper to improve readability, identify relevant literature, and suggest a structure for a research paper. We did not use generative AI tools to create or modify scientific figures or images, suggest experimental parameters, create artifacts, discover research topics or identify gaps, format references, and propose a title or keywords for a research paper. Formulating questions for surveys or interviews and transcribing recordings of research materials are not applicable to this work. We have reviewed all AI-assisted work. We independently checked all proofs for mathematical correctness, tested all experimental code, and read and evaluated every cited work. We take responsibility for the final content of this work, including text, claims, or artifacts produced with the aid of generative AI.
ETHICS STATEMENT
This work is a theoretical study of adversarial robustness supported by experiments on synthetic and real-world benchmark datasets. We use only publicly available datasets and do not collect new data or involve human participants. Our experiments do not interact with deployed systems.
REPRODUCIBILITY STATEMENT
We state all assumptions explicitly in the main text and provide complete proofs of all theoretical results in the appendix. Detailed experimental settings are provided in Section A. The supplementary material contains the code to reproduce the reported experimental results.
REFERENCES
Kwangjun Ahn, Xiang Cheng, Hadi Daneshmand, and Suvrit Sra. Transformers learn to implement preconditioned gradient descent for in-context learning. In NeurIPS, volume 36, pp. 45614–45650, 2023.
Maksym Andriushchenko and Nicolas Flammarion. Understanding and improving fast adversarial training. In NeurIPS, volume 33, pp. 16048–16059, 2020.
Usman Anwar, Johannes Von Oswald, Louis Kirsch, David Krueger, and Spencer Frei. Understanding in-context learning of linear models in transformers through an adversarial lens. TMLR, 2025. ISSN 2835-8856.
Anish Athalye, Nicholas Carlini, and David Wagner. Obfuscated gradients give a false sense of security: Circumventing defenses to adversarial examples. In ICML, pp. 274–283, 2018.
Yu Bai, Fan Chen, Huan Wang, Caiming Xiong, and Song Mei. Transformers as statisticians: Provable in-context learning with in-context algorithm selection. In NeurIPS, volume 36, pp. 57125–57211, 2023.
Arjun Nitin Bhagoji, Daniel Cullina, and Prateek Mittal. Lower bounds on adversarial robustness from optimal transport. In NeurIPS, volume 32, 2019.
Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language models are few-shot learners. In NeurIPS, volume 33, pp. 1877–1901, 2020.
Nicholas Carlini and David Wagner. Towards evaluating the robustness of neural networks. In SP, pp. 39–57, 2017a.
Nicholas Carlini and David Wagner. Adversarial examples are not easily detected: Bypassing ten detection methods. In ACM Workshop, pp. 3–14, 2017b.
Xiang Cheng, Yuxin Chen, and Suvrit Sra. Transformers implement functional gradient descent to learn non-linear functions in context. In ICML, 2024.
Francesco Croce and Matthias Hein. Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks. In ICML, pp. 2206–2216, 2020.
Chen Dan, Yuting Wei, and Pradeep Ravikumar. Sharp statistical guarantees for adversarially robust gaussian classification. In ICML, pp. 2345–2355, 2020.
Li Deng. The MNIST database of handwritten digit images for machine learning research. Signal Processing Magazine, 29(6):141–142, 2012.
Deqing Fu, Tian-qi Chen, Robin Jia, and Vatsal Sharan. Transformers learn to achieve second-order convergence rates for in-context linear regression. In NeurIPS, volume 37, pp. 98675–98716, 2024.
Shaopeng Fu and Di Wang. Understanding and improving continuous LLM adversarial training via in-context learning theory. In ICLR, 2026.
Shaopeng Fu, Liang Ding, Jingfeng Zhang, and Di Wang. Short-length adversarial training helps LLMs defend long-length jailbreak attacks: Theoretical and empirical evidence. In NeurIPS, volume 38, pp. 64351–64391, 2025.
Khashayar Gatmiry, Nikunj Saunshi, Sashank J Reddi, Stefanie Jegelka, and Sanjiv Kumar. Can looped transformers learn to implement multi-step gradient descent for in-context learning? In ICML, 2024.
Angeliki Giannou, Liu Yang, Tianhao Wang, Dimitris Papailiopoulos, and Jason D Lee. How well can transformers emulate in-context newton's method? arXiv:2403.03183, 2024.
Ian J. Goodfellow, Jonathon Shlens, and Christian Szegedy. Explaining and harnessing adversarial examples. In ICLR, 2015.
Shruthi Gowda, Bahram Zonooz, and Elahe Arani. Conserve-update-revise to cure generalization and robustness trade-off in adversarial training. In ICLR, pp. 15465–15485, 2024.
Gregory Griffin, Alex Holub, and Pietro Perona. Caltech-256 object category dataset. Technical report, 2007.
Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The elements of statistical learning: data mining, inference, and prediction. Springer, 2 edition, 2009.
Pengyue Hou, Ming Zhou, Jie Han, Petr Musilek, and Xingyu Li. Adversarial fine-tune with dynamically regulated adversary. In IJCNN, pp. 1–8, 2022.
Andrew Ilyas, Shibani Santurkar, Dimitris Tsipras, Logan Engstrom, Brandon Tran, and Aleksander Madry. Adversarial examples are not bugs, they are features. In NeurIPS, volume 32, pp. 125–136, 2019.
Ahmadreza Jeddi, Mohammad Javad Shafiee, and Alexander Wong. A simple fine-tuning is all you need: Towards robust deep learning via adversarial fine-tuning. In CVPR Workshop, 2021.
Xiaojun Jia, Yong Zhang, Xingxing Wei, Baoyuan Wu, Ke Ma, Jue Wang, and Xiaochun Cao. Prior-guided adversarial initialization for fast adversarial training. In ECCV, pp. 567–584, 2022.
Hoki Kim, Woojin Lee, and Jaewook Lee. Understanding catastrophic overfitting in single-step adversarial training. In AAAI, volume 35, pp. 8119–8127, 2021.
Alex Krizhevsky. Learning multiple layers of features from tiny images. Technical report, University of Toronto, 2009.
Soichiro Kumano, Hiroshi Kera, and Toshihiko Yamasaki. Adversarially pretrained transformers may be universally robust in-context learners. In ICLR, pp. 124615–124659, 2026.
Ya Le and Xuan Yang. Tiny ImageNet visual recognition challenge. CS231N course report, Stanford University, 2015.
Jonathan Lee, Annie Xie, Aldo Pacchiano, Yash Chandak, Chelsea Finn, Ofir Nachum, and Emma Brunskill. Supervised pretraining can learn in-context reinforcement learning. In NeurIPS, volume 36, pp. 43057–43083, 2023.
Tianle Li, Chenyang Zhang, Xingwu Chen, Yuan Cao, and Difan Zou. On the robustness of transformers against context hijacking for linear classification. In NeurIPS, volume 38, pp. 69373–69411, 2025.
Licong Lin, Yu Bai, and Song Mei. Transformers as decision makers: Provable in-context reinforcement learning via supervised pretraining. In ICLR, 2024.
Aleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras, and Adrian Vladu. Towards deep learning models resistant to adversarial attacks. In ICLR, 2018.
Arvind Mahankali, Tatsunori B Hashimoto, and Tengyu Ma. One step of gradient descent is provably the optimal in-context learner with one layer of linear self-attention. In ICLR, 2024.
Geon Yeong Park and Sang Wan Lee. Reliably fast adversarial training via latent adversarial perturbation. In ICCV, pp. 7758–7767, 2021.
Ludwig Schmidt, Shibani Santurkar, Dimitris Tsipras, Kunal Talwar, and Aleksander Madry. Adversarially robust generalization requires more data. In NeurIPS, volume 31, 2018.
Ali Shafahi, Mahyar Najibi, Amin Ghiasi, Zheng Xu, John Dickerson, Christoph Studer, Larry S Davis, Gavin Taylor, and Tom Goldstein. Adversarial training for free! In NeurIPS, volume 32, 2019.
Dong Su, Huan Zhang, Hongge Chen, Jinfeng Yi, Pin-Yu Chen, and Yupeng Gao. Is robustness the cost of accuracy?—a comprehensive study on the robustness of 18 deep image classification models. In ECCV, pp. 631–648, 2018.
Satoshi Suzuki, Shin'ya Yamaguchi, Shoichiro Takeda, Sekitoshi Kanai, Naoki Makishima, Atsushi Ando, and Ryo Masumura. Adversarial finetuning with latent representation constraint to mitigate accuracy-robustness tradeoff. In ICCV, pp. 4367–4378, 2023.
Christian Szegedy, Wojciech Zaremba, Ilya Sutskever, Joan Bruna, Dumitru Erhan, Ian Goodfellow, and Rob Fergus. Intriguing properties of neural networks. In ICLR, 2014.
Florian Tramer, Nicholas Carlini, Wieland Brendel, and Aleksander Madry. On adaptive attacks to adversarial example defenses. In NeurIPS, volume 33, pp. 1633–1645, 2020.
Dimitris Tsipras, Shibani Santurkar, Logan Engstrom, Alexander Turner, and Aleksander Madry. Robustness may be at odds with accuracy. In ICLR, 2019.
Eric Wong, Leslie Rice, and J Zico Kolter. Fast is better than free: Revisiting adversarial training. In ICLR, 2020.
Sophie Xhonneux, Alessandro Sordoni, Stephan Günnemann, Gauthier Gidel, and Leo Schwinn. Efficient adversarial training in llms with continuous attacks. In NeurIPS, volume 37, pp. 1502–1530, 2024.
Han Xiao, Kashif Rasul, and Roland Vollgraf. Fashion-MNIST: a novel image dataset for benchmarking machine learning algorithms. arXiv:1708.07747, 2017.
Sang Michael Xie, Aditi Raghunathan, Percy Liang, and Tengyu Ma. An explanation of in-context learning as implicit bayesian inference. In ICLR, 2022.
Dinghuai Zhang, Tianyuan Zhang, Yiping Lu, Zhanxing Zhu, and Bin Dong. You only propagate once: Accelerating adversarial training via maximal principle. In NeurIPS, volume 32, 2019.
Ruiqi Zhang, Spencer Frei, and Peter L Bartlett. Trained transformers learn linear models in-context. JMLR, 25(49):1–55, 2024.
Yufeng Zhang, Fengzhuo Zhang, Zhuoran Yang, and Zhaoran Wang. What and how does in-context learning learn? bayesian model averaging, parameterization, and generalization. In AISTATS, 2025.
Haizhong Zheng, Ziqi Zhang, Juncheng Gu, Honglak Lee, and Atul Prakash. Efficient adversarial training with transferable adversarial examples. In CVPR, pp. 1178–1187, 2020.
A Additional Experimental Results 14
A.1 Synthetic Experiments 14
A.2 Real-World Experiments 16
B Robust Bayes Implementation by Linear Transformers: Proof of Theorem 3.2 17
B.1 Robust Bayes classifier 17
B.2 Query-Linear Representation 21
B.3 Krylov structure and sufficient-depth realization 21
C Adversarial and Standard Training: Proofs of Theorems 3.4 and 3.5 25
C.1 Directions selected by infinite-sample margin risks 25
C.2 Infinite-sample minimizers and finite-context transfer 26
C.3 Finite-task adversarial risk minimization 27
D Gradient Flow to Robust Bayes Optimality 31
E Accuracy-Robustness Trade-Off 33
F Demonstration Complexity 34
A ADDITIONAL EXPERIMENTAL RESULTS
All experiments were conducted on a Linux server with an x86_64 CPU architecture and four NVIDIA A100-SXM4-80GB GPUs.
A.1 SYNTHETIC EXPERIMENTS
Experimental design. We choose an anisotropic Gaussian distribution for which the standard and robust Bayes directions differ, allowing the experiments to distinguish standard from robust direction recovery. Specifically, we set and and, for every , define the mean and diagonal covariance entries by
For every , we set and . The active signal-to-variance ratios therefore range logarithmically from 10 to . Because the ten active coordinates have distinct covariance eigenvalues, this construction has Krylov dimension . We independently draw each task basis from the normalized Haar distribution on and then sample demonstrations and queries from Eq. (1). Each fixed pretraining dataset contains task bases, clean demonstrations per task, and one clean query per task. For evaluation, we use 40,000 independently drawn test tasks, a fresh context with the same value of for each task, and 200 independent queries per context. We conduct three independent runs for and and five independent runs otherwise. Each run uses separate training and evaluation random streams, and we report means and sample standard deviations across runs.
Model and training. We use the one-head masked linear-attention architecture in Eq. (4) and restrict its parameters to a rotation-equivariant family that respects the symmetry of the task distribution. In particular, every layer has the form

Figure A1: Cosine similarity between the population-context effective direction of an adversarially trained transformer and the robust Bayes direction. The distribution and the three experimental conditions are the same as in Fig. 1. The left panel varies the depth at T = 40,000 and N = 100,000, the center panel varies T with L = 10 and N = 1,000, and the right panel varies N with L = 10 and T = 1,000. Means and sample standard deviations are shown over three runs in the left panel and five runs in the other panels.
The four coefficients in each layer are trainable and initialized independently from . We minimize the logistic loss , which satisfies Assumption 3.1(d), by full-batch Adam for at most 2,500 updates on the fixed pretraining dataset. The learning rate increases linearly to 0.01 over the first 30 updates and subsequently either remains constant or follows cosine annealing to 0.001 without restarts. For each schedule, we retain the checkpoint with the smallest training loss and report the better of the two retained checkpoints under the same criterion.
Robust evaluation and Bayes baselines. Masked linear attention is linear in the query, so both adversarial training and robust evaluation can use the exact worst-case perturbation rather than an approximate attack such as the fast gradient sign method (Goodfellow et al., 2015) or projected gradient descent (PGD) (Madry et al., 2018). The adversary perturbs only the query and leaves all in-context demonstrations fixed and clean. Writing for the context-dependent effective query direction, the exact perturbation for is
When the effective direction is zero, we instead set , and during adversarial training we recompute the perturbation from the current model at every update. For comparison with the theoretical optimum, we obtain the robust Bayes direction by numerically solving
and compute all Bayes risks analytically from the resulting Gaussian margins.
Alignment with the robust Bayes direction. To examine whether adversarial training recovers the optimal classifier rather than merely its error, Fig. A1 compares the effective direction of linear transformers with the robust Bayes direction characterized in Lemma B.4. At T = 40,000 and N = 100,000, the cosine similarity increases with depth and approaches one at depth ten. Thus, the depth-10 model recovers not only the robust Bayes error but also the unique optimal direction up to positive scaling. Increasing the number of pretraining tasks similarly improves the cosine similarity, while the values throughout the demonstration sweep remain close to one. Together with the robust errors in Fig. 1, these results support the convergence to the robust Bayes predictor established in Theorem 3.4.
Accuracy–robustness trade-off and demonstration complexity. To assess the accuracy–robustness trade-off and the qualitative dependence on context length, Tab. A1 compares clean and robust accuracy as the number of demonstrations increases. Standard training gives higher clean accuracy overall, whereas adversarial training gives substantially higher robust accuracy, supporting the accuracy–robustness trade-off in Theorems 3.5 and E.1. Moreover, standard clean accuracy saturates with relatively few demonstrations, while adversarial robust accuracy continues to improve toward the robust Bayes accuracy. This behavior is qualitatively consistent with Theorem F.1.
Table A1: Clean and robust accuracies (%), reported as mean ± sample standard deviation across five runs, for depth-10 models trained on T = 1,000 tasks. Each row uses the displayed number of demonstrations in both pretraining and evaluation. Robust accuracy uses , and every model is evaluated on 40,000 test tasks with 200 queries per task.
| N | Standard training | Adversarial training | ||
|---|---|---|---|---|
| Clean | Robust | Clean | Robust | |
| 10 | 84.6 ± 4.2 | 63.5 ± 4.5 | 84.8 ± 0.7 | 67.8 ± 0.3 |
| 50 | 95.1 ± 4.3 | 52.8 ± 20.6 | 92.4 ± 0.3 | 75.5 ± 0.1 |
| 100 | 98.0 ± 0.6 | 45.1 ± 15.9 | 93.6 ± 0.3 | 76.6 ± 0.1 |
| 500 | 98.7 ± 0.2 | 39.6 ± 7.0 | 94.1 ± 0.3 | 77.5 ± 0.1 |
| 1,000 | 98.4 ± 0.6 | 45.1 ± 13.0 | 94.0 ± 0.1 | 77.6 ± 0.1 |
A.2 REAL-WORLD EXPERIMENTS
Datasets and class splits. We evaluate whether the benefit of adversarial pretraining extends beyond the theoretical Gaussian model by considering CIFAR-100 (Krizhevsky, 2009), Tiny ImageNet (Le & Yang, 2015), and Caltech-256 (Griffin et al., 2007). In each of the five independent runs, the respective pretraining splits contain 80, 180, and 236 classes, while each validation and test split contains ten classes, with all three partitions mutually disjoint. We draw a different class partition in each run.
PCA features. We represent each image by an unwhitened principal component analysis (PCA) features to reduce the input dimension before constructing the in-context episodes. Let denote the number of retained components and hence the dimension of each PCA feature. For every dataset and run, we scale RGB values to [0, 1] and flatten each image in channel–height–width order. We fit the coordinatewise mean and PCA components using only images from that run's pretraining classes, excluding all images from validation and test classes. We compute PCA with 32 oversampling dimensions and seven power iterations. After fitting PCA, we use the same mean and components to project every image in the training and query splits. We retain components for CIFAR-100 and components for Tiny ImageNet and Caltech-256. For Caltech-256, we exclude the clutter class and select 60 training images and 20 query images from each of the remaining 256 classes. Before computing its PCA feature, we convert each Caltech-256 image to RGB, center it on a square canvas padded with the RGB value (128, 128, 128), and resize it to pixels using bicubic interpolation with antialiasing.
Binary in-context episodes. Each episode is a binary classification task whose two classes determine the meaning of the labels within that context. At the beginning of every pretraining epoch, we randomly permute the pretraining classes and pair consecutive classes, ensuring that each class appears in exactly one task during that epoch. For each class in a task, we sample 50 demonstrations and 10 queries without replacement from its training features, with the demonstration and query sets disjoint within the task. Validation and testing instead enumerate all 45 unordered pairs of the corresponding ten held-out classes. For each pair, we form one fixed context from 50 training features per class and evaluate it on 10 query-split features per class, yielding 900 queries in each final test.
Transformer and optimization. We use a six-layer pre-normalization transformer with softmax attention, residual connections, and GELU feed-forward networks, thereby testing whether the qualitative prediction of the linear-attention theory persists in a standard nonlinear architecture. Each PCA feature is augmented with one of three learned embeddings that identifies a demonstration with label -1, a demonstration with label +1, or an unlabeled query. CIFAR-100 uses four attention heads and a feed-forward dimension of 1,024, whereas Tiny ImageNet and Caltech-256 use eight attention heads and a feed-forward dimension of 2,048; every attention head has dimension 64. A linear head applied after the final layer normalization produces the scalar score optimized with the logistic loss. We use Xavier uniform initialization for linear weights, zero linear biases, independent initialization for the three embeddings, and unit scales and zero biases for layer normalization. We train for 300 epochs with AdamW, exponential decay rates 0.9 and 0.95, numerical stability constant , weight decay 0.05, and global gradient clipping at 1.0. The standard and adversarial runs use peak learning rates of and , respectively, with linear warmup over the first 5% of updates followed by cosine decay to zero. We initialize the standard model from scratch and the adversarial model from the corresponding standardly trained model. Model selection minimizes the clean validation logistic loss for standard training and the 20-step PGD validation loss for adversarial training.
Adversarial training and evaluation. The real-world threat model follows the theoretical setting by perturbing only the query while keeping all demonstrations clean and fixed. Specifically, the adversary may change a query PCA feature within an ball of radius , where in both training and evaluation. Adversarial training uses untargeted 10-step PGD with one uniformly sampled random start and step size . For final evaluation, we measure robust accuracy using APGD-CE and binary FAB (Croce & Hein, 2020), each run for 100 iterations. We omit the remaining AutoAttack components because the DLR loss is undefined for scalar binary scores and Square Attack relies on spatial image structure.
B ROBUST BAYES IMPLEMENTATION BY LINEAR TRANSFORMERS: PROOF OF THEOREM 3.2
B.1 ROBUST BAYES CLASSIFIER
In this section, we characterize the robust Bayes classifier and its error for a fixed task independently of the linear-transformer architecture. For and thus , we derive the robust zero-one error of every linear function in Lemma B.1, the standard Bayes error in Lemma B.2, and the robust Bayes error and all linear functions attaining it in Lemma B.3. Then, for every and , we generalize these results in Lemma B.4.
Variants or equivalent formulations of these results appear in Hastie et al. (2009); Bhagoji et al. (2019); Dan et al. (2020). These lemmas are auxiliary to our main results, and we do not claim them as novel contributions. For completeness, we provide self-contained proofs, since adapting the existing results to our setting would require essentially as much exposition as proving them directly.
Lemma B.1 (Robust error of linear functions for the identity-basis task). Suppose that is uniform on and , where . For every , define by . Then, for every and ,
where denotes the cumulative distribution function of the standard normal distribution.
Proof. For every perturbation , the signed margin is
Cauchy–Schwarz shows that its minimum over the perturbation ball is
The class-conditional model implies
Since and , the variance is strictly positive. Therefore, standardizing the Gaussian signed margin gives
□
Lemma B.2 (Bayes error for the identity-basis task). Suppose that is uniform on and , where and . Then, for every measurable function ,
where denotes the cumulative distribution function of the standard normal distribution.
Proof. Lower bound. Let and denote the conditional densities of x given and , respectively. Since the two labels have equal probability, conditioning on y gives
For every , the integrand satisfies
Consequently,
Function that attains the lower bound. The Gaussian density formula gives
Therefore, the linear function is positive exactly when and negative exactly when . Because , the hyperplane on which has Lebesgue measure zero. Thus,
Value of the lower bound. The class-conditional model and the definition of imply
The mean and variance are both equal to , which is strictly positive because and . Standardizing therefore yields
□
Lemma B.3 (Robust Bayes characterization for the identity-basis task). Suppose that is uniform on and , where and . Suppose also that . There exists a unique satisfying
For this , define
Then, for every measurable function ,
Among linear functions, equality is attained exactly by the functions with .
Proof. Existence and uniqueness of . Let be the eigenvalues of , let be corresponding orthonormal eigenvectors, and write . For , the spectral theorem gives
Since both sides of the equation defining are nonnegative, that equation is equivalent to . Each map is continuous and strictly increasing from zero to one on . Because , at least one is nonzero, and hence is continuous and strictly increasing with
If , the equation has the unique solution . If , the inequality and the intermediate value theorem give a unique solution .
Lower bound. For the resulting , define the label-dependent perturbation . This perturbation is admissible because
Therefore, for every measurable function ,
The definition of implies
Consequently, the perturbed input has the class-conditional distribution
Since , applying Lemma B.2 to this symmetric Gaussian mixture gives
Attainment of the lower bound. Applying Eq. (A6) with to the linear function gives
The definitions of and give
Substitution into the preceding robust-error formula yields
Thus, attains the lower bound.
Uniqueness among linear functions. Positive scale invariance in Eq. (A6) shows that every positive multiple of attains the same lower bound. Fix . The identities and , followed by the Euclidean Cauchy–Schwarz inequality and the Cauchy–Schwarz inequality for the inner product induced by , give
The denominator is strictly positive because . Dividing by this denominator and using the strict monotonicity of in Eq. (A6) show that the robust error of is at least the lower bound. The robust error equals the lower bound only if both inequalities in the preceding display hold with equality. If , equality in the first inequality requires , which holds exactly when for some . If , the first inequality is automatically an equality, while equality in the -inner-product Cauchy–Schwarz inequality again holds exactly when for some . Conversely, every such positive multiple attains equality, as observed above. Finally, is identically zero and therefore has robust error one, whereas the lower bound is strictly less than one half because .
Lemma B.4 (Taskwise robust Bayes characterization). Suppose that (a) and (b) in Assumption 3.1 hold. For every and , define the linear function by
(a) For every and ,
(b) For every ,
Among linear functions, the robust Bayes error is attained exactly by the functions with .
Proof. Define and . Conditional on , the transformed input satisfies
Orthogonality of U gives
The map is a bijection of the perturbation ball onto itself.
Part (a). Applying Eq. (A6) to in the transformed coordinates proves Eq. (A40).
Part (b). For every measurable function , define by . The map is a bijection on the class of measurable functions, and the preceding change of coordinates gives
Applying Lemma B.3 in the transformed coordinates proves Eq. (A41). Its uniqueness conclusion for linear functions proves the final statement of part (b).
B.2 QUERY-LINEAR REPRESENTATION
Define the population second moment by
The latent finite-context matrix and its population limit are
The strong law gives almost surely. The corresponding ambient context matrix is
For a context matrix , define and, for , recursively define
For any context matrix G, define the depth-L effective direction by
Here, is the last standard basis vector of . The mask in Eq. (4) removes the query column from every context matrix. Induction over the layers therefore shows that every depth-L transformer is linear in its query:
B.3 KRYLOV STRUCTURE AND SUFFICIENT-DEPTH REALIZATION
Define the feature and label projectors by
We first relate the active spectra of and .
Lemma B.5 (Active spectrum under the rank-one update). The matrix has exactly distinct active eigenvalues, where an eigenvalue is active when its orthogonal spectral projector satisfies and is defined in Eq. (2).
Proof. Since , induction in both directions gives
The spectral decomposition of and the Vandermonde determinant show that the right-hand side has dimension , the number of distinct covariance eigenvalues with nonzero projection of . For any symmetric matrix, the dimension of the Krylov space generated by a vector equals the number of distinct eigenvalues whose spectral projectors do not annihilate that vector. Applying this fact to proves the claim.
We characterize the population output induced by block-selective parameters. We then choose their scalar coefficients to interpolate the desired response on the active spectrum.
Lemma B.6 (Population response of block-selective processing layers). Fix an integer . For , let and define
Set . Set and , and, for , recursively define
. (A54)
Then,
Consequently,
Proof. The claim is immediate at . Suppose that the claimed block form holds after layers, where , and denote this cumulative transformation by . Direct block multiplication gives
Substituting this expression and the -st parameters from Eq. (A53) into Eq. (A48) gives the recursion in Eq. (A54) and proves Eq. (A55) by induction. The definition in Eq. (A49) gives .
Lemma B.7 (Sufficient-depth population optimal-direction comparator). Fix and , define , and suppose that . There is a parameter tuple such that, for every ,
Proof. Let be the active eigenvalues of S, whose number is r by Lemma B.5, and set
It is enough to construct the first layers in latent coordinates at the population context . For the first layers, use the notation and response recursion of Lemma B.6 with .
These layers process active eigenvalues sequentially. At the beginning of stage , let be the indices not yet processed and define
We maintain the invariant that these numbers are positive and pairwise distinct. This holds initially because . Let be the unique index attaining their minimum and set
where c > 0 will be chosen sufficiently small. Equation Eq. (A54) then gives
Every later increment of either response at this eigenvalue contains a factor , so the response remains fixed. For every remaining index , the next transformed value is
The function is positive and strictly increasing for , because its derivative is . Thus, positivity and pairwise distinctness hold at the next stage. When , induction gives and at every stage. The finitely many responses and denominators in Eq. (A61) depend continuously on near zero, so some sufficiently small makes every denominator nonzero.
Suppose first that , and let denote the single index left after these stages. Let and define
The strict inequality holds because the Schur complement of the bottom-right entry of is and has final coordinate one. In the final layer, choose
Direct block multiplication gives , where
Shrinking if necessary ensures that , because this expression is continuous in and equals one at . Set
The denominator defining is therefore nonzero because the induction invariant also gives . Equations Eqs. (A62), (A66) and (A67) imply
If , the same conclusion follows directly by choosing and . The spectral theorem and activity of give
and the Sherman–Morrison identity gives
Every constructed parameter commutes with , so rotation equivariance gives Eq. (A58) at depth . If , set for . These additional zero layers leave the effective direction unchanged, completing the proof for every .
We finally transfer the constructed comparator from the population context to finite contexts.
Lemma B.8 (Finite-context accuracy of the sufficient-depth comparator). Under the conditions of Lemma B.7, let and be the comparator and target direction constructed there. There is a constant such that, for every and ,
Proof. Conditional on any fixed U, induction in Eq. (A48) gives
The right-hand side is a fixed polynomial in the entries of and whose value at is . For every fixed integer , Gaussian sample-moment bounds give
for a constant . Expanding the polynomial difference around and applying these bounds to its finitely many monomials proves Eq. (A71).
Lemma 3.3 (Proof sketch of Theorem 3.2). Suppose that (a) and (b) in Assumption 3.1 hold. Suppose also that ; write . Let be the unique solution of
(Bayes classifier) For every ,
(Krylov order of the optimal direction) Let . Then,
(Effective weights of a linear transformer) There exists a parameter family whose corresponding effective weights satisfy, for every , , and ,
(Span of the effective weights) For the same parameter family,
Proof. Part (i) is the optimal-direction conclusion of Lemma B.4.
For part (ii), let be the distinct active eigenvalues of . Polynomial interpolation gives a polynomial of degree at most satisfying for every . The spectral theorem gives
The polynomial has degree exactly . This is immediate when . If and had smaller degree, then would have degree at most and vanish at the distinct points , so it would vanish identically. This contradicts its value at . Since are linearly independent, the nonzero leading coefficient of implies , proving part (ii).
For parts (iii) and (iv), fix and define the shared parameter tuple by
These parameters do not depend on . Set . Direct induction in Eq. (A48) at the latent population context gives
Solving this scalar recursion yields
Since and commute with , rotation equivariance and Eq. (A49) give
Therefore, the population-context version of Eq. (A50) gives
which proves part (iii).
Choose distinct nonzero numbers . Relative to the monomial basis , the coefficient matrix of has entries and reduces to an invertible Vandermonde matrix after nonzero row and column scalings. Hence, spans all polynomials of degree at most . Since , induction on the Krylov order gives . Combining these facts yields
(A80)
proving part (iv).
Theorem 3.2 (A single linear transformer can be Bayes optimal across tasks). Suppose that (a) to (c) in Assumption 3.1 hold. Then, there exists a parameter such that, for every ,
The implied constant may depend on d, , , and .
Proof. Fix , , and . Let be the parameter tuple from Lemma B.7 with the solution of Eq. (A24) and . Define for . By Eq. (A40), this function does not depend on . By Lemma B.4, and is a global minimizer of . The vector is nonzero, so is twice continuously differentiable on a neighborhood of . Its gradient vanishes at this global minimizer, and Taylor's theorem gives a quadratic upper bound for on a sufficiently small ball centered at . Outside that ball, the same bound holds after increasing its constant because and the distance from is bounded away from zero. Consequently, there is a constant such that
Let denote the excess error on the left-hand side of Eq. (8) with . Conditional on a realized context, Lemma B.4 and Eq. (A81) give
Taking the conditional expectation and applying Lemma B.8 yield
Markov's inequality therefore gives
Since was arbitrary and the constants are independent of , this proves Eq. (8) with .
C ADVERSARIAL AND STANDARD TRAINING: PROOFS OF THEOREMS 3.4 AND 3.5
C.1 DIRECTIONS SELECTED BY INFINITE-SAMPLE MARGIN RISKS
For , define the population margin risk
The following result shows that minimizing this population surrogate risk selects the corresponding Bayes-optimal direction.
Lemma C.1 (Population margin-risk minimizers align with Bayes-optimal directions). Suppose that . Then the function is strictly convex and coercive and therefore has a unique minimizer , which is nonzero. There is a constant such that
Proof. For every fixed , the map is concave, so its composition with the convex nonincreasing function is convex. For two distinct directions, the corresponding random margins differ almost surely because . Strict convexity of , together with concavity of the margin map, therefore makes the expected risk strictly convex. Moreover, for every unit vector and ,
This bound follows from the tangent inequality for on the event and nonnegativity of on its complement. The expectation on the right is positive and continuous in , so compactness of the unit sphere gives a positive uniform lower bound. Hence, is coercive and has a unique minimizer. Its one-sided derivative at the origin along equals , so the minimizer is nonzero.
Let and set . The derivative bounds and Gaussian moments justify differentiation under the expectation and the Gaussian integration by parts below. The first-order condition at the nonzero minimizer is
Gaussian integration by parts gives
Substitution into the first-order condition yields
Setting gives
Uniqueness in Lemma B.3 gives . Setting proves Eq. (A86).
C.2 INFINITE-SAMPLE MINIMIZERS AND FINITE-CONTEXT TRANSFER
The infinite-task, infinite-context risk is
The preceding result also identifies the infinite-sample global optimum of the unrestricted transformer risk, independently of gradient dynamics.
Theorem C.2 (Functional identification of unrestricted fixed-depth infinite-sample minimizers). Suppose that and . The unrestricted infinite-task, infinite-context risk in Eq. (A92) attains the lower bound
Every global minimizer satisfies
for every . In particular, standard training identifies the direction , whereas adversarial training identifies the direction in Eq. (A25).
Proof. Fix satisfying . Conditional on , orthogonality gives
Apply Lemma B.7 with the solution of Eq. (A24) and . Equation Eq. (A86) shows that the resulting comparator attains equality simultaneously for every . Hence, the lower bound in Eq. (A95) is attainable simultaneously for every , proving Eq. (A93). If a parameter tuple attains this value, the nonnegative conditional optimality gap in Eq. (A95) has expectation zero. The effective direction in Eq. (A49) is continuous in , so this conditional optimality gap is continuous on . Since normalized Haar measure has full support, a nonnegative continuous function with zero Haar integral vanishes everywhere. Strict convexity from Lemma C.1 therefore gives Eq. (A94) for every .
For and , define
and set .
Lemma C.3 (Uniform finite-context transfer). Fix a depth-L parameter tuple and suppose that there is a nonzero vector such that its population-context effective direction in Eq. (A49) satisfies
Then, for every satisfying ,
Proof. Couple the contexts for all task bases using the same latent vectors . Equations Eqs. (A46) and (A47) and the strong law give
almost surely. Continuity of the fixed-depth recursion in Eq. (A48) and compactness of imply that the finite-context latent direction converges to uniformly over almost surely. Since , the map is continuous on a neighborhood of the limiting directions. By Lemma B.4, the conditional robust-error formula therefore converges uniformly over almost surely. Since the robust errors and their limit belong to , bounded convergence gives
Under the coupling above, the distribution of each context agrees with that of conditional on its task basis, and hence
which proves Eq. (A98).
C.3 FINITE-TASK ADVERSARIAL RISK MINIMIZATION
In statements and arguments involving a single generic task, we suppress the task index from , , , , and derived quantities, whereas we retain when the training tasks are considered jointly. The parameter constraint in Eq. (21) makes the empirical minimum attainable and is assumed to contain the comparator from Lemma B.7. For parameter tuples, denotes the Euclidean product of the matrix Frobenius norms.
Let denote the distribution of a generic task induced by the generative process. Let consist of independent tasks drawn from . For the finite-context representation above, the finite-sample risk in Eq. (6) at perturbation level is
Its infinite-task counterpart at context length N is
Theorem 3.4 (Adversarial training yields robust linear transformers). Suppose that Assumption 3.1 holds. For sufficiently large B > 0, choose any empirical risk minimizer
Then, for every ,
The implied constant may depend on d, B, L, , , , and .
Proof. Let be the comparator from Lemma B.7 with the solution of Eq. (A24) and from Eq. (A86).
Uniform concentration over training tasks. Let denote the summand in Eq. (A102), where contains one context and its independent query. Equations Eqs. (A48) and (A49) show that is a polynomial of fixed degree in and . Compactness of the parameter constraint in Eq. (21) and boundedness of imply the existence of nonnegative envelopes and such that
The envelopes can be chosen as fixed polynomials in and , with coefficients independent of and . The Gaussian task model and the averaging in give
The constrained parameter set is compact and finite-dimensional and hence has logarithmic Euclidean covering entropy in the covering radius. Define
Symmetrization, the Euclidean covering bound, and Cauchy–Schwarz with Eq. (A105) yield a constant such that, for every ,
Loss geometry and calibration. Define , and
By Lemma C.1, . Positive scale invariance of and Eqs. (A40), (A41) and (A96) therefore give
The function is twice continuously differentiable near the nonzero vector , and its gradient vanishes there. Set and Z^\star := h_\epsilon^\star^\top a - \epsilon \sqrt{d} \|h_\epsilon^\star\|_2. Direct differentiation at gives, for every ,
The strict inequality holds because the first expectation is positive by and , while the second term is nonnegative by . Taylor's theorem gives a quadratic upper and lower bound for the margin-risk gap on a neighborhood of . Boundedness of makes globally Lipschitz, so its quadratic upper bound extends outside this neighborhood because is then bounded away from zero. Uniqueness and coercivity of extend the truncated lower bound. Positive scale invariance of , the identity from Eq. (A86), and Eq. (A81) give . Consequently, there are constants such that, for every ,
Finite-context comparator and finite-sample risk. Set . Applying Lemma B.8 with gives
The infinite-context direction of is , so Eq. (A92) gives . The quadratic upper bound in Eq. (A116) therefore gives
Every conditional latent risk is at least by Lemma C.1. The minimizing property in Eq. (21) and the definition of yield
(A119)
Uniform calibration over the task basis. We next record the finite-dimensional comparison that turns Haar averages into worst-task bounds without changing the rate. Let be an upper bound on the total degree in the entries of of the latent direction , and let be the vector space of restrictions to of -valued polynomials of degree at most . Since is finite dimensional and normalized Haar measure has full support, its uniform norm and its norm under Haar measure are equivalent. Hence, there is such that
Consequently,
Since , every satisfies
Using the coupled latent context matrix from Eq. (A46), the ambient context is . The recursion in Eq. (A48) uses only matrix addition and multiplication, so for fixed latent vectors and fixed , the map
(A123) belongs to , with a degree bound independent of , , and the realized latent vectors. Applying Eqs. (A116) and (A122) for each fixed latent context and then taking expectations gives
(A124)
Conditional on the pretraining sample, apply Eq. (A119) to Eq. (A124) with , and then take the expectation over the pretraining sample. Define
Then, for every fixed ,
Since the excess error is nonnegative, Markov’s inequality shows that, for every ,
This proves Eq. (22).
Theorem 3.5 (Standard training does not yield robust linear transformers). Suppose that Assumption 3.1 holds. Suppose also that ; write and . For sufficiently large , choose any population risk minimizer
Then, there exists a constant such that, for every ,
The constant C may depend on d, , , and .
Proof. Define . Applying Eq. (A86) at , the unique minimizer of the standard latent margin risk is . Let be the comparator from Lemma B.7 with and , and take sufficiently large that this comparator is feasible in Eq. (23). The conditional lower bound in Eq. (A95) and the comparator construction give
for every parameter tuple . Therefore, the minimizing property in Eq. (23) implies that is also an unrestricted global minimizer of the infinite-sample standard risk. Applying Theorem C.2 yields, for every ,
Hence, query linearity, positive scale invariance of , and Lemma B.4 give
(A130)
In particular, the right-hand side is independent of U.
If , then and , so Eq. (A130) is zero. Suppose next that , and let be the unique active eigenvalue of . Then and , so the two directions are positive multiples of each other and Eq. (A130) is again zero.
It remains to consider and . Equation Eq. (A24) implies . Choose two distinct active eigenvalues of , with spectral projectors and . If for some , then projecting this identity onto either active eigenspace gives
This is impossible because and . Thus, is not a positive multiple of , so the uniqueness conclusion of Lemma B.4 shows that its robust error is strictly larger than the robust Bayes error. Consequently, the constant
is strictly positive, and Eq. (A130) equals for every . In the zero-gap cases, any positive choice of is admissible because that constant does not appear in the corresponding branch of Eq. (24).
D GRADIENT FLOW TO ROBUST BAYES OPTIMALITY
For each task t, the adversarial loss as a function of the last-layer parameter takes the form
Because the Euclidean norm is nondifferentiable at , this objective need not be differentiable when ; we therefore use subgradient flow, which agrees with ordinary gradient flow wherever all effective directions are nonzero.
Theorem D.1 (Bayes consistency of last-layer gradient flow). Assume and . Suppose that Assumption 3.1 holds. For sufficiently large , let . Fix any . Let be the unique global solution to the Frobenius subgradient flow
Assume that contains a population-risk minimizer and, almost surely, the entire unconstrained subgradient-flow trajectory . Then, for every and ,
Proof. For task t, let be its finite-context matrix in Eq. (A47).
The final cumulative transformation and its effective direction are
Thus, is affine in . Since is decreasing, query linearity gives
For every , the argument of in Eq. (A137) is concave in . Because is convex and decreasing, its composition with this argument is convex. Hence, is finite, continuous, and convex.
We next show that the restricted last-layer class contains an infinite-sample optimal comparator. For , define . Replacing the finite-context matrix in Eq. (A136) by the population context and multiplying the blocks at gives the population latent direction
The same latent direction is realized for every because the fixed prefix and commute with . Let and recall that by assumption. The subspace contains and, by Eq. (A86), , and it is invariant under . By Lemma B.5, has exactly distinct active eigenvalues on . Write
If , then spans . If , the spectral theorem and strict monotonicity of on the positive active eigenvalues make and linearly independent. Thus, span in both cases. Since , Eq. (A140) therefore gives scalars such that . Set , which belongs to by the choice of . Equation Eq. (A92) and the optimality of show that minimizes even within the unrestricted depth-two class.
Continuity of the finite-sample risk and compactness of give a finite-sample minimizer
Since the finite-sample risk is finite, continuous, and convex, its subdifferential is maximal monotone. Therefore, the flow in Eq. (A133) exists uniquely for all .
Because and belong to , the finite-sample risk gap between them is nonnegative. The subgradient inequality gives, for almost every ,
The convex subgradient-flow chain rule shows that the finite-sample risk is nonincreasing along the flow. Integrating the preceding inequality and using this monotonicity and gives, for every ,
It remains to transfer empirical optimization to robust Bayes error. Since is fixed, Eq. (A48) makes its finite-context direction a fixed polynomial in the empirical latent moments whose population value is . The Gaussian sample-moment bound in Eq. (A73) therefore gives, for every ,
The quadratic upper bound in Eq. (A116) therefore yields
Define the restricted uniform deviation
The uniform concentration argument in the proof of Theorem 3.4, with parameter bound and restricted to the compact last-layer class, gives
(A148) uniformly over . Fix any . Since minimizes the finite-sample risk over and , Eqs. (A124) and (A144) give
(A149)
Taking the expectation over the pretraining sample and applying Eqs. (A146) and (A148) give a constant C > 0 such that
Markov's inequality therefore gives, for every ,
which proves Eq. (A134).
E ACCURACY-ROBUSTNESS TRADE-OFF
Theorem E.1 (Adversarial training loses standard accuracy). Suppose that Assumption 3.1 holds. Suppose also that ; write and . For sufficiently large , choose any population risk minimizer
Then, there exists a constant C > 0 such that, for every ,
The constant C may depend on d, , , and .
Proof. Define . By Eq. (A86), the unique minimizer of the adversarial latent margin risk is for some . Let be the comparator from Lemma B.7 with the solution of Eq. (A24) and , and take sufficiently large that this comparator is feasible in Eq. (A152). The conditional lower bound in Eq. (A95) and the comparator construction give
for every parameter tuple . Therefore, the minimizing property in Eq. (A152) implies that is also an unrestricted global minimizer of the infinite-sample adversarial risk. Applying Theorem C.2 yields, for every ,
Hence, query linearity, positive scale invariance of , and Lemma B.4 give
(A156)
In particular, the right-hand side is independent of U.
If , then and , so Eq. (A156) is zero. Suppose next that , and let be the unique active eigenvalue of . Then and , so the two directions are positive multiples of each other and Eq. (A156) is again zero.
It remains to consider and . Equation Eq. (A24) implies . Choose two distinct active eigenvalues of , with spectral projectors and . If for some , then projecting this identity onto either active eigenspace gives
This is impossible because and . Thus, is not a positive multiple of , so the uniqueness conclusion of Lemma B.4, applied at perturbation radius zero, shows that its standard error is strictly larger than the standard Bayes error. Consequently, the constant
is strictly positive, and Eq. (A156) equals for every .
F DEMONSTRATION COMPLEXITY
Theorem F.1 (Robust prediction requires more demonstrations). Suppose that, for constants ,
Fix any depth . For every target error , define
Then, for every fixed and all sufficiently large ,
The constants hidden in depend only on c, C, and .
Proof. Write .
The robust Bayes error is asymptotically attained by the mean direction. For every unit vector , define its robust standardized margin by
By Lemma B.4, the robust Bayes error is , where . Substituting gives
Every maximizer therefore has a positive numerator in Eq. (A162), and hence
The spectral bounds and Eq. (A164) imply
The numerator of is at most , while every denominator in Eq. (A162) is at least . It follows that
Since the standard normal density is bounded, Eq. (A166) yields
uniformly over .
The empirical-mean predictor. Given N demonstrations, define
For every depth , this predictor is realized by setting for , , and . Conditional on a task basis , its latent direction is
One demonstration suffices for standard prediction. For , Eq. (A169) and the spectral bounds give
Hence, the standardized clean margin diverges in probability:
Equations Eqs. (A40) and (A171), boundedness of the error, and convergence in probability imply
The standard Bayes error is nonnegative, so Eq. (A172) shows that, for every fixed and all sufficiently large ,
Upper bound for robust prediction. Fix , set , and define . Let . Markov's inequality and Eq. (A159) give
On A, normalization is Lipschitz and therefore
Taking expectations in Eq. (A175) yields
for a constant depending only on c and C. Moreover, Cauchy–Schwarz, Eq. (A174), and the same normalization bound give
The map is uniformly Lipschitz on the unit sphere under Eq. (A159). Combining Eqs. (A40), (A167), (A174), (A176) and (A177) with the Lipschitz continuity of gives
(A178) for a constant depending only on c and C. Choosing proves
uniformly over L.
Lower bound for robust prediction. A standard volumetric packing argument gives unit vectors such that
for a numerical constant . Fix a constant , to be chosen sufficiently large below, set , and, for each , let be the rotation through angle in the plane spanned by and that maps to
and acts as the identity on the orthogonal complement of this plane. For all sufficiently large d, Eq. (A180) implies
Let be the distribution of one labeled demonstration under task . The label is independent of the task, while the signed feature has distribution
Each difference has rank at most four and Frobenius norm . In particular,
To control the covariance contribution to the Gaussian relative entropy, apply on the compact interval to the eigenvalues of
The Gaussian relative-entropy formula, Eqs. (A159) and (A184), and this scalar bound give
for a constant depending only on and . Fix and suppose that . Tensorization, Eqs. (A180) and (A186), and Fano's inequality show that every estimator based on demonstrations satisfies
By Eq. (A50), every linear transformer has an effective direction determined by the demonstrations. Assign an arbitrary unit direction when this effective direction is zero, and otherwise normalize it to obtain . Decode the task by choosing the element of nearest to . Whenever this decoder is incorrect, Eq. (A182) gives
On this event, the numerator in the conditional robust-error formula is bounded below by
The choice makes this lower bound nonnegative. Its standard deviation is at most by Eq. (A159). Thus, Eqs. (A40), (A187) and (A189) lower-bound the robust error averaged over the packed tasks by
The zero effective direction itself has robust error one, so the arbitrary assignment made above does not weaken the lower bound. The mean direction is a feasible robust classifier, so
Since , first choose sufficiently large and then sufficiently small that the lower bound in Eq. (A190) is strictly larger than for all sufficiently large . The worst-task error is at least the average over the packed tasks, so Eq. (A191) implies
uniformly over . Combining Eqs. (A173), (A179) and (A192) proves Eq. (A161).