We study in-context learning problems where a Transformer is pretrained on tasks drawn from a mixture distribution
π=∑α∈Aλαπα, called the pretraining prior, in which each mixture component
πα is a distribution on tasks of a specific difficulty level indexed by
α. Our goal is to understand the performance of the pretrained Transformer when evaluated on a different test distribution
μ, consisting of tasks of fixed difficulty
β∈A, and with potential distribution shift relative to
πβ, subject to the chi-squared divergence
χ2(μ,πβ) being at most
κ. In particular, we consider nonparametric regression problems with random smoothness, and multi-index models with both random smoothness and random effective dimension. We prove that a large Transformer pretrained on sufficient data achieves the optimal rate of convergence corresponding to the difficulty level
β, uniformly over test distributions
μ in the chi-squared divergence ball. Thus, the pretrained Transformer is able to achieve faster rates of convergence on easier tasks and is robust to distribution shift at test time. Finally, we prove that even if an estimator had access to the test distribution
μ, the convergence rate of its expected risk over
μ could not be faster than that of our pretrained Transformers, thereby providing a more appropriate optimality guarantee than minimax lower bounds.