Manuscript Offprint
arXiv:2610.21901In-Context Learning Before Specialisation: Theory of Learning in a Solvable Topic Model
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
ABSTRACT
Sequence models can generalise in fundamentally distinct ways: extrapolating structures seen in training, or using their prompt to adapt to novel tasks. The prevailing strategy determines how the model behaves beyond its training distribution, controlling potential capabilities and risks. Recent work has characterised many different strategies theoretically, and empirically described the transition between them as the quality and quantity of pretraining data vary. However, there is no learning theory for this competition, hence no fundamental understanding of why one solution might be favoured over another. Here we provide such a theory in a solvable topic model—documents drawn from a finite mixture of latent topics, mirroring the heterogeneity of modern pretraining data. The dataset comes with two distinct solutions: a specialised predictor, that stores the finite topic mixture, and an in-context one, optimal for topics never seen during training. Our theory predicts their emergence at distinct sample complexities: the in-context predictor is available early, while the specialised one emerges only after the training tokens outnumber the parameters of the data-generating process. Trained transformers reproduce both scales and the separating crossover in remarkable agreement with the theory, with no fitted parameters.


Figure 1: In-context learning and specialisation in a random topic model. Left: A random topic model consists of topics, i.e. unigram probabilities over a vocabulary of size . Training sequences are obtained by sampling a topic uniformly, then tokens i.i.d. from . Right: Learning curve of a one-layer transformer trained for next-token prediction on a random topic model with . Initially, both In-Distribution (ID, on the training topics, blue) and Out-Of-Distribution (OOD, on a new topic , orange) descend with towards the entropy of the Bayes-optimal OOD predictor (orange dotted): the add-one estimator . Later, the predictor specialises to the training topics: the ID loss converges to the ID Bayes-optimal floor (blue dotted), while the OOD loss rises as in overfitting. Code: https://github.com/fracagnetta/random-topic-model.
Correspondence to: fr.cagnetta@gmail.com.
1 INTRODUCTION
Large language models generalise in ways that were not anticipated in training. In particular, novel behaviours can be elicited simply via prompting, including few-shot learning of supervised tasks (Brown et al., 2020) or adopting different roles depending on a set of instructions (Shanahan et al., 2023). This In-Context Learning (ICL) mechanism is not captured by the classical learning-theoretic paradigm, where a model is evaluated on fresh samples from the same the distribution it was trained on. Nevertheless, ICL is a critical source of both generality and risk (Anwar et al., 2024) in modern AI systems, calling for a theory of what trained models do beyond their training distribution.
An early theoretical attempt framed ICL as implicit Bayesian inference of the latent concept behind the prompt (Xie et al., 2022). This framework has found extensive support: trained transformers behave as Bayes-optimal estimators for many families of tasks (Garg et al., 2022), and how such estimators are represented and acquired during training is understood in simple settings (Nichani et al., 2024; Edelman et al., 2024; Lu et al., 2025; Zhang et al., 2025; Bondaschi et al., 2026). However, other settings admit distinct classes of predictors, and models transition between them as the training conditions vary (Akyürek et al., 2023). Raventos et al. (2023) identified task diversity as the key control parameter: When trained at low diversity, the transformer can only memorise the training tasks, acquiring general ICL abilities only above a certain task-diversity threshold.
The role of task diversity has been explored in synthetic data, revealing that the competition between the two behaviours extends along training time (Singh et al., 2023; Reddy, 2024; Nguyen & Reddy, 2025; Park et al., 2025; Gibson et al., 2026), culminating in a hierarchical Bayesian framework that fits the model behaviour to a weighted mixture of the memorising and generalising predictors (Carroll et al., 2025; Wurgaft et al., 2025). This framework is phenomenological: still missing is a microscopic theory that predicts the favoured solution from data properties alone, and how much data it takes for one solution to give way to the other.
Our Contribution Here we provide this theory in a synthetic dataset containing the minimal required ingredients: a task diversity parameter D, a vocabulary of size K, a document length T and a corpus of N training documents. Task diversity enters as a mixture of D latent topics from which documents are generated (Fig. 1, left). In this setting, we provide:
• A solvable model of strategy competition. We characterise analytically two distinct Bayes-optimal predictors: a specialised one, relying on knowledge of the D topics in the data-generating process, and an in-context one, equivalent to the add-one estimator from statistics under our data model (Sec. 2).
• A first-principles learning-curve theory for specialisation. We derive the specialisation learning curve in a Bayesian learning setting: the excess loss over the asymptotic floor is at leading order—a function of the number of training tokens per parameter of the data-generating process (Sec. 3).
• A statistical mechanism for the in-context phase. The in-context predictor is linear in the token counts, and a learner that estimates this map from data acquires it at a sample complexity set by its parameters and by the information that a context carries about the next token: both independent of D. Hence, comparison with the specialisation scale gives a task-diversity threshold above which (see Fig. 1) the in-context solution emerges first, it remains stable in a window that widens with task diversity, then it gives way to the specialised solution (Sec. 4).
• Parameter-free agreement with trained transformers. Across vocabularies, task diversities, sequence lengths and corpus sizes, transformer in-distribution losses collapse as functions of , converging to the specialised solution at the predicted rate. Non-trivial ICL performance develops at the predicted, D-independent sample complexity, then vanishes again with specialisation (Sec. 5).
• Separation from classical spectral methods. Reconstructing the topics from low-order moments (Hsu et al., 2012; Anandkumar et al., 2014) requires resolving a Marchenko–Pastur bulk of eigenvalues, which takes samples: a worse scaling with task diversity than the Bayes-optimal followed by trained transformers (Sec. 5.1).
1.1 RELATED WORK
Mixtures of tasks as ICL testbeds. Finite task mixtures underlie most theoretical studies of ICL: linear regression (Garg et al., 2022; Akyürek et al., 2023; Raventos et al., 2023; Lu et al., 2025; Zhang et al., 2025; Bordelon et al., 2026; Letey et al., 2026), classification (Reddy, 2024; Nguyen & Reddy, 2025), and mixtures of Markov (Edelman et al., 2024; Park et al., 2025; Bondaschi et al., 2026; Gibson et al., 2026) and hidden Markov (Riechers et al., 2025; Ray et al., 2026) models. The “Balls & Urns” setting of Wurgaft et al. (2025) is precisely the random topic model studied here, and their memorising and generalising predictors are our specialised and in-context ones. Our work complements their phenomenological Bayesian framework: where they assume a scaling law and a low-Kolmogorov-complexity bias, we derive the sample complexities of the two predictors from first principles. Thus, our approach does not require estimating Kolmogorov complexities and fitting parameters, but rather prescribes a simple picture where the functional simplicity of the ICL solution promotes its emergence as long as it leads to a noticeable loss gain with fewer data.
Representations, Belief-state geometry and task vectors. Due to next-token pretraining, transformers linearly represent the belief state over latent structure (Shai et al., 2024). In particular, mixtures of independent components, or non-ergodic sources, give rise to a telescopic geometry, which sparsifies along the context (Ray et al., 2026). The random topic model is the simplest non-ergodic source, and our results predict the sample dependence of the resulting belief geometry. Beyond controlled data structures, ICL has been linked to task vectors encoding the inferred task (Hendel et al., 2023), whose geometry distinguishes dual modes of task inference corresponding to our two predictors (Yan et al., 2026). Overall, these approaches describe how a trained network implements the chosen strategies; ours predicts when the data favours each.
Learning theories of ICL. Most analytical studies of learning focus on the infinite-data and infinite-diversity limit. Lu et al. (2025) is closest to us: they solve linear attention trained on Gaussian regression in a proportional asymptotic limit, obtaining sharp learning curves and a genuine transition with increasing task diversity. However, since their linear model cannot fit the specialised predictors exactly, they did not observe the crossover from in-context to specialised predictor as the number of data increases. Furthermore, our setup can be extended to mixtures of Markov chains (Gibson et al., 2026) and generic hidden Markov models (Riechers et al., 2025).
Random Topic Model A dataset is specified by a vocabulary size , a number of topics and a document length . Each topic is a probability distribution over the vocabulary, with entries for , drawn independently and uniformly from the simplex, for , and then held fixed. We collect the topics as the columns of the topic matrix . A document is generated by drawing a topic index uniformly from , then tokens independently from (Fig. 1, left). Given the topic, the likelihood of a context depends only on its histogram, the count vector
The training corpus consists of N documents, all generated with the same topic matrix P.
Data versus topic distribution. Two kinds of averages appear throughout. denotes the expectation over documents at fixed topic matrix , i.e. over the topic index and the tokens: this is the average that defines the loss of any predictor, including a trained transformer. denotes the further average over the draw of the topics. Unless stated otherwise, the curves in the figures are averaged over independent realisations of the topic matrix .
Next-token prediction, In- and Out-Of-Distribution. We consider two test distributions. In-distribution (ID) documents are generated as the training ones, from one of the topics of . Out-of-distribution (OOD) documents are generated from a fresh topic , drawn from the same prior as the training topics but independently, and hence almost surely different from all of them. A next-token predictor maps each context to a distribution over . We measure ID performance by the next-token loss at context length , or -gram entropy
where the expectation is over fresh documents generated from the training topics. The same expectation over a fresh topic defines the OOD loss . The usual autoregressive loss is the average of over positions.
2.1 THE SPECIALISED PREDICTOR
A learner that knows the topic matrix P still does not observe the topic Z of a given document, and must infer it from the context. The Bayes-optimal next-token distribution is the posterior mixture of the topics,
where the posterior over the topic depends on the context only through the counts. is the true conditional distribution of given the context, hence it minimises over all predictors (App. B). We call it specialised, as it is built from the topics realised in training.
The cross-entropy loss splits into an entropy plus a Kullback–Leibler divergence,
both averaged over the unknown topic. The first term is the loss of an oracle that observes the topic, and no predictor can go below it: it is the entropy rate of the data-generating process. For sufficiently large , the entropy rate converges to the average over draws of the topic matrix , which is for large (App. A), with Euler's constant. The second term is the excess loss due to the uncertainty on the topic and, by Eq. 3, it is controlled by the posterior mass on the wrong topics . As shown in App. B, the mass on a wrong topic decays exponentially in , at a rate given by the divergence . For random topics this divergence is of order one (App. A), so that discriminating the true topic from the other requires a context of length (App. B). This scale is visible in the left panel of Fig. 2.
2.2 THE IN-CONTEXT PREDICTOR
Consider now an OOD document, generated from a new topic that does not belong to the topic matrix . A learner that knows the prior but not must infer from the context the topic itself, rather than its index within a known dictionary. By Dirichlet categorical conjugacy, the posterior over given is , and the Bayes-optimal next-token distribution is its mean, the add-one smoothing of the histogram (App. C)
We call it in-context as it does not depend on the topic matrix P, and thus applies unchanged to documents from seen or unseen topics.
The OOD loss of decomposes as in Eq. 4, with the unseen topic in place of ,
where the expansion holds at fixed K for (App. C). Simply put, the histogram needs to include at least order K tokens to depart from a trivial prediction . Note that, since is drawn from the same prior as the topics of P, the entropy floor is the same for the two predictors, while the approach is significantly different (see Fig. 2, left). Identifying one of D known topics requires nats of evidence, which the context delivers at a constant rate per token, hence the exponential convergence of Sec. 2.1. Estimating a new topic is instead a -dimensional problem, and the excess in Eq. 6 is the classical half of the number of parameters per observation behaviour.

Figure 2: Next-token loss profiles of the two Bayes-optimal predictors and of trained transformers, for K = 64 and T = 128. Left: ID loss of the specialised predictor for D from 32 to 8192 (colour), averaged over realisations of the topic matrix, and OOD loss of the in-context predictor (black dashed), which does not depend on D. Dotted line: log K. Markers: context length at which each specialised profile has covered half of its descent, growing as log D (grey guide; Sec. 2.1). Middle and right: the same two references at D = 32 and D = 8192, with the ID (blue) and OOD (orange) loss profiles of a one-layer transformer trained on N documents at that D, mean s.e. over four runs with independent topic matrix, corpus and initialisation, at the checkpoint of minimal validation loss. At D = 32 the transformer matches the specialised predictor in distribution and stays above log K out of distribution; at D = 8192 both profiles follow the in-context predictor.
3 LEARNING-CURVE THEORY OF SPECIALISATION
The training corpus contains only the D topics in the matrix P. Hence, a sufficiently expressive, well-optimised machine learning model must converge to the specialised solution Eq. 3 in the infinite-data and training time limit. But how many training documents does it take to specialise?
Bayesian learning We answer this question with a Bayesian learner that uses the training corpus optimally: It knows the model class, including and , but not the realised topic matrix , and observes a collection of length- training documents, together with the test context. The training corpus informs a posterior over the topic matrix , proportional, by Bayes' rule, to prior times the joint probability of the corpus under , . The Bayes-optimal learner is the posterior mean of the -dependent specialised predictor from Eq. 3,
where the posterior also includes the test context (see App. D for details). Note that, after averaging over the draw of the topics, no predictor built from the same data has a lower loss than . Its loss is the statistical limit of specialisation from N training documents, hence a natural reference against which a transformer trained on the same corpus can be measured.
Learning curve and mutual information. The learning curve of specialisation is the excess loss of the Bayes-optimal learner over the specialised predictor, averaged over topic matrices,
Averaging over the topics gives it an information-theoretic meaning: is the conditional mutual information between and the next token, given corpus and context (App. D),
(9) where adds the test document to the corpus. The excess loss of the learner on the test document equals the information that this document adds about the topic matrix. Thus, the learning curve quantifies how fast the corpus reveals P.
The DK/NT law. The topic matrix has free parameters, and a corpus of N documents reveals them at the rate of parametric statistics: under identifiability and regularity, (Clarke & Barron, 1990; 1994). The increment gives the leading term of the learning curve at fixed D and K (App. D),
Specialisation thus requires , and the learning curve is a function of the number of training tokens per parameter, , decaying as . As shown in Sec. 5, trained transformers specialise on the same sample-complexity scale, and with the same decay. Two remarks. First, identifiability, i.e. that the law of a document determines up to a relabelling of the topics, requires a sufficiently long document and a generic topic matrix. For , suffices: the columns of are linearly independent almost surely under the topics draw, and the third-order moment of the tokens has a unique decomposition with the topics as factors (Kruskal, 1977; Anandkumar et al., 2014). For larger the same holds for the lifted topics , which are generic in the same sense, i.e. linearly independent, as long as , the dimension of the space of symmetric tensors, at the price of longer documents, (App. D). For instance, pairs of tokens cover with . Secondly, the learning curve is an average over topic matrices, whereas an experiment runs on individual realisations. Comparing the two assumes that the excess loss of a given realisation is close to its average, i.e. typicality of the random topic matrix. An empirical check of this typicality is the spread across independent realisations in Sec. 5.
The same law at fixed, large position. Equation 10 concerns the loss averaged over positions; at a fixed position the same law follows from a simple picture. Beyond the resolution scale of Sec. 2.1, the learner can identify the topic of the test document, and likewise the topics of the training documents if . It is then left with estimating the token distribution of the test topic from the training documents of that topic, about of them, i.e. from tokens: this is the problem solved by the in-context predictor of Sec. 2.2, with in place of , whose excess becomes . The -gram loss at large therefore obeys the same law as the average, and App. D makes this rigorous at fixed , under conditions on , and ; Fig. 10 compares it with the -gram learning curves of trained transformers.
4 WHEN DOES ICL EMERGE?
Simplicity of the in-context predictor. If any learner eventually converges to the specialised predictor, when does ICL emerge? Both predictors of Sec. 2 are functions of the counts, but of very different complexity. The in-context predictor is linear up to normalisation,
whereas the specialised predictor is exponential in the counts (Eq. 3). Then, simplicity bias suggests that the in-context predictor is easier to learn. represents a point in the family of linear maps from counts to next-token probability, whereas random topic models lie in dimensions. The estimation error follows from the same argument as Sec. 3, in the form appropriate to a fitted parametric family rather than a Bayesian posterior (App. E). Simply put, a learner estimating the parameters of the linear map from a corpus of NT tokens pays an excess over the optimal in-context solution, again proportional to the number of parameters per training token.
Estimation penalty versus loss gain. This excess must be compared with the gain of the add-one rule over the uniform predictor, equal to the mean mutual information between the next token and its context (App. E),
The new solution can only appear once the error due to finite data is smaller than the gain, i.e. for
independently of the task diversity D.
Task-diversity threshold. By Eq. 10, the specialised solution emerges at . Hence, if
then the in-context solution emerges before the specialised one, and persists in the window . The resulting picture is that of Fig. 1, right. In the window the learner applies the same rule to seen and unseen topics alike, thus OOD and ID loss decay together towards the OOD optimum . At , the learner resolves the dictionary: the ID loss descends to the entropy rate, and the OOD loss rises towards —OOD loss of the specialised predictor.
5 TRANSFORMER EXPERIMENTS
This section collects empirical learning curves of one-block transformers trained with Adam on data generated from random topic models of varying K and D. Experiments with varying T are reported in App. H. Since we are testing the scaling of performance with the number of training tokens, we conducted extensive hyperparameter search, looking for the best configuration of model size, learning rate, batch size and training time at fixed depth and optimiser. Further details of architectures and training algorithms are reported in App. G.
Fig. 3 shows that transformers learn random topic models at the same rate as the Bayesian learner of Sec. 3.

Figure 3: Transformers match the Bayes-optimal specialisation learning curve. Left: Scaled ID autoregressive loss ( )/( ) versus number of training sequences for one-block transformers trained on random topic model data with varying , . The scaled loss is 1 at the uniform predictor 1/K, 0 at the specialised predictor. Middle: Rescaling the x-axis as the number of tokens per parameter of the data-generating process collapses all the curves onto a single functional form. Right: The decay towards 0 (black dashed) shows remarkable agreement with the rate of the Bayes-optimal learning curve.
Even above the task-diversity threshold Eq. 14, specialisation kicks in as soon as the number of tokens NT surpasses the number of parameters DK. This is clearly shown by Fig. 4: the large-N decay of the ID loss scales with , while the early-N decay develops a D-independent behaviour. Correspondingly, the OOD losses at early stopping (dashed lines) show an initial descent, followed by a steep ascent around . This result shows that the transience of ICL is inevitable, unless the learning model is regularised.
Fig. 5 shows OOD learning curves in the high-diversity regime: the initial D-independent descent scales like as predicted in Eq. 13. Since specialisation occurs at , the

Figure 4: In-context learning gives way to specialisation at the parametric scale . Left: Scaled ID (solid) and OOD (dashed) autoregressive losses, both subtracting the ID loss floor for comparison. Right: Rescaling the x-axis as the number of tokens per parameter of the data-generating process collapses both the descent of ID losses and the ascent of OOD losses.
in-context solution remains stable for a window of training set sizes linear in D. Fig. 11 of App. H shows the same scaling behaviour for the initial decay of ID learning curves.

Figure 5: Empirical OOD learning curves decay at the predicted sample scale. Left: Scaled OOD autoregressive loss ( )/ versus number of training tokens NT for one-block transformers trained on random topic model data with varying at (solid), and with , at (dotted) and (dashed). These losses are not recorded at early stopping (training step with the lowest ID validation loss), but at the training step with the lowest OOD validation loss. Hence, the OOD losses shown in this figure do not rise at as in Fig. 4. Right: The early-N departure from the trivial loss does not depend on D and collapse after dividing the number of training sequences by , in perfect agreement with the theory of Eq. 13.
5.1 COMPARISON WITH SPECTRAL BASELINES
Latent-variable models like the random topic model are classically learnt by spectral methods based on the moments of the tokens (Hsu et al., 2012; Balle et al., 2014; Anandkumar et al., 2014). The first step is recovery of the -dimensional subspace spanned by the topics from a low-order moment: the pair moment , of rank , when , and the moment of tokens when , the number of independent products of topic entries. The topics themselves then follow from the moment with one more token, which is the identifiability step of Sec. 3 (App. F). The subspace is resolved once the empirical moment, estimated from independent -tuples, is close to the population moment. The corresponding sample size is a lower bound for the method to work.
The error on the empirical moment is of order by the matrix Bernstein inequality (App. F, verified numerically in Fig. 8). The scales of the population moments, instead, follow from random matrix theory, in the limit . With and , the bulk of 's spectrum converges to a Marchenko–Pastur distribution with eigenvalues of order (Fig. 6). Comparison with the noise gives . With and , the relevant bulk of is of order (Fig. 7). Comparison with the noise gives . This analysis is carried out in a different limit from the rest of the paper, and it counts independent tuples rather than documents of tokens, so we only compare the dependence on task diversity: quadratic in for the spectral baseline, against the linear of the Bayes-optimal learner, which the trained transformers follow. Furthermore, in the spectral baseline, the order of grows with the order of the required moment.
6 CONCLUSIONS
We have studied a solvable model of a mixture of D topics, where two strategies compete: in-distribution specialisation to the finite mixture, or out-of-distribution generalisation to topics never seen in training. Specialisation requires more training tokens than there are parameters in the data-generating process—a statistical limit that no learner can beat. The in-context solution is available at a D-independent scale, hence it comes first whenever the number of topics is large enough. Trained transformers follow both scales. It follows that the transience of ICL (Singh et al., 2023) is inevitable as the corpus grows, unless a constraint on parameters or training budget keeps the learner in the in-context window.
The specialised solution was called memorising in previous studies of the same competition (Raventos et al., 2023; Nguyen & Reddy, 2025; Carroll et al., 2025; Wurgaft et al., 2025). Indeed, its placement after the in-context phase mirrors the training dynamics of diffusion models, where generalisation is acquired before the memorisation of the training set (Favero et al., 2025). We find the label misleading: the specialised predictor stores the D topics of the population, not the N documents of the corpus—memorisation happens in feature space. This is a form of in-distribution generalisation, distinct from the adaptation to new topics of the in-context predictor, and we name it after the specialisation of teacher-student networks, where the hidden units of the student align with those of the teacher (Goldt et al., 2019; Barbier et al., 2025).
Several directions are open. The first is the training dynamics of transformers on the random topic model, which would connect our sample complexities with the phenomenological description of Wurgaft et al. (2025). More importantly, the dynamics determine which representations are learned in each phase and the corresponding geometry of the residual stream (Shai et al., 2024; Ray et al., 2026). Clarifying the distinction between representations in the two phases could help understand the emergence and role of task vectors (Hendel et al., 2023), including scenarios where multiple solutions coexist (Yan et al., 2026). The second is the competition between task diversity and other structures of the data. The tools developed here can address this problem in general non-ergodic hidden Markov models (Riechers et al., 2025), of which the random topic model is the simplest instance. Such mixtures are natural models of large heterogeneous corpora. Solvable models like the one proposed here could help understand how heterogeneity contributes to data statistics and scaling laws (Cagnetta et al., 2026), and how improvements on the individual components of a mixture interact.
AI USE STATEMENT
In this work, we used generative AI tools for: assistance in the writing of proofs; implementation of numerical methods. We have not used generative AI tools for: Generating synthetic data sets, helping develop theoretical models or conceptual frameworks, formulating mathematical claims, providing critical ingredients for proving mathematical claims, proposing or refining hypotheses, designing feedback on research methodology or experiments, interpreting results, and assisting with translation, cleaning and reformatting dataset, supporting qualitative and thematic data analysis are not applicable to this work. Additionally, we used generative AI tools for: modifying scientific figures, drafting parts of a research paper, identifying relevant literature. We have reviewed all AI-assisted work. We checked LLM-generated proofs; LLM-generated numerical implementations were verified and tested for correctness by 2 authors; We checked LLM-generated descriptions of additional related works. We take responsibility for the final content of this work, including text, claims or artifacts produced with the aid of generative AI.
REPRODUCIBILITY STATEMENT
The theoretical results are stated with their assumptions and proved in the appendices. Appendices A–C prove the statements of Sec. 2: the averages over the topic prior, the optimality and loss decomposition of the two predictors, and the exact finite-t loss of the in-context predictor, Eq. 28, from which the in-context reference, the gain and the sample scale used to rescale the axes of the figures are computed. App. D states the identifiability and regularity assumptions behind the DK/NT law, Eq. 10, gives sufficient conditions on under which they hold almost surely, proves the law and gives its fixed-position version. App. E lists the conditions under which the estimation excess of a fitted family equals its parameter count, behind Eq. 13, and App. F states the joint limit in which the spectral scales hold. Arguments that we do not prove are identified as such where they appear: the concentration of pairwise divergences behind the log D constant, the signal-to-noise criterion and the block approximation of the spectral baseline, and the applicability of the estimation argument to a trained transformer.
The experiments are fully specified in App. G: the data-generating process, with the topic prior, the sizes of the validation and OOD sets and the number of fresh OOD topics; the architecture, initialisation and parameter count; the optimiser, learning-rate schedule and batching; the evaluation protocol, the definition of early stopping and the two readings of the OOD loss; and the hyperparameter grid with the selection rule. Every point of a learning curve is the mean over four runs with independent topic matrix, corpus and initialisation, with standard errors as error bars, and every run stores its full configuration, including the seeds of the draws, so that any point can be regenerated exactly. The theoretical references in the figures are evaluated from closed-form expressions or by Monte Carlo estimates over topic realisations, as stated in the captions. The code for data generation, training, evaluation and the theoretical curves is available at https://github.com/fracagnetta/random-topic-model.
REFERENCES
Ekin Akyürek, Dale Schuurmans, Jacob Andreas, Tengyu Ma, and Denny Zhou. What learning algorithm is in-context learning? investigations with linear models. In The Eleventh International Conference on Learning Representations, 2023. URL https://openreview.net/forum?id=0g0X4H8yN4I.
Elizabeth S. Allman, Catherine Matias, and John A. Rhodes. Identifiability of parameters in latent structure models with many observed variables. The Annals of Statistics, 37(6A):3099–3132, 2009. URL http://www.jstor.org/stable/25662188.
Animashree Anandkumar, Rong Ge, Daniel Hsu, Sham M. Kakade, and Matus Telgarsky. Tensor decompositions for learning latent variable models. J. Mach. Learn. Res., 15(1):2773–2832, 2014. doi: 10.5555/2627435.2697055. URL https://dl.acm.org/doi/10.5555/2627435.2697055.
Usman Anwar, Abulhair Saparov, Javier Rando, Daniel Paleka, Miles Turpin, Peter Hase, Ekdeep Singh Lubana, Erik Jenner, Stephen Casper, Oliver Sourbut, Benjamin L. Edelman, Zhaowei Zhang, Mario Günther, Anton Korinek, Jose Hernandez-Orallo, Lewis Hammond, Eric J Bigelow, Alexander Pan, Lauro Langosco, Tomasz Korbak, Heidi Chenyu Zhang, Ruiqi Zhong, Sean O hEigeartaigh, Gabriel Recchia, Giulio Corsi, Alan Chan, Markus Anderljung, Lilian Edwards, Aleksandar Petrov, Christian Schroeder de Witt, Sumeet Ramesh Motwani, Yoshua Bengio, Danqi Chen, Philip Torr, Samuel Albanie, Tegan Maharaj, Jakob Nicolaus Foerster, Florian Tramèr, He He, Atoosa Kasirzadeh, Yejin Choi, and David Krueger. Foundational challenges in assuring alignment and safety of large language models. Transactions on Machine Learning Research, 2024. ISSN 2835-8856. URL https://openreview.net/forum?id=oVTkOs8Pka. Survey Certification, Expert Certification.
Borja Balle, William L. Hamilton, and Joelle Pineau. Methods of moments for learning stochastic languages: unified presentation and empirical comparison. In Proceedings of the 31st International Conference on Machine Learning, volume 32, pp. 1386–1394. PMLR, 2014.
Jean Barbier, Francesco Camilli, Minh-Toan Nguyen, Mauro Pastore, and Rudy Skerk. Optimal generalisation and learning transition in extensive-width shallow neural networks near interpolation. arXiv preprint arXiv:2501.18530, 2025.
Marco Bondaschi, Nived Rajaraman, Xiuying Wei, Razvan Pascanu, Caglar Gulcehre, Michael Gastpar, and Ashok Vardhan Makkuva. From markov to laplace: How mamba in-context learns markov chains. In The Fourteenth International Conference on Learning Representations, 2026. URL https://openreview.net/forum?id=kmK3WSCOCT.
Blake Bordelon, Mary Letey, and Cengiz Pehlevan. Theory of scaling laws for in-context regression: Depth, width, context and time. In The Fourteenth International Conference on Learning Representations, 2026. URL https://openreview.net/forum?id=qA42mWsnbl.
Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D. Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, Tom Henighan, Rewon Child, Aditya Ramesh, Daniel M. Ziegler, Jeffrey Wu, Clemens Winter, Chris Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, and Dario Amodei. Language models are few-shot learners. In Advances in Neural Information Processing Systems, volume 33, pp. 1877–1901, 2020. URL https://proceedings.neurips.cc/paper/2020/hash/1457c0d6bfcb4967418bfb8ac142f64a-Abstract.html.
Francesco Cagnetta, Allan Raventos, Surya Ganguli, and Matthieu Wyart. Deriving neural scaling laws from the statistics of natural language. In Forty-third International Conference on Machine Learning, 2026. URL https://openreview.net/forum?id=VXlniX0C5y.
Liam Carroll, Jesse Hoogland, Matthew Farrugia-Roberts, and Daniel Murfet. Dynamics of transient structure in in-context linear regression transformers. arXiv preprint arXiv:2501.17745, 2025.
Djalil Chafai and Konstantin Tikhomirov. On the convergence of the extremal eigenvalues of empirical covariance matrices with dependence. Probability Theory and Related Fields, 170:847–889, 2018. doi: 10.1007/s00440-017-0778-9. URL https://arxiv.org/abs/1509.02231.
Bertrand S. Clarke and Andrew R. Barron. Information-theoretic asymptotics of Bayes methods. IEEE Transactions on Information Theory, 36(3):453–471, 1990. doi: 10.1109/18.54897. URL https://bertrandsclarke.weebly.com/uploads/2/7/3/6/2736392/clarkebarron1990.pdf.
Bertrand S. Clarke and Andrew R. Barron. Jeffreys' prior is asymptotically least favorable under entropy risk. Journal of Statistical Planning and Inference, 41(1):37–60, 1994. doi:10.1016/0378-3758(94)90153-8. URL https://doi.org/10.1016/0378-3758(94)90153-8.
Ezra Edelman, Nikolaos Tsilivis, Benjamin L. Edelman, eran malach, and Surbhi Goel. The evolution of statistical induction heads: In-context learning markov chains. In The Thirty-eighth Annual Conference on Neural Information Processing Systems, 2024. URL https://openreview.net/forum?id=qaRT6QTIqJ.
Alessandro Favero, Antonio Sclocchi, and Matthieu Wyart. Bigger isn’t always memorizing: Early stopping overparameterized diffusion models. arXiv preprint arXiv:2505.16959, 2025.
Shivam Garg, Dimitris Tsipras, Percy Liang, and Gregory Valiant. What can transformers learn in-context? a case study of simple function classes. In Advances in Neural Information Processing Systems, 2022. URL https://openreview.net/forum?id=flNZJ2eOet.
Cole Gibson, Wenping Cui, and Gautam Reddy. Distinct mechanisms underlying in-context learning in transformers. arXiv preprint arXiv:2604.12151, 2026.
Sebastian Goldt, Madhu Advani, Andrew M. Saxe, Florent Krzakala, and Lenka Zdeborová. Dynamics of stochastic gradient descent for two-layer neural networks in the teacher-student setup. In Advances in Neural Information Processing Systems, volume 32, 2019.
Roee Hendel, Mor Geva, and Amir Globerson. In-context learning creates task vectors. In The 2023 Conference on Empirical Methods in Natural Language Processing, 2023. URL https://openreview.net/forum?id=QYvFUlF19n.
Daniel Hsu, Sham M. Kakade, and Tong Zhang. A spectral algorithm for learning hidden Markov models. Journal of Computer and System Sciences, 78(5):1460–1480, 2012.
Joseph B. Kruskal. Three-way arrays: rank and uniqueness of trilinear decompositions, with application to arithmetic complexity and statistics. Linear algebra and its applications, 18(2):95–138, 1977. doi: 10.1016/0024-3795(77)90069-6. URL https://linkinghub.elsevier.com/retrieve/pii/0024379577900696.
Mary Letey, Jacob A Zavatone-Veth, Yue M. Lu, and Cengiz Pehlevan. Pretrain–test task alignment governs generalization in in-context learning. In The Fourteenth International Conference on Learning Representations, 2026. URL https://openreview.net/forum?id=KZLeg0MQ2r.
Yue M. Lu, Mary Letey, Jacob A. Zavatone-Veth, Anindita Maiti, and Cengiz Pehlevan. Asymptotic theory of in-context learning by linear attention. Proceedings of the National Academy of Sciences, 122(28):e2502599122, 2025. doi: 10.1073/pnas.2502599122. URL https://www.pnas.org/doi/abs/10.1073/pnas.2502599122.
Alex Nguyen and Gautam Reddy. Differential learning kinetics govern the transition from memorization to generalization during in-context learning. In The Thirteenth International Conference on Learning Representations, 2025. URL https://openreview.net/forum?id=INyi7qUdjZ.
Eshaan Nichani, Alex Damian, and Jason D. Lee. How transformers learn causal structure with gradient descent. In Forty-first International Conference on Machine Learning, 2024. URL https://openreview.net/forum?id=jNM4imlHZv.
Alain Pajor and Leonid Pastur. On the limiting empirical measure of eigenvalues of the sum of rank one matrices with log-concave distribution. Studia Mathematica, 195(1):11–29, 2009. doi:10.4064/sm195-1-2. URL https://arxiv.org/abs/0710.1346.
Core Francisco Park, Ekdeep Singh Lubana, and Hidenori Tanaka. Competition dynamics shape algorithmic phases of in-context learning. In The Thirteenth International Conference on Learning Representations, 2025. URL https://openreview.net/forum?id=XgH1wfHSX8.
Allan Raventos, Mansheej Paul, Feng Chen, and Surya Ganguli. Pretraining task diversity and the emergence of non-bayesian in-context learning for regression. In Thirty-seventh Conference on Neural Information Processing Systems, 2023. URL https://openreview.net/forum?id=BtAz4a5xDg.
Kyle J. Ray, Paul M. Riechers, and Adam S. Shai. The geometry of nonergodic composition. Belief Updates (Simplex Blog), 2026. URL https://belief-updates.pub/nonergodic-geometry/.
Gautam Reddy. The mechanistic basis of data dependence and abrupt learning in an in-context classification task. In The Twelfth International Conference on Learning Representations, 2024. URL https://openreview.net/forum?id=aN4Jf6Cx69.
Paul M Riechers, Henry R Bigelow, Eric A Alt, and Adam Shai. Next-token pretraining implies in-context learning. arXiv preprint arXiv:2505.18373, 2025.
Adam Shai, Paul M. Riechers, Lucas Teixeira, Alexander Gietelink Oldenziel, and Sarah Marzen. Transformers represent belief state geometry in their residual stream. In The Thirty-eighth Annual Conference on Neural Information Processing Systems, 2024. URL https://openreview.net/forum?id=YIB7REL8UC.
Murray Shanahan, Kyle McDonell, and Laria Reynolds. Role play with large language models. Nature, 623(7987):493–498, 2023.
Aaditya K Singh, Stephanie C.Y. Chan, Ted Moskovitz, Erin Grant, Andrew M Saxe, and Felix Hill. The transient nature of emergent in-context learning in transformers. In Thirty-seventh Conference on Neural Information Processing Systems, 2023. URL https://openreview.net/forum?id=Of0GBzow8P.
Joel A. Tropp. User-friendly tail bounds for sums of random matrices. Foundations of computational mathematics, 12(4):389–434, 2012. doi: 10.1007/s10208-011-9099-z. URL https://link.springer.com/content/pdf/10.1007/s10208-011-9099-z.pdf.
Daniel Wurgaft, Ekdeep Singh Lubana, Core Francisco Park, Hidenori Tanaka, Gautam Reddy, and Noah Goodman. In-context learning strategies emerge rationally. In The Thirty-ninth Annual Conference on Neural Information Processing Systems, 2025. URL https://openreview.net/forum?id=bBUUOQ10N6.
Sang Michael Xie, Aditi Raghunathan, Percy Liang, and Tengyu Ma. An explanation of in-context learning as implicit bayesian inference. In International Conference on Learning Representations, 2022. URL https://openreview.net/forum?id=RdJVFCHjUMI.
Hao Yan, Haolin Yang, and Yiqiao Zhong. Task vector geometry underlies dual modes of task inference in transformers. arXiv preprint arXiv:2605.03780, 2026.
Yedi Zhang, Aaditya K Singh, Peter E. Latham, and Andrew M Saxe. Training dynamics of in-context learning in linear attention. In Forty-second International Conference on Machine Learning, 2025. URL https://openreview.net/forum?id=aFNq67ilos.
A STATISTICS OVER RANDOM TOPIC MODELS
This appendix collects the averages over the topic prior used in the main text. Let be independent, i.e. uniform on the simplex , and let denote the digamma function. Each entry is marginally , with moments
where the last two follow by differentiating the first with respect to r at r = 0 and r = 1.
Entropy of a topic. By symmetry of the entries,
using and . A random topic thus has entropy nats below the uniform value , at leading orders: this gap is the height of the descent of every profile in Fig. 2.
Divergence between two topics. Expanding the divergence and using the independence of p and ,
by the recurrence . Two random topics are thus separated by an order-one divergence for every vocabulary size, which sets the rate of topic resolution in App. B.
Bhattacharyya coefficient. The non-asymptotic resolution bound of App. B involves , whose average follows from Eq. 15 at ,
B THE SPECIALISED PREDICTOR
This appendix proves the statements of Sec. 2.1: the optimality of , the loss decomposition Eq. 4, and the resolution of the topic on the context scale . Throughout, the topic matrix is fixed, with distinct columns, and all expectations are over documents at fixed .
Optimality. Conditional on the context, is distributed as : by construction , using that is independent of the context given . For any predictor , therefore,
with equality if and only if . Averaging over contexts, .
Loss decomposition. Conditioning instead on the topic and the context, , and the same identity gives ; averaging over the topic, uniform on , and over the context yields Eq. 4. The floor is the loss of the oracle , which is not a function of the context and hence not a predictor in the sense of Eq. 2; by the optimality of , every predictor pays at least the excess above it.
Excess loss and wrong-topic mass. Write the posterior in terms of the likelihood ratios of the wrong topics against the true one,
Isolating the true topic in Eq. 3, entrywise, hence
Conditional on Z, the tokens are i.i.d. from , so by the strong law of large numbers
i.e. each wrong topic is suppressed exponentially in t, at a rate equal to its divergence from the true topic. This is the mechanism described in the main text; it is asymptotic in t at fixed P.
Resolution on the scale . A bound valid at every follows from a fractional moment of the likelihood ratios. Using in Eq. 21, then the independence of the tokens given ,
(23)
where is the Bhattacharyya coefficient of topics and , and by the Cauchy–Schwarz inequality and the distinctness of the topics. Hence the excess loss of the specialised predictor is below any as soon as
which is the log scale of Sec. 2.1, with a rate set by the closest pair of topics. The guaranteed rate is at most half of the almost-sure rate in Eq. 22, since by Jensen's inequality, and grows with as the closest pair among random topics gets closer: Eq. 24 is a statement about the dependence on at fixed , not a sharp constant. For the constant, the typical pair is the relevant one: two random topics have and (App. A), and if the divergences from the true topic concentrate near their mean, the odds of a wrong topic in Eq. 21 are approximately , so that the floor is reached for . This last estimate is heuristic, as it assumes a concentration of the pairwise divergences that we do not prove; it is consistent with the half-descent points in Fig. 2, which grow linearly in .
C THE IN-CONTEXT PREDICTOR
This appendix proves the statements of Sec. 2.2: the form and optimality of , the loss decomposition Eq. 6, and the exact finite-t risk behind its expansion. Throughout, the document is OOD: and, given , the tokens are i.i.d. from .
Posterior and add-one rule. The prior density is constant on the simplex and the likelihood of a context is , so the posterior density is proportional to : this is , whose density is proportional to with . Given and the context, , and the mean of is , so the posterior predictive distribution is
which is Eq. 5.
Optimality. As in App. B, is the conditional distribution of given the context, so for any predictor f
with equality if and only if ; averaging over contexts, . Unlike , the predictor does not depend on the topic matrix: on a document generated from any topic , its loss is a function of that topic alone. Its ID loss at fixed is and its OOD loss is , whence .
Loss decomposition. Conditioning on and the context, , so ; averaging over and the context gives the first equality in Eq. 6, with because has the law of the training topics. Moreover, by Eq. 26 at , is a conditional entropy; since the tokens are exchangeable given , , and conditioning on one more token shows that is non-increasing in .
Exact finite-t risk. Integrating the likelihood against the uniform prior, the count vector of a context is uniform over the weak compositions of t into K parts,
Hence, by Eq. 25 and the symmetry of the entries, for
(28)
where counts the compositions with . In particular and as . Expanding at large and fixed gives the second equality in Eq. 6,
where the logarithm in the remainder comes from the mass that the uniform prior puts near the boundary of the simplex. The leading correction is one half of the number of parameters of a topic, K - 1, per observation, and the expansion requires : at K = 64 and t = 128, Eq. 28 gives an excess of 0.15 nats over the floor, against 0.25 for the leading term alone; the former is the gap between the dashed line and the floor at the end of the profiles in Fig. 2.
D THE BAYESIAN LEARNER
This appendix proves the statements of Sec. 3: the form and optimality of the Bayesian learner, the information identity, the DK/NT law and its fixed-position version.
Posterior and predictor. Let be the corpus, with count vectors , and write for the likelihood of a count vector under a topic. Given a candidate topic matrix , integrating out the latent topic of each document gives the likelihood of corpus and context,
up to multinomial factors that do not depend on . The posterior of is , with the product of uniform priors on the simplex, and Eq. 7 reads , where is the specialised predictor of Eq. 3 computed with . By construction is the conditional law of given under the joint law of topics, corpus and test document, so, as in App. B, every predictor built from corpus and context satisfies , with equality if and only if .
Excess and mutual information. At fixed , conditioning on the context, and the corpus is independent of the test document, so . Averaged over , the two losses are the conditional entropies and , whence
The second entropy does not change if one more document is added to the corpus, since given the corpus is irrelevant, so : the learning curve is non-increasing in . Summing Eq. 31 over positions with the chain rule, and using that the test document has the law of and is independent of the corpus given ,
which is Eq. 9, the document-level form of the cumulative predictive risk identity of Clarke & Barron (1990).
The DK/NT law. Up to a relabelling of the topics, the law of a document has parameters. Assume that is identifiable up to relabelling and regular: twice continuously differentiable in local coordinates, with positive definite Fisher information, and with a prior density that is positive and continuous. Then, for fixed , , and , Theorem 1 of Clarke & Barron (1994) gives
with a constant that depends on prior and document model but not on . The increment in Eq. 32 does not follow by direct subtraction, since an term need not have increments, but it does follow from monotonicity. Let , non-increasing in , and for let and . Summing over and over and using monotonicity,
where both numerators equal by Eq. 33. Letting and then squeezes between and , both of which tend to ; dividing by gives Eq. 10.
Identifiability. For the third-order moment of the tokens, , is a marginal of , and by Kruskal's theorem (Kruskal, 1977; Allman et al., 2009) its decomposition into rank-one terms is unique up to permutation when , where the Kruskal rank is the largest such that any columns of are linearly independent. For topics drawn from the simplex, almost surely, so the condition holds for (and up to ), and the topics can be recovered constructively: the second moment has rank and whitens into an orthogonally decomposable tensor whose factors are the topics (Anandkumar et al., 2014). For larger , lift the topics to , which lie in the space of symmetric tensors, of dimension , and span it as ranges over the simplex, since a homogeneous polynomial vanishing on the simplex vanishes identically; some minor of is then a nonzero polynomial in the topic entries, so the lifted topics are linearly independent almost surely whenever . In that case the -token moment has rank , the rank of the Hankel matrix of the token process, and together with the -token moment it determines the law of documents of every length, hence up to relabelling (Balle et al., 2014) (App. F). Moreover, for the Fisher information of a document is nonsingular: a perturbation that leaves the law of a document unchanged to first order leaves the -token marginal unchanged, and contracting its variation with , where the functionals satisfy , gives , whose sum over coordinates forces and then . Hence and suffice almost surely: with , with , and so on; these conditions are sufficient, not necessary, and they are the only place where the genericity of the topic matrix is used. Regularity additionally excludes the sets, of prior measure zero, where two topics coincide or a topic lies on the boundary of the simplex.
Fixed position: the resolved learner. Reveal to the learner the topic labels of the training documents and of the test document. Conditional on the labels, by the conjugacy of App. C, the Bayesian predictor is the add-one rule on the pooled counts of the test topic,
where is the number of training documents of topic and their total count of token : the in-context predictor of Eq. 5 applied to tokens. Averaged over topics, its excess over the entropy rate is therefore , with the excess of the in-context predictor in Eq. 6 and . If then in probability, and if moreover and , so that the event that the test topic is absent from the corpus is negligible on the scale, Eq. 6 gives
The resolved learner is not the Bayesian learner, which must also infer the labels and the topic matrix. For a fixed P with distinct topics, and assuming identifiability from a marginal of tokens, the two excesses differ by at most
with from Eq. 23 and . The first two terms are the costs of unresolved test and training labels, by the bound of App. B applied to the test context and to each of the N training documents; the last is the posterior mass on topic matrices outside a fixed neighbourhood of P, exponentially small in N by a likelihood-ratio test on the identifying marginal, against the polynomial prior mass of the neighbourhood. Hence the Bayesian learner obeys Eq. 36 at fixed P whenever t and T grow like with A large enough for Eq. 37 to be : the fixed-position form of the DK/NT law. The statement is conditional on P; averaging it over the prior would require uniform control over nearly coinciding topics, for which is arbitrarily small.
E THE IN-CONTEXT SOLUTION
This appendix supports Sec. 4: the estimation excess of a fitted parametric family, the count-linear family that contains the in-context predictor, and the gain with its interpretation and expansions.
Estimation excess of a fitted family. Let be a family of distributions of a document , with all coordinates of free, and let and be its log loss and its population risk under the true law of . Let be an interior minimiser of , isolated up to finite symmetries, around which is three times continuously differentiable, and define the risk curvature and the gradient covariance
the gradient has zero mean because is a minimiser. Let be a consistent fit on independent documents whose empirical gradient is , as for an interior minimiser of the empirical risk , and let , which has mean zero and covariance by independence. Expanding the empirical gradient and the population risk around ,
with and . If the remainders are also small in expectation, and , then substituting and using for centred ,
If the family is well specified, i.e. the true law is , differentiating twice gives , the Fisher information of one document, and whenever it is nonsingular. The remainder bounds hold, for instance, for an empirical-risk minimiser over a compact set that contains in its interior and on which probabilities are bounded below; they are not automatic for an unrestricted fit, nor for a transformer. Divided by , Eq. 40 is a per-token excess . For the topic matrix itself, , and the Fisher information is nonsingular almost surely for and (the Jacobian of the three-token marginal is injective when the topics are linearly independent), so a fitted dictionary recovers Eq. 10 by an argument on a fitted parameter rather than on the posterior; for the count map below, .
The count-linear family. The predictors that are linear in the counts up to normalisation,
contain the in-context predictor at . Counts are bounded by , so the family is positive and smooth on a neighbourhood of this point, and it has free parameters, the overall scale of being immaterial. On OOD documents the family is well specified, since the law of an OOD document is the product of its add-one predictors (App. C), so and Eq. 40 gives the excess of Sec. 4 for a learner that fits this family. On the training distribution the family is misspecified at finite , its optimum being a fit to , a ratio of exponentials of the counts. The misspecification vanishes as : writing Eq. 3 as a ratio of averages over the dictionary,
by the strong law of large numbers applied to numerator and denominator at fixed and count vector, and the Dirichlet moment , of which Eq. 15 is the one-entry case. The convergence is pointwise in the count vector, and the dictionary size needed for a given accuracy grows with , since the weights in Eq. 42 concentrate on a neighbourhood of the empirical frequencies that shrinks with . Note that the family cannot be reached through the specialised predictor of a small dictionary. is a convex combination of the topics, so its Jacobian with respect to the counts has rank at most , whereas that of the add-one map is : a learner whose predictor tracks the in-distribution optimum can realise the count-linear rule only if .
The gain of the in-context predictor. On an OOD document every token is marginally uniform, , so , and by App. C; hence
by the chain rule, and with . The gain per token is thus the entropy gap between the uniform distribution and a random topic, by Eq. 16, minus the information about its own topic that the document leaves unrevealed. Its exact value follows from Eq. 28, and its two regimes are
The first follows by summing Eq. 29 over positions, which gives : a long context reveals its topic up to the usual parametric cost. The second follows from Eq. 28 at : a given token appears once in the context with probability and more than once with probability , so that ; in a short context most tokens are new, and the gain comes from the few repeated ones.
F THE SPECTRAL BASELINE
This appendix supports Sec. 5.1: the Hankel formulation of spectral learning, the spectra of the pair and four-token moments under the random topic model, the noise of their empirical estimates, and the resulting sample complexities. Its asymptotic statements are in the joint limit with , respectively , fixed.
Hankel matrix and subspace. For the token process, the Hankel matrix has entries , indexed by a prefix string and a suffix string ; since tokens are i.i.d. given the topic, with , so that (Balle et al., 2014). Spectral learning first recovers the column space of from a complete sub-block, i.e. one of rank , then the observation operators from the block with one more symbol; for the random topic model the hidden state is constant within a document, the transition matrix is the identity and the observation matrix is (Hsu et al., 2012). The block on prefixes and suffixes of tokens is , whose nonzero spectrum is that of the Gram matrix . The lifted topics lie in the space of symmetric tensors, of dimension , and span it as ranges over the simplex, since a homogeneous polynomial vanishing on the simplex vanishes identically; some minor of the lifted topic matrix is therefore a nonzero polynomial in the topic entries, and almost surely for topics drawn from the simplex. The single-token block is thus complete for , the two-token block for , and so on; the topics follow from , , ..., for through the whitening of by and the decomposition of the resulting orthogonal tensor (Anandkumar et al., 2014), as recalled in App. D.
Spectrum of . By Eq. 15, for and , so the mean of over the topics is , with one eigenvalue along 1 and on its complement. For a realisation, write with centred, orthogonal to 1, of covariance and independent across topics; the nonzero spectrum of is that of with . In the -dimensional complement of 1, the rescaled columns are independent, isotropic and log-concave, being uniform on a convex set, so that as with the eigenvalues of follow the Marchenko–Pastur law of ratio , with extreme eigenvalues converging to the edges (Pajor & Pastur, 2009; Chafai & Tikhomirov, 2018). The rank-one term removes at most one eigenvalue from this bulk, by interlacing, and produces the outlier ; dividing by ,
and the remaining eigenvalues vanish: one spike at and a bulk of eigenvalues at scale , as in Fig. 6.
Spectrum of . For the complete block is , whose nonzero spectrum is that of . Writing with separates three scales. The mean feature has squared norm and gives one spike at ; the linear features span directions with covariance eigenvalue ; the centred quadratic features span the remaining directions, with average covariance eigenvalue . Neglecting the coupling between the blocks, a Marchenko–Pastur approximation of each predicts eigenvalues of order , with edges , and eigenvalues of order , with edges when . This block picture is heuristic, since the quadratic features are neither isotropic nor log-concave and the coupling is neglected; Fig. 7 compares it with the spectrum of one realisation at , where both bulks follow the predicted curves and their Frobenius norms agree with the predictions within 7% for the linear block and 2% for the quadratic one, for from 64 to 192.

Figure 6: Population spectrum of for . Left: ranked eigenvalues DK against the scaled rank at , for and one topic realisation per ; dashed: the ranked Marchenko–Pastur law; the spike is the outlier at . Right: density of the bulk eigenvalues, spike removed, on the scale, against the Marchenko–Pastur density (dashed).

Figure 7: Population spectrum of for . Left: ranked eigenvalues of for one realisation at , : the spike at (dotted), the eigenvalues of the linear block and, beyond (dotted), the eigenvalues of the quadratic block, against the Marchenko–Pastur predictions of the two blocks (dashed). Right: Frobenius norm of each block against , for , with the parameter-free predictions (dashed).
Noise and sample complexity. Let be the empirical pair moment from independent pairs, so that with centred, and , with the unigram marginal, of entries close to . The matrix Bernstein inequality (Tropp, 2012) then gives, with probability at least ,
a noise level of order ; the measured error follows across eleven configurations (Fig. 8, left). Treating the noise as a generic perturbation, an eigenvalue of is resolved once : the spike at , and the lower edge of the bulk, , at , i.e. at up to an -dependent constant. This criterion is heuristic, but the scale is confirmed by the eigenvectors: the overlap between the bulk eigenvector subspaces of and rises from its random value to one around (Fig. 8, right). For the four-token moment the same bound has a variance proxy of order and gives a noise level of order , so the spike at is resolved at , the linear block at and the quadratic block, of scale , at ; extrapolating, the bulk of sits at against a noise of , and its resolution takes .

Figure 8: Convergence of the empirical pair moment for . Left: operator-norm error , geometric mean over eight replicas, against NK for eleven configurations, times plus with ; colour encodes , line style ; all curves collapse on the dotted ; circles mark where each curve crosses its own population , beyond which the lower bulk edge is resolved. Right: overlap between the bulk eigenvector subspaces of and , mean one standard deviation over replicas, against ; each curve rises from the random-subspace value towards one around (dashed line at one). One topic realisation per , uniform topic prior.
G EXPERIMENTAL DETAILS
This appendix specifies the transformer experiments of Sec. 5. The code to reproduce them is available at https://github.com/fracagnetta/random-topic-model.
Data. Every run draws its own topic matrix P, with D topics from and uniform topic weights, and from it N training documents and 32 768 validation documents; a further 32 768 OOD documents are generated from 16 fresh topics, drawn independently of P from the same prior. Each point of a learning curve averages four runs with independent topic matrices, test ID and OOD corpora and initialisation, and error bars are standard errors over the four. Documents carry tokens: the model reads the first T and is trained to predict tokens 2 to , so that its loss profile covers context lengths 1 to T, the T-gram loss is the loss at context length T, and the autoregressive loss is the average of the profile over the T positions.
Model. A one-block decoder-only transformer: token embeddings of dimension with no positional embedding, so that the causal mask is the only source of order, as befits documents that are exchangeable given their topic; one causal self-attention head; a ReLU multilayer perceptron with one hidden layer of width ; both sub-layers pre-normalised and residual; a final layer normalisation and an untied linear readout to the K logits. Attention and perceptron carry no biases and there is no dropout. The model has parameters, from at to at . Weights are initialised as standard normals and each linear map is scaled by the inverse square root of its input dimension, the readout by .
Training. The loss is the cross-entropy of the next token, averaged over the T positions and the documents of a batch. Batches of b documents are taken cyclically from the corpus and the parameters are updated with Adam, moment parameters (0.9, 0.999) and no weight decay, at a learning rate raised linearly from zero over the first 8 steps and constant thereafter, for a fixed number of passes over the corpus.
Evaluation and early stopping. The validation autoregressive loss is measured at log-spaced steps throughout training. The checkpoint of lowest validation loss defines early stopping, and its loss is the value that enters the ID learning curves (Fig. 1, Fig. 3, Fig. 9). At a coarser log-spaced subset of the steps the full loss profiles on the validation and on the OOD documents are recorded as well. The T-gram ID loss of a run (Fig. 10) is the minimum over these recorded checkpoints of the loss at context length T; the OOD losses are read either at the recorded checkpoint of lowest validation loss, “at early stopping” (Fig. 1, Fig. 4), or minimised over the recorded checkpoints, “best over training” (Fig. 1, Fig. 5), as stated in each caption.
Hyperparameter selection. The embedding dimension, batch size, learning rate and training budget are selected separately for every on the validation loss at early stopping, so that each learning curve reports the best model of the family rather than a fixed architecture, and the model is not the bottleneck of the comparison with the Bayes-optimal learning curves. The grid is from K to 512 in powers of two, and ; larger dictionaries require larger , and the selected width grows with D at fixed K. The number of passes is extended until the early-stopping checkpoint falls well inside the budget, or until a doubling of the budget improves the validation loss by less than the spread over seeds. A candidate combination replaces the incumbent only when its early-stopping validation loss, over four fresh seeds, is lower beyond the standard errors, or tied with a clearly earlier early-stopping step. The combination selected on the ID validation loss serves for every quantity reported at that , including the OOD losses, which play no role in the selection.
H ADDITIONAL FIGURES

Figure 9: Learning curves at different document lengths collapse on the number of tokens per parameter. Left: Scaled ID autoregressive loss ( )/( ) versus number of training sequences for one-block transformers trained on random topic model data with K = 128, D = 16 and T = 128, 256, 512 (colour). is the autoregressive loss of the specialised predictor at each T, averaged over 32 realisations of the topic matrix. Right: Against NT/(DK) the three curves coincide: at fixed N, longer documents bring the loss closer to its floor in proportion to the number of tokens they contribute.

Figure 10: Transformers match the Bayes-optimal specialisation learning curve at the longest context too. T-gram counterpart of Fig. 3, for the same twelve at . Left: Scaled ID T-gram loss versus number of training sequences, where is the mean entropy of the topics of each run, the large-context floor of the specialised predictor. Middle: Rescaling the x-axis as the number of tokens per parameter of the data-generating process collapses all the curves onto a single functional form, more tightly than for the autoregressive loss. Right: The decay towards 0 (black dashed) follows the rate of the Bayes-optimal learning curve.

Figure 11: The ID loss descends to the in-context level at the predicted sample scale. Left: ID autoregressive loss at early stopping, scaled as , where is the autoregressive loss of the in-context predictor, the same on ID and OOD documents (App. C). This scaled loss is 1 at the uniform prediction, 0 at the in-context solution, and negative at specialisation. Versus number of training tokens NT, for the and T of Fig. 5, with the same line styles. Right: When plotted against (Eq. 13) the descents to the in-context level coincide for all K, D and T, with no adjustable constant. The subsequent departure below zero is specialisation.