Transformers struggle to learn searchTransformers Struggle to Learn to Search
Small transformers can learn to search on the balanced DAG distribution, but as graphs grow larger, adding scale or intermediate tokens still makes it hard to learn.
- LLMs are not robust at proof search, possibly due to data, parameters, or architecture. The authors use infinitely generable DAG next-step search to estimate the upper bound of small transformers learning to search.
- Construct a balanced distribution with uniform lookahead and weakened shortcuts, train small transformers from scratch to predict the next vertex; use activation patching to reconstruct the computation graph, and compare scaling, DFS, and selection-inference.
- The authors claim that with a suitable distribution, search can be learned. In Figure 2, with naive training and balanced testing at L=5, the accuracy is 0.26; when trained only up to L≤12, the accuracy at L=20 is 0.49. Scaling up on larger graphs or adding intermediate tokens remains difficult.
- The conclusion states that scaling to much larger sizes may lead to the emergence of search capabilities, and curriculum learning and looped transformers may help; the model may simultaneously use other algorithms, and analysis scaled to larger models still needs improvement. The experiments are small transformers trained from scratch, and no pretrained LLMs are reported.
- Evaluated models
- small transformers with the same architecture as GPT-2decoder-only transformers with rotary positional embeddings (RoPE)
- Benchmarks
- naïve distributionstar distributionbalanced distributionnatural language proof searchdepth-first searchselection-inference
- Metrics
- accuracycross-entropy lossproportion of examples explained by path-mergingproportion of maximal path-merge operationsfraction of converged seeds
The paper uses graph connectivity problems as a testbed to train small Transformers, and finds that given a suitable training distribution, Transformers can learn to search, but learning the task becomes increasingly difficult as input graphs grow, and increasing parameter count cannot solve it; searching in context (chain of thought) also cannot solve this difficulty on large graphs. The authors use a new mechanistic interpretability method to extract computational graphs from trained models, and find that Transformers perform search in parallel at each vertex, computing the set of reachable vertices for each vertex, and expanding these sets layer by layer, thereby completing search on vertex counts that grow exponentially with the number of layers n_layers.
Paper analysis
What problem does this paper attempt to solve?
Whether small transformers can learn DAG search on shortcut-free data, and whether the difficulty of large graphs can be eliminated by scale or intermediate steps.
Can a small transformer learn DAG search on data with shortcuts removed, and can difficulties on large graphs be eliminated by adding parameters or intermediate tokens.
- Scenario: The authors argue that search is fundamental to reasoning, planning, and navigation. Existing work shows that transformer-based LLMs cannot robustly perform proof search, but it is unclear whether this is due to lack of data, insufficient parameters, or architectural limitations; whether search and planning can be achieved with continued scaling remains unclear.
- Chain of thought may still be insufficient: Chain of thought decomposes search into repeated prediction of the next step. The authors argue that in the worst case, to avoid going astray, the model must still complete the search within a single forward pass; after going astray, errors or confabulations may occur.
- Distribution determines what is learned: In a naive random DAG, lookahead is typically 1 or 2, the probability of larger lookahead decreases exponentially, and heuristics suffice to solve the problems. The authors therefore require a training distribution that makes shortcuts useless.
- Approach in this paper: With the task "given a DAG, a start node, and a reachable target, predict the next vertex on the path," they generate essentially infinite ideal data, train small transformers, and estimate the upper bound of learning search; they then reconstruct the computation graph and examine graph size, parameter size, and intermediate tokens such as DFS and selection-inference.
What related research exists?
Related work discusses graph reasoning, expressiveness, mechanistic interpretation, and scaling; the authors focus on whether it can be trained.
Section 2 of the paper divides related work into search capability, mechanistic interpretation, and scaling laws, and compares expressibility results within search capability.
Graph search and reasoning
- Fan et al. (2024), Fu et al. (2024), Sanford et al. (2024a;b) study graph reasoning, repeated function composition, and k-hop induction. The paper states that these benchmarks are still relatively small compared to the graphs considered in this paper.
- Ruoss et al. (2024), Gandhi et al. (2024), Shah et al. (2024) report that transformers can approximate or simulate search algorithms, but with performance gaps, and do not examine whether scaling up or training can close the gap.
- The paper paraphrases: Wang et al. (2023), Bachmann and Nagarajan (2024) show that LLMs can do some graph reasoning but are misled by spurious correlations; Zhang et al. (2023) find that transformers strongly prefer heuristics and thus fail to learn proof search. Zhang et al. (2024), Borazjanizadeh et al. (2024) report difficulties on real graph reasoning and diverse search tasks. The authors' contrast is: if heuristics are additionally removed, transformers can learn to search.
Expressibility
- Merrill and Sabharwal (2024) report that transformers with chain of thought can simulate arbitrary Turing machines. The paper states that this does not indicate whether training can succeed; this paper still finds difficulty learning to search on larger graphs when intermediate tokens are allowed.
- Sanford et al. (2024a;b) show that graph connectivity requires logarithmic depth. The authors believe this is consistent with the layer-by-layer expansion of reachable sets identified in this paper.
Mechanistic interpretation and scaling
- Hou et al. (2023), Kim et al. (2024) search for pre-specified circuits in activations and attention. This paper does not presuppose an algorithm, but reconstructs the computation graph from activations and attention, and uses activation patching (Vig et al., 2020; Geiger et al., 2021).
- Brinkmann et al. (2024), Stolfo et al. (2023) and others apply mechanistic interpretation to reasoning; Yang et al. (2024), Jenner et al. (2024) provide evidence that LLMs do shallow search in forward passes; Ivanitskiy et al. (2023) see internal representations of maps on maze tasks.
- Kaplan et al. (2020), Hoffmann et al. (2022) and others discuss scale, data, and compute. Caballero et al. (2023) tasks do not involve search, reasoning, or planning. Wei et al. (2022a) propose that capabilities may emerge with scale; Schaeffer et al. (2023) argue that such emergence can be explained by metric choice; Du et al. (2024) advocate measuring capability with training loss.
Comparison settings: accuracy experiments do not use external search algorithms as baselines, but compare three self-generated distributions: naïve, star, and balanced; mechanistic analysis uses randomly initialized models as controls. The authors position this paper as: expressibility does not guarantee trainability, search can be learned after removing heuristics, but scaling up or intermediate tokens do not eliminate learning difficulty on larger graphs.
How does the paper address this problem?
Train a small transformer on the balanced distribution, then use activation patching to check whether exponential path merging is learned.
balanced distribution trains small transformers from scratch to predict the next vertex on DAG paths; then activation patching reconstructs the computation graph to test whether what is learned is layer-by-layer merging of reachable sets or shortcuts.
Task and three distributions
- Each sample contains a DAG, a start vertex, and a guaranteed-reachable target. The output is the next vertex on a path from start to target. Difficulty is measured by lookahead: let P be the path, S_i be a path from the start whose remaining part is disjoint from P, then L=min{|P|,maxi|Si|}, i.e., the minimum number of steps to look ahead.
- naïve: vertices are first arranged in topological order, edges only go right, in-degree cap is 4 to avoid overly dense graphs and too-small lookahead; then vertex labels are randomly shuffled. Appendix A.1.1 gives the sampling of parent counts. Figure 8 uses 10M graphs of 41 vertices to show that large lookahead is rare; the authors state that values greater than 6 are possible but almost never sampled.
- balanced: given L, first build a true path of L edges, then add branches of length about L and incoming chains pointing to the start, and use additional edges with high in-degree or out-degree to remove shortcuts such as "the start is the only source, all other in-degrees are exactly 1." During training, L is uniform. Details are in Appendix A.1.2.
- star: the center is the start, k chains of length L go outward, and the target is at the end of one of them; k and L are uniform. The paper states that the shape corresponds to the graphs of Bachmann and Nagarajan (2024).
Model, loss, and judgment
- Architecture is the same as GPT-2, with activations changed to ReLU. Token and absolute position are both 1-hot, concatenated rather than added, for mechanistic interpretation. Each layer has 1 attention head, and feedforward dimension equals model dimension. Edge order is random, and attention does not use a causal mask. Distribution experiments use 6 layers, hidden dimension 16, input 128 tokens.
- Streaming sampling, no fixed training set. The first few batches are held out for testing, and thereafter exact matching removes samples that appeared in the test set. Optimizer is Sophia, learning rate 10^{-5}, weight decay 0.1, no dropout; unless otherwise stated, batch is 1024. Cross-entropy is minimized.
- When multiple paths exist, training uniformly randomly selects one as the label. At evaluation, a predicted vertex is correct if it lies on any path to the target.
Computation graph reconstruction
For a single input, five steps are done. First, a normal forward pass. Then, the attention weights of the last layer, last token are changed to 0, or changed to the row maximum and renormalized; if the predicted logit drops by more than α, it is marked as important. If no important operation is found in this step, fall back to marking the operation that causes the largest logit drop. Apply the same perturbation to the remaining layers: if the log attention change of an important operation in the last layer exceeds κ1/√d (d is model dimension), or the predicted logit drops by more than α, it is also marked as important. Then do activation patching: replace a vertex label with a label not present in the input, or zero out the position embedding of a position; freeze attention before the current layer, and keep positions previously zeroed by ReLU still zero, and use the change in the dot product of query and key to determine which input features of source and target embeddings causally affect that attention. Finally, keep only operations that go from input along interpretable attention to the output prediction. The paper states that this process requires many forward passes, so it is used on smaller models. For models with very high test accuracy, take α=0.4, κ1=20, κ2=10.
Judgment of path merging
- The authors hypothesize: each vertex's embedding stores the set of vertices reachable within a few steps, or conversely stores which vertices can reach the current vertex. Each layer copies from the frontier of the reachable set and takes the union; the set size can theoretically double per layer, so the number of searchable vertices grows exponentially with depth. Figure 4 is a schematic. Search can be forward, or backward from the target.
- Attention is divided into path merging, or copying of vertices reachable from the start or target; the rest is discarded. Path merging can be token matching by reachable-set overlap, or finding vertices one step away by position. If every vertex on the start-to-target path has continuous path merging, and the first-layer corresponding token is finally copied to the last token of the last layer, then the input is said to be explained by the path-merging algorithm.
Two tasks allowing intermediate tokens
- DFS: input is the graph's edges and the sequence of visited vertices up to the current vertex. Right-side tokens are reserved for the visited sequence, with padding in the middle, so that edge positions are stable across samples. Predict the next vertex of the DFS trajectory. Training graph backtrack distances are uniform, corresponding to the earlier balanced. Experiments fix 3 layers.
- selection-inference: each step is split into two subtasks: select a vertex from those already visited that still has unvisited child vertices; then predict one of its unvisited child vertices. Use frontier size F and current vertex branching factor B, making (F, B) uniform. Input is the graph and visited edges, again using padding to stabilize edge positions. Experiments fix 4 layers. Generation details are in Appendix A.7 and A.10.
What experiments did the paper conduct?
The authors state that after full balanced training, search is possible; in Figure 2, naïve training with balanced testing at L=5 has accuracy 0.26.
Experimental Setup
- Models: GPT-2 architecture transformers trained from scratch, with ReLU, 1-hot concatenated positional encoding, 1 head per layer, no causal mask. Distribution experiments use 6 layers, hidden dimension 16. Scaling experiments additionally fix 8 layers, hidden dimension 16, or vary non-embedding parameter count. Appendix A.5 is decoder-only with learnable token embeddings and RoPE.
- Data: naïve, star, and balanced DAG distributions. Also natural language proof search: each edge is written as a conditional sentence, words and punctuation are tokens, and the task becomes finding the next step of a proof from a starting proposition. Also DFS and selection-inference. The model in Figure 2 has at most 41 vertices, input 128 tokens, trained on 883M examples. Scaling experiments change batch to 256 due to GPU memory.
- Metrics and criteria: accuracy rule is that the predicted vertex lies on any path to the goal. Training objective is cross-entropy. Mechanism analysis reports the proportion explained by path merging, and the proportion of maximal path merging. Scaling experiments mark training accuracy greater than 0.995 as convergence. No LLM judge.
- Testing and repetition: test samples come from held-out batches and are filtered by exact matching. Figure 6 uses 14 seeds per maximum graph size; Figure 7 uses 4 seeds per model size; Figure 9 top row uses 5 seeds per graph size; Figure 14 each point is the minimum loss over 15 seeds; Figures 11 and 12 are minimum loss over 2 seeds. Mechanism analysis text says 2000 inputs total, 100 per lookahead; Figure 5 has 100 examples per cell.
Main Results
Figure 2: maximum 41 vertices, 883M examples, input 128 tokens. The L column is held-out testing on the balanced distribution for that lookahead, not lookahead within the naïve graph.
Swipe horizontally to read the table
Training distribution naïve test balanced L=5 balanced L=14 balanced L=20 naïve 0.99 0.26 0.51 0.49 star 0.65 1.00 0.99 1.00 balanced, L≤20 0.99 1.00 0.99 0.97 balanced, L≤12 0.99 1.00 0.96 0.49 - The authors claim naïve training cannot robustly handle larger lookaheads, with low accuracy even for lookaheads that appeared in training (e.g., L=5); they attribute this to the distribution generating large lookaheads with exponentially decreasing probability.
- The authors claim star training is acceptable on balanced tests but poor on naïve tests; full balanced training can search on all test settings and generalizes to unseen lookahead counts.
- When trained only up to L≤12, the authors claim generalization to lookaheads 13 and 14, but not to larger lookaheads. Outside the table, same figure and column: L=13 is 0.99, L=15 is 0.84.
Mechanism Explanation
- What was tested: on models trained on balanced with high test accuracy, reconstruct the computation graph on naïve and balanced held-out samples, with thresholds α=0.4, κ1=20, κ2=10. Control is a randomly initialized model.
- Results: the authors claim the method is highly specific, identifying path merging in trained models but not in random models. In Figure 5 top half, random model visible values are 0.05 or 0.00; the full balanced training row has minimum visible value 0.92 (100 examples per cell). The naïve training row has cells as low as 0.43. Bottom half: the authors claim the proportion of maximal path merging is clearly less than 1.
- Authors' interpretation: the model has no reason to learn maximal merging, because training lookaheads do not align with powers of 2, and the number of layers exceeds what the maximum lookahead requires. The authors use this to explain why the L≤12 model cannot fully generalize to larger lookaheads. Appendix A.12 uses 100 examples with lookahead 9 to examine direction: the model with maximum lookahead 20 has early layers more like searching backward from the goal; the L≤12 model has some layers like forward and some like backward. The authors think direction may depend on initialization seed and say more experiments are needed to fully describe it.
Scaling
- Fixing 8 layers, hidden dimension 16, training on balanced with 236M examples, testing on naïve held-out samples, 14 seeds. The authors claim that as maximum graph size increases, the proportion of seeds reaching training accuracy ≥ 0.995 becomes very small; on converged models, the minimum test loss over 14 seeds rises at an increasing rate (Figure 6). The text does not give specific loss values for each graph size.
- Fixing maximum graph size 31, non-embedding parameters are 0.9M, 1.3M, 6.0M, 60.4M (Figure 7, 4 seeds per size). The authors claim larger models reach local minima faster, but there is no discernible pattern between model size and the amount of training needed to find the global minimum.
- Appendix A.5 changes to decoder-only with learnable token embeddings multiplied by RoPE, with d_model the same as the corresponding experiments in Section 5. The authors claim scaling behavior is unchanged (Figures 11, 12, each point is minimum loss over 2 seeds).
Intermediate Steps
- DFS: fixing 3 layers and varying graph size, the authors claim the model can learn the training distribution on all tested graph sizes, so only a constant number of layers is needed; but larger graphs remain difficult (Figure 14 top; test is balanced held-out with backtrack 8, minimum loss over 15 seeds). Fixing maximum 35 vertices and increasing model size, the authors claim it does not become easier to learn. Larger models learn with fewer samples, but this benefit disappears in terms of FLOPs, with larger models requiring far more FLOPs.
- selection-inference: fixing 4 layers, the authors claim larger graphs remain difficult (Figure 16). Fixing maximum 45 vertices and increasing scale does not help either (Figure 17; non-embedding parameters include 3.2M, 3.8M, 13.4M, 14.8M, 40.3M). Appendix A.10 claims transformers do well on the selection subtask and poorly on the inference subtask for large graphs. The paper does not give accuracies for these two statements.
- padding: Figure 15, 7 layers, input 128, trained on 746M examples. Standard padding is 1.00 at backtrack 0 and 0.15 at backtrack 15; random padding is 1.00 at backtracks 0 through 4 and 0.87 at backtrack 15. The authors claim random padding is sufficient for the model to backtrack further, but does not help learn search on larger graphs; the scaling experiment's training distribution already uniformly includes all backtrack distances.
Other Ablations and Analyses
- Natural language proof search (Section 3.1.2, Figure 9): training behavior is qualitatively similar to graph search; larger graphs are harder to learn, more so in terms of FLOPs. Maximum graph sizes in the legend include 6, 9, 14, 19, 25, 30; top row uses 5 seeds per size. The text does not give an accuracy table for this setting.
- Figure 8: naïve, 41 vertices, 10M graphs; the authors claim lookaheads greater than 6 are possible but almost never sampled.
- Figure 10: training dynamics for the same setting as Figure 6, 14 seeds; Figure 6 is a slice at 236M examples.
- Several loss curves are smoothed per figure captions: window 81, one point recorded every 2^{18}=262K examples. The paper does not report specific loss numbers at each point on these curves.
What are some points that can be further explored?
In the conclusion, the authors propose larger scale, curriculum learning, and looped transformers, and state that extending the analysis to large models still needs improvement.
Limitations and future directions noted by the authors
The paper has no section named Limitations. The following all come from future directions explicitly written by the authors in the conclusion or appendix.
- Conclusion: scaling to much larger model sizes could potentially lead to the emergence of search capability. This is a possibility written by the authors, not a result already observed in this paper.
- Conclusion: other training methods might make it easier for transformers to learn to search, such as curriculum learning; other architectures might also help, such as looped transformers.
- Conclusion: path merging can explain almost all samples of the trained model, but on some samples the model may simultaneously use other algorithms or heuristics.
- Conclusion: further work is welcome to improve the scalability of this analysis to larger models; analyses on small models can be separately tested on large models.
- Appendix A.12: the search direction may depend on the random initialization seed, and further experiments are needed for a more complete description.
- The conclusion also judges: under standard training, future transformer-based models will not solve search tasks, and other training methods may be needed.
Experimental coverage
- The experimental subjects are small transformers trained from scratch: main setting 6 layers, hidden dimension 16, 1 head, ReLU, no causal mask; scale settings fix 8 layers, hidden dimension 16, or fix 31 vertices with non-embedding parameters at 0.9M, 1.3M, 6.0M, 60.4M. There is also a RoPE decoder-only (Appendix A.5, Figure 11, 2 seeds per point).
- Graph distributions are naïve (in-degree cap 4), star, and balanced. Tasks also include natural language conditional proof, DFS (experiments fix 3 layers; when varying the model, max 35 vertices) and selection-inference (fix 4 layers; when varying the model, max 45 vertices).
- Distribution experiments use input 128 tokens, max 41 vertices, 883M examples, batch 1024, Sophia, learning rate 10^{-5}. Scale experiments use 236M examples, batch 256, 14 seeds; the convergence line is training accuracy greater than 0.995, and the test distribution is naïve.
- Mechanistic analysis uses α=0.4, κ1=20, κ2=10. The main text states a total of 2000 inputs, 100 per lookahead; Figure 5 has 100 examples per cell, with randomly initialized models as controls.
- Success is judged by the rule: a predicted vertex is correct if it lies on any path to the target. The paper does not report experiments on pretrained LLMs, nor does it report agreement between this rule and human judgment.
Summarize the main content of the paper
With suitable data, parallel path merging can be learned, but large graphs are hard to learn, and adding scale or intermediate tokens does not eliminate this.
The authors use DAG connectivity as a testbed to examine whether small transformers fail to learn search due to data, parameters, or architecture; idealized infinite data is used to estimate the upper bound of learning to search.
- The task is: given a directed acyclic graph, a start vertex, and a reachable target, predict the next vertex on a path. Difficulty is measured by lookahead. naïve and star leave shortcuts; balanced makes lookahead uniform and removes heuristics such as "the start is the only source."
- The model is a GPT-2-style transformer trained from scratch, main experiments 6 layers, hidden dimension 16, no causal mask. The authors use activation patching to reconstruct the computation graph and hypothesize that what is learned is parallel exponential path merging over all vertices: embeddings store reachable sets, and each layer expands the set. The analysis finds path merging, but the maximal merging proportion is less than 1; the search direction can be forward or backward across different seeds.
- Figure 2 (max 41 vertices, 883M examples): naïve training on balanced testing at lookahead=5 has accuracy 0.26; full balanced training on naïve testing is 0.99, and at lookahead=20 is 0.97. When training only up to L≤12, lookahead=14 is 0.96 and lookahead=20 is 0.49. The authors state that after full balanced training, search is possible on the tested settings, and L≤12 only generalizes to 13 and 14.
- As graph size increases, an 8-layer, hidden-dimension-16 model increasingly struggles to reach training accuracy 0.995 on 236M examples and 14 seeds (Figure 6). With non-embedding parameters increased to 60.4M, the authors state it also does not appear easier to find a global minimum (Figure 7). With DFS fixed at 3 layers and selection-inference fixed at 4 layers, larger graphs remain difficult, and scaling does not eliminate this.
- The authors' conclusion is: under standard training, future transformers will not solve search just by scaling up, and other approaches such as curriculum learning or looped transformers may be needed. The authors also believe that scaling to much larger sizes could still lead to the emergence of search capability; beyond path merging, the model may use other algorithms on some samples.