Spectral Journey: How Transformers Predict the Shortest Path
Andrew Cohen, Andrey Gromov, Kaiyu Yang, Yuandong Tian
TL;DR
This work probes whether decoder-only transformers can plan or reason by training 2-layer models from scratch to predict shortest paths on simple graphs. It reveals that the models develop edge embeddings aligned with the spectral structure of the line graph $L(G)$ and exhibit attention dynamics focused on current and target edges, enabling a novel spectral path-finding algorithm called Spectral Line Navigation (SLN). SLN, built directly from the learned representations, achieves near-perfect accuracy on the test set, underscoring that spectral methods can underlie seemingly sequential neural computations. The findings advance mechanistic interpretability in language models and suggest a principled, spectrum-based approach to graph-based reasoning with practical implications for understanding planning-like behavior in neural networks.
Abstract
Decoder-only transformers lead to a step-change in capability of large language models. However, opinions are mixed as to whether they are really planning or reasoning. A path to making progress in this direction is to study the model's behavior in a setting with carefully controlled data. Then interpret the learned representations and reverse-engineer the computation performed internally. We study decoder-only transformer language models trained from scratch to predict shortest paths on simple, connected and undirected graphs. In this setting, the representations and the dynamics learned by the model are interpretable. We present three major results: (1) Two-layer decoder-only language models can learn to predict shortest paths on simple, connected graphs containing up to 10 nodes. (2) Models learn a graph embedding that is correlated with the spectral decomposition of the line graph. (3) Following the insights, we discover a novel approximate path-finding algorithm Spectral Line Navigator (SLN) that finds shortest path by greedily selecting nodes in the space of spectral embedding of the line graph.
