Transformers meet Neural Algorithmic Reasoners

Wilfried Bounsi, Borja Ibarz, Andrew Joseph Dudzik, Jessica B Hamrick, Larisa Markeeva, Alex Vitvitskyi, Razvan Pascanu, Petar Veličković · Submission to ICLR 2025 · Rejected

TL;DR

While large language models (LLMs) excel at natural language understanding, they notoriously stumble on algorithmic tasks when evaluated out-of-distribution. TransNAR solves this by using a pre-trained Graph Neural Network-based Neural Algorithmic Reasoner (NAR) as a differentiable "internal tool" via cross-attention, drastically boosting length generalization on algorithmic problems. Crucially, the authors show this reasoning capability can be distilled back into a vanilla, text-only Transformer.

What Problem Does This Paper Address?

Standard autoregressive Transformers are notoriously fragile when executing algorithmic tasks that demand precise computation, particularly under distribution shift (e.g., generalizing to problem sizes larger than those seen in training). Even on simple tasks like sorting or counting, decoder-only LLMs often fail because their causal objectives struggle with non-autoregressive algorithmic execution.

Conversely, Neural Algorithmic Reasoners (NARs)—typically graph neural networks trained to simulate classical algorithms—can generalize to inputs orders of magnitude larger than their training set. However, NARs require rigid, structured graph inputs and cannot handle problems formulated in natural language. This paper bridges the gap: combining the linguistic flexibility of Transformers with the robust computational backbone of NARs.

Methods

The authors introduce TransNAR, a hybrid multimodal architecture with a two-phase training recipe:

  1. Architecture (Flamingo-style Cross-Attention): A decoder-only language model (a 70M-parameter Chinchilla Transformer) is interleaved with gated cross-attention layers. Token representations query the node and edge embeddings produced by a multi-task Graph Neural Network (Triplet-GMPNN).
  2. Two-Phase Training: The NAR is pre-trained on algorithmic execution over graph representations and then kept frozen during TransNAR training. Freezing prevents language gradients from destroying the NAR's learned algorithmic inductive biases.
  3. Randomized Positional Encodings: To prevent position-based overfitting on long sequences, randomized positional encodings are layered on top of Rotary Positional Encodings (RoPE).
  4. Knowledge Distillation to Text-Only Models: To eliminate the need for graph inputs at test time, the authors distill TransNAR (teacher) into a standard Transformer (student) using a convex combination of next-token prediction and teacher distillation loss across both in-distribution and "soft out-of-distribution" (OOD) sizes.
Text Input  ──> Transformer Layer ──> [Cross-Attention] ──> Next Layer / Output
                                             ▲
                                             │ (Keys / Values)
Graph Input ──> [Frozen GNN / NAR] ──────────┘

Datasets

  • CLRS-Text: A text-based counterpart to the CLRS-30 benchmark, covering 30 classical algorithms (sorting, searching, dynamic programming, graph algorithms, etc.).
  • Data Splits: Models are trained on smaller sizes ($[4, 8]$ and $12$, totaling 2.4 million examples) and evaluated on size $10$ (OOD interpolation), size $12$ (in-distribution), and sizes $14$ & $16$ (OOD extrapolation).

Key Insights and Ideas

  • NAR as an "Internal Tool": Rather than forcing an LLM to generate discrete API tool calls in text (which introduces string parsing bottlenecks), TransNAR exposes the NAR's continuous latent space directly through cross-attention.
  • Why Transformers Fail OOD (The "Shape" Breakdown): The authors decompose accuracy into parse, shape, and execution (CLRS) scores. Standard LLMs fail OOD largely because they cannot even emit the correct shape of an output (e.g., outputting 12 elements when sorting a list of 14). Grounding tokens in NAR states drastically repairs this dimensional awareness.
  • Decoupling Failure Modes: Without randomized positional embeddings, hybrid models inherit the base LLM’s total failure modes. Combining randomized embeddings with NAR representations breaks this dependency: the hybrid model succeeds even on tasks where the base LLM achieves 0% accuracy.
  • "Soft OOD" Distillation: A pure text-only Transformer can be taught OOD robustness simply by imitating the TransNAR teacher on unlabelled larger sizes, without ever requiring ground-truth supervision or graph inputs during deployment.

Key Results

  • OOD Reasoning Improvements: TransNAR significantly outperforms baseline Transformers across algorithmic families (e.g., Graph, Sorting, Dynamic Programming), posting >20% absolute improvements in execution accuracy across multiple algorithm classes on OOD test sets.
  • Distillation Gains: Distilled student Transformers dramatically beat vanilla baselines. For example, on the task_scheduling problem:
  • At size $10$ (interpolation), accuracy jumped from $0.121$ (baseline) to $0.511$ (distilled).
  • At size $14$ (extrapolation), accuracy jumped from $0.051$ (baseline) to $0.296$ (distilled).
  • Failure Modes on Index-Searching: Tasks requiring search over specific indices (e.g., Binary Search, Quickselect, Find Maximum Subarray) remained stubborn failure points, suggesting that cross-attention struggles to map abstract NAR states onto unseen textual index boundaries.

Limitations and Future Work

  • Reliance on Graph Pre-training: Training the teacher requires a canonical graph formulation and known execution trajectories, limiting applicability to problems where clear formal representations already exist.
  • Distillation Weight Sensitivity: The optimal distillation loss weight $\alpha$ varies by regime (e.g., $\alpha = 0.5$ for interpolation vs. $\alpha = 0.25$ or pure logits $\alpha = 1.0$ for extrapolation).
  • Future Directions: Incorporating algorithmic index hints, progressive multi-step cross-attention decoding, and adapting NAR representations to less structured domains such as mathematical word problems and formal logic.

Summary updated

BibTeX
@misc{bounsi2024transformers,
  author = {Wilfried Bounsi and Borja Ibarz and Andrew Joseph Dudzik and Jessica B Hamrick and Larisa Markeeva and Alex Vitvitskyi and Razvan Pascanu and Petar Veličković},
  title = {{Transformers meet Neural Algorithmic Reasoners}},
  year = {2024},
  eprint = {2406.09308},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2406.09308},
}
Figure