HyperAIHyperAI

Command Palette

Search for a command to run...

Transformer
LLM

Rewirable Circuits in Transformers with Loom Attention

Da Xiao Qingye Meng Shengping Li Xingyuan Yuan

Abstract

We propose loom attention, which allows a Transformer to dynamically rewire its circuits at every token by interweaving a head’s vertical attention over the outputs of earlier heads (to obtain its query, key and value) with its horizontal attention over tokens. We instantiate vertical attention efficiently with normalized and gated linear attention over a per-token matrix memory, which stores the compressed head outputs and serves as a second residual stream. This yields Loom-Former, a dual-stream architecture that splits control and content between the vector and matrix streams. Across model sizes and training token budgets in language modeling and downstream tasks, LoomFormer matches Transformers trained with over 3× compute and recent residual-stream baselines (HC/mHC, MUDDFormer, AttnRes) trained with ~1.7–2.8×. For example, trained on the same 300B tokens with only 2% extra FLOPs, LoomPythia-2.8B achieves ~1.6× the average downstream gain of mHC-Pythia-2.8B over Pythia-2.8B, and matches (0-shot) or surpasses (5-shot) Pythia-12B.

One-sentence Summary

Beijing University of Posts and Telecommunications and ColorfulClouds Technology propose LoomFormer, a Transformer that dynamically rewires its circuits at every token using loom attention, which interweaves a head’s vertical attention over earlier head outputs with its horizontal attention over tokens via normalized, gated linear attention over a per-token matrix memory, yielding a dual-stream architecture that splits control and content between vector and matrix streams and matches Transformers trained with over 3×3\times3× the compute.

Key Contributions

  • The paper introduces loom attention, which dynamically rewires Transformer circuits at every token by interleaving horizontal attention over tokens with vertical attention over earlier head outputs, where vertical attention supplies the head’s query, key, and value.
  • It presents LoomFormer, a dual-stream architecture that instantiates vertical attention efficiently with normalized and gated linear attention over a per-token matrix memory serving as a second residual stream; the vector stream carries control and the matrix stream carries content, adding about 2.0–3.7% forward FLOPs.
  • Experiments across language modeling and downstream tasks show LoomFormer matches Transformers trained with over 3× compute and recent residual-stream baselines trained with about 1.7–2.8× compute; a 2.8B LoomPythia model trained on 300B tokens achieves about 1.6× the average downstream gain of mHC-Pythia over Pythia and matches (0-shot) or surpasses (5-shot) Pythia-12B.

Introduction

Transformers solve tasks by composing attention heads across layers, but the vertical wiring between heads is fixed after training, so different circuits must stay connected at once and can only be gated indirectly. Recent residual-stream mechanisms make depth-wise aggregation input-dependent, yet they operate on whole-layer hidden states and cannot single out individual heads. The authors propose loom attention, in which each head attends vertically over earlier head outputs at the same token to select its query, key, and value before performing horizontal token attention, making circuits rewirable per token. They instantiate this as LoomFormer with a shared per-token matrix memory and show it adds only 2.0 to 3.7 percent FLOPs while matching Transformers trained with over 3 times more compute.

Method

The authors conceptualize attention heads as communicating through the residual stream via writers (outputs) and readers (inputs such as query, key, and value). A writer WiW_iWi​ reaches a reader RjR_jRj​ through a virtual weight Cˉij=WiOWjs\bar{C}_{ij} = W_i^O W_j^sCˉij​=WiO​Wjs​. To allow different circuits at different tokens, a dynamic wiring matrix CCC scales these virtual weights, making the effective wiring cijCˉijc_{ij} \bar{C}_{ij}cij​Cˉij​.

Standard Transformers with pre-LayerNorm are inherently node-gated. This means their wiring matrix has a rank of at most one, taking the form C=gg′⊤C = g g'^\topC=gg′⊤, where gate vectors ggg and g′g'g′ determine which writers and readers are active. Consequently, Transformers can only gate entire heads on or off, restricting them to connecting rectangular patterns within the fixed support of their virtual weights. This limitation forces a trade-off: dense virtual weights allow broad connectivity but cause circuit interference when non-rectangular patterns are required, while sparse virtual weights prevent interference but leave cross-group pairs unreachable.

To overcome the quadratic cost of naive loom attention, where every reader attends over all earlier writers, the authors introduce a matrix memory M∈Rdk×dM \in \mathbb{R}^{d_k \times d}M∈Rdk​×d to compress head outputs along the depth dimension. This creates a second residual stream, the matrix stream, alongside the original vector stream. Writer WiW_iWi​ writes its output to MMM using a key kimk_i^mkim​, and reader RjR_jRj​ reads from MMM using a query qjmq_j^mqjm​. The interface for these operations is defined by dual ports:

vector stream:uj=xWjs,Δx=oiWiOmatrix stream:uj=qjmM,ΔM=kim⊗oi\begin{array}{ll} \text{vector stream:} & u_j = x W_j^s, \quad \Delta x = o_i W_i^O \\ \text{matrix stream:} & u_j = q_j^m M, \quad \Delta M = k_i^m \otimes o_i \end{array}vector stream:matrix stream:​uj​=xWjs​,Δx=oi​WiO​uj​=qjm​M,ΔM=kim​⊗oi​​

By shrinking the port dimensions to vectors of length dkd_kdk​, the model can generate these ports per token from the vector stream, which acts as the control path, while the matrix stream carries the moved content.

The LoomFormer retains the standard Transformer block backbone but fundamentally alters how sub-layers interface with the two streams. The architecture is built from the bottom up using specialized modules for reading and writing to the matrix stream.

The MRead and MWrite modules realize the matrix-stream ports. MRead generates a query qmq^mqm to read a vector uuu from MMM. To keep generation efficient, it utilizes a low-rank feature xrx^rxr shared across all MRead modules in a sub-layer. The query is formed by normalizing and gating a projected xrx^rxr, then summing it with a gated static query. MWrite similarly generates a key kmk^mkm from a shared feature xwx^wxw and writes a vector ooo into MMM via their outer product. Normalization and gating in these modules separate a port's direction from its magnitude, allowing the normalized vector to select slots and the gate to control the magnitude.

The LoomMHA sub-layer integrates vertical and horizontal attention. It first applies MShift to mix the current token's memory with the previous token's memory via a per-slot gate, followed by MNorm for RMS-normalization. Each attention head then reads four vectors from the normalized matrix M~\tilde{M}M~ using separate MRead modules: query, key, value, and an output bypass omo^mom. The query and key are concatenated with rotary position embeddings applied to standard projections. Crucially, the value is read entirely from MMM, meaning the vector stream only supplies ports and routing queries and keys, while all attention content originates from the matrix stream. The head output oio_ioi​ combines the bypass and standard scaled dot-product attention over tokens with a strictly causal mask. The outputs of all heads are then summed into ΔM\Delta MΔM via MWrite modules.

The FFN sub-layer also interacts with the matrix stream. While the standard FFN reads only from the vector stream xxx, a secondary, smaller FFN computes values to be written to MMM. These values are split into head-sized vectors and written via MWrite, serving as the sole channel for vector stream content to enter the matrix memory.

Finally, the LoomFormer block updates both streams residually. The embedding initializes both x0x_0x0​ and M0M_0M0​, and each subsequent block applies LoomMHA and FFN with pre-LayerNorm. The model typically sets dk=2nd_k = 2ndk​=2n slots, matching the parameter budget of a standard Transformer by adjusting FFN widths.

On the matrix stream, the wiring matrix becomes C=KQ⊤C = K Q^\topC=KQ⊤, where KKK and QQQ contain the keys and queries of the writers and readers. When ports are generated per token, LoomFormer achieves rewirability with one head per reader for any wiring pattern involving up to dkd_kdk​ writers. Instead of requiring a combinatorial explosion of heads to isolate specific connections as in node-gated architectures, the model simply assigns dkd_kdk​ slots per token. This allows LoomFormer to dynamically select a specific Transformer wiring from a continuum of possibilities at each token, sharing all other weights and incurring minimal overhead for port selection.

Experiment

The experiments train models on the Pile dataset with dynamic port gates initialized near zero, then evaluate scaling laws, large-scale pretraining, mechanisms, efficiency, and ablations. Scaling-law comparisons against Transformer++ and residual-stream baselines show LoomFormer improves validation loss across model scales while matching baseline performance at substantially lower compute. Large-scale pretraining and downstream evaluation confirm that LoomPythia improves accuracy and in-context learning, matching a much larger Pythia model, and mechanistic analysis attributes these gains to per-token dynamic rewiring, higher-rank routing, and greater head utilization. Efficiency tests find only modest FLOP and throughput overhead relative to the compute savings, and ablations validate the contributions of dynamic readers and writers, port normalization and gating, sub-layer components, and memory capacity.

LoomFormer differs from earlier residual-stream mechanisms by computing memory ports per head and per query/key/value input, which raises its wiring rank to min(d_k, 3n), defaulting to 2n. In contrast, DenseFormer, HC/mHC, AttnRes, and MUDDFormer use layer-level ports and have wiring rank 1 or 3. LoomFormer also combines matrix and vector residual streams with a smaller typical memory state than HC/mHC. Prior residual-stream mechanisms share ports at the layer level, limiting their wiring rank to 1, or to 3 in the case of MUDDFormer. LoomFormer computes ports per head and per Q/K/V input, enabling dynamic wiring rank up to 2n by default. LoomFormer maintains a matrix plus vector memory of typical size 2D(+D), compared with HC/mHC's 4D matrix state, while supporting finer-grained routing.

LoomPythia-2.8B delivers higher average downstream accuracy than Pythia-2.8B and larger gains than the mHC residual-stream baseline, especially in five-shot evaluation. Its Pile perplexity is close to Pythia-12B, and its FLAN perplexity is the best reported, outperforming larger baselines. The widening zero-shot to five-shot advantage suggests stronger in-context learning compared with the baseline. LoomPythia-2.8B improves average downstream accuracy over Pythia-2.8B by 3.6 points zero-shot and 4.3 points five-shot, about 1.6 times the gain of the mHC baseline. Its zero-shot average matches Pythia-12B and its five-shot average surpasses it despite having fewer parameters. It achieves Pile perplexity on par with Pythia-12B and the lowest FLAN perplexity among reported models. The accuracy gain grows from zero-shot to five-shot, whereas the baseline gain remains nearly unchanged, pointing to stronger in-context learning.

LoomFormer adds only a small analytical FLOP overhead relative to matched-size Transformers, from about 2% to 3.7%, with the overhead shrinking at larger scales. Measured training throughput remains at 89-92% of the Transformer baseline, and inference throughput remains at 84-92% across prefill and decode batch sizes. This modest overhead is far outweighed by reported compute savings exceeding 3x. The added FLOP percentage decreases with model scale, from 3.70% for Medium to 1.95% for the 2.8B model. Training throughput stays within 89-92% of the matched-size Transformer across all tested scales. Inference throughput ranges from 84% to 92% across prefill and decode batch sizes, with the largest model also showing the lowest relative FLOP overhead.

Medium-scale ablations show that dynamic read queries and write keys both contribute to LoomFormer's advantage over the Transformer++ baseline, but dynamic queries matter more than dynamic keys. When both are replaced with static vectors, the model retains roughly half of its gain, indicating the static head-level dual-stream backbone and per-token rewiring make comparable contributions. Port normalization and gating are complementary, with their combination providing the best configuration. Full LoomFormer records the lowest validation loss and the highest retained gain among the compared variants. Replacing dynamic read queries with static vectors reduces retained gain much more than replacing dynamic write keys. Removing both dynamic read and write components leaves only about half the gain, suggesting the static backbone and per-token rewiring contribute similar shares. Port normalization and gating are individually helpful, and combining them works best by separating slot direction from read/write magnitude.

The experiments evaluate LoomFormer against layer-level residual-stream baselines and standard Transformers, covering downstream accuracy, perplexity, efficiency, and component ablations. LoomPythia-2.8B improves downstream accuracy over matched and larger baselines, with gains widening from zero-shot to five-shot and indicating stronger in-context learning, while adding only modest FLOP and throughput overhead that shrinks with scale. Ablations show dynamic read queries matter more than dynamic write keys, the static dual-stream backbone and per-token rewiring contribute comparably, and port normalization combined with gating gives the best configuration.


Build AI with AI

From idea to launch — accelerate your AI development with free AI co-coding, out-of-the-box environment and best price of GPUs.

AI Co-coding
Ready-to-use GPUs
Best Pricing

HyperAI Newsletters

Subscribe to our latest updates
We will deliver the latest updates of the week to your inbox at nine o'clock every Monday morning
Powered by MailChimp