Assign and Add: A Mechanistic Study of Compositional Arithmetic

Brady Exoo, Alberto Bietti, John SousNeurIPS 2026

TL;DR

How do neural networks snap together separate skills—like looking up a variable's value and doing math—to solve brand-new problems they’ve never seen? By putting a tiny transformer under the microscope, the authors discover that it builds literal plug-and-play circuitry: an attention-based "lookup" module fetches numbers and pipes them directly into the exact same math module used for plain constants. Even cooler, gradient descent wires these modules together sequentially in distinct, predictable phases.

What Problem Does This Paper Address?

Human reasoning is effortlessly compositional: if you know how to add $14 + 17$, and someone tells you $b = 17$, you don't need to relearn arithmetic to solve $14 + b$. Large language models (LLMs) display flashes of this compositional generalization, yet also suffer bizarre failures when problems are slightly rearranged.

We still don’t really know how neural weights wire themselves during training to compose distinct skills. Mechanistic interpretability (reverse-engineering neural networks down to their weights) has thoroughly studied two classic, wildly different mechanisms in isolation:

  1. Variable binding (associative recall): Typically solved by "induction heads"—attention circuits that scan context to match patterns and copy tokens.
  2. Modular arithmetic (clock math, e.g., $(42 + 19) \bmod 59$): Typically solved via structured sinusoidal waves (Fourier features) inside multilayer perceptrons (MLPs).

The authors ask: what happens inside a transformer when a task demands both at the exact same time, and how do gradients build a bridge between them?

Methods

To keep the math and weight-inspection clean, the authors train a stripped-down, 2-layer causal transformer (1 attention head per layer, $d_{\text{model}}=128$, no biases, no layer norms, and no Layer-1 MLP).

They pair empirical reverse-engineering with theory:

  • Circuit & Representation Analysis: Inspecting Query-Key (QK) routing and Output-Value (OV) projections, alongside cosine similarity checks and linear probes on the residual stream right before the final MLP.
  • Causal Interventions: Using activation patching (swapping internal activations between clean and variable-swapped prompts) and attention-edge ablations (severing specific attention links) to prove their proposed circuit actually drives the model's answers.
  • Gradient Dynamics Theory: Analyzing a simplified mathematical model ("disentangled" embeddings) to prove why gradient descent naturally snaps the lookup circuit onto an already-trained math circuit.

Datasets

The authors introduce a synthetic, on-the-fly sequence dataset combining variable assignment and addition modulo $N = 59$ across $V = 12$ variables. Prompts are 16 tokens long, padded randomly to prevent positional cheating, with + placed before the operands due to causal masking (e.g., `b 17 ...

  • b 19 =`). Sequences contain 0, 1, or 2 variables in the addition.

To test genuine out-of-distribution generalization, they carve two big holes out of the training data:

  • Held-out addition pairs (add-restricted): Roughly 30% of all $59^2$ number pairs (like 1 and 3) are completely banished from training—never appearing as 1+3, c+3, or 1+c.
  • Held-out variable positions (var-restricted): Certain variables are locked into specific slots during training—a and b only ever appear as the first operand, while k and l only appear as the second. At test time, those rules are broken (e.g., testing 14 + b).

Key Insights and Ideas

  • One Math Module to Rule Them All: The network doesn't build separate pathways for word problems versus raw numbers. Whether you feed it + 3 4 = or `b 3 ...
  • b 4 =`, the residual stream vectors arriving at the Layer-2 MLP are nearly identical (cosine similarity $\approx 1$). The Layer-2 MLP uses standard Fourier features to compute the sum on whatever is handed to it.
  • A Modified Induction Head Acts as a Router: Instead of copying a token to the output, the two attention layers team up to route values into the MLP. In Layer 1, assigned constants look one step back to "tag" themselves with their variable's identity, while the final = token looks at the two operand slots. In Layer 2, = matches those variable tags to attend directly to the assigned constant tokens, piping their numerical embeddings straight into the addition MLP.
Figure 5: Attention patterns for an example sequence. Left (Layer 1): The = token attends to the two immediately preceding positions representing the operands (orange boxes). Simultaneously, constant tokens in positions 1–11 act as previous-token heads, attending to their assigned variables (red boxes). Right (Layer 2): The = token attends directly to the constants required for the addition (yellow boxes). These behaviors are consistent across all sequences and training initializations.
  • Learning Happens in Three Distinct Phases: The network doesn't learn everything at once. First, it rapidly masters 0-variable modular addition (steps 0–5,000). Second, a sudden spike around step 5,300 marks the birth of the variable-routing attention circuit. Third, around step 15,000, a targeted "refinement" phase fixes slight attention blind spots on position-restricted variables (like b on the right-hand side), unlocking full out-of-distribution generalization.
Figure 2: Accuracies during training partitioned by evaluation set. Add-restricted sets contain sequences with held-out addition pairs as discussed in Section 3, and var-restricted sets contain sequences with held-out variable positions. The (1) and (2) for the 2-var var-restricted sets denote how many of the variables are in “bad” positions. Train sets are those with both valid addition pairs and variable positions. An alternate run is displayed in Appendix A Figure 10.
  • The Math Module Pulls the Router into Place: Why does variable routing snap so cleanly onto the MLP? Their theoretical analysis shows that once the MLP knows how to add constants, its gradients act like a beacon: during 1-variable training, the gradient for the Layer-2 QK matrix is dominated by constructive interference pointing directly toward the true assigned constant, naturally building the exact associative memory block needed.

Key Results

  • Near-Perfect Generalization: Across 0-var, 1-var, and 2-var tasks, test accuracy exceeds 98%. Specifically, the model hits 99.6% on unseen variable positions (like 14 + b) and 99.4% on held-out number pairs.
  • Isolating the Subnetwork: Running just the isolated math equation $W_U(\text{MLP}_2(OV_2(a) + OV_2(b)))$ on raw constant embeddings recovers 99.94% accuracy on modular addition.
  • Causal Proof: Patching Layer-1 or Layer-2 activations at the assigned constants flips the model's output to the exact circuit-predicted answer ~99% of the time (~90% when patching at =). Severing the Layer-2 attention edge from = to the assigned constant craters accuracy from 99.0% down to 1.6% (while control ablations stay above 92%).

Limitations and Future Work

To make weight-level reverse engineering and gradient proofs tractable, the authors deliberately kept the sandbox tiny: a 2-layer, single-head, normalization-free transformer solving a single synthetic task. They note that a natural next step is testing how these compositional dynamics scale up to deeper, multi-head architectures, richer multi-step reasoning tasks, and deriving tighter quantitative bounds on sample complexity.

Summary updated

Abstract

Modern large language models are able to compose skills in order to perform complex tasks, many of which might not have been seen during training. The details of how exactly this composition occurs remain elusive. In this paper, we study a mechanism for compositional generalization in transformers by considering a simple controlled setting involving variable assignment and modular addition. By partitioning our training data into disjoint sets, we observe that small transformers are able to generalize to previously unseen combinations of variables and numbers. Our mechanistic analysis shows that the same ``modular addition'' MLP module is used whether the inputs are given directly or indirectly through a separate variable assignment mechanism. We also analyze the training dynamics from an empirical lens, which reveals three phases of learning: first, modular addition is learned, then the structure required for variable assignment, and finally a refinement phase where the model generalizes to sequences not seen in training. Finally, we provide a theoretical framework to explain how compositionality emerges from training dynamics. These results suggest that compositional generalization can be a natural consequence of the compositionality of internal mechanisms in transformers.
BibTeX
@inproceedings{exoo2026assign,
  author = {Brady Exoo and Alberto Bietti and John Sous},
  title = {{Assign and Add: A Mechanistic Study of Compositional Arithmetic}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=MPwsN5TWrW},
}
Figure