Manuscript Offprint
arXiv:2610.02909Constraint-Aware Training
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
When generating programs with language models, constrained decoding can apply program analyses to exclude tokens that violate syntax, scope, or typing rules. However, there is a duplication: standard training already teaches the model to suppress the tokens rejected by these analyses. This duplication leads to the question: if we will perform some analysis to filter a set tokens out during inference anyways, can we avoid teaching the model the said analysis altogether during training, and does this externalization lead to more efficient models? This paper defines a general constraint-aware objective satisfying this externalization desideratum and formalizes the benefits of externalization into three concrete theorems about model size and data efficiency. We show, through a controlled synthetic experiment, that the theorems survive training dynamics: constraint-aware training yields lower prediction loss at a matched parameter count and data compared to ordinary cross-entropy training, motivating training objectives that incorporate the analyses used during generation.
1 Introduction
Large language models (LLMs) are being increasingly used to generate outputs with a formal syntax and semantics: tool calls, programs, and proofs. In many cases, such outputs have a notion of validity: for example, only a small fraction of all strings are valid programs. For formal artifacts, this validity is almost always defined by a computable analysis (e.g., language membership over a grammar or typing rules).
Of particular interest for autoregressive (AR) LLMs is the case where these analyses can become prefix-grounded, allowing us to soundly filter out next-token selections depending on whether they would result in a valid output or not. For example, when completing an expression coming after the prefix "int x = 10; int r = ", a scope analysis, among candidate variable names, may allow only the in-scope x while filtering out other undefined names (such as y or z).
This technique, commonly known as constrained (or guided) decoding [3, 7–9] is well-studied and developed, but there exists a fundamental mismatch, or inefficiency in its deployment scenario. In our previous example, a model trained on standard next-token cross-entropy (CE) will already place near-zero probability mass on the tokens corresponding to the variables y or z. In other words, the model has already learned to separate the valid x from the invalid y and z, even though constrained decoding will provide this information at runtime. This raises the question: if we will perform a prefix analysis to filter a certain set of tokens out during inference anyways, can we externalize this analysis and avoid teaching the model a problem we already know how to solve symbolically? More practically, can a model where a prefix analysis is somehow externalized be more efficient than a model without externalization?
*Work partly done while an intern at Microsoft Research.
Preprint.
Token order (x, y, z)
| Prefix mask and gold | Model prediction | After masking | Scalar losses | ||
|---|---|---|---|---|---|
| (a) | CE: CA: | ||||
| (b) | CE: CA: | ||||
| (c) | CE: CA: |
Figure 1: Standard (CE) and constraint-aware (CA) loss compared on three different scenarios on each row. In each row, mask denotes the set of tokens allowed (marked with T) according to the analysis, the one-hot target, the model prediction, and the model prediction renormalized on tokens allowed by . (a) With only the gold x allowed, CA loss is zero. (b) When the mask allows both x and y, CA penalizes assigning probability to the non-gold y. (c) Changing the mass on the rejected token (vs. (b)) without changing the x : y ratio changes CE but leaves CA unchanged.
Consider the example again, for a 3-token tokenizer . Standard CE loss requires the model to predict the distribution . However, if we assume that the model will always be deployed with the scope analysis at inference, the space of solutions becomes much freer. , , and all become valid predictions, as filtering out the probabilities of and then renormalizing yields the target distribution for all these distributions; in general, any distribution becomes valid as long as . In other words, the space of solutions where the scope analysis is externalized is strictly larger than the space of solutions defined by the standard CE loss, and it is plausible that a model with limited capacity can more easily fit the larger externalized space than the single CE solution.
Our main observation is that prefix-definable analyses can be externalized by defining a constraint-aware (CA) loss for training: at each prefix, apply the analysis, renormalize over the remaining tokens, and compute cross-entropy against the target token. Figure 1 illustrates how the CA loss is computed: intuitively, only tokens that are admitted by the prefix analysis receive a signal.
Variants of the CA loss we propose have appeared in specialized domains [1, 5]; our contribution is generalizing and formalizing the effect of the CA loss precisely as the externalization of a prefix analysis (Theorem 2). We use this connection to prove three theorems about the benefits of externalizing analyses: two capacity theorems, which show that choosing not to externalize an analysis imposes certain (i) width (Theorem 3) and (ii) depth (Theorem 4) requirements on the size of the transformer, and a data efficiency theorem (Theorem 5) showing how constraint-aware training can reduce the amount of data required to reach a target loss. We then test, preliminarily, whether these theoretical benefits carry over to actual transformer training via controlled small-scale training runs over a synthetic language.
Overall, our theorems and the results of our experiments argue for constraint-aware training: across our experiments, models trained over CA loss and deployed under constrained decoding exhibit consistently lower loss compared to ‘ordinary’ models trained over CE loss, both when the CE model is deployed normally (where the CE model loss is computed over the entire set of tokens) and under constrained decoding (where the CE model loss is computed only over the set of tokens allowed by the analysis). The empirical advantage persists across training: CA training attains lower loss even when the theory no longer provides a guarantee that CA will achieve better loss (e.g., when the model is wide enough), providing evidence that the theoretical benefits of constraint-aware training transfer to actual training.
2.1 Constraint-Aware Loss Decomposition
We start with the definition of a prefix analysis.
Definition 1 (Prefix Analysis). A prefix analysis over a finite vocabulary is a computable function , where a token is allowed at a prefix iff . For a prefix , we define the allowed set as , the disallowed set as , and the prefix mask .
We drop the and quantifiers and simply denote the allowed set, disallowed set, and mask as , , and when and are clear from context. In the example from the introduction, the allowed set while the disallowed set . In this paper, we assume analyses are sound with respect to the training data: for all prefix-next token pairs in the training data, .
Given a prefix , let denote the total probability mass on allowed tokens. For any fixed next-token , we observe the probability predicted by the model can be decomposed as . Taking negative log yields a decomposition of the loss:
In Equation (1), denotes the standard cross-entropy loss induced by , which is decomposed as the sum of two elements: (i) the support loss and (ii) the constraint-aware loss . We observe that is precisely the penalty induced by assigning non-zero probability to tokens that are disallowed by the analysis, while is precisely the penalty induced by mispredicting the renormalized distribution on the allowed support S. For example, reconsider row (b) of Figure 1. The losses are
and . This decomposition carries over to gradients in the per-token logit space: defines a gradient that pushes mass off of disallowed tokens, while defines a gradient that rebalances mass amongst allowed tokens, which becomes the main motivation behind constraint-aware training.
To see the gradient decomposition, let denote the logit-level prediction for a token on the prefix (i.e., ). Let denote renormalized on the allowed set , with probability zero outside . Let denote the one-hot distribution on . For a fixed training pair (prefix , gold token ), differentiating Equation (1) over the logit space for a fixed analysis gives:
(A precise derivation of Equation (2) can be found in Section A.1). If a token is disallowed by the analysis , , so the entire gradient comes from the support component towards decreasing the probability of the token . Conversely, if is allowed, the support component , so the support component increases the probability of while the constraint-aware component rebalances probability amongst allowed tokens.
For example, in row (b) of Figure 1, , , and . Collecting the entries for x, y, and z gives
We use as shorthand for . For the disallowed token , only gives signal decreasing its probability. For allowed tokens and , moves the probability took from to and while redistributes mass from to .
2.2 Constraint-Aware Training
Because an analysis A is independent of the parameters , the chain rule preserves the split when backpropagating through the model:
Constraint-aware training drops the support gradient completely and trains only on . For a fixed corpus , training exclusively on has the effect of fitting the model's probabilities after masking and renormalization to how often each token follows each prefix in .
Precisely speaking, let denote a multiset of prefix–next-token training pairs. Let denote the number of pairs in with prefix , and the fraction of these pairs whose next token is . Constraint-aware training upsates the parameters minimize the average CA loss over the training corpus :
Theorem 2 states the correctness of this training objective.
Theorem 2 (Correctness of Constraint-Aware Training). Let be a training-pair multiset and an analysis. Let denote the average next-token entropy of : and the next-token distribution renormalized on the allowed set . Then
Because the entropy term is fixed, minimizing also minimizes the right-hand side term, the weighted average Kullback–Leibler (KL) divergence between (i) , the next-token distribution defined by , and (ii) , the distribution predicted by when deployed with the analysis A.
Theorem 2 proves that constraint-aware training minimizes KL divergence with the training set: the same correctness statement as standard training, conditioned on the renormalized distributions obtained by applying the analysis. For example, if the training-pair set C contains a prefix is followed by x four times and y once, and the analysis allows only those two tokens, both the distributions and satisfy the objective (unlike standard training, which would force the model towards ).
Theorem 2 defines, mathematically, how constraint-aware training has externalized the analysis: it effectively ignores tokens that would be filtered out by the analysis when minimizing KL divergence against the distribution of the training set. During inference, the analysis filters these tokens out anyways; constraint-aware training thus focuses solely on learning the relative distribution between x and y. Sections A.2 and A.3 provide a proof of Theorem 2 and a connection to sequence likelihood over C.
3 The Benefits of Externalization: Width
Now that we have established how constraint-aware training externalizes an analysis, we proceed to show how externalization brings concrete benefits: starting by identifying an analysis that enforces a lower bound on the width of a transformer, and showing that externalization can alleviate this bound.
We illustrate the problematic analysis with an example. Consider a language with five candidate variable names , of which exactly two are in scope. Different prefixes can have any of the ten possible pairs in scope: for example, at the prefix int ; int ; int scope analysis allows only . Suppose the corpus uses these two names equally often, so the target distribution over the five candidates at this point is .
Let us assume that the transformer contains a readout layer of size that consumes a hidden state of width and converts it into logits over the vocabulary . Let us assume, in our example, that we are working with a trunk that produces a hidden state of width , and thus the readout receives a single number from the trunk. Under the CA objective, a possible solution for is : yields a base probability distribution of , which becomes the target after masking and renormalization. Assuming the trunk is sufficiently capable, is a concrete solution for the optimization problem the CA objective tries to solve: for any allowed pair of tokens and their probability ratio, there exists an output from the trunk such that renormalized obtains the target ratio.
On the other hand, without the analysis filter, there does not exist a readout that is sufficient to obtain any desired probability ratio while assigning arbitrarily little probability to the disallowed tokens: multiplying the five readout weights in by can only preserve their ordering ( ), reverse it ( ), or make all tokens equally likely ( ), but not make each of the ten possible allowed pairs outrank the other three tokens. In fact, the width must be at least 4 for the CE objective to model any pair-live distribution in our example (Section B.1 and Theorem 3): internalizing the analysis enforces a minimal width on the transformer, larger than when the analysis is externalized. Theorem 3 formalizes this difference in required width.
Theorem 3 (Minimum Width for Analysis). Let A be a prefix analysis that allows between one and m tokens at each prefix, where . Suppose that, as the prefix varies, its allowed set can be any m-element subset of a pool of at least tokens. Then the minimum hidden-state widths permitting a capable readout are
In Theorem 3, we call a readout capable for any target distribution on every allowed set, there exists some input of hidden states such that achieves arbitrarily small excess loss. A precise definition is given in Section B.1, along with a more precise theorem statement and a proof.
Theorem 3 establishes a necessity: a capable readout is required to support an analysis A which can allow any m-element subset of tokens with arbitrary precision, thus the hidden state must be at least as wide as for CA and for CE. Analyses that allow m-subsets of tokens are relatively common in programming: as the prefix varies, scope or type analyses can allow any m-element subset of a pool of at least identifiers (e.g., constants, variable names).
Experimental setup. We test whether the predicted difference in required width transfers to an actual advantage in model size by training a transformer on a synthetic corpus modeling a scope analysis. Each statement in the corpus is of the form (scope x_i1 ...x_i12 f_j y), where (i) the variables x_i1 ...x_i12 denote the 12 variables in-scope (drawn from a universe of 61 variable names x_1 ...x_61), (ii) y is one of the 12 in-scope variables, and (iii) f_j is one of 12 functions, each of which defines a probability distribution over the variables: e.g., f_1 might assign a distribution (0.5, 0.5, 0, ...0) to (x_1 ...x_61).
We train models with four layers of internal dimension 64, followed by a learned projection to w dimensions, while varying w. The model is trained to predict the token at y given the scope and the function as a prefix (details in Section E.1). The allowed set of the analysis is the set of 12 names that are in scope; model trained on CA loss must learn the probability distribution that the function name enforces, while a model trained on CE loss must learn to suppress the 49 out-of-scope variables in addition. Theorem 3 states that w must be at least 11 for CA and 24 for CE to achieve arbitrary precision. (Whether training finds an accurate model (both the readout and the trunk) at these widths is a separate empirical question.) We measure excess loss on a held-out dataset after training: for the CA objective, for the CE objective, and also , the loss of the CE model limited to the allowed set .
Results. Figure 2 reports excess loss (loss minus the target distribution entropy) on 480,000 held-out queries. As expected from Theorem 3, drops sharply when the width reaches 11: from 0.01 at w = 10 to 0.0004 at w = 11. Beyond w > 11 loss stays near 0.0004–0.0005, with little benefit from additional width; CA training finds a highly accurate model as soon as the readout has sufficient width to express the variable-usage preferences.
Even if the lower width bound in Theorem 3 is satisfied, achieving arbitrary precision in practice is a training question that requires the model to find the capable readout (and a matching capable trunk) through training.
The mismatch between program identifiers and tokens is discussed in Section B.3.
On the other hand, standard CE shows significantly higher loss. Excess loss stays high (> 0.8) when , and although does drop sharply starting from , it remains over 0.05 across all widths. Although Theorem 3 states that an optimal readout (that is, a readout capable of arbitrary precision given a perfect trunk) exists for CE at , the CE model failed to learn it; was the smallest width displaying capability across sampled queries (see Section E.1 for details). Even then, was 0.1812, indicating that the readout-trunk pair failed to reach an optimal state.
Both CA and CE models retained residual error after training; settles near 0.0005, while reached 0.1812 at and 0.0537 at ,

Figure 2: Mean losses , , and , each reported in excess of the target distribution's entropy. All values are nats per answer.
even though its learned readouts were empirically capable. continues to improve between these widths, but remains far from . Overall, constraint-aware training displayed substantial benefits: was smaller than both and across all widths, often by orders of magnitude. The result at shows that CA training can achieve much lower excess loss even at smaller model sizes. Externalizing scope during training yielded a much closer fit to the variable-usage distribution throughout this sweep, including at widths well above the capability thresholds of both objectives. Section E.1 illustrates additional controls using a fixed scope and a longer training schedule.
4 The Benefits of Externalization: Depth
We next consider analyses that cannot be computed by a single layer of weights and impose a requirement on the depth of a transformer [4, 6, 10]: externalizing these analyses can reduce the depth needed to model the target distribution. Again, we illustrate with an example. Consider a language with five disjoint groups of four variable names, through . At a prefix (if F : tag0, where F is an arithmetic formula, let an analysis evaluate F mod 5 and allow only the group corresponding to its value: e.g., if , then F mod 5 = 3 and the allowed set .
Suppose tag0 specifies a target distribution (0.4, 0.3, 0.2, 0.1) over the allowed four names. The CA objective can simply learn to associate the tag name tag0 with the relative weights (4, 3, 2, 1) to the four names in every group: then, whichever group the analysis allows, renormalizing on that group yields the target distribution (0.4, 0.3, 0.2, 0.1). On the other hand, a model trained on CE loss must identify which group to assign its probability mass to, which requires, in essence, the model to be able to compute the formula F. If evaluating F requires more layers than learning the tag-dependent probabilities, then internalizing the analysis imposes an additional depth requirement, similar to the width requirement in Theorem 3. Theorem 4 formalizes this intuition.
Theorem 4 (Depth required to internalize an analysis). Let C be a training corpus and A be an analysis. Let be the minimum depth needed to identify the allowed set with average error probability at most , over the distribution of prefixes c defined by the corpus C, and the target next-token distribution at prefix c modeled by C.
Then for an error bound where , for a model to achieve expected KL divergence , it must have depth at least .
In Theorem 4, we use ‘average probability at most ’ to mean that the transformer is allowed to compute the wrong allowed set for at most an -fraction of prefixes in C; a precise definition is given in Section C.1. We note that for a fixed , many common analyses force to increase as the corpus contains samples of longer size: for example, formal language recognition [4, 6, 10] often requires the depth of the transformer to grow with input length.
This observation yields the practical reading of Theorem 4: an CE-trained transformer must grow in depth in order to support expected loss on inputs of longer size. Even if an analysis requires only constant depth (e.g., the scope analysis from Section 4), CE training enforces this depth as a lower

Depth (layers)

Formula size (operators)
Figure 3: Left: excess losses obtained by training on the depth corpus, associated with , (from CE training), and (from CA training). All losses are nats per answer. Right: CE excess loss by formula size for 2, 4, and 8 depth configurations.
bound; constraint-aware training is free from this lower bound or the scaling requirement. A more precise version of Theorem 4 and a proof can be found in Section C.1 and Section C.3.
Experimental setup. We test the depth separation on a synthetic corpus following the example at the start of this section: each statement is of the form (if F : tag_i y), F is an arithmetic formula as described, and the goal of the model is to predict the token at the position y. The analysis evaluates F and returns the set of four allowed names, so the CA objective only needs to learn the probability distribution specified by tag_i across the allowed variable names; the CE objective must learn to evaluate F in addition, in order to drive the probability of the disallowed variables to zero.
We train models of width 128 while varying depth over 2, 4, and 8 layers, with two initialization seeds at each depth. Training details are in Section E.2. We measure the excess losses associated with , , and , as in Section 3, and also the accuracy of the CE model in computing the correct allowed set as a function of complexity (number of operators) in evaluating F.
Results. Figure 3 summarizes the results of the experiment, evaluated on a held out set of queries: the left graph illustrates that , the loss of the CA-trained model, outperforms both (the total loss of the CE-trained model) and (the loss of the CE model measured only on the allowed tokens). In particular, CA loss stays relatively constant at around nats as depth increases, but CE loss improves significantly with depth: from 1.1 nats at depth 2 to 0.53 at depth 8, illustrating that the model is using (and requires) the additional layers for evaluating F (the analysis).
The right of Figure 3 illustrates that the complexity of F is directly correlated with the loss of the CE model: for example, the CE model shows low excess loss on formulas 2 – 3 operators, even at depth 2. However, the loss starts increasing sharply as the number of operators increases, eventually plateauing at about 1.1 nats, at which point the CE model fails to make a prediction about the allowed set at all and instead just predicts a uniform distribution: the experiment thus illustrates that the CE model is actually learning an input-size dependent circuit for evaluating F via training, necessitating increasingly larger depths to support inputs of larger size. Constraint-aware training is free of this burden and achieves a much lower constant excess loss compared to CE models at any depth. Section E.2 gives more detailed experimental results.
5 The Benefits of Externalization: Data Efficiency
Having established that analyses require lower bounds on the size of transformers, we now show that externalizing an analysis can reduce the amount of data required to achieve a certain error. The main contributor is variance across training corpora: different finite corpora expose the model to different prefixes. Consequently, even models that fit their training targets exactly can make different predictions at the same unseen prefix. Under certain assumptions about training, Theorem 5 shows that this variation can lead to higher expected loss against the true distribution for CE-trained models than for CA-trained models.
We do note that modeling the inner distribution of allowed variables may require transformers of depth larger than the lower bounds imposed by Theorem 4. How the depth requirements of the inner distribution interact in this case with the bounds in Theorem 4 is left for future work.

Training pairs (millions)
Excess KL loss (nats).
| Pairs (M) | CA () | CE () | ||
|---|---|---|---|---|
| 2.4 | 0.351 | 0.0277 | 26.3 | 1.99 |
| 7.2 | 0.0716 | 0.0081 | 10.5 | 0.987 |
| 24 | 0.0671 | 0.00782 | 7.25 | 0.725 |
| 36 | 0.0664 | 0.00809 | 6.58 | 0.688 |
Figure 4: Excess loss curves against corpus size (left), and loss of the mean prediction across all 16 models ( ) and the average variance component of individual losses ( ) across corpus sizes (right). Units are in nats. CA achieves a significantly lower excess at all corpus sizes. For both CE and CA, is much higher than , indicating that variance from the training corpus is a significant source of loss.
Theorem 5 (Data efficiency). Let and be the expected KL divergences from to the two models' masked predictions after training on a corpus of prefixes, averaged over corpora and held-out prefixes. Under the minimum-change fitting and conditional-centering assumptions in Sections D.1 and D.3,
We observe that Theorem 5 does not imply a loss floor: both CA and CE distributions can be centered around , but have a positive expected KL divergence (i.e., loss). At a high level, the proof of the theorem shows that CE training results in a larger change of parameters compared to CA training, which translates under the conditional-centering assumption to a higher degree of variance. The proof, and the assumptions on which this proof hold, are presented in Sections D.3 and D.4.
Experimental setup. In addition to stating that CE training requires equal or more samples than CA training to achieve the same loss, Theorem 5 also names the source of the high loss displayed by CE: variance. We thus center our experiment on two aspects: (i) showing that CA training is indeed more data-efficient, and (ii) varying the corpus used for training while keeping other parameters fixed, to measure the variance in loss induced by variation of the training corpus.
We use the same family of statements as the scope analysis in Section 4, and train transformers of depth 4 and internal width 128 by varying (i) the corpus over 2.4M, 7.2M, 24M, 36M training pairs, and (ii) draw 16 independent corpora at each size. We fix all other hyperparameters and allocate the same training compute by revisiting examples in smaller training pools to isolate the effects of corpus size and variation. We report excess loss , (for CE), and (for CA) as in Sections 3 and 4. For variance, we report (i) , the loss of the mean prediction generated by averaging the predictions of all 16 models trained on different corpuses (for a fixed size) against the true distribution and (ii) , the average individual loss of each model minus :
Where is the allowed-set distribution of the model trained on the corpus and . Intuitively, measures variance: how much of an individual model's loss can be attributed to corpus variation. Training details and controls are in Section E.3.
Results. Figure 4 summarizes the CA vs. CE loss investigation (left) and the metrics (right). Again, CA achieves much lower loss compared to CE across all document sizes. In particular, the measured metrics (right) indicate that variance for CA has flattened by 7.2M training pairs, while CE only shows a decreasing trend in variance reduction from 24M to 36M pairs. Overall,
Our corpus is generated via a generator modeling , the target distribution defined in Sections 3 and E.
we observe that CA achieves lower excess loss with substantially fewer training samples, and its predictions fluctuate less across independently sampled corpora. (We are unsure of the cause of the floor observed in CA training, but conjecture that it is noise related with training or nondeterminism of the training kernel dominating corpus variance.)
The right table of Figure 4 illustrates that is much higher compared to (roughly an order of magnitude higher), indicating that variance is a significant contributor to expected excess loss. These results indicate that variance reduction is an important element for minimizing excess loss during training, and thus that the data efficiency advantage of constraint-aware training manifest as practical benefits. We do note that the higher of CE is not explained by our experiments, but the results still illustrate that CA displays significant benefits in variance reduction, reaching a floor with 7.2M training samples.
6 Discussion and Related Work
Gradient Decomposition and Semantic Objectives. We observe that the loss and gradient decomposition in Section 2 can be extended to multiple analyses: for example, a parser can reject syntactically invalid tokens, a scope analysis can then remove unbound names, and a type analysis could then further restrict remaining tokens. If the analyses can be nested: that is, denoting the allowed set of the j-th analysis as , we observe that the loss decomposition can be chained:
Where quantifies how much of the remaining probability mass (after ) the analysis removes. Summing these nested losses one can obtain , where is the final allowed set . The interesting part is that because we have isolated the contribution of each analysis, we may assign a separate weight to it: , which defines a semantically modified training objective where each component contributed by an analysis is weighed differently. Take the gradient of the modified objective to obtain
Equation (8) illustrates how the coefficients survive into the gradients over the parameter space generated by each analysis, thus showing how the coefficients can amplify or dampen signal. This paper studies the specific case where all . Whether different configurations of lead to practically relevant training mechanisms is a very interesting direction of future work.
Constrained and Guided Decoding. There is a plethora of work on constrained / guided decoding, much of which are focused on developing different efficient prefix analyses for computing the allowed set [3, 7–9]. This paper discusses how to apply previous work on developing prefix analyses towards training.
Of particular interest are works which focus on making constrained decoding efficient at runtime [7]: because constraint-aware training assumes that the model will be deployed with the analysis at all times, the analysis must be efficient enough as to not impose a significant overhead during inference.
Masked Losses. Our training objective defined in Section 2 is not completely novel: variants of the objective have appeared in different domain-specific settings, for example GraFT [1], or recommender systems [5]. As far as we are aware, we are the first to show that the decomposition holds for any general analysis A, connect it to a semantic objective as above, and formulate a general mathematical theory on how constraint-awareness benefits training. Both GraFT and Liao et al. [5] focus on fine tuning, whereas we investigate the effect of analyses on the pretraining stage.
References
[1] William English, Dominic Simon, Sumit Kumar Jha, and Rickard Ewetz. Grammar-forced translation of natural language to temporal logic using llms. arXiv preprint arXiv:2512.16814, 2025.
[2] David Gale. Neighborly and cyclic polytopes. In Convexity, volume 7 of Proceedings of Symposia in Pure Mathematics, pages 225–232. American Mathematical Society, 1963. URL https://paisajes.matcuer.unam.mx/IMG/pdf/1963-gale-neighborly-cyclic-polytopes.pdf.
[3] Saibo Geng, Martin Josifoski, Maxime Peyrard, and Robert West. Grammar-constrained decoding for structured nlp tasks without finetuning. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, pages 10932–10952, 2023.
[4] Selim Jerad, Anej Svete, Sophie Hao, Ryan Cotterell, and William Merrill. Context-free recognition with transformers. arXiv preprint arXiv:2601.01754, 2026.
[5] Hao Liao, Jiwei Zhang, Jianxun Lian, Wensheng Lu, Mingqi Wu, Yong Zhang, Yitian Huang, Mingyang Zhou, Rui Mao, et al. Eliminating out-of-domain recommendations in llm-based recommender systems: A unified view. In Findings of the Association for Computational Linguistics: ACL 2026, pages 6251–6271, 2026.
[6] Will Merrill and Ashish Sabharwal. A little depth goes a long way: The expressive power of log-depth transformers. Advances in Neural Information Processing Systems, 38:95315–95339, 2025.
[7] Michał Moskal, Harsha Nori, Hudson Cooper, and Loc Huynh. LLGuidance: Making structured outputs go brrr. Microsoft, June 2025. URL https://guidance-ai.github.io/llguidance/llg-go-brrr.
[8] Niels Mündler, Jingxuan He, Hao Wang, Koushik Sen, Dawn Song, and Martin Vechev. Type-constrained code generation with language models. Proceedings of the ACM on Programming Languages, 9(PLDI):601–626, 2025.
[9] Shaan Nagy, Timothy Zhou, Nadia Polikarpova, and Loris D'Antoni. ChopChop: A programmable framework for semantically constraining the output of language models. Proceedings of the ACM on Programming Languages, 10(POPL):1905–1932, 2026. doi: 10.1145/3776708.
[10] Andy Yang, David Chiang, and Dana Angluin. Masked hard-attention transformers recognize exactly the star-free languages. Advances in Neural Information Processing Systems, 37:10202–10235, 2024.
A Proofs for Section 2: Constraint-Aware Loss
We derive the loss and gradient identities, prove Theorem 2, and connect the token objective to likelihood over complete strings.
A.1 Loss and gradient decomposition
Fix a prefix with nonempty allowed set and a target law supported on . Write for the model prediction renormalized on . Substituting into cross-entropy gives
Thus the excess CE loss is the sum of the masked KL divergence and support loss. Taking gives Equation (1).
Fix a training pair with , and hold the allowed set fixed. We use the notation of Section 2.
To evaluate the support gradient, substitute the softmax probabilities into :
Differentiating the two logarithms gives
(9)
The indicator appears because the second sum contains only when .
For the CA loss, the full-vocabulary normalization cancels in the ratio , leaving
The first term differentiates to as above, while the derivative of with respect to is . Thus
Substituting these expressions into Equation (2) recovers the ordinary CE gradient:
A.2 Proof of Theorem 2
Proof. Write for the nonempty training-pair multiset in the theorem, and group its pairs by their prefixes. Since the analysis retains all observed targets, is supported on , and the definition of CA loss gives
The second equality follows by adding and subtracting the log of the empirical conditional probability inside the sum. Terms with contribute zero. Subtracting proves Equation (5). This identity holds for every parameter setting . Since is independent of , the average CA loss and the weighted average KL divergence have the same minimizers.
Each weight is positive on the observed prefixes, and each KL divergence is nonnegative and vanishes exactly when its two distributions agree. Thus the excess loss is zero precisely when at every observed prefix. In terms of the raw predictions, this condition is equivalent to
The remaining mass may be distributed among the disallowed tokens in any proportions. A neural model's parameterization may restrict which such predictions it can realize. In particular, if an allowed token has zero empirical frequency, exact agreement requires its masked probability to be zero. With finite softmax logits this can only be approached as a limit; the loss identity still holds for every finite parameter setting.
A.3 Likelihood of complete strings
Suppose the training pairs come from m complete strings, each ending at its first end-of-sequence token EOS. The analysis is fixed independently of and retains every training target. For this sequence-level statement, assume the analysis admits a token at every reachable nonterminal prefix and forces EOS within a fixed number of steps. These conditions make sampling from the masked next-token distributions a normalized distribution over complete strings:
Here is the prefix before token , and the product includes EOS. At each node of the finite prefix tree, the outgoing probabilities sum to one, so its terminal leaves have total mass one. Strings containing a rejected token have probability zero.
For any training string, taking logarithms of the product gives
Let contain all training pairs from the strings and let be their empirical string distribution. Summing over the corpus gives
The factor m/N and entropy are independent of . Minimizing average CA loss therefore also minimizes the KL divergence from the empirical string distribution to the deployed generator.
If the masked predictions match the empirical next-token frequencies at every observed prefix, this generator recovers the empirical string frequencies exactly. To see this, let count corpus strings beginning with , including repeats. Each observed transition has probability , so the probability of a complete string telescopes to . Unobserved branches have probability zero. This statement is conditional on fitting those frequencies; it does not assert that a particular model can attain the entropy bound.
The sequence identity requires scoring every position, including termination. When only designated answer positions are scored, as in our experiments, the token identities apply at those positions without defining a likelihood for the entire surrounding program.
B Proofs for Section 3: Width
The width result separates two requirements on the final hidden state: setting the ratios among allowed tokens, and making those tokens more likely than all rejected tokens. We first state the full version of Theorem 3, including the conditions on a fixed readout. We then prove the conditions and the matching width bounds. The remaining subsections explain the readout checks used in the experiments and how the theorem applies when names span several vocabulary tokens.
B.1 Capability and proof of Theorem 3
Theorem 3. Let be a finite vocabulary and a nonempty family of allowed sets with for every . Set and assume . A trunk of width supplies a hidden state directly to a bias-free linear readout , whose row for token is denoted by . Let , and let be restricted to and renormalized. All matrix and state entries are finite real numbers.
A fixed is CA-capable on if, for every , every target distribution positive on and zero outside it, and every , there exists with . CE capability has the same quantifiers and requires instead. The hidden state may depend on , , and ; the readout remains fixed.
-
A fixed readout is CA-capable on if and only if, for every , its rows are affinely independent.
-
A fixed readout is CE-capable on if and only if it satisfies the CA condition and, for every , there exist a vector and a scalar such that
- For any such family S, a CA-capable readout exists if and only if , and a CE-capable readout exists whenever . If, in addition, there is a set with such that every m-element subset of K belongs to S, a CE-capable readout can exist only if . Under this additional assumption, the minimum widths admitting the respective capabilities are therefore
The lower bounds constrain the trunk width because it is the input dimension of . The sufficient-width constructions provide readouts and suitable hidden states; realizing them with a particular trunk additionally requires that trunk to compute those states.
For the first two parts, fix an allowed set and write . The conditions obtained below must hold for every .
CA criterion: fitting the allowed-token ratios. Choose a reference token . To fit a positive target after applying the analysis, the hidden state must solve
Every vector in occurs on the right for some positive target. Thus every target can be fitted exactly if and only if the row differences on the left are linearly independent. Equivalently, the rows indexed by are affinely independent, or
If this rank condition fails, some target log-ratio vector lies outside the image of the linear map. The image is closed, so even a sequence of hidden states cannot approach that vector. Since convergence in KL to a positive target implies convergence of all its probability ratios, that target cannot be approximated to arbitrary precision. This proves the CA criterion and the necessary width .
CE criterion: suppressing the rejected tokens. Suppose the CA criterion holds, and let and satisfy Equation (13). Choose a state fitting any positive target within . Along , all allowed logits change by the same amount , so their conditional distribution stays exactly . Every rejected logit falls relative to them as . The support mass tends to one, so total excess CE tends to zero.
Why a successful CE readout must admit such a vector. Let , and let be the restriction of this subspace to the allowed coordinates. If CE excess tends to zero along states , both within-mask KL and support loss tend to zero. Normalize
Then and every coordinate of tends to . The restriction has a linear right inverse on its image. Therefore is bounded, and has and for all sufficiently large . Writing such a gives the required separator. CE capability also implies CA capability, completing the equivalence. This argument uses a fixed ; its right-inverse norm need not be uniform as the readout changes.
Constructing a CA readout of width . Place token rows at distinct points on . Every set of at most rows is affinely independent by the Vandermonde determinant, so width suffices for all allowed sets. A size- allowed set gives the matching lower bound.
Constructing a CE readout of width 2m. Use the classical neighborly moment-curve construction [2] in . Every set of at most m rows is affinely independent. For a particular allowed set S of size , the polynomial
has degree , vanishes exactly at its token parameters, and is strictly negative at all other token parameters. Its coefficients give an affine functional exposing S. The CE criterion therefore holds at width 2m. Appending zero columns to either construction, with zero entries in the additional hidden-state coordinates, preserves its predictions and proves sufficiency at every larger width.
Why smaller CE readouts cannot serve every allowed set. Under the additional assumption on K, suppose a CE-capable readout exists with . Each m-subset of K is then the vertex set of an exposed simplex face of the convex hull of all token rows. Every smaller nonempty subset of K is also an exposed face: extend it to an m-subset and expose the desired subface within that simplex. To see this directly, add a sufficiently small multiple of a functional exposing the subface to the functional exposing the full simplex; the strict gaps to the finitely many other rows persist.
Let the affine dimension of the rows indexed by be . As , choose of these rows. An affine dependence, split into its positive and negative coefficients and normalized, gives disjoint nonempty sets with intersecting convex hulls. Choose the smaller side as ; then . But is exposed, whereas every row of lies strictly below its exposing hyperplane. Their convex hulls cannot intersect, a contradiction. Thus , proving Theorem 3.
Relation to the normalized experimental models. The theorem allows freely chosen hidden states. Restricting those states through RMS normalization cannot invalidate its lower bounds. With unit gain and the positive normalization constant used in the experiments,
For any finite collection of states , choose . Replacing by and supplying before normalization preserves every logit vector: . Thus normalization does not obstruct realizing these finite collections at the stated width when scale may change. It does not make a single fixed, bounded-scale model capable of arbitrarily small CE excess.
B.2 Lower bounds for the loss of a learned readout
A trained model can have high loss because of its readout, its trunk, or both. To isolate a restriction imposed by the readout, we fix the learned and allow the hidden state to be chosen freely for each target. A positive lower bound in this easier problem also bounds the loss of the actual trunk. The bound applies to this fixed readout, not to every readout of the same width. For a fixed readout and target extended by zero, define
Any probability distribution on satisfying gives the lower bound by the variational inequality for log-sum-exp. Requiring to be supported on gives the analogous within-mask lower bound. Feasibility is checked with rational arithmetic. For a rational target approximating the intended target , an interval enclosure supplies . A lower bound at transfers to
Indeed, cross-entropy against is at least times cross-entropy against , since . Entropies and the target enclosure are handled in interval arithmetic. The rank and separator criteria above establish when the infimum is zero. If no positive lower bound can be verified, we report only zero as the lower bound. No optimization or training algorithm can invalidate a verified bound for the fixed readout, but changing the readout changes the bound.
B.3 When a variable name spans several vocabulary tokens
The width theorem concerns allowed sets in the model’s vocabulary V. The running example and the synthetic scope experiments use one vocabulary token per variable name. When a name instead consists of several subword tokens, an analysis over complete names must induce an allowed set at each intermediate token prefix. For example, if x1 and x2 are tokenized as (x, 1) and (x, 2), an allowed name set permits only x at the first step, then either 1 or 2 at the second step. The CA objective uses these sets of actual next tokens.
To apply Theorem 3, both m and the condition that every m-element subset of K belongs to S must be checked for this induced family of allowed token sets. A large choice among complete names can become a sequence of smaller token choices, so neither the largest allowed-set size nor the condition on K transfers automatically from lexemes to vocabulary tokens. General implementations must also account for unfinished lexemes and tokens that cross lexeme boundaries. The loss decomposition and CA objective still apply to any resulting computable prefix analysis that retains the desired target tokens.
C Proofs for Section 4: Depth
Theorem 4 relates the depth needed for small CE excess to the depth needed to identify the allowed set. We first prove this relation, then show how CA can leave the decision to the analysis. A separate result uses a bound on decision accuracy at each input size to obtain an explicit lower bound on expected CE excess.
C.1 Analysis accuracy and proof of Theorem 4
Fix a corpus distribution and a model architecture of width . Let size be the size of the input analyzed at prefix ; in the formula example, it counts operators in the current formula. Each prefix contains a visible cue (the tag in the example). The cue specifies nonempty, pairwise disjoint candidate sets and a target distribution on each set . The analysis selects one of these sets, indexed by ; thus and .
Let be the family of models of depth and width . For a model's prediction , define its decision by
with ties broken by the smallest index. For , define
with the minimum of an empty set taken to be . The corpus distribution, candidate sets, width, and architecture are fixed when comparing depths; suppresses these fixed choices, as in Theorem 4. Error is averaged over sizes according to their corpus probabilities; it need not be at most separately at every size. This definition concerns the best model at each depth, regardless of how its parameters are obtained.
Proof of Theorem 4. For candidate , let . The candidate sets are disjoint, so . On an incorrect decision, some competing set has mass at least . Consequently , and the support loss is at least . Support loss is nonnegative on every other prefix. Taking expectations and using the excess-loss decomposition gives
Thus expected CE excess at most implies average decision error at most under the same prefix distribution. By the definition of , the model's depth must be at least .
The same argument applies to a corpus restricted to size(c) ≤ , provided that event has positive probability. In that case, both the loss expectation and the decision error defining must use this restricted distribution. Disjointness is essential: overlapping candidates can share most of the target mass, so a wrong set decision need not cost log 2. In particular, this reduction does not apply directly to arbitrary overlapping scope sets.
The depth in counts the transformer layers producing the probabilities; the fixed rule that sums candidate probabilities and selects the largest is the same at every depth. This rule uses the cue-defined candidate sets, not the answer supplied by the analysis. To apply a recognition lower bound with a different output convention, one must also account for the computation of these candidate sets and the sums and comparison. An exact-recognition lower bound alone does not bound for positive : a model can fail on rare inputs while attaining high accuracy under the corpus distribution.
C.2 Leaving the decision to the analysis
The prediction uses only the visible cue. After the analysis selects a candidate set, it becomes exactly that set's target law. It therefore has zero CA excess and support loss , without computing . For a strictly positive softmax prediction on the entire vocabulary, replace it by , where is uniform and . On the selected set,
so CA excess tends to zero as . Both constructions depend only on the cue. Realizing them with a shallow transformer requires that the cue-dependent probabilities be computable at that depth.
C.3 A loss bound from decision hardness at larger input sizes
The next result adds a quantitative assumption about how often models err at each input size, using the same prefix distribution and candidate sets as above. Let specify a size beyond which a depth-L model's decision accuracy is bounded as follows.
Theorem 6 (Depth under decision hardness). Fix and . Suppose that, for every depth , every model , and every size with positive probability under the corpus distribution,
Then every such model has expected CE excess bounded below by
If a model in whose predictions depend only on attains expected CA excess at most , then CA can attain this tolerance at depth . Any CE model attaining the same tolerance must have a depth L for which the final lower bound in Equation (15) is at most .
Proof. At each size , the assumed decision error is at least . Weighting by the corpus probabilities of these sizes gives
Substituting into Equation (14) proves Equation (15). A model with CE excess at most must make this lower bound at most ; the stipulated cue-only model attains that tolerance under CA.
The decision-hardness assumption concerns every model in the specified class, on the actual encoded prefix distribution. The trained models’ size-dependent errors in Section 4 do not establish this assumption or a lower bound on for that distribution.
D Proofs for Section 5: Data Efficiency
This appendix makes the training model in Theorem 5 explicit. We first describe the two fitting problems, then identify the extra parameter change required by the support constraints. We follow that change to an unseen prefix and compare the resulting losses. The last parts derive the sample requirement and justify the loss decomposition used to measure corpus variation in Figure 4.
D.1 The two fitting problems
Let contain sampled training prefixes, and write for the true next-token law. The fits below use this conditional law at each sampled prefix; the randomness comes from which prefixes are sampled, rather than from estimating their target probabilities using next-token counts.
Let be a parameter change from a fixed initialization. At training prefix , write and , and choose a reference token . The choice is determined by the prefix, independently of a sampled next token. Let and be the initial logits of the other allowed tokens and the rejected tokens, respectively, minus the reference logit. In the affine model these become
where the Jacobian matrices stay fixed during fitting.
Suppose the target law is positive on . CA must fit the relative logits for . Subtract the initial values and stack these equations over training prefixes to obtain
There are no equations for rejected tokens in this system.
For the CE fit, also fix a leakage level . If , require every rejected relative logit to equal
The allowed exponentials sum to , and the rejected ones to . After normalization, the rejected mass is therefore exactly , while the allowed-token conditional remains . Subtracting the initial rejected scores and stacking the additional equations gives . Prefixes with no rejected tokens add no rows to this system.
The two fitted parameter changes are
We assume the stacked matrix has full row rank, so both systems are consistent and their minimum-norm solutions are unique. There are stacked scalar constraints, so this assumption requires and their independence. The sample-size comparison is restricted to sizes meeting this condition. This is an idealized interpolation model: the targets are whole conditional distributions, the CE fit is stopped at finite leakage, and the Jacobians do not move. A sampled-token AdamW run need not satisfy these conditions. Expectations in the theorem are over samples for which these rank and moment assumptions hold; duplicate or dependent constraints need not meet the rank condition.
D.2 The extra parameter change needed to fit support
Let and be its orthogonal projector; a superscript + denotes the Moore–Penrose pseudoinverse. The minimum-norm CA solution is and lies in . Every solution of both systems is therefore uniquely with and . By orthogonality its squared norm is . Hence the minimum-norm addition is
The stacked rank assumption makes full row rank: any row dependence would put a combination of rows of in row . This proves the decomposition and orthogonality in Theorem 5. At held-out , the affine model gives the exact difference .
D.3 Full statement and proof of Theorem 5
At a held-out prefix, the CA relative logits are , and CE changes them by . The expected relative-logit loss is , where the sum omits the reference token. Write and for the fitted models' masked predictions. For , define
where C has size n and c is drawn independently from the held-out prefix distribution. This distribution and the law used to sample training corpora are the same for both fits.
Theorem 5. Under the fitting assumptions in Section D.1, , where and . Thus the additional change preserves every fitted training conditional. Suppose its effect at held-out prefixes is conditionally centered:
If the expectations below are finite, then
(16)
In particular, if . Consequently, on any common range of sample sizes satisfying these assumptions, CA requires no more examples than CE to reach a fixed expected within-set excess loss.
The parameter decomposition was proved in Section D.2. The equality in Equation (16) follows by subtracting the same target entropy from the two expected token losses. To compare those losses, recall the function above. It is convex, with Hessian , where and omits the reference token. For any , is a variance under and lies between zero and , so . Fix and , which also fixes . The centering assumption says that the mean of under this conditioning is . Jensen's inequality for the convex function therefore gives
Averaging once more proves the lower bound in Equation (16). For the upper bound, the Hessian bound gives
and conditional centering removes the linear term in expectation, giving the upper bound.
For finite logits, is strictly convex in the nonreference coordinates: its Hessian is positive definite because every token, including the reference, has positive probability. Equality in the expected-loss comparison therefore holds exactly when almost surely, meaning the extra CE update leaves the held-out masked predictions unchanged.
Centering also identifies the added variance directly. When the relative logits have finite second moments, set . Both fits have this same mean relative-logit vector at , and
The cross term vanishes because is fixed given , and is centered under that conditioning. This is a variance comparison for relative logits; it does not require the mean CA prediction to equal the true conditional distribution.
Conditional centering is an additional assumption: preserving the training conditionals does not prevent a systematic change at an unseen prefix. The loss ordering above uses this assumption to remove the linear term; the larger parameter norm alone does not imply it.
D.4 How many examples are needed to reach a target loss?
Let be the expected held-out within-mask excess of learner X, including expectation over its training sample. Consider a common set I of sample sizes at which the two learner families satisfy Theorem 5, and define
The theorem gives at each such . Hence every sample size meeting the CE target also meets the CA target, so
If and , the inequality is strict: CE meets the target neither at nor at any earlier size, where even CA fails to meet it. No monotonic learning curve or asymptotic rate is needed for this set-inclusion argument. A positive risk gap alone does not ensure strictness at every chosen tolerance, because both risks can already be below it. The result concerns the specified learner families and valid sample-size range; it supplies neither a universal sample multiplier nor a rate for AdamW.
D.5 The corpus-fluctuation loss in Figure 4
Fix one prefix with target law , and let be the masked predictions from the sixteen training corpora. Their mean is . Subtracting its loss from the average individual loss gives
Concavity of the logarithm makes every bracket nonnegative. Averaging this identity over the shared evaluation prefixes gives in Equation (7); the average individual excess is exactly . Both components are measured in nats. The latter is the average loss removed by averaging predictions, rather than the variance of the scalar losses. The identity needs no assumptions about training or conditional centering.
E Experimental Setup and Supporting Results
All three studies use known target distributions so that excess loss can be measured directly. The width study varies model size, the depth study varies the number of layers, and the data-efficiency study varies the available training corpus. We give their shared architecture and optimizer below, followed by the setup and supporting results for each.
Shared architecture and optimization. The model is a causal decoder with bias-free attention and MLP projections, rotary position embeddings (base 10,000), pre-block RMS normalization, SwiGLU MLPs, and an untied output readout. An optional linear bottleneck projects the trunk to the readout dimension before final RMS normalization. The MLP hidden dimension is for trunk dimension . Vocabulary size is 134, context length 4,096, and there are four heads. Weights use normal initialization with standard deviation 0.02; RMS normalization uses . AdamW uses , , weight decay 0.1, and gradient clipping at norm 1, with bf16 forward/backward autocast. Each update processes 16 documents. The nominal -position budget rounds to 9,156 complete updates, or 600,047,616 processed positions. Only designated answer positions have positive training weight.
The scope width and main data recipes use peak learning rate , 2% warmup (183 updates), and a cosine schedule. The width runs end at 10% of peak learning rate; the 16-corpus data study ends at zero. Parameters and samples are matched within each objective pair. Changing readout width changes both the bottleneck and output parameter counts; the capacity theorem refers specifically to the readout dimension.
E.1 Width: setup and controls for Section 3
Target distribution. The scope analysis reads the twelve listed variable names. The remaining prediction task uses a fixed table Z, with one score for each identifier and function. At a scored prefix, its target is the softmax of the selected function's column restricted to the listed scope. We construct this table so that eleven score features are sufficient for every function. For identifier , let . Orthonormalize the columns of the Vandermonde matrix in order and put . Let have the unit vertices of a regular simplex as columns (a scaled Helmert contrast matrix), and set . Then rank , its columns are centered, and every 12-row restriction of is nonsingular. Since the 12 simplex columns span , the conditional targets at each allowed set span its relative-logit space. The cue-only state and readout rows . fit the ideal masked law exactly. Equal state norms allow the final RMS gain to absorb the common normalization. The float64 law differs by at most per logit from the ideal construction; all reported KL values use that numerical law. Statements are independent: each draws a uniform 12-subset of names, a uniform function, and then an answer from the corresponding target law, with 240 queries per document. The target entropy is approximately 2.2052 nats, and uniform prediction within the allowed set has excess 0.2797.
Training and evaluation. The sweep in Figure 2 uses four layers of internal width 64, with a learned projection to readout widths 8, 10, 11, 12, 16, 23, 24, 32, 64. The training pool contains 150,000 documents; 9,156 updates consume 146,496 of them. Each document packs 240 training pairs, giving 35,159,040 pairs consumed under the shared recipe above. Excess losses are evaluated against the known target law on 480,000 queries from 2,000 held-out documents.
What the learned readout can represent. To distinguish a readout limitation from an imperfect trunk, we hold fixed and allow a different hidden state for every target. The rank and separator conditions in Section B.1 determine capability; the bounds in Section B.2 measure residual loss when arbitrary precision is impossible for that readout. The latter use 256 sampled allowed sets and all twelve functions, giving 3,072 pairs, with a set-bootstrap 5–95% interval. This sample is separate from the 480,000-query loss panel.
The CA readout at width 11 can fit all 3,072 checked targets exactly. At the same width, the CE readout has mean excess-loss lower bound 1.0172 on this panel. Its actual excess on this panel is 1.0786; the 1.0698 reported on the main validation panel uses different queries. At width 24, the learned CE readout still has a positive mean lower bound of approximately 0.153. Width 32 is the first tested CE width at which every checked target can be fitted to arbitrary precision. These checks apply to the learned readouts on the sampled targets; they do not say that every readout of the same width has the same loss.
Fixed-scope control. Fixing the same twelve in-scope names throughout the corpus, with their order randomized, lets both objectives fit accurately at readout width 12: CE total excess is 0.000229 and CA masked excess is 0.000200. The learned CE readout satisfies the rank and separator conditions for this single allowed set. This control changes both the input distribution and the task of identifying the current scope.
Longer-schedule control. We keep trunk and readout width 64, four layers, seed 0, the 150,000-document pool, and the same 480,000-query evaluation panel. Updates increase from 9,156 to 18,311, with the full cosine schedule rescaled and warmup increased from 183 to 366 updates. The longer run consumes all 150,000 documents before repeating most of them, versus 146,496 distinct documents in the shorter run. CE's masked excess decreases from 0.027137 to 0.015593 and its total excess from 0.0537 to 0.0290. CA's masked excess decreases from 0.000520 to 0.000472. Thus CE improves under the longer recipe but retains higher loss. The comparison changes exposure and the learning rate trajectory together; it does not establish a fixed optimization floor. Each objective has one run under each schedule.
Table 1: All six matched two-stage pairs, evaluated on the same uniform-size panel. Losses are nats per answer; the two within-mask columns use different scales. The last column is the largest operator count up to which CE meets the 95%-accuracy criterion at every size. No CA model meets this criterion even at the first evaluated size.
| Depth | Seed | CE range | |||
|---|---|---|---|---|---|
| 2 | 0 | 3.008 | 1.639 | 1.1036 | 4 |
| 2 | 1 | 2.382 | 1.536 | 1.1006 | 3 |
| 4 | 0 | 3.283 | 1.972 | 0.8318 | 5 |
| 4 | 1 | 2.451 | 2.236 | 0.8552 | 5 |
| 8 | 0 | 3.178 | 1.706 | 0.4764 | 8 |
| 8 | 1 | 2.450 | 1.494 | 0.5861 | 7 |
E.2 Depth: setup and controls for Section 4
The depth comparison follows one task through the same curriculum for both objectives. CA learns the tag-dependent probabilities at the smallest tested depth. Additional CE layers improve formula evaluation, reducing support loss, while its masked prediction remains less accurate.
Formula distribution and matched curriculum. Formula tree shape is proposed uniformly over full binary trees of a given operator count, and rejection sampling balances the five values exactly at each size. This accepted distribution is the data law. Both objectives use width 128, depths 2, 4, and 8, and seeds 0 and 1. Each model starts from random initialization and first trains on the uniform short-size law , then continues on for . Each stage processes approximately positions in 9,156 updates. The first stage uses peak learning rate . Both stages use warmup and a cosine schedule ending at of the peak rate. Continuation uses peak learning rate , a fresh optimizer state, and a restarted schedule. CA continues from its own CA-trained first stage. Each objective pair shares both corpora, initialization and ordering seeds, and both stages' recipes. Separate hyperparameter selection for CA and CE remains untested on this task.
Loss and decision accuracy. The primary evaluation samples operator counts uniformly from 2 to 24 on 8,000 documents, giving 551,576 queries and at least 23,400 queries per size. The loss columns in Table 1 are query means; the main figure averages the two seeds at each depth.
CA's masked excess is lower in every pair, by factors of 54–91. Within each trained-model pair, the nominal 95% intervals from 10,000 document-clustered bootstrap replicates are disjoint. For example, depth 2, seed 0 gives for CA and for CE. These intervals describe variation over held-out documents; the two-seed ranges are not confidence intervals over training runs.
CE's total excess is over 99.6% support loss in each pair, and its accuracy at identifying the allowed group improves with depth. The right panel of Figure 3 averages query-level CE excess losses within each size and then averages the two seeds. For decision accuracy, the largest difference between document-level and query-weighted estimates over the 96 size/objective/seed cells at sizes 2–9 is 0.00313. CA's decision accuracy remains near 1/5, while the analysis supplies the correct group at deployment.
The reported 95%-accuracy range requires every size up to its endpoint to have a nominal Bonferroni document-bootstrap lower bound of at least 95%, using 10,000 replicates and level 0.05/23 per size. All-correct sizes use the exact document-binomial bound instead. A size needs at least 30 contributing documents; a missing size or a degenerate non-all-correct bootstrap stops the range. The CE endpoints are across depths at seed 0 and at seed 1. These are properties of the trained models, rather than hardness bounds for the model class.
Evaluation under the training size distribution. Under the geometric size law used during the second training stage, the ordering of CE total loss by depth is unchanged. On 2,000 held-out documents and 230,537 queries, the total excesses at depths 2, 4, and 8 are (0.6672, 0.4183, 0.1618) for seed 0 and (0.7213, 0.4349, 0.2239) for seed 1. CA's masked losses remain in the same small
○ CE: 2 layers
□ CE: 4 layers
△ CE: 8 layers

Figure 5: Full-size CE curves for the same two-stage seed-0 models. Left: total excess. Right: query-weighted accuracy of identifying the allowed set. The main figure averages the two seeds and shows loss by size only for operator counts 2–9.
Table 2: Primary data study over sixteen independent training corpora at each pool size, with fixed initialization and order seed. Masked excess is mean sample standard deviation; other entries are means. CE masked excess plus support loss equals CE total before rounding. Pool sizes are in millions of training pairs; losses are held-out nats per query.
| Pairs (M) | CE | |||
|---|---|---|---|---|
| 2.4 | 0.000379 ± 0.000080 | 0.028276 ± 0.002998 | 0.017490 | 0.045766 |
| 7.2 | 0.000080 ± 0.000005 | 0.011467 ± 0.005526 | 0.017969 | 0.029436 |
| 24 | 0.000075 ± 0.000004 | 0.007973 ± 0.003928 | 0.015902 | 0.023875 |
| 36 | 0.000074 ± 0.000003 | 0.007268 ± 0.002713 | 0.015219 | 0.022487 |
range as under uniform sizes. This checks the effect of the evaluation size distribution; neither evaluation establishes a lower bound on the best achievable error at a given depth.
E.3 Data efficiency: setup and controls for Section 5
Training corpora and evaluation. We use the scope law in Section E.1, four layers, internal width 128, and readout width 64. Each 4,096-token document packs 240 training pairs. The 2.4M, 7.2M, 24M, and 36M pairs in the main text therefore correspond to pools of 10k, 30k, 100k, and 150k documents. At each size, sixteen independently generated corpora provide the training replications. Their generator seeds are , with corpus index and size index .
Each CA/CE pair shares its corpus, initialization seed 0, batch-order seed 0, and 9,156-update schedule ending at zero learning rate. Smaller pools are revisited; the largest contributes 146,496 distinct documents within the fixed budget. All 128 runs are evaluated at the final checkpoint on the same 120,000 queries from 500 held-out validation documents. The training corpora are the independent replications; the evaluation queries are shared across models.
Loss and corpus variation. At each held-out prefix, we normalize each model's prediction over its allowed set and average these distributions across the sixteen corpora. We then compute the KL loss of this mean prediction and subtract it from the mean individual KL loss, exactly as in Equation (7). Finally, we average both quantities over the shared evaluation panel. Section D.5 proves that the difference is nonnegative. Both quantities are losses in nats, rather than squared distances between probability vectors.
Table 2 adds the across-corpus sample standard deviations and the CE support loss to the main figure. Across the four sizes, averaging the sixteen predictions removes 89–93% of CA's excess and 91–93% of CE's. The absolute amount removed is 75–146 times larger for CE. CA at 2.4M pairs has lower masked excess and than CE at 36M pairs under this fixed recipe. These comparisons measure corpus-dependent prediction error; they do not establish the minimum-change or conditional-centering assumptions of Theorem 5 for AdamW training.
Table 3: Independent selection for masked deployment. Each objective uses the same six-recipe search and two tuning corpora per size. Losses are means over four new evaluation corpora; the masked-loss column also gives the sample standard deviation. Pool sizes are in millions of training pairs; all losses are excess in nats per query. The CE total column describes the same masked-loss-selected CE model.
| Pairs (M) | Objective | Peak LR | Readout decay | Masked excess | CE total |
|---|---|---|---|---|---|
| 2.4 | CA | 0.010 | 0 | - | |
| 2.4 | CE | 0.003 | 0.1 | 0.049277 | |
| 36 | CA | 0.001 | 0 | - | |
| 36 | CE | 0.003 | 0.1 | 0.027421 |
Table 4: Larger-pool and longer-schedule study. Within-mask excess is mean ± sample standard deviation over 16 corpora. is the average loss removed by averaging their masked predictions. Both numerical columns use units of nats.
| Cell | Objective | Masked excess ( nats) | ( nats) |
|---|---|---|---|
| A | CA | 0.0664 | |
| A | CE | 6.5800 | |
| B | CA | 0.0414 | |
| B | CE | 4.4032 | |
| C | CA | 0.0410 | |
| C | CE | 5.3315 |
Independent hyperparameter selection. At each of 2.4M and 36M training pairs, each objective searches learning rates and readout weight decays , using two independent tuning corpora per recipe. Architecture, initialization and order seed, and the zero-endpoint schedule match the primary study. Each objective selects by mean masked loss on the tuning corpora's validation splits. The choices are fixed before training on four new evaluation corpora per size; the common 120,000-query reporting panel is held out from selection.
CA has lower masked excess in all eight evaluation pairs (Table 3). The ratios of mean CE to mean CA excess are approximately 193 at 2.4M pairs and 156 at 36M. Selecting CE by unmasked validation loss instead gives rate 0.001 and no readout decay at 2.4M, with masked excess 0.027084 versus 0.029823 under masked selection. The paired difference has unresolved sign in the four-corpus resampling analysis. At 36M both criteria select the same CE recipe. CA remains lower in every pair under either selection criterion. These comparisons assess sensitivity within the stated grid, rather than optimal hyperparameters.
Longer training with fixed and larger data pools. Three cells, each with sixteen paired corpus runs, distinguish repeating a fixed pool from accessing a larger one under the same longer schedule:
| Cell | Available pairs (M) | Updates | Distinct pairs consumed (M) |
|---|---|---|---|
| A | 36 | 9,156 | 35.15904 |
| B | 36 | 18,312 | 36 |
| C | 72 | 18,312 | 70.31808 |
Cell A reuses the primary runs; B and C add 64 runs with the same architecture, initialization and order seeds, and evaluation panel. A and B use identical available corpora. B rescales the entire cosine schedule, including warmup from 183 to 366 updates. Each C corpus extends its A generator stream, but its larger pool changes the loader's permutation. Thus C is not a continuation of A's realized training stream. The missing 72M-pair short-schedule cell prevents separating all effects of corpus size and schedule. The longer schedule here has 18,312 updates, versus 18,311 in the width control.
CA has smaller mean masked excess and in all three cells (Table 4). Its fluctuation loss decreases from to nats with the longer schedule at the same available pool size, showing that the residual in the primary sweep is sensitive to the training recipe. CE's loss varies substantially across corpora: its standard deviation is 1.10 times its mean in B and 1.13 times its mean in C, versus 0.37 in A. Resampling the sixteen corpus indices jointly across cells and objectives, using 2,000 replicates, gives 2.5–97.5 percentile bands spanning zero for the CE changes in log fluctuation loss. These bands describe sensitivity to the observed corpora. These controls support the observed CA advantage while leaving the source of the residual errors open.