Task Vector Geometry Underlies Dual Modes of Task Inference in Transformers

Hao Yan, Haolin Yang, Yiqiao Zhong

TL;DR

When you give a Transformer a few examples in a prompt, is it remembering a task it learned during training, or figuring out something genuinely new on the fly? It turns out a single model can do both, and this paper uncovers the remarkably clean internal geometry behind how: Transformers track familiar tasks by sliding along a geometric simplex of memorized "task vectors" like a Bayesian statistician, while carving out a completely separate, perpendicular subspace to compute novel tasks from scratch.

What Problem Does This Paper Address?

One of the most magical properties of Large Language Models (LLMs) is in-context learning (ICL)—handing a model a few input-output pairs and watching it infer the underlying rule without updating a single weight.

Researchers have long suspected LLMs operate in two distinct modes: retrieving memorized tasks from training (in-distribution, or ID) and generalizing to genuinely novel tasks (out-of-distribution, or OOD). Meanwhile, mechanistic interpretability studies found that prompts create "task vectors"—specific directions in a model's middle-layer hidden states (activation space) that steer its output.

However, task vectors have mostly been extracted using ad-hoc heuristics, leaving major theoretical gaps. What is a task vector mathematically? How does training data shape its geometry? And if task vectors represent memorized tasks, what happens inside the hidden states when the model successfully solves a brand-new OOD task?

Methods

To avoid reverse-engineering messy, web-scale models blindly, the authors build a controlled "physics lab" for Transformers. They model data generation using latent variables: an unobserved task $z$ is drawn from a space of tasks, and a sequence of tokens is generated from $z$.

Figure 1: Connections between data distribution and representation geometry. This diagram illustrates the synthetic rolling biased dice experiment. Each sequence is generated from an unobserved latent z controlling the outcome distribution. A transformer trained on mixture data learns internal task vectors that encode these latents. Two near-orthogonal subspaces largely determine a model’s inference mode and generalization behavior.

Taking a "gray-box" approach that looks only at residual-stream hidden states (making the math architecture-agnostic), they introduce a rigorous framework of four testable geometric properties (P0–P3) grounded in the Markov property (where the future depends only on the current token and the latent task):

  1. Stability & Decoupling (P0–P1): At long contexts, hidden states cleanly separate into an additive sum: global mean + current token vector + task vector (defined rigorously as the centered, long-context class-conditional mean).
  2. Bayesian Interpolation (P2–P3): At finite contexts, the hidden state sits inside the convex hull (simplex) of the memorized task vectors, with mixture weights directly tracking the exact Bayesian posterior probability of each task.

Finally, they use causal interventions—surgically erasing or replacing projections onto the task-vector subspace or its orthogonal complement—to prove these geometric structures actually drive model predictions.

Datasets

The authors primarily train small (6- and 16-layer) decoder-only Transformers from scratch on four synthetic benchmarks:

  • E1 (Rolling Biased Dice): Token sequences drawn from task-specific Dirichlet probability vectors.
  • E2 (In-Context Linear Regression): Continuous $(x, y)$ token pairs governed by a latent weight vector.
  • E3 (Mixture of Markov Chains): Sequences generated from task-specific transition matrices.
  • E4 (Planted Dyck Language): A newly constructed non-Markovian counterexample where balanced bracket strings are hidden inside random background tokens, requiring unbounded long-range memory.

To verify their findings at scale, they also evaluate 12 pretrained LLMs (0.5B–8B parameters across 7 families, such as Qwen2.5 and Llama-3.1) on 12 word-function tasks (with unnatural text transforms for OOD variants) and a persona belief-dynamics dataset (statements spoken by distinct personas).

Key Insights and Ideas

  • Hidden States Do Literal Bayesian Updating: As an ID prompt gets longer, the model's hidden state physically migrates from the center of the task-vector triangle toward the true task's vertex, matching the ground-truth Bayesian posterior step-for-step.
Simplex-projected hidden state coefficients closely tracking the ground-truth Bayesian posterior across context positions.
  • Orthogonal Subspaces Enable Dual Modes: A low-dimensional subspace of memorized task vectors mathematically cannot express high-dimensional OOD tasks. Instead of overwriting task vectors, the Transformer allocates a nearly orthogonal subspace to compute empirical context statistics (like ridge regression or bigram counts) for OOD generalization.
  • Data Per Task Drives the Phase Transition: Training with 3 "major" tasks and $2^m$ "minor" tasks reveals a sharp phase transition. As task diversity $m$ increases, the model shifts from Bayesian retrieval to extrapolative OOD learning—driven not by model capacity limits, but by having too few training examples per minor task to memorize them.
  • When Markov Breaks, Task Vectors Break: In the Planted Dyck Language (E4), no finite window summarizes the past. Here, hidden states fail to stabilize into fixed task vectors and instead memorize the entire bracket prefix—showing that standard task-vector heuristics fail when data lacks a compact statistical summary.

Key Results

  • Clean Additive & Simplex Geometry: In synthetic tasks E1–E3, latent task and current token explain nearly all hidden-state variance at late positions (residual variance ratios of 0.004–0.045), and convex combinations of task vectors fit finite-context hidden states with $R^2 \approx 1$ across mid-depth layers.
  • Causal Steering: Forcing hidden states to a target point on the task-vector simplex steers predictions to match theoretical task mixtures, dropping KL divergence from 0.11 to 0.03 (E1) and 0.23 to 0.06 (E3), and reducing regression RMSE from 2.8 to 1.1 (E2).
  • Double Dissociation of Subspaces: Ablating the task subspace destroys major-task ICL performance (83.6% to 211.1% relative loss degradation) while leaving OOD performance intact (-1.0% to 13.1%). Conversely, ablating an optimized low-rank orthogonal subspace wipes out 85.4%–99.6% of OOD in-context gains while changing major-task loss by 4.0% or less.
  • Scaling to Pretrained LLMs: Across 11 of 12 pretrained LLMs (Gemma-3-4B being the sole outlier), word-function task representations peak in $R^2$ at mid-depth layers while OOD variants remain nearly orthogonal. On Llama-3.1-8B-Instruct, persona belief weights rise cleanly from 1/3 to 0.95 over 128 statements ($R^2 \approx 0.85$).

Limitations and Future Work

The authors note several clear boundaries to their work:

  • Markovian Reliance: The clean task-vector math relies on sequences having a compact Markovian summary; characterizing which natural language tasks satisfy this remains open.
  • Why Orthogonal? While Theorem 2 proves OOD representations must leave the task-vector subspace, there is not yet a formal theory of learning dynamics explaining why they settle specifically into an orthogonal one, nor a mechanistic account of how OOD algorithms execute inside it.
  • Mid-Layer Focus & Observational LLM Evidence: The geometric properties hold primarily in mid-depth layers before re-encoding occurs in final layers. Furthermore, the pretrained LLM experiments are purely observational—causal subspace steering in full-scale LLMs is left for future work.

Summary updated

Abstract

Transformers are effective at inferring the latent task from context via two inference modes: recognizing a task seen during training, and adapting to a novel one. Recent interpretability studies have identified from middle-layer representations task-specific directions, or *task vectors*, that steer model behavior. However, a lack of rigorous foundations hinders connecting internal representations to external model behavior: existing work fails to explain how task-vector geometry is shaped by the training distribution, and what geometry enables out-of-distribution (OOD) generalization. In this paper, we study these questions in a controlled synthetic setting by training small transformers from scratch on latent-task sequence distributions, which allows a principled mathematical characterization. We show that two inference modes can coexist within a single model. In-distribution behavior is governed by Bayesian task retrieval, implemented internally through convex combinations of learned task vectors. OOD behavior, by contrast, arises through extrapolative task learning, whose representations occupy a subspace nearly orthogonal to the task-vector subspace. Taken together, our results suggest that task-vector geometry, training distributions, and generalization behaviors are closely related.
BibTeX
@inproceedings{yan2026task,
  author = {Hao Yan and Haolin Yang and Yiqiao Zhong},
  title = {{Task Vector Geometry Underlies Dual Modes of Task Inference in Transformers}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=QvgaAPuT4e},
}
Figure