The Research Report
Transformer X-Ray: Analyzing Attention Commitment Depth Across 6 Architectures
A deep, multi-angle technical analysis of Luiz Spies' "Transformer X-Ray" research, mapping context commitment, attention sinks, and structural fingerprints across diverse LLM designs.
Executive Summary
How does a large language model process context and decide when to "commit" to a factual answer? Does a 7-billion parameter model evaluate information deeper in its hidden layers than a 500-million parameter model of the same family?
Recent empirical research by Luiz Spies, titled "Transformer X-Ray," addresses these fundamental questions. By developing an elegant, direct integration with llama.cpp to dump raw attention weights during inference, Spies mapped and compared the inner workings of six distinct model architectures—ranging from standard dense Transformers to sliding-window hybrids and Liquid MoEs.
The core finding is as simple as it is profound: model architecture, rather than parameter scale, is the primary driver of attention commitment depth.
While standard dense Transformers like Qwen2.5 commit to factual associations almost immediately in their embedding and first attention layers, hybrid architectures (like Gemma-4’s sliding window attention or Liquid Foundation Models' MoE) distribute their cognitive load, processing context and retrieving facts gradually across the depth of the network. Furthermore, scaling up a model does not shift where the model commits, but rather changes the magnitude of its attention disruption when presented with incorrect or conflicting context.
1. Under the Hood: The "X-Ray" Methodology
Traditional mechanistic interpretability is often hampered by the opacity of modern optimized runtime environments. High-performance inference engines use kernel-fusion techniques like Flash Attention to bypass the materialization of the full attention matrix in memory to save bandwidth and compute.
To inspect the raw attention maps, Spies engineered a non-invasive tensor extraction pipeline using llama.cpp's native C/C++ API.
[ Inference Request ]
│
▼
[ llama.cpp (Flash Attention Disabled) ]
│
(Intercepts via cb_eval callback)
│
▼
[ Raw kq_soft_max Tensors ]
Shape: [n_kv, n_tokens, n_head]
│
▼
[ Rust (xray_llama.rs) ]
Calculates Entropy, Sink, JS-Divergence
│
▼
[ Comparative Plots & Insights ]
The Tensor Capture Hack
The pipeline disables Flash Attention (LLAMAFLASHATTNTYPEDISABLED) to force the engine to materialize intermediate attention tensors. It then taps into cb_eval—a per-tensor evaluation callback built into llama.cpp's compute graph execution loop.
After every attention operation, the callback intercepts the kqsoftmax-{layer} tensor. These tensors have the shape:
$$\text{Shape} = [n{\text{kv}}, n{\text{tokens}}, n_{\text{head}}]$$
This represents the complete softmax-normalized attention weight matrix for each layer and head.
The extracted tensors are written to raw binary files, which are subsequently ingested and parsed using a custom high-performance analyzer written in Rust (xrayllama.rs) and visualized using Python (xrayarticle_plots.py).
Quantifying Disruption with Jensen-Shannon Divergence
To measure where a model "commits" to an answer, the research uses 40 hand-crafted factual completion prompts spanning six categories (such as capitalcity, historicalyear, and science_fact). For each prompt, two variants are executed:
- Neutral Prompt: "The capital of France is"
- Conflicting/Wrong Prompt: "The capital of France is [wrong suffix, e.g., ' Berlin']"
The attention distribution across all layers is captured for both runs. The research calculates the Jensen-Shannon (JS) Divergence between the two distributions layer-by-layer:
$$\text{JSD}(\text{layer}) = D{\text{JS}}(P{\text{neutral}} \parallel P_{\text{wrong}})$$
A high JS-divergence at a specific layer indicates that the addition of the conflicting suffix heavily disrupts the attention map at that layer. This peak is defined as the Commitment Depth—the exact structural location where the model reconciles context and commits to its factual representation.
2. Tested Architectures: A Diverse Structural Grid
The study evaluated six models across distinct design paradigms, summarizing the direct relationship between layer structure, attention head mechanics, and overall architecture:
| Model | Layers | Attention Heads | Architectural Paradigm |
|---|---|---|---|
| Gemma-4-E2B (Q4_0) | 35 | 8 (GQA, kv=1) | Sliding-Window Attention (SWA) Hybrid — 28/35 layers use sliding windows |
| LFM2.5-8B (Q6_K) | 6 (Attn) | 32 | Liquid MoE — only 6 standard attention layers, interspersed with liquid/recurrent layers |
| Llama-3.2-1B (Q4_0) | 16 | 32 | Standard Dense Transformer |
| Phi-3-mini (Q4) | 32 | 32 | Standard Dense Transformer (Microsoft) |
| Qwen2.5-0.5B (Q4_0) | 24 | 14 | Standard Dense Transformer (Grouped-Query Attention) |
| Qwen2.5-7B (Q4KM) | 28 | 28 | Standard Dense Transformer (Grouped-Query Attention) |
3. The Structural Fingerprint: Attention Entropy & Sinks
The first major finding of the Transformer X-Ray study is that different architectures exhibit highly distinct entropy trajectories and attention sink profiles during inference.
Three Distinct Attention Entropy Regimes
Attention entropy measures how broadly or narrowly a model distributes its attention weights. A low entropy indicates attention is concentrated on a few tokens; a high entropy signifies a broad, distributed attention pattern. The models fell into three distinct regimes:
- The Liquid MoE Regime (LFM2.5-8B): Recorded the highest average attention entropy (0.826). Since LFM has only 6 standard attention layers mapped across its entire depth, those few attention layers must distribute their focus broadly. The intermediate liquid/recurrent layers handle sequential recurrence and state tracking, relieving the attention layers from doing all the heavy lifting.
- The SWA Hybrid Regime (Gemma-4-E2B): Exhibited a continuous, high average entropy trajectory (0.810). In sliding-window attention, tokens cannot easily focus back on the earliest tokens (the "sinks") outside their window, forcing a more distributed attention pattern throughout.
- The Standard Dense Regime (Llama, Phi-3, Qwen): Demonstrated significantly lower average entropy (0.47 to 0.55). These models feature a steep convergence, quickly channeling attention toward a single dominant sink.
The Power of the BOS (Beginning of String) Attention Sink
The "attention sink" phenomenon—where early layers learn to dump excess attention weight onto the first token (BOS) to maintain numeric stability—varies drastically by model design:
- Llama-3.2-1B showed the strongest attention sink behavior, with a mean BOS sink weight of 0.835.
- Phi-3-mini (0.793), Qwen2.5-0.5B (0.711), and Qwen2.5-7B (0.684) similarly rely heavily on the BOS token.
- Gemma-4-E2B (0.593) has a weaker sink due to SWA constraints.
- LFM2.5-8B recorded the weakest sink at 0.445. Because its recurrent liquid layers maintain memory state natively across sequence positions, its attention mechanisms are freed from having to establish a dominant, synthetic "sink" token to manage long-context numeric distributions.
4. Deep Dive: Where Does Attention Commit?
The core contribution of the study is mapping the exact layer where JS-divergence peaks when conflicting context is introduced.
Attention Divergence (JSD) Curves by Architecture:
Standard Dense (Qwen) SWA Hybrid (Gemma) Liquid MoE (LFM)
JSD JSD JSD
▲ ▲ ▲
│ █ │ │
│ █ │ │ █
│ █ │ █ │ █ █
│ █ │ █ █ │ █ █
└───┴───┴───┴───┴───► Layer └─┴─┴───┴───┴───┴───► Layer └─┴───┴───┴───┴───► Layer
0 5 10 15 20 0 5 10 15 20 0 5 10 15 20
(Early: Layer 0 Commit) (Mid: Layer 6/14 Commit) (Distributed: Smear Commit)
1. Early-Layer Pattern Matchers (Qwen)
Both Qwen2.5 models (0.5B and 7B) exhibit an instantaneous commitment spike at Layer 0. The moment a wrong suffix (like " Berlin") is appended to a factual query (like "The capital of France is"), the attention maps in the very first layer are maximally disrupted.
This suggests that Qwen models behave primarily as direct associative pattern matchers. The pairing of "France" and "capital" is mapped to "Paris" during embedding and the initial attention projection. Conflicting suffix tokens immediately throw off this early associative lookup.
2. Gradual Context Processors (Gemma-4)
Gemma-4-E2B pushes its commitment depth much deeper. For simple associative facts (like capital cities), Gemma commits at Layer 6. For more complex contextual facts, its commitment peaks at Layer 14.
Because Gemma-4 utilizes sliding-window attention on 28 of its 35 layers, information cannot simply bypass intermediate steps and sink to the beginning of the sequence. Instead, context is processed, integrated, and routed step-by-step through successive layers, forcing a gradual factual retrieval pattern.
3. Distributed Checkpointers (LFM2.5)
In Liquid Foundation Models (LFM), the commitment is smeared across Layers 6 to 18. Since there are only 6 standard attention checkpoints interspersed throughout the architecture, commitment is not localized to a single sharp peak. Instead, the model resolves conflict progressively at each available attention junction while the recurrent layers process context in between.
4. Full-Depth Reasoners (Phi-3)
The most striking outlier was Microsoft's Phi-3-mini. For the science_fact category (e.g., "DNA stands for deoxyribonucleic"), the JS-divergence peaked at Layer 31 (the final layer).
This indicates that Phi-3-mini does not resolve or commit to its scientific relational logic early. It requires the full depth of its 32-layer stack to process, cross-reference, and finalize its attention commitment. Appending a wrong suffix disrupts attention all the way to the output projection.
5. The Scale Myth: 0.5B vs. 7B Parameters
A persistent hypothesis in LLM interpretability has been that larger models possess "more room" to think, shifting their conceptual retrieval and reasoning to deeper, more specialized layers. The Transformer X-Ray research definitively disproves this for standard architectures.
Comparing Qwen2.5-0.5B and Qwen2.5-7B reveals nearly identical JS-divergence curves. Both models:
- Peak at exactly the same layer (Layer 0).
- Share an almost identical relative attention trajectory across their respective depths.
The only variance is the amplitude of the divergence. The 0.5B model exhibits slightly higher JS-divergence peaks than the 7B model. This indicates that scale does not change where knowledge is resolved, but it does change sensitivity. The smaller 0.5B model is more fragile and highly disrupted by conflicting context, whereas the larger 7B model maintains a slightly more robust internal attention state, even though it commits at the exact same location.
6. Contextual Resilience: Historical Years vs. Science Facts
Analyzing attention divergence by category reveals which types of knowledge are most deeply embedded in the weights of these architectures.
The research showed that historical_year prompts (e.g., "WWII ended in [wrong suffix, e.g., '1950']") generated the highest JS-divergence across all tested models—frequently 5 to 10 times higher than other categories (with Qwen2.5-0.5B recording a massive JSD peak of 0.109 at Layer 0).
This high divergence means that historical dates are incredibly robustly encoded in LLMs. Appending an incorrect year creates massive cognitive dissonance within the attention mechanism, causing intense disruption. In contrast, scientific and relational facts represent a more fluid type of compositionality that models resolve more gradually and with lower overall attention divergence.
7. Practical Implications for AI Development
Luiz Spies' Transformer X-Ray study offers several critical takeaways for machine learning engineers, model compilers, and system architects:
- Layer-Pruning and KD (Knowledge Distillation): Since dense models like Qwen commit to factual lookups almost immediately (Layer 0–2), the remaining middle-to-upper layers are likely dedicated to formatting, syntactic structuring, and next-token probability distribution. This suggests we can aggressively prune or compress middle layers of dense models for specialized factual-retrieval tasks without destroying knowledge recall.
- Flash Attention Tuning: Hybrid SWA models (Gemma-4) and Liquid MoEs (LFM) do not rely on early BOS attention sinks. System compilers can optimize KV-cache management and flash-attention block sizes dynamically per layer based on these known attention sink profiles, rather than applying a blanket kernel strategy across the entire network.
- Draft Models for Speculative Decoding: The identical commitment curves of Qwen2.5-0.5B and Qwen2.5-7B provide empirical validation for using small parameter models as speculative drafts. Because they retrieve facts and process context in the exact same layers, their token distribution trajectories are highly aligned, making them structurally ideal speculative pairs.
8. What's Next for the X-Ray Pipeline?
As noted in the research, the initial study was bounded by two main limitations:
- Prompt Scale: Spies evaluated 40 hand-crafted prompts (4–8 per category). While sufficient to show strong signal, the next iteration is scaling to 500–1,000 prompts per category sourced from Wikidata and common benchmarks (TriviaQA, NaturalQuestions) to establish formal confidence intervals.
- Reasoning Depth: Hand-crafted categories do not cleanly separate single-hop factual associations from multi-hop compositional reasoning. The next development phase leverages LLMs to auto-generate prompts stratified by reasoning depth to test if multi-hop queries push commitment depth deeper in standard dense architectures.
By open-sourcing the entire extraction toolchain—from the raw C++ cb_eval interceptor to the Rust tensor analyzer—Spies has provided the AI community with an incredibly powerful, lightweight instrument to peer inside running models, laying the groundwork for a more rigorous, empirical taxonomy of LLM architecture.
The source code, scripts, and Rust binaries can be found in the official repository: geographdb-experiments.