When Can Transformers Count to n?

Gilad Yehudai, Haim Kaplan, Asma Ghandeharioun, Mor Geva, Amir Globerson · Submission to ICLR 2025 · Rejected

TL;DR

While large language models can write code and reason through multi-step math problems, they fundamentally struggle with simple counting. This paper proves that a standard single-layer transformer can only reliably count token frequencies if its embedding dimension scales with the vocabulary size ($d \ge \Omega(m)$), uncovering a sharp representational phase transition at $d \approx m$.

What Problem Does This Paper Address?

Language models are increasingly deployed on long-context tasks, yet they frequently stumble on basic queries like "How many times does the letter 'a' appear in this text?"

The authors investigate whether this failure is merely an optimization artifact or a fundamental architectural limitation of transformers. Specifically, they analyze two core tasks:

  1. Query Count (QC): Given a sequence $x_1, \dots, x_n$, return the count of the final query token $x_n$.
  2. Most Frequent Element (MFE): Return the count of the most frequently occurring token in the sequence.

Because self-attention inherently computes a weighted average rather than a direct sum, transformers without positional information cannot even distinguish a sequence $S$ from a duplicated sequence $SS$. The authors ask: under what conditions (embedding dimension $d$, vocabulary size $m$, and context length $n$) can fixed-size transformers accurately count?

Methods

The authors analyze counting through both constructive proofs and complexity lower bounds:

  • Histogram Construction ($d > m$): When the embedding dimension exceeds the vocabulary size ($d > m$), each token can be assigned an orthogonal standard basis vector $e_i$. A single attention head with uniform weights accumulates an exact unnormalized histogram of the context, after which a standard MLP extracts the count.
  • Welch Bound Obstruction ($d < m$): By Welch's bound, any set of $m \ge 2d$ unit vectors in $\mathbb{R}^d$ must contain pairs with inner product $\Omega(1/\sqrt{d})$. This dot-product "crosstalk" causes histogram-based counting errors to grow with sequence length as $\Omega(\sqrt{n})$.
  • CountAttend & Inversion Bottleneck: To count when $d < m$, the query token can attend exclusively to matching tokens, yielding a softmax weight equal to $1/\text{count}$. However, the authors prove via approximation theory (Lemma 4.4) that any 2-layer ReLU MLP approximating $f(x) = 1/x$ on $[1/n, 1]$ within an error of $1/2$ requires $\Omega(n)$ neurons, making it impossible for a fixed-size network to extrapolate to arbitrary lengths.
  • Communication Complexity Lower Bound: Using a reduction from Yao's two-party Set Disjointness problem, the authors prove that any 1-layer transformer with $h$ heads, embedding dimension $d$, and $p$-bit arithmetic solving MFE must satisfy $dhp \ge \Omega(\min\{m, n\})$.

Datasets

  • Synthetic Sequences (Trained from Scratch): Sequences of length $n = 10m$ sampled uniformly from a vocabulary of $m$ discrete tokens, evaluated over 1,600 test examples per configuration.
  • Pretrained LLM Benchmark (Gemini 1.5): Synthetic integer arrays constructed by sampling $m$ unique values from $\{1, \dots, 1000\}$. The context length was scaled with $m$ to keep the expected token count fixed at $c = 40$, alongside a 2-token "binary baseline" matched to the same sequence lengths and target counts.

Key Insights and Ideas

  • The $d \approx m$ Phase Transition: There is a sharp threshold in transformer capability governed by the ratio of embedding dimension to vocabulary size. When $d > m$, exact orthogonal token histograms make counting trivial; when $d < m$, interference between non-orthogonal embeddings degrades accuracy.
  • Softmax Normalization Forces Inversion: Because attention weights must sum to 1, focusing attention on identical tokens yields the reciprocal frequency ($1/k$). Inverting this fractional value back into an integer count requires an MLP width scaling linearly with context length ($\Omega(n)$).
  • Separation from "Needle-in-a-Haystack": Finding whether a token exists (retrieval) can be handled by a single induction head regardless of sequence length. In contrast, tallying all occurrences requires accumulating magnitude across the entire sequence, exposing the limitations of fixed-width embeddings.

Key Results

  • Synthetic Scaling Thresholds: For models trained from scratch (2 layers, 4 heads), the vocabulary threshold $m_{\text{thr}}(d)$ at which accuracy drops below 80% scales linearly with $d$ across both QC and MFE tasks.
  • Pretrained LLM Degradation: Evaluating Gemini 1.5 on sequences where the expected count was kept constant at 40 revealed that increasing vocabulary size $m$ dramatically increased the absolute counting error (from $<5$ when $m=5$ to $>30$ when $m=100$ on QC, and nearly $100$ on MFE). This error was far worse than on length-matched binary baselines, confirming that vocabulary diversity—not sequence length alone—drives counting failure.

Limitations and Future Work

  • Single-Layer Restriction: The impossibility lower bound based on communication complexity is currently proven only for 1-layer attention networks; extending this lower bound rigorously to multi-layer transformers remains an open theoretical challenge.
  • Architectural Scope: Synthetic training experiments were conducted on small, custom architectures rather than standard open-weight production models (e.g., Llama).
  • Mechanistic Interpretability: The authors do not analyze the internal circuits of trained transformers to verify whether they implement approximate histograms, attention inversion, or alternative counting heuristics in practice.

Summary updated

BibTeX
@misc{yehudai2024when,
  author = {Gilad Yehudai and Haim Kaplan and Asma Ghandeharioun and Mor Geva and Amir Globerson},
  title = {{When Can Transformers Count to n?}},
  year = {2024},
  eprint = {2407.15160},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2407.15160},
}
Figure