Context-free Recognition with Transformers
Selim Jerad, Anej Svete, Sophie Hao, Ryan Cotterell, William Merrill
ICML 2026
Abstract. Transformers excel on tasks that process well-formed inputs according to some grammar, such as natural language and code. However, it remains unclear how they can process grammatical syntax internally. In fact, under standard complexity conjectures, standard transformers cannot recognize context-free languages (CFLs), a canonical formalism to describe syntax, or even regular languages, a subclass of CFLs. Merrill & Sabharwal (2025) show that looping layers (w.r.t. input length ) allows transformers to recognize regular languages, but the question of context-free recognition remained open. In this work, we show that looped transformers with looping layers and padding tokens can recognize all CFLs. However, training and inference with padding tokens is potentially impractical. Fortunately, we show that, for natural subclasses such as unambiguous CFLs, the recognition problem on transformers becomes more tractable, requiring padding. We empirically validate our results and show that looping helps on languages that require logarithmic depth. Overall, our results shed light on the intricacy of CFL recognition by transformers: while general recognition may require an intractable amount of padding, natural constraints such as unambiguity yield efficient recognition algorithms.
Are you an author? Claim this paper to see who's reading it, with views and other statistics, and to write about it here.
Claim this paperedit · history
Loading the discussion…