betaFeedback

WorksComputer Science

Rewirable Circuits in Transformers with Loom Attention

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 LoomFormer, 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 3x compute and recent residual-stream baselines (HC/mHC, MUDDFormer, AttnRes) trained with ~1.7-2.8x. For example, trained on the same 300B tokens with only 2% extra FLOPs, LoomPythia-2.8B achieves ~1.6x the average downstream gain of mHC-Pythia-2.8B over Pythia-2.8B, and matches (0-shot) or surpasses (5-shot) Pythia-12B. Code is available at https://github.com/Caiyun-AI/LoomFormer

Introduction

Transformers solve tasks by composing attention heads across layers into circuits [11, 36, 50, 34]: an earlier head writes a feature into a subspace of the residual stream, and a later head reads from that subspace into its query, key or value. Induction heads, for example, read the output of a previous-token head through their keys (K-composition) [36].

The composition between two heads, however, is determined by the product of their output and input projections, a virtual weight that does not change after training [11]. Attention makes the horizontal flow of information across tokens input-dependent: a head chooses which tokens to attend to. In contrast, the vertical flow across layers

is fixed: a head cannot choose which heads to read from. A model that needs different circuits for different inputs therefore keeps all of them wired at once, lets them compete for the residual stream, and can gate them only indirectly, e.g., by sending a head’s attention to a sink token [56]. We ask whether the wiring itself can be chosen per token, i.e., whether circuits can be made rewirable.

Recent work has enriched the vertical flow. Dense connections let a layer aggregate the outputs of all earlier layers [37]; MUDDFormer [55] and Attention Residuals (AttnRes) [27] make this aggregation input-dependent, turning it into a depth-wise (i.e., vertical) attention (separate for the query, key, value and residual inputs in MUDDFormer); and Hyper-Connections (HC) (Zhu et al., [63]) and its manifold-constrained variant mHC (Xie et al., [57]) maintain several residual streams with learnable or dynamic mixing. In all of them, however, the vertical channel meets horizontal attention only through the hidden state of a layer, in which the outputs of all heads have already been summed and mixed together: a head can neither single out a particular earlier head nor be singled out by a later one. The vertical and horizontal flows run side by side, never woven together.

To make circuits rewirable, we propose loom attention, in which a head chooses which earlier heads to read from just as it chooses which tokens to attend to. By attending vertically over the outputs of these heads at the same token, the head obtains its query, key and value to perform the standard horizontal attention over tokens, and its output is in turn attended to vertically by later heads. Vertical and horizontal attention are thus interwoven, each feeding the other at every head, like the warp and weft of a loom (Figure 1).

Figure 1. Conceptual sketch of loom attention. At each token, each head chooses which slots of that token’s matrix memory MM to read and write (i.e., vertical attention, every head does both; only one is shown per layer) and which tokens to attend to (horizontal attention), so a different circuit is woven for each token.

Naive vertical attention over the outputs of all earlier heads is, however, expensive. We therefore instantiate it 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. We call the resulting dual-stream architecture LoomFormer, after a drawloom—a loom in which a separate stored pattern selects which warp threads to lift at each pick, rather than repeating one fixed pattern. 1 Here the ordinary vector stream plays the pattern, carrying control—which memory slots each head writes and reads (weaving a different circuit per token) as well as which tokens to attend to—while the matrix stream carries the content moved across tokens. The two streams are coupled through attention outputs and FFN writes.

Extensive experiments on language modeling and downstream tasks across model sizes and training token budgets show that LoomFormer adds only 2.0–3.7% FLOPs while matching 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, 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 (Figure 2). We also analyze the trained 2.8B models to understand how and why LoomFormer works—e.g., by rewiring head outputs to inputs per token, it keeps over three times as many deep-layer heads off attention sinks as Pythia and mHC.

Figure 2. Downstream accuracy averaged over 10 tasks.

Rewirable Circuits

Writers, readers and circuits. Attention heads communicate through the residual stream (Elhage et al., [11]). Consider a Transformer with LL layers of nn heads of dim dd, and model dim D=ndD = nd. We call the output of a head a writer and each of its inputs (query, key and value) a reader, so a head has one writer and three readers. Writer WiW_i adds its output oi∈Rdo_i \in\mathbb{R}^d to the residual stream through its block WiO∈Rnd×dW_i^O \in\mathbb{R}^{n d \times d} of the output projection, and reader RjR_j of a later head reads the stream through its input projection Wjs∈RD×dW_j^s \in\mathbb{R}^{D \times d} (s∈{Q,K,V}s \in\{Q, K, V\}), so WiW_i reaches RjR_j through the virtual weight Cij=WiOWjs∈Rd×dC_{ij} = W_i^O W_j^s \in\mathbb{R}^{d \times d}: the two communicate only if WiW_i writes into a subspace that RjR_j reads. Heads composed in this way form circuits whose nodes are the writers and readers.

A task may need different circuits at different tokens, i.e., different pairs of writers and readers to be connected (Figure 3). To describe how the wiring can change, we give it a dynamic part besides the static virtual weights: at a token, reader RjR_j receives

Figure 3. Effective wiring for three wiring patterns. Transformers (top two rows) can only gate whole heads, i.e., rows and columns, on and off, so they connect only rectangles within the fixed support of their virtual weights. LoomFormer (bottom row) connects exactly the required pairs.

uj=∑ioicijC~ij,(1)u_j = \sum_i o_i c_{ij} \widetilde{C}_{ij}, \tag*{(1)}

where the per-token scalars cijc_{ij} form the wiring matrix C∈Rw×rC \in\mathbb{R}^{w \times r} from the ww earlier writers to the rr readers of one layer, and cijC~ijc_{ij}\widetilde{C}_{ij} is the effective wiring from WiW_i to RjR_j. The two are connected at the token if their effective wiring is nonzero. 2 A wiring pattern P⊆[w]×[r]P \subseteq[w] \times[r] is a set of writer-reader pairs, realized when each reader in PP is connected to exactly its writers in PP.

Definition 2.1. An architecture with fixed virtual weights is rewirable w.r.t. a set of wiring patterns if every pattern in the set is realized by some wiring matrix CC that it admits at a token.

Transformers are node-gated. In a Transformer, pre-LN only rescales all writers of a token by a common factor (Theorem A.1 in Section A.1). Within a token, nodes can thus only be gated through whole heads: a head that attends to a sink token (Xiao et al., [56]) outputs nearly nothing, turning off both its writer and, since what its readers receive has no effect, its readers.

Definition 2.2. An architecture is node-gated if, at every token, its wiring matrix has the form

C=gg′T,(2)C = g g^{\prime\mathsf{T}}, \tag*{(2)}

with gate vectors g∈Rwg \in\mathbb{R}^w and g′∈Rrg' \in\mathbb{R}^r whose nonzero entries mark the writers and readers that are on.

We call the rank of CC the wiring rank; a node-gated architecture has wiring rank at most one, so existing connections can be gated on and off, but not rewired.

Proposition 2.3. A Transformer with pre-LN is node-gated: at any token, it connects precisely the pairs with Cˉij≠0\bar{C}_{ij} \ne0 whose writer and reader are both on, a rectangle within the fixed support of the virtual weights.

Gating a writer or a reader acts on its whole row or column of CC, so a wiring pattern is realized only if it is such a rectangle, as in the first column of Figure 3; other patterns fail in one of two ways. With dense virtual weights, where heads share subspaces, every pair can be connected, but a non-rectangular pattern such as {W1→R1,W3→R3}\{\mathrm{W}_1 \to\mathrm{R}_1,\mathrm{W}_3 \to\mathrm{R}_3\} (last column) also connects W1→R3\mathrm{W}_1 \to\mathrm{R}_3 and W3→R1\mathrm{W}_3 \to\mathrm{R}_1: the two circuits interfere. With sparse virtual weights, where groups of heads use separate subspaces, circuits in different groups do not interfere, but pairs across groups such as W3→R2\mathrm{W}_3 \to\mathrm{R}_2 (second column) are unreachable.

The price of rewiring by node gating. Can a node-gated architecture overcome this by spending more heads? Suppose the role of each of r≥2r \ge2 readers may be played by several heads, gated on and off per token, and at every token each reader must receive exactly one of ww writers, chosen independently of the other readers; the last pattern in Figure 3 is the smallest instance. Let N(w,t)N(w,t) denote the minimum size of a ground set carrying a tt-cover-free family of ww sets, i.e., ww sets none of which is covered by the union of tt others [26].

Theorem 2.4. To realize all such wiring patterns, a node-gated architecture needs at least N(w,r−1)N(w,r-1) heads per reader, and this number suffices, where N(w,1)≈log⁡2wN(w,1) \approx\log_2 w, N(w,t)=Ω(t2log⁡w/log⁡t)N(w,t) = \Omega(t^2 \log w/\log t) for 2≤t≤w2 \le t \le\sqrt{w} and N(w,t)=Θ(w)N(w,t) = \Theta(w) for t>wt > \sqrt{w}.

Intuitively, a head receives every writer that is on and has a nonzero virtual weight to it, so a reader must hold in reserve a head that sees its chosen writer and none of the up to r−1r-1 writers chosen by the other readers (Theorem A.2 in Section A.2; bounds in Section A.3). With the r=3nr=3n readers of a layer choosing among its w=nlw=nl earlier writers, r−1>wr-1>\sqrt{w} whenever l≤9n−6l \le9n-6, so at practical sizes node gating needs Θ(w)\Theta(w) heads per reader.

Naive loom attention makes Transformers rewritable.

To rewire with one head per reader, the wiring matrix must be chosen entry by entry at each token. The most direct way is to let every reader attend over the outputs of all earlier heads of the same token, with attention weights generated from the token itself:

uj=∑iαij(x) oi,α⋅j(x)=softmax⁡(xWjα),(3)u_j = \sum_i \alpha_{ij}(x)\,o_i,\qquad\alpha_{\cdot j}(x)=\operatorname{softmax}(xW_j^\alpha), \tag*{(3)}

where Wjα∈RD×nlW_j^\alpha\in\mathbb{R}^{D \times nl} for a reader in layer ll, which has nlnl earlier writers. We call this naive loom attention: its virtual weights are identities and all the wiring is left to C=[αij]C=[\alpha_{ij}], unlike a Transformer, which wires heads through fixed virtual weights and only gates them through a rank-one CC. With one head per reader, it is rewritable w.r.t. all wiring patterns (cf. Figure 3, bottom row), but expensive: over the 3n3n readers of all LL layers, generating the attention weights takes about 32n2L2D\frac{3}{2}n^2L^2D parameters and multiply-adds per token, growing quadratically in the total number of heads nLnL and rivaling the whole model at practical sizes (Section A.4).

Method

From Naive to Affordable Loom Attention

As linear attention compresses a growing key–value cache into a fixed-size state (Katharopoulos et al., [25]; Schlag et al., [42]), we compress the head outputs of each token along depth into a matrix memory M∈Rdk×dM \in\mathbb{R}^{d_k \times d} of dkd_k slots of width dd. Writer WiW_i writes its output to MM with a key kim∈Rdkk_i^m \in\mathbb{R}^{d_k}, and reader RjR_j reads with a query qjm∈Rdkq_j^m \in\mathbb{R}^{d_k}, so a reader attends over dkd_k slots instead of all earlier writers, at a cost independent of depth. Since MM accumulates writes layer by layer, it is a second residual stream, the matrix stream, besides the original vector stream (Figure 4 left).

Figure 4. LoomFormer architecture: the model (left), the LoomMHA and FFN sub-layers of a block (middle), and the MRead (MR) and MWrite (MW) modules (right). Vertical attention: reads from MM are in red and writes to MM in blue.

We call the interface through which a head reads from or writes to a stream a port. The two streams have dual ports:

vector stream:uj=xWjs,Δx=oiWiomatrix stream:uj=qjmM,ΔM=kim⊗oi(4)\begin{aligned} \text{vector stream:}\quad&u_j=xW_j^s,\qquad\Delta x=o_iW_i^o \\ \text{matrix stream:}\quad&u_j=q_j^mM,\qquad\Delta M=k_i^m\otimes o_i \tag*{(4)} \end{aligned}

where kim⊗oi=(kim)Toik^{m}_{i} \otimes o_{i} = (k^{m}_{i})^{\mathsf{T}}o_{i} is the outer product. Data and ports swap shapes: a port shrinks from a D×dD \times d matrix to a vector of length dkd_k, small enough to be generated per token from the vector stream, which we keep as the control path.

Architecture

LoomFormer keeps the backbone of the Transformer block and changes how sub-layers interface with the two streams: the vector stream carries control, i.e., where to attend and how to wire, and the matrix stream carries the content that is moved (Figure 4). We describe the architecture bottom up, from ports to sub-layers to the model (pseudocode in Section C), with xx denoting a sub-layer’s pre-LN input.

MRead and MWrite. MRead and MWrite realize the matrix-stream ports of Eq. (4). MRead(M,x,xr)(M, x, x^r) generates a query qm∈Rdkq^m \in\mathbb{R}^{d_k} to read u∈Rdu \in\mathbb{R}^{d} from MM, where xr=GELU⁡(xW1R)∈RDrx^r = \operatorname{GELU}(xW^R_1) \in\mathbb{R}^{D_r} with W1R∈RD×DrW^R_1 \in\mathbb{R}^{D \times D_r} (Dr≪DD_r \ll D) is a low-rank feature shared by all MRead modules of a sub-layer to keep port generation cheap:

qm=Norm⁡(xrW2R)⊙σ(xWgR)+qˉ⊙σ(xWgˉR)u=qmM(5)\begin{aligned} q^m &= \operatorname{Norm}(x^rW^R_2) \odot\sigma(xW^R_g) + \bar{q} \odot\sigma(xW^R_{\bar{g}}) \\ u &= q^m M \tag*{(5)} \end{aligned}

Here xrx^r is projected by W2R∈RDr×dkW^R_2 \in\mathbb{R}^{D_r \times d_k}, normalized with RMSNorm and gated to get a dynamic query, which is summed with a static query qˉ\bar{q} (also gated) to obtain qm∈Rdkq^m \in\mathbb{R}^{d_k}. The two scalar gates are computed from xx by projecting to scalars with WgR,WgˉR∈RD×1W^R_g, W^R_{\bar{g}} \in\mathbb{R}^{D \times1} and then applying sigmoid. Similarly, with a shared xw=GELU⁡(xW1W)∈RDrx^w = \operatorname{GELU}(xW^W_1) \in\mathbb{R}^{D_r}, MWrite(o,x,xw)(o, x, x^w) generates a key km∈Rdkk^m \in\mathbb{R}^{d_k} and writes a vector o∈Rdo \in\mathbb{R}^{d} into MM as their outer product:

km=Norm⁡(xwW2W)⊙σ(xWgW)ΔM=km⊗o(6)\begin{aligned} k^m &= \operatorname{Norm}(x^wW^W_2) \odot\sigma(xW^W_g) \\ \Delta M &= k^m \otimes o \tag*{(6)} \end{aligned}

Normalization and gating separate a port’s direction from its magnitude: the normalized vector selects which slots to read or write, and the gate alone sets how much.

LoomMHA. To access the previous token’s memory without horizontal attention, MShift first mixes M[t]M_{[t]} with M[t−1]M_{[t-1]} via a per-slot gate z[t]=σ(x[t]WgS)∈Rdkz_{[t]} = \sigma(x_{[t]}W^S_g) \in\mathbb{R}^{d_k} (WgS∈RD×dkW^S_g \in\mathbb{R}^{D \times d_k}), and MNorm RMS-normalizes the matrix into M~[t]\widetilde{M}_{[t]}. Each head then reads four vectors from M~\widetilde{M} with separate MRead modules: query, key, value and output bypass omo^m:

M~[t]=MNorm⁡(z[t]⊙M[t−1]+(1−z[t])⊙M[t])q~,k~,v,om=MRead⁡Q,K,V,O(M~,x,xr)(7)\begin{aligned} \widetilde{M}_{[t]} &= \operatorname{MNorm}\left(z_{[t]} \odot M_{[t-1]} + (1-z_{[t]}) \odot M_{[t]}\right) \\ \widetilde{q}, \widetilde{k}, v, o^m &= \operatorname{MRead}^{Q,K,V,O}(\widetilde{M}, x, x^r) \tag*{(7)} \end{aligned}

q,k=RoPE⁡(xWQ,K)∥(q~,k~)q, k = \operatorname{RoPE}(xW^{Q,K}) \mathbin{\|} (\widetilde{q}, \widetilde{k})

where WQ,WK∈RD×d/4W^Q, W^K \in\mathbb{R}^{D \times d/4} project xx to d/4d/4 dimensions, to which rotary position embedding (RoPE) ((Su et al., 2024) is applied; the results are concatenated (∥\Vert) with q~\tilde{q} and k~\tilde{k} read from MM. The value is read from MM alone: the vector stream supplies only ports and RoPE queries/keys for slot and token routing, while all content moved by attention comes from MM. Unlike MHA, LoomMHA has two outputs: the projected head outputs for the vector stream, and the writes of all heads i∈{1,…,n}i \in\{1,\ldots,n\} summed into ΔM\Delta M:

oi=oim+Attention⁡(qi,ki,vi)o_i = o_i^m + \operatorname{Attention}(q_i,k_i,v_i)
ΔM=∑i=1nMWrite⁡i(Norm⁡(oi),x,xw)\Delta M = \sum_{i=1}^{n}\operatorname{MWrite}_i(\operatorname{Norm}(o_i),x,x^w)
LoomMHA⁡(x,M)=(Concat⁡i=1n[oi]WO,ΔM)(8)\operatorname{LoomMHA}(x,M) = (\operatorname{Concat}_{i=1}^{n}[o_i]W^O,\Delta M) \tag*{(8)}

where qiq_i, kik_i, viv_i, oimo_i^m are given by Eq. (7) for head ii, and Attention is scaled dot-product attention over tokens with a strictly causal mask that excludes the current token: a token’s own content reaches the head’s output through the bypass oimo_i^m instead. LoomMHA is where vertical and horizontal attention are interwoven: the vertical reads from MM feed the horizontal attention of head ii, and its output oio_i is written back to MM for later layers.

FFN with MWrite. The feed-forward network (FFN) sub-layer reads only xx and, like LoomMHA, returns a pair (FFN⁡x(x),ΔM)(\operatorname{FFN}_x(x),\Delta M), where FFN⁡x\operatorname{FFN}_x is a standard FFN module. A second, smaller FFN⁡M\operatorname{FFN}_M computes the values to write, which are split into nn head-sized vectors (split⁡i)(\operatorname{split}_i) and written to MM with the sub-layer’s MWrite modules. This write is the only channel through which content of the vector stream enters MM, since attention moves only content read from MM.

ΔM=∑i=1nMWrite⁡i(split⁡i(FFN⁡M(x)),x,xw)(9)\Delta M = \sum_{i=1}^{n}\operatorname{MWrite}_i(\operatorname{split}_i(\operatorname{FFN}_M(x)),x,x^w) \tag*{(9)}

LoomFormer. The embedding initializes both residual streams; M0M_0 is written from the embedding x0x_0 in the same way as the FFN writes:

x0=Embedding⁡(X)x_0 = \operatorname{Embedding}(X)
M0=∑i=1nMWrite⁡i(split⁡i(x0WE),x0,x0w)(10)M_0 = \sum_{i=1}^{n}\operatorname{MWrite}_i(\operatorname{split}_i(x_0W^E),x_0,x_0^w) \tag*{(10)}

where WE∈RD×DW^E \in\mathbb{R}^{D \times D} is a value projection and x0w=GELU⁡(x0W1W)x_0^w = \operatorname{GELU}(x_0W_1^W). Each block ll then applies the two sub-layers with pre-LN, updating both streams residually (pairs are added element-wise):

(xl′,Ml′)=(xl,Ml)+LoomMHA⁡(LN⁡1(xl),Ml)(xl+1,Ml+1)=(xl′,Ml′)+FFN⁡(LN⁡2(xl′))(11)\begin{aligned} (x_l',M_l') &= (x_l,M_l) + \operatorname{LoomMHA}(\operatorname{LN}_1(x_l),M_l) \\ (x_{l+1},M_{l+1}) &= (x_l',M_l') + \operatorname{FFN}(\operatorname{LN}_2(x_l')) \tag*{(11)} \end{aligned}

for l=0,…,L−1l = 0,\ldots,L-1. Finally, xLx_L is normalized and projected to produce the final output. As MLM_L is not used, the last block does not write to MM. We typically set dk=2nd_k = 2n slots (so MM has size 2D2D) and Dr=ndk/2=n2D_r = nd_k/2 = n^2 (a 2×2\times compression bottleneck relative to ndknd_k), matching the Transformer’s parameter budget by adjusting FFN widths at an approximately 2:1 ratio between FFN⁡x\operatorname{FFN}_x and the FFN⁡M\operatorname{FFN}_M write branch.

Rewiring Capacity

On the matrix stream without MShift, reader RjR_j receives uj=qjmM=∑i⟨qjm,kim⟩oiu_j = q_j^m M = \sum_i \langle q_j^m,k_i^m\rangle o_i by Eq. (4). The matrix stream thus keeps the division of roles of naive loom attention: its virtual weights are identities, and its wiring matrix is C=KQ⊤C = KQ^\top, of rank at most dkd_k, where the rows of KK and QQ are the keys kimk_i^m of the writers and the queries qjmq_j^m of the readers.

Proposition 3.1. (i) With ports fixed to (K,Q)(K,Q), LoomFormer is a standard Transformer Tfm⁡K,Q\operatorname{Tfm}_{K,Q} with residual stream (x,vec⁡(M))∈RD+dkd(x,\operatorname{vec}(M)) \in\mathbb{R}^{D+d_kd}, whose virtual weights absorb KQ⊤KQ^\top, hence node-gated. (ii) With ports generated per token, LoomFormer is rewritable with one head per reader w.r.t. the wiring patterns with at most dkd_k writers, whatever the total number of writers ww.

In (ii), only the writers in the pattern are on, each taking a slot through a one-hot key while each reader’s query selects the slots of its writers (Section A.6). The N(w,r−1)N(w,r-1) heads per reader that node gating needs (Theorem 2.4) are thus replaced by a per-token assignment of dkd_k slots; when more than dkd_k writers are on, slots are shared and writers interfere, as in linear attention. By (i), this rewiring capacity comes from generating ports per token, not from the matrix memory itself. Together, (i) and (ii) give a model-level view of LoomFormer’s expressiveness: within each token, LoomFormer wires heads as Tfm⁡K(x),Q(x)\operatorname{Tfm}_{K(x),Q(x)}, selecting per token one Transformer from the continuum {Tfm⁡K,Q}\{\operatorname{Tfm}_{K,Q}\} much as a mixture of experts selects experts ([16]), except that the experts are wirings, share all other weights, and cost only dkd_k numbers per port to select.

Connections to Prior Work

Table 1 compares LoomFormer with residual-stream mechanisms (derivations in Section A.7; extended related work in Section B). In DenseFormer (Pagliardini et al., [37]), HC (Zhu et al., [63]), mHC (Xie et al., [57]), AttnRes (Kimi Team, [27]) and MUDDFormer (Xiao et al., [55]), the ports are shared by all heads of a layer: apart from node gating and the fixed projections, their wiring depends on a writer only through its layer and on a reader only through its layer (and Q/K/V input in MUDDFormer). Their wiring rank is therefore 1, or 3 in MUDDFormer, one per Q/K/V input, whereas LoomFormer generates its ports per head and per token and reaches min⁡(dk,3n)\min(d_k,3n), i.e., 2n2n by default, with a smaller state than HC (2D+D2D + D against 4D4D).

Effective wiringWiring rankGranularityMemory: slots × width = typical sizeResidual stream
Transformer C‾ij\overline{C}_{ij}1–1×D=D1 \times D = Dvector
DenseFormer ⟨qljm,klim⟩C‾ij\langle q^{m}_{l_j}, k^{m}_{l_i}\rangle\overline{C}_{ij}1layerl×D=lDl \times D = lDvector
HC / mHC ⟨qljm(M),klim(M)⟩C‾ij\langle q^{m}_{l_j}(M), k^{m}_{l_i}(M)\rangle\overline{C}_{ij}1layerdk×D=4Dd_k \times D = 4Dmatrix
AttnRes (full) softmax⁡li⟨qljm,klim(M)⟩C‾ij\operatorname{softmax}_{l_i}\langle q^{m}_{l_j}, k^{m}_{l_i}(M)\rangle\overline{C}_{ij}1layer2l×D=2lD2l \times D = 2lDnone
MUDDFormer ⟨qljm,s(x),klim⟩C‾ij\langle q^{m,s}_{l_j}(x), k^{m}_{l_i}\rangle\overline{C}_{ij}3layer × QKVl×D=lDl \times D = lDvector
LoomFormer ⟨qjm,s(x),kim(x)⟩I\langle q^{m,s}_{j}(x), k^{m}_{i}(x)\rangle Imin⁡(dk,3n)=2n\min(d_k,3n)=2nhead × QKVdk×d=2D(+D)d_k \times d = 2D (+D)matrix + vector

Table 1. LoomFormer among residual-stream mechanisms. Ports kmk^{m}, qmq^{m} are indexed by heads ii, jj, or, when shared across a layer, by layers lil_i, ljl_j (and Q/K/V input ss), and marked (x)(x) or (M)(M) when computed from the vector stream or from the memory itself; softmax⁡li\operatorname{softmax}_{l_i} normalizes over writer layers. Typical sizes assume dk=4d_k=4 in HC and dk=2nd_k=2n in LoomFormer (+DD for its vector stream).

Linear attention. Linear attention ([25, 42]) and its gated and delta-rule variants ([58, 60, 39] (Dao & Gu 2024)) also read and write a fixed-size matrix state per head with keys and queries from the vector stream, but differ in axis and sharing. Their state accumulates across tokens and its read is the head output, replacing horizontal attention, whereas MM accumulates along depth and its reads feed the query, key and value of horizontal attention. Their state is also private to one head across tokens, so heads still compose through the static ports of the vector stream, whereas MM is shared by all heads of all layers at a token, as a channel through which heads read each other. The two are thus orthogonal and can be combined.

Experiments

We train all models on the Pile dataset (Gao et al., [18]) in JAX, initializing dynamic port gates near zero so training starts smoothly from static ports (Section D.1). We evaluate scaling laws (§ 5.1), large-scale pretraining and downstream performance (§ 5.2), mechanisms of the trained models (§ 5.3), computational efficiency (§ 6) and ablations (§ 7).

Scaling Laws

Settings. We train three model scales—Medium (432M), Large (778M) and XL (1.4B)—with sequence length T=4096T=4096, batch size 0.5M tokens (128 sequences), and token budgets proportional to non-embedding parameters following Hoffmann et al. [23] (architectural dimensions and optimizer hyperparameters in Section D.1).

Baselines. We compare LoomFormer against recent residual-stream baselines on the same Transformer++ backbone (Touvron et al., [48]) (RoPE (Su et al., 2024), SwiGLU FFN (Shazeer, [43]), RMSNorm, no linear bias): DHC (dynamic HC with expansion rate 4; Zhu et al., [63]), mHC (Xie et al., [57]), AttnRes (full) (Kimi Team, [27]), and MUDDFormer (Xiao et al., [55]) (details in Section D.2).

Results. Across the Medium, Large and XL scales (Figure 5), mHC, AttnRes and DHC improve over Transformer++, and MUDDFormer improves further, while LoomFormer achieves the lowest loss at every scale. Interpolating log-linearly along each baseline curve across Medium and Large, LoomFormer matches Transformer++ trained with 3.19–3.25× compute (3.10× net at Large after the 3.1% FLOP overhead in Table 3) and all four residual-stream baselines at 1.73–2.76×. At XL, where LoomFormer lies below the largest model of every baseline, it lowers validation loss from 2.101 to 1.979 (ΔL=0.122\Delta L = 0.122, 1.8× MUDDFormer’s 0.068) at 2.8% extra FLOPs (Table 3).

Figure 5. Scaling curves on Pile validation loss against training compute (total parameters × training tokens).

Model+FLOPs (%)Train (%) v5pPrefill (%) bs 1 / 8Decode (%) bs 1 / 16 / 64
Medium3.7090.587.4 / 90.491.7 / 89.2 / 92.3
Large3.1389.285.3 / 86.285.4 / 87.8 / 84.9
XL2.7792.383.8 / 85.386.9 / 84.6 / 86.6
2.8B1.9592.487.5 / 90.586.4 / 87.6 / 88.9

Table 3. Analytical computational overhead (+FLOPs) and measured relative throughput of LoomFormer vs. matched-size Transformer at sequence length TT (absolute speeds in Section F).

Large-Scale Pretraining and Evaluation

Settings. To test whether LoomFormer’s gains persist under extended training, we compare against the Pythia suite (Biderman et al., [2]) on 30B Pile tokens (over 5× the Chinchilla budget of § 5.1; Hoffmann et al., [23]). Specifically, we train LoomPythia-2.8B and mHC-Pythia-2.8B—the residual-stream baseline that also keeps a depth-independent state size (Table 1)—and compare them with Pythia 2.8B–2. Except for using serial instead of parallel sub-layers,3 both LoomPythia and mHC-Pythia use the same architecture choices and training hyperparameters as

Pythia ([2 Appendix E]). We evaluate zero- and five-shot accuracy across 10 standard benchmarks.

Results. As shown in Table 2 and Figure 2, LoomPythia-2.8B improves average accuracy over Pythia-2.8B by +3.6 in 0-shot and +4.3 in 5-shot (+3.95 on their mean), achieving 1.6× the gain of mHC-Pythia-2.8B (+2.5 / +2.6, mean +2.55). Its 0-shot average (59.9) matches Pythia-12B (59.9), its 5-shot average (61.6) exceeds Pythia-12B (60.8), and its 0/5-shot mean (60.75) matches a log-linear extrapolation of Pythia at ~4.9× compute. On pretraining metrics, LoomPythia-2.8B reaches Pile ppl 6.02, on par with Pythia-12B (6.01) and well ahead of mHC-Pythia-2.8B (6.24).

ModelPile ppl↓FLAN ppl↓LAM BADAPIQAWino GrandeARC-EARC-CSciQBoolQHella SwagRACE-MRACE-HAvg acc↑/∆acc
Pythia-2.8B6.638.1664.773.959.464.429.588.264.545.438.134.956.3
Pythia-6.9B6.297.8567.375.260.967.331.389.763.748.040.637.058.1
mHC-Pythia-2.8B6.247.350-shot68.574.462.867.130.790.566.947.542.337.058.8/+2.5
Pythia-12B6.017.2670.576.063.970.231.890.267.450.340.638.359.9
LoomPythia-2.8B6.026.9471.874.763.768.531.792.465.849.142.339.059.9/+3.6
Pythia-2.8B--60.573.660.667.332.394.365.645.138.435.657.3
Pythia-6.9B--63.875.563.770.235.695.165.748.139.036.559.3
mHC-Pythia-2.8B--5-shot62.474.964.170.835.595.669.447.640.338.259.9/+2.6
Pythia-12B--67.376.064.271.036.595.368.050.340.138.860.8
LoomPythia-2.8B--69.075.765.770.835.196.071.249.543.140.161.6/+4.3

Table 2. Zero/five-shot downstream evaluation results (Δ\Deltaacc is over Pythia-2.8B; best in bold within each block).

As an out-of-domain evaluation, Table 2 also reports target-span perplexities on a randomly sampled subset of the FLAN Collection ([32]), which features instruction following, chain-of-thought and in-context few-shot data. The advantage of LoomPythia on FLAN is even larger than on Pile: FLAN ppl 6.94 is best in the table, beating both Pythia-12B (7.26) and mHC-Pythia-2.8B (7.35). Whereas mHC’s gain barely changes from 0-shot to 5-shot (+2.5 vs. +2.6), LoomPythia’s widens from +3.6 to +4.3, indicating stronger in-context learning that § 5.3 traces to per-token rewiring freeing deep heads from attention sinks.

Mechanistic Analysis

We analyze Pythia-2.8B, mHC-Pythia-2.8B and LoomPythia-2.8B (§ 5.2) on held-out Pile validation sequences; metric definitions and additional visualizations are in Section H.

Per-token circuit rewiring. After subtracting each pair’s token-mean static component, the dynamic wiring matrix on the 3n=963n = 96 Q/K/V readers of layer ll has rank 0 under fixed ports (Theorem 3.1(i)), at most 1 in Transformer and mHC, at most 3 in MUDDFormer, and up to min⁡(dk,3n)=64\min(d_k, 3n) = 64 in LoomFormer (Table 1). In Figure 6(a), LoomPythia-2.8B’s dynamic effective rank rises with depth to 41.0 (26.4 mean), placing 71.0% of dynamic wiring energy (90.7% at layer 32) outside rank 1, and averages 14.3 (20.9 at layer 32) within a single Q, K or V input where MUDDFormer also has rank ≤1\le1. Figure 6(b) directly tests Theorem 3.1(i) vs. (ii) in Rdk\mathbb{R}^{d_k}: whereas static or scalar-gated ports have zero cross-token cosine distance, LoomPythia’s read ports q~,k~,v~,om\tilde{q}, \tilde{k}, \tilde{v}, o^m average 0.33–0.46 (up to 0.68) and its attention and FFNM\mathrm{FFN}_M write ports average 0.36 and 0.56 (up to 0.75); Section H traces an in-context circuit rewiring across adjacent tokens).

Figure 6. Mechanistic comparison of 2.8B models across layers l=1,…,32l = 1, \ldots, 32 on Pile validation sequences (definitions in Section H). (a) Energy effective rank of the token-centered dynamic Q/K/V wiring matrix (band: 10th–90th percentiles) and per single Q, K or V input, vs. the bounds of Table 1. (b) Cross-token cosine distance (1−cos⁡1-\cos) of read ports (q~,k~,v~,om\tilde{q}, \tilde{k}, \tilde{v}, o^m) and write ports (kMHAm,kFFNmk_{\mathrm{MHA}}^m, k_{\mathrm{FFN}}^m) in Rdk\mathbb{R}^{d_k} (static/gated =0= 0). (c) Percentage of heads that are on (non-sink; legend: 32-layer mean). (d) Within-head writer routing similarity across port pairs in layers 3–32.

Head utilization and within-head specialization. In a node-gated model (§ 2, Theorem 2.4), heads whose

fixed inputs are not needed at a token turn themselves off by attending to sink tokens ([49, 56]). Counting non-sink heads as on ((Xiao et al., 2025)), Figure 6(c) shows that in layers 17–32, only 22.9% of heads are on in Pythia-2.8B and 17.7% in mHC-Pythia-2.8B—whose four streams still merge into one shared input per layer—whereas LoomPythia-2.8B keeps 74.4% on (3.3× and 4.2×), more than doubling content-token attention mass and accounting for its 5-shot and FLAN gains (§ 5.2). Finally, Figure 6(d) verifies head × QKV specialization (Table 1): although routing looks correlated at the layer level (0.92–0.96), per-writer correlation within the same head drops to 0.71–0.84 and top-32 writer overlap is 0.38–0.49, so over half of the top writers read by a head’s q~\tilde{q}, k~\tilde{k}, vv, omo^m are distinct.

Computational Complexity and Efficiency

Analytical computational overhead. Under a matched parameter budget, LoomFormer adds 1d(1+ρ/12)+88(1+12/ρ)\frac{1}{d(1+\rho/12)}+\frac{8}{8(1+12/\rho)} relative forward FLOPs from reading/writing MM and wider Q/K (dk=2nd_k = 2n, ρ=T/D\rho= T/D; derived in Section E), totaling 1.95%–3.70% across our four scales (Table 3).

Wall-clock training and inference throughput. Table 3 reports relative throughput for JAX training on TPU v5p pods (with fused Pallas kernels) and BF16 PyTorch inference on an NVIDIA A800 GPU (with a fused Triton kernel and torch.compile; Section F). LoomFormer sustains 89%–92% of Transformer training speed and 84%–92% of inference speed across prefill and decode batch sizes; the gap beyond the 2.0%–3.7% FLOPs reflects HBM I/O on MM, lower arithmetic intensity of per-token MM contractions, and smaller split projections and norms, and is far outweighed by the over 3× compute savings (§ 5.1 and § 5.2).

Ablation Studies

We ablate LoomFormer at the Medium scale (432M, 7B tokens; § 5.1), reallocating saved parameters to FFNx_x to match the parameter budget, and report Pile validation loss and the retained gain Gain =(LTfm++−L)/(LTfm++−LLoom)= (L_{\mathrm{Tfm++}} - L)/(L_{\mathrm{Tfm++}} - L_{\mathrm{Loom}}) (Table 4; full suite in Section G).

VariantLoss↓ΔLossGain
LoomFormer (full)2.266—100.0%
Transformer++ (baseline)2.443+0.1770.0%
Dynamic rewiring (Theorem 3.1)
— Static write keys (kmk^m)2.283+0.01790.3%
— Static read queries (qmq^m)2.310+0.04375.4%
— Static read & write (qmq^m, kmk^m)2.344+0.07856.0%
Port normalization & gating (Eqs. (5)–(6))
— dynamic port gates2.277+0.01193.7%
— dynamic port Norm2.289+0.02387.1%
— dynamic port gates & Norm2.283+0.01790.3%
Sub-layer components (§ 3.2)
— FFNM_M write2.300+0.03480.7%
— output bypass omo^m2.299+0.03281.8%
— vector-stream RoPE WQ,KW^{Q,K}2.286+0.02088.7%
— MShift2.277+0.01094.2%

Table 4. Ablations of LoomFormer at the Medium scale.

Dynamic rewiring. Replacing dynamic kmk^m, dynamic qmq^m, or both with learned static vectors (dropping their gates)

tests Theorem 3.1. Fixing both reduces LoomFormer to TfmK,Q_{K,Q} and cuts the gain to 56.0%—still ahead of layer-wise dynamic baselines (Figure 5)—so the static head-level dual-stream backbone and per-token rewiring contribute roughly equal halves. Fixing qmq^m hurts far more than fixing kmk^m (75.4% vs. 90.3% retained): writers can use stable slots if readers select among them per token.

Port normalization and gating. Removing either the dynamic-branch gates or port RMSNorm hurts, yet removing both beats removing RMSNorm alone (90.3% vs. 87.1%): an unnormalized projection already varies in norm, making a separate gate redundant. Pairing RMSNorm with gating works best by separating slot direction from read/write magnitude.

Sub-layer components. Removing FFNM_M (Eq. (9)) hurts most, as the sole post-embedding path from the vector stream into MM, followed closely by removing the bypass omo^m and restoring self-attention to the current token (Eq. (8)). Applying RoPE to d/4d/4 of the MM-read coordinates instead of xWQ,KxW^{Q,K} (Eq. (7)) also hurts, supporting separate streams

for positions and content, whereas removing MShift still retains 94.2% of the gain.

Memory capacity. As we vary the slot count dkd_k (Figure 7), validation loss drops sharply (−0.026-0.026) from dk=16d_k = 16 to 32 with diminishing returns beyond, placing our default dk=2nd_k = 2n at the knee given the linear growth of MRead/MWrite FLOPs (Section E) and I/O with dkd_k. Even at dk=16d_k = 16 (2D2D total state), LoomFormer already outperforms DHC (4D4D) and MUDDFormer (lDlD, averaging 9D9D across L=18L = 18 layers), showing that head-level rewiring uses state memory far more effectively than layer-wise mechanisms.

Figure 7. Validation loss vs. per-token memory size and matrix slots dkd_k at the Medium scale (L=18L = 18).

Conclusion

Viewing Transformer circuits through their dynamic wiring matrix shows that standard Transformers and layer-wise residual-stream mechanisms are restricted to low-rank gating, requiring many heads per reader to avoid circuit interference. Loom attention lifts this bottleneck by interweaving vertical linear attention over a per-token matrix memory with horizontal attention over tokens, making circuits rewirable per token at one head per reader and 2.0%–3.7% extra forward FLOPs. Across model scales and 300B-token pretraining, LoomFormer matches Transformers trained with over 3× compute and recent residual-stream baselines with ~1.7–2.8×, while keeping over three quarters of its attention heads on and rewiring its ports from token to token. Because the matrix memory operates along depth at each token, combining loom attention with linear or sparse attention along the sequence is a natural direction for future foundation models.

Theory of Rewirable Circuits

Normalization and proof of Proposition 2.3

Lemma A.1. In a Transformer with pre-LN (LayerNorm or RMSNorm), the contribution of earlier writers to reader RjR_j’s input uj=LN⁡(x)Wjsu_j = \operatorname{LN}(x)W_j^s is λ(x)∑ioiCˉij\lambda(x)\sum_i o_i\bar{C}_{ij}, where the scale λ(x)>0\lambda(x) > 0 is shared by all writers and the virtual weights Cˉij\bar{C}_{ij} are fixed.

Proof. Write x=∑ioiWiO+xotherx = \sum_i o_iW_i^O + x_{\mathrm{other}}, where xotherx_{\mathrm{other}} sums the embedding and earlier FFN outputs. LayerNorm computes LN⁡(x)=λ(x)(x−μ(x)1)⊙γ+β\operatorname{LN}(x) = \lambda(x)(x-\mu(x)\mathbf{1})\odot\gamma+\beta with λ(x)=D/∥x−μ(x)1∥>0\lambda(x) = \sqrt{D}/\lVert x-\mu(x)\mathbf{1}\rVert> 0 (putting λ(x)=0\lambda(x)=0 on the degenerate set x∈span⁡(1)x\in\operatorname{span}(\mathbf{1})). Since centering is the fixed linear map x−μ(x)1=x(I−1D11T)x-\mu(x)\mathbf{1}=x\left(I-\frac{1}{D}\mathbf{1}\mathbf{1}^{\mathsf T}\right),

uj=LN⁡(x)Wjs=λ(x)∑ioiCˉij+λ(x)xother(I−1D11T)diag⁡(γ)Wjs+βWjs,u_j=\operatorname{LN}(x)W_j^s=\lambda(x)\sum_i o_i\bar{C}_{ij}+\lambda(x)x_{\mathrm{other}}\left(I-\frac{1}{D}\mathbf{1}\mathbf{1}^{\mathsf T}\right)\operatorname{diag}(\gamma)W_j^s+\beta W_j^s,

with fixed virtual weights Cˉij=WiO(I−1D11T)diag⁡(γ)Wjs\bar{C}_{ij}=W_i^O\left(I-\frac{1}{D}\mathbf{1}\mathbf{1}^{\mathsf T}\right)\operatorname{diag}(\gamma)W_j^s absorbing the linear maps of the normalization (any projection bias adds to βWjs\beta W_j^s). For RMSNorm, centering is omitted, β=0\beta=0 and λ(x)=D/∥x∥\lambda(x)=\sqrt{D}/\lVert x\rVert.

Proof of Proposition 2.3. By Theorem A.1, pre-LN rescales all writers of a token by the same λ(x)>0\lambda(x)>0. Within a token, what depends on the input is only this scale and which heads are on: let gi=λ(x)g_i=\lambda(x) if the head of WiW_i is on and 0 otherwise, and gj′=1g'_j=1 if the head of RjR_j is on and 0 otherwise. Then C=gg′TC=gg'^{\mathsf T}, which is Eq. (2), and since λ(x)>0\lambda(x)>0, WiW_i and RjR_j are connected (gigj′Cˉij≠0g_ig'_j\bar{C}_{ij}\ne0) if and only if both are on and Cˉij≠0\bar{C}_{ij}\ne0.

Full statement and proof of Theorem 2.4

Setting. The role of reader RjR_j (j∈[r]j\in[r], r≥2r\ge2) is played by a set HjH_j of heads, so a reader is here a role rather than one input of one head; by Eq. (2), head h∈Hjh\in H_j receives WiW_i when its effective wiring gigh′Cˉihg_ig'_h\bar{C}_{ih} is nonzero. A wiring task assigns to each reader a writer π(j)∈[w]\pi(j)\in[w], and the tasks are all maps π:[r]→[w]\pi:[r]\to[w]. Reader RjR_j receives exactly Wπ(j)W_{\pi(j)} if some h∈Hjh\in H_j receives Wπ(j)W_{\pi(j)} and no h∈Hjh\in H_j receives any WiW_i with i≠π(j)i\ne\pi(j). We require every head in HjH_j that is on to be free of other writers because query and key inputs feed a softmax, so interference at one head cannot be cancelled downstream. Every writer in π([r])\pi([r]) must therefore be on (gπ(j)≠0g_{\pi(j)}\ne0), and turning others on can only add interference, so we may assume the writers that are on are π([r])\pi([r]). For a fixed reader RjR_j, let Bi={h∈Hj:Cˉih≠0}B_i=\{h\in H_j:\bar{C}_{ih}\ne0\}. A family {Bi}i=1w\{B_i\}_{i=1}^w is tt-cover-free if Bi⊈⋃i′∈JBi′B_i\not\subseteq\bigcup_{i'\in J}B_{i'} for every i∈[w]i\in[w] and every J⊆[w]∖{i}J\subseteq[w]\setminus\{i\} with ∣J∣≤t|J|\le t.

Theorem A.2 (full version of Theorem 2.4). For r≥2r\ge2, a node-gated architecture with ww writers realizes all wiring tasks π:[r]→[w]\pi:[r]\to[w] if and only if, for every reader, {Bi}i=1w\{B_i\}_{i=1}^w is an (r−1)(r-1)-cover-free family. Hence each reader needs at least N(w,r−1)N(w,r-1) heads, and this number suffices.

Proof. If. Given π\pi, turn on only the writers π([r])\pi([r]). For reader RjR_j, let J=π([r])∖{π(j)}J=\pi([r])\setminus\{\pi(j)\}, so ∣J∣≤r−1|J|\le r-1. Since {Bi}\{B_i\} is (r−1)(r-1)-cover-free, there is a head h∈Bπ(j)∖⋃i∈JBih\in B_{\pi(j)}\setminus\bigcup_{i\in J}B_i; turn on hh and no other head of HjH_j. Then hh receives Wπ(j)W_{\pi(j)} and none of the other writers that are on.

Only if. Fix a reader RjR_j, a writer ii and a set J⊆[w]∖{i}J\subseteq[w]\setminus\{i\} with ∣J∣≤r−1|J|\le r-1. Choose π\pi with π(j)=i\pi(j)=i that maps the other r−1r-1 readers onto JJ, which is possible since r−1≥1r-1\ge1, ∣J∣≤r−1|J|\le r-1 and different readers may share a writer (if J=∅J=\varnothing, map them to ii). Realizing π\pi requires a head h∈Hjh\in H_j that has Cˉih≠0\bar{C}_{ih}\ne0 and Cˉi′h=0\bar{C}_{i'h}=0 for all i′∈Ji'\in J, i.e., h∈Bi∖⋃i′∈JBi′h\in B_i\setminus\bigcup_{i'\in J}B_{i'}. Hence Bi⊈⋃i′∈JBi′B_i\not\subseteq\bigcup_{i'\in J}B_{i'}, and the family is (r−1)(r-1)-cover-free.

Counting. The sets BiB_i are subsets of HjH_j, so ∣Hj∣≥N(w,r−1)|H_j|\ge N(w,r-1). Conversely, given an (r−1)(r-1)-cover-free family of ww sets on a ground set of size N(w,r−1)N(w,r-1) for each reader, create one head per point and set Cˉih=Id\bar{C}_{ih}=I_d if h∈Bih\in B_i and 0 otherwise; this is realized in D=min⁡{w,rN(w,r−1)}dD=\min\{w,rN(w,r-1)\}d dimensions by assigning orthogonal dd-dimensional subspaces either to the ww writers or to the rN(w,r−1)rN(w,r-1) heads. □\square

Remarks. (i) Attention sinks gate heads off only approximately; under the threshold of § 2, the counting argument is unchanged. (ii) Sufficiency at N(w,r−1)N(w,r-1) heads per reader holds in a Transformer when each of the rr readers belongs to a separate head (with its other two inputs fixed); when r=3nr=3n counts all Q, K and V inputs of nn heads, coupling Q, K and V inside the same physical head (and sink gate gh′g'_h) can only require more heads, while the lower bound N(w,r−1)N(w,r-1) still applies. Likewise, if several heads of a value reader share identical attention weights, their outputs add linearly and interference could in principle cancel, whereas our clean-head requirement is necessary for query and key inputs. (iii) The model excludes routing through FFNs, discussed in Section A.5.

Bounds on N(w,t)N(w,t) and remarks on Theorem 2.4

Bounds. A 1-cover-free family is an antichain, so by Sperner’s theorem [44] N(w,1)N(w,1) is the smallest NN with (N⌊N/2⌋)≥w\binom{N}{\lfloor N/2\rfloor} \ge w, about log⁡2w\log_2 w. For 2≤t≤w2 \le t \le\sqrt{w}, N(w,t)=Ω(t2log⁡w/log⁡t)N(w,t) = \Omega(t^2 \log w/\log t) [10, 40, 17] and N(w,t)=O(min⁡{t2log⁡w,w})N(w,t) = O(\min\{t^2 \log w,w\}) [14]; for t>wt > \sqrt{w}, Bassalygo’s bound N(w,t)≥min⁡{(t+22),w}N(w,t) \ge\min\{\binom{t+2}{2},w\} [10] together with the singleton construction N(w,t)≤wN(w,t) \le w gives N(w,t)=Θ(w)N(w,t) = \Theta(w), reaching N(w,t)=wN(w,t) = w (one head per writer) once (t+22)≥w\binom{t+2}{2} \ge w.

Group testing. Theorem A.2 is an instance of non-adaptive group testing: the heads of a reader are tests that must isolate the selected writer from up to r−1r-1 other writers that are on.

Dense and sparse layouts. With a single head per reader (∣Hj∣=1|H_j| = 1), the two layouts of Figure 3 are degenerate codes: B1=⋯=Bw=HjB_1 = \cdots= B_w = H_j (dense), which is not 1-cover-free and makes circuits interfere, and Bi=∅B_i = \varnothing for some writer ii (sparse), which leaves (i,j)(i,j) unreachable.

Superposition. At layer scale (r=3nr = 3n, N(w,r−1)=Θ(w)N(w,r-1) = \Theta(w)), separating ww writers as above takes Θ(wd)\Theta(wd) dimensions (wdwd with orthogonal writer subspaces). With nLnL writers sharing D=ndD = nd dimensions, writers across layers must overlap in superposition [12], so virtual weights are rarely exactly zero and in practice part of the price is paid as interference.

Cost of naive loom attention

Indexing layers by l=0,…,L−1l = 0,\ldots,L-1 as in § 3.2, every reader of layer ll attends over nlnl earlier head writers. Over the 3n3n readers of all LL layers, the projections WαW^\alpha of Eq. (3) take ∑l=0L−13n⋅nl⋅D=32n2L(L−1)D≈32n2L2D\sum_{l=0}^{L-1} 3n \cdot nl \cdot D = \frac{3}{2}n^2L(L-1)D \approx\frac{3}{2}n^2L^2D parameters, and as many multiply-adds per token. This grows quadratically in the total number of heads nLnL and rivals the 12LD212LD^2 of the whole model once n2L≈8Dn^2L \approx8D (i.e., nL≈8dnL \approx8d), e.g., 70% of it for our XL configuration (L=28L = 28, n=20n = 20, D=1920D = 1920). Factorizing the weights into keys and queries removes WαW^\alpha, but still leaves ≈32n2L2\approx\frac{3}{2}n^2L^2 attention weights per token to compute and store for backpropagation, plus ≈32nL2D\approx\frac{3}{2}nL^2D multiply-adds to aggregate the oio_i’s.

Routing through FFNs

An intermediate FFN between the writers and the reader layer can route any pattern P⊆[w]×[r]P \subseteq[w] \times[r] by copying oio_i into a dd-dimensional subspace private to RjR_j whenever (i,j)∈P(i,j) \in P. Concretely, suppose the residual stream x∈RDx \in\mathbb{R}^D carries binary indicators pij∈{0,1}p_{ij} \in\{0,1\} of PP (pij=1p_{ij} = 1 iff (i,j)∈P(i,j) \in P) and the writer outputs satisfy ∥oi∥∞≤Λ\lVert o_i \rVert_\infty\le\Lambda (ignoring pre-LN rescaling). Since ReLU(z−Λ(1−p))−ReLU⁡(−z−Λ(1−p))(z - \Lambda(1-p)) - \operatorname{ReLU}(-z - \Lambda(1-p)) equals zz when p=1p = 1 and 00 when p=0p = 0 for every z∈[−Λ,Λ]z \in[-\Lambda,\Lambda], a two-layer ReLU FFN can compute the gated copy pijoi∈Rdp_{ij}o_i \in\mathbb{R}^d coordinate-wise for each pair (i,j)(i,j) and sum over ii into RjR_j’s private subspace. However, this construction uses 2wr2wr hidden units—hence 4wrdD=Θ(wrdD)4wr dD = \Theta(wrdD) parameters, or 12nLD212nLD^2 when routing w=nLw = nL writers to r=3nr = 3n readers (nn times the 12lD212lD^2 parameters of all ll preceding blocks)—requires an intervening FFN step, and needs disjoint subspaces for the ww writers, rr readers and wrwr control coordinates (D≥(w+r)d+wrD \ge(w+r)d + wr). We give this construction only as an upper bound and do not prove a lower bound on FFN routing.

Proof of Proposition 3.1

Part (i). Flatten M∈Rdk×dM \in\mathbb{R}^{d_k \times d} row by row into vec⁡(M)∈Rdkd\operatorname{vec}(M) \in\mathbb{R}^{d_kd}, so that entry (a,b)(a,b) of MM is entry (a−1)d+b(a-1)d+b of vec⁡(M)\operatorname{vec}(M). For a static read port q∈Rdkq \in\mathbb{R}^{d_k}, (qM)b=∑aqaMab=(vec⁡(M)(qT⊗Id))b(qM)_b = \sum_a q_aM_{ab} = (\operatorname{vec}(M)(q^\mathsf{T} \otimes I_d))_b. For a static write port k∈Rdkk \in\mathbb{R}^{d_k}, vec⁡(kTo)(a−1)d+b=kaob=(o(k⊗Id))(a−1)d+b\operatorname{vec}(k^\mathsf{T}o)_{(a-1)d+b} = k_a o_b = (o(k \otimes I_d))_{(a-1)d+b}. Hence every read and write of MM is a fixed linear map between vec⁡(M)\operatorname{vec}(M) and the head, i.e., a Transformer projection with Kronecker structure, qT⊗Idq^\mathsf{T} \otimes I_d for reads and k⊗Idk \otimes I_d for writes, and the composition weight between WiW_i and RjR_j is the constant ⟨qjm,kim⟩\langle q_j^m,k_i^m\rangle. The coupling KQTKQ^\mathsf{T} is therefore fixed and belongs to the virtual weights, Cˉij=⟨qjm,kim⟩/Id\bar{C}_{ij} = \langle q_j^m,k_i^m\rangle/I_d; only gating heads through attention sinks (together with normalization scales) depends on the input, as in Eq. (2), so Tf⁡M,K,Q\operatorname{Tf}_{M,K,Q} is node-gated. In the full architecture § 3.2, MNorm is

彩大发快三 RMSNorm over vec⁡(M)\operatorname{vec}(M) and rescales all matrix-stream writers by one shared factor (Theorem A.1), while the bypass omo^m and (FFNx,FFNM)(\mathrm{FFN}_x,\mathrm{FFN}_M) become a fixed linear skip and a standard FFN on (x,vec⁡(M))(x,\operatorname{vec}(M)). The per-head Norm⁡(oi)\operatorname{Norm}(o_i) on LoomMHA writes (Eq. (8)) applies a fixed diagonal gain (absorbed into the write projection) and rescales writer WiW_i by dv/∥oi∥\sqrt{d_v}/\lVert o_i\rVert, and even if the scalar port gates σ(xWgW)\sigma(xW^W_g), σ(xWgR)\sigma(xW^R_g) (Eqs. (5)–(6)) are retained on static port directions, they multiply whole rows or columns of CC, leaving C=gg′TC = gg'^{\mathsf{T}} of rank at most one (cf. Section G). With ports generated per token, the computation at each token and layer coincides with that of Tfm⁡K(x),Q(x)\operatorname{Tfm}_{K(x),Q(x)}. The coincidence holds within a token; across tokens, attention mixes values computed by different members, so the model as a whole is not any single Tfm⁡K,Q\operatorname{Tfm}_{K,Q}.

Part (ii). Let SWS_W be the writers in a wiring pattern P⊆[w]×[r]P \subseteq[w] \times[r], with ∣SW∣≤dk\lvert S_W\rvert\le d_k. Turn on only SWS_W, pick an injection ι:SW→[dk]\iota:S_W \to[d_k], give each i∈SWi \in S_W the write key kim=eι(i)k_i^m = e_{\iota(i)} (kim=0k_i^m = 0 for i∉SWi \notin S_W), and give reader RjR_j the read query qjm=∑i∈SW:(i,j)∈Peι(i)q_j^m = \sum_{i\in S_W:(i,j)\in P}e_{\iota(i)}. Then ⟨qjm,kim⟩=1\langle q_j^m,k_i^m\rangle= 1 if (i,j)∈P(i,j)\in P and 00 otherwise for all i∈[w]i\in[w], so cij≠0c_{ij}\ne0 if and only if (i,j)∈P(i,j)\in P; since the virtual weights of the matrix stream are identities, the connected pairs are PP, with one head per reader and dkd_k independent of ww. The RMSNorm of the actual ports rescales each key and each query by a constant, and the sigmoid gates set their magnitudes (turning off writers outside SWS_W), so the pattern is realized up to per-reader scales. In the full model, computing ι\iota and PP from the vector stream is the role of the port generators on the control path.

Wiring matrices of residual-stream mechanisms

This section derives the entries of Table 1. As in § 2, we consider the wiring within a token from the earlier head writers (oi∈Rdo_i\in\mathbb{R}^d) to the query, key and value readers (uju_j) of one later layer. Other reads of the history—the FFN inputs of HC/mHC and AttnRes, the residual input of MUDDFormer and the bypass omo^m of LoomFormer—feed no head input and are not readers. We mark a port by (x)(x) if it is computed from the vector (residual) stream and by (M)(M) if it is computed from the memory itself. Per-token scales such as pre-LN are absorbed into the wiring matrix as in Theorem A.1, and the node-gating factors g,g′g,g' of Theorem 2.2 are common to all mechanisms, so we omit them from the tables. For LoomFormer we consider the matrix stream only and ignore MShift, which mixes neighbouring tokens (the d/4d/4-dimensional RoPE slice from xx belongs to the node-gated vector stream of Theorem 2.3). Ports are row vectors, as in § 3.1.

A common form. Each mechanism keeps at a token a memory MM of dkd_k slots of width dvd_v. Writer WiW_i adds kim⊗(oiWiO)k_i^m\otimes(o_iW_i^O) to MM, reader RjR_j receives uj=(qjmM)VjSu_j=(q_j^mM)V_j^S, and between layers MM may be updated linearly, M←ΦlMM\leftarrow\Phi_lM; here kimk_i^m and qjmq_j^m are the write and read ports, and WiO=WjS=IdW_i^O=W_j^S=I_d in the matrix stream of LoomFormer. Composing these steps gives

uj=∑i(qjmΦlilj(kim)T)oiWiOWjS,(12)u_j=\sum_i\left(q_j^m\Phi_{l_i l_j}(k_i^m)^{\mathsf{T}}\right)o_iW_i^OW_j^S, \tag*{(12)}

where Φlilj=Φlj−1⋯Φli\Phi_{l_i l_j}=\Phi_{l_j-1}\cdots\Phi_{l_i} is the product of the updates between the layer lil_i of WiW_i and the layer ljl_j of RjR_j: the wiring matrix has entries cij=qjmΦlilj(kim)Tc_{ij}=q_j^m\Phi_{l_i l_j}(k_i^m)^{\mathsf{T}} and the virtual weights are C~ij=WiOWjS\widetilde{C}_{ij}=W_i^OW_j^S. This representation is not unique: a change of slot basis by an invertible GG maps kim↦kimGTk_i^m\mapsto k_i^mG^{\mathsf{T}}, qjm↦qjmG−1q_j^m\mapsto q_j^mG^{-1} and Φl↦GΦlG−1\Phi_l\mapsto G\Phi_lG^{-1} without changing cijc_{ij}. For mechanisms that keep the outputs of all earlier layers, we use the basis in which every stored output has its own slot, the write port is elie_{l_i} and Φl=I\Phi_l=I; residual copies then become part of the read port. Transitions Φlilj\Phi_{l_i l_j} can also be absorbed into the ports without adding slots: for a fixed reader layer ljl_j, setting k~im=kimΦlilj\widetilde{k}_i^m=k_i^m\Phi_{l_i l_j} writes cij=⟨qjm,k~im⟩c_{ij}=\langle q_j^m,\widetilde{k}_i^m\rangle even when Φl\Phi_l is singular (and when every Φl\Phi_l is invertible, setting Φ~l=Φl−1⋯Φ1\widetilde{\Phi}_l=\Phi_{l-1}\cdots\Phi_1 makes this split independent of ljl_j via q~jm=qjmΦ~lj−1\widetilde{q}_j^m=q_j^m\widetilde{\Phi}_{l_j}^{-1} and k~im=kimΦ~li\widetilde{k}_i^m=k_i^m\widetilde{\Phi}_{l_i}). Table 5 lists the parameterization of each mechanism, justified below; Table 1 omits factors equal to 11 or II.

Write port kimk_i^mRead port qjmq_j^mUpdate Φl\Phi_l
Transformer111111
DenseFormerelie_{l_i}staticII
HC / mHCβli(M)\beta_{l_i}(M)αlj(M)\alpha_{l_j}(M)Ali(M)A_{l_i}(M)
AttnRes (full)Norm⁡(vli)\operatorname{Norm}(v_{l_i})static, softmaxII
MUDDFormerelie_{l_i}per Q/K/V, from xxII
LoomFormerper head, from xxper head and Q/K/V, from xxII

Table 5. Ports of residual-stream mechanisms in the common form of Eq. (12).

Transformer. One slot of width DD with kim=qjm=Φ=1k_i^m=q_j^m=\Phi=1 gives cij=1c_{ij}=1 and the virtual weights Cˉij=WiOWjs\bar{C}_{ij}=W_i^O W_j^s, with the node gates, this is Eq. (2).

DenseFormer. The input of each block is a static weighted sum of the embedding and the outputs of all earlier blocks, and the block adds its own attention and FFN outputs to this input through its internal residual [37]. Unfolding these residual copies, the input of block l′l' is a static combination of the outputs of all earlier blocks, so cijCˉij=⟨qljm,klim⟩WiOWjsc_{ij}\bar{C}_{ij}=\langle q_{l_j}^m,k_{l_i}^m\rangle W_i^O W_j^s with a static read port, so only node gating makes the wiring matrix input-dependent. DenseFormer keeps one slot per block, about ll slots at layer ll (size lDlD).

HC and mHC. HC keeps dkd_k parallel streams of width DD (we use dk=4d_k=4, the main configuration of Zhu et al. [63]). Each sub-layer reads αM\alpha M and updates the streams as M←AM+β⊤hM\leftarrow AM+\beta^\top h, with α\alpha, β\beta and AA all computed from MM in the dynamic version [63], and AA projected onto the Birkhoff polytope of doubly stochastic matrices in mHC [57]. Heads read and write through the attention sub-layer, with ports αl\alpha_l and βl\beta_l, while the FFN and subsequent attention stream-mixing matrices between attention sub-layers lil_i and ljl_j compose into Φlilj=Alilj\Phi_{l_i l_j}=A_{l_i l_j}. In the common form, cij=αljAliljβli⊤c_{ij}=\alpha_{l_j}A_{l_i l_j}\beta_{l_i}^\top—the unrolled weight of Eq. (27) of Zhu et al. [63], which Kimi Team [27] interpret as depth-wise linear attention with queries α\alpha and keys β\beta. Since all factors are computed from the streams MM, absorbing AliljA_{l_i l_j} into the write port as above (without requiring AltoA_{\mathrm{lto}} be invertible) gives the entry ⟨qljm(M),klim(M)⟩\langle q_{l_j}^m(M),k_{l_i}^m(M)\rangle of Table 1, with dkd_k-dimensional ports and state size dkD=4Dd_kD=4D.

AttnRes. Full AttnRes keeps the embedding and the outputs vmv_m of all earlier sub-layers, without a residual connection, and gives sub-layer m′m' the input ∑msoftmax⁡m⟨wm′,Norm⁡(vm)⟩vm\sum_m\operatorname{softmax}_{m}\langle w_{m'},\operatorname{Norm}(v_m)\rangle v_m with a learned query wm′w_{m'} [27]. In the slot basis of Eq. (12), writers of layer lil_i write to their attention sub-layer’s slot (elie_{l_i}, while FFN and embedding slots hold no head writer) and heads of layer ljl_j read linearly with the softmax weight vector over all stored slots; Table 1 and Table 5 instead display the underlying softmax query qljm=wljq_{l_j}^m=w_{l_j} (static) and key klim(M)=Norm⁡(vli)k_{l_i}^m(M)=\operatorname{Norm}(v_{l_i}) (from MM), normalized by softmax across all stored sub-layer slots. Full AttnRes keeps one slot per sub-layer, about 2l2l slots at layer ll (size 2lD2lD); its block variant sums the outputs within each block into one slot.

MUDDFormer. MUDDFormer keeps the embedding and the outputs of all earlier blocks, and gives the next block four inputs—for its queries, keys, values and residual—each a weighted sum of these outputs with weights generated from the latest hidden state [55]. The residual input carries dynamic combinations of earlier outputs into the next block output; unfolding these recursions expresses the effective read port qljm,s(x)q_{l_j}^{m,s}(x) of input s∈{Q,K,V}s\in\{Q,K,V\} as a function of the hidden states along the vector stream xx, giving cijCˉij=⟨qljm,s(x),klim⟩WiOWjsc_{ij}\bar{C}_{ij}=\langle q_{l_j}^{m,s}(x),k_{l_i}^m\rangle W_i^O W_j^s. Like DenseFormer, MUDDFormer keeps about ll slots at layer ll (size lDlD).

LoomFormer. The matrix stream keeps dkd_k slots of width dd that accumulate writes (Φl=I\Phi_l=I) and passes content without fixed projections: absorbing the per-token RMS scales of Norm⁡(oi)\operatorname{Norm}(o_i) and MNorm into kimk_i^m and qjm,sq_j^{m,s} (and the learned diagonal gain of Norm⁡(oi)\operatorname{Norm}(o_i) into the writer output oio_i) leaves Cˉij=Id\bar{C}_{ij}=I_d. Indexing a reader by its head j∈[n]j\in[n] and input s∈{Q,K,V}s\in\{Q,K,V\} as in Table 1 gives cij=⟨qjm,s(x),kim(x)⟩c_{ij}=\langle q_j^{m,s}(x),k_i^m(x)\rangle, with both ports generated per head and per token from the vector stream Theorem 3.1(ii). With dk=2nd_k=2n, MM has size dkd=2Dd_kd=2D, plus DD for the vector stream.

Wiring ranks. Node gating multiplies CC entrywise by gg⊤gg^\top—equivalently C↦diag⁡(g)Cdiag⁡(g′)C\mapsto\operatorname{diag}(g)C\operatorname{diag}(g')—which cannot increase its rank. All readers of a layer share one read port in DenseFormer, HC/mHC and AttnRes, so CC has a single distinct column and rank at most 1; MUDDFormer has one read port per Q/K/V input, hence at most three distinct columns and rank at most 3 (reached once at least three earlier layers are present with linearly independent Q/K/V read ports). In LoomFormer every reader has its own query, so the rank is that of KQ⊤KQ^\top restricted to the 3n3n readers of the layer, at most min⁡(w,dk,3n)\min(w,d_k,3n)—hence min⁡(dk,3n)\min(d_k,3n) once w≥min⁡(dk,3n)w\geq\min(d_k,3n), reached whenever the writer keys and reader queries span a common min⁡(dk,3n)\min(d_k,3n)-dimensional subspace.

Linear attention. The same form describes linear attention along the sequence instead of depth: the writers and readers are one head at different tokens, MM is the head’s private state, the ports are its keys and queries, and the update Φ\Phi distinguishes the variants—II for linear attention [25], a scalar decay in Mamba2 (Dao & Gu, 2024), a gated diagonal in gated linear attention [58], I−βk⊤kI-\beta_k^\top k in DeltaNet [59], and γ(I−βk⊤k)\gamma(I-\beta_k^\top k) in Gated DeltaNet [60]. It differs from LoomFormer in the axis and the sharing of the state (§ 4).

Extended Related Work

Cross-layer connections and residual-stream architectures. Beyond standard residual connections ((He et al., 2016)), early work strengthened depth-wise signal propagation through input-dependent gating in Highway Networks ([45]) and all-to-all layer aggregation with static or learnable weights in DenseNet ([24]), DLCL ([52]) and DenseFormer ([37]). Subsequent architectures introduced cross-layer attention over earlier layer representations ([13, 15, 51, 27]), multi-stream residual states with dynamic or manifold-constrained mixing in HC and mHC ([63, 57]), and decoupled Q/K/V/residual layer aggregation in MUDDFormer ([55]). As analyzed in § 4 and Section A.7, all of these mechanisms operate at the granularity of whole layers (or layer ×\times Q/K/V), summing the outputs of all heads within a layer before routing and restricting the within-token wiring rank to 1 (or 3).

The Residual Matrix Transformer (RMT) ([33]) replaces the vector residual stream entirely with a pure matrix residual stream, which heads and FFNs read and write through static key vectors so the stream can be widened cheaply. LoomFormer instead keeps a dual-stream architecture that separates control on the vector stream from content on the matrix stream: the compact vector stream generates per-token ports cheaply, whereas RMT’s static ports fall under Theorem 3.1(i) and remain node-gated however wide the matrix is made (4DD in RMT’s main configuration vs. 2DD + DD in LoomFormer).

Cross-layer token attention and KV sharing. OmniNet ([47]) lets every token attend directly to all tokens across all layers, incurring attention cost quadratic in LTLT; loom attention instead factors cross-layer routing within each token through a fixed-size matrix memory MM in O(LTDdk)O(LT D d_k) time and composes it with standard within-layer horizontal attention. Cross-Layer Attention (CLA) ([4]) shares key-value caches across adjacent layers to reduce inference memory at a modest quality trade-off, whereas loom attention dynamically composes earlier head outputs into distinct per-head queries, keys and values at every layer (§ 5.3).

Mechanistic interpretability and intra-layer advances. Circuit-level interpretability studies ([11, 36, 7, 21, 34] (Ni et al. 2025)) show that Transformers implement tasks by composing specific upstream and downstream heads across layers; loom attention turns this implicit, static composition into an explicit, per-token operation over MM. Orthogonal intra-layer advances—including improved horizontal attention ([31, 54] (Ye et al. 2024; Levithian et al. 2024)), sequence-axis linear attention and state-space models ([39, 59, 60] (Gu & Dao 2024; Dao & Gu 2024)), and sparse Mixture-of-Experts FFNs ([16, 8]})—modify horizontal mixing or FFN capacity within a layer and can be combined directly with loom attention along depth.

PyTorch-Style Pseudocode for LoomFormer

# b = batch size, t = seq len, n = num_heads, d = head_dim
# k = num_slots d_k, r = RoPE dim d // 4. M is of shape btkd

def MRead(M, x, xr):
    qm = rearrange(xr @ W_r2, 'bt (nk)->btnk')
    qm = rmsnorm(qm) * sigmoid(rearrange(x @ W_rg, 'btn->btn1'))
    qm += q_bar * sigmoid(rearrange(x @ W_rg_bar, 'btn->btn1')) # nk,btn1->btnk
    u = einsum('btnk,btkd->btnd', qm, M)
    return u


def MWrite(o, x, xw):
    km = rearrange(xw @ W_w2, 'bt (nk)->btnk')
    km = rmsnorm(km) * sigmoid(rearrange(x @ W_wg, 'btn->btn1'))
    dM = einsum('btnk,btnd->btkd', km, o)
    return dM


def MShift(M, x):
    M_prev = shift_right(M, 1, dim=1)  # shift t dim of btkd
z = sigmoid(rearrange(x @ W_sg, 'btk->btk1'))
return z * M_prev + (1 - z) * M

def loom_mha(x, M, write_M=True):
    M = RMSNorm(MShift(M, x), dim=(-2, -1))
    xr, xw = gelu(x @ W_r1), gelu(x @ W_w1)
    q, k, v, o = [MRead[s](M, x, xr) for s in ['q', 'k', 'v', 'o']]
    qr = rope(rearrange(x @ W_q, 'bt(nr)->btnr'))
    kr = rope(rearrange(x @ W_k, 'bt(nr)->btnr'))
    q, k = concat([qr, q], dim=-1), concat([kr, k], dim=-1)

    allow_mask = tril(ones(T, T), diagonal=-1) # strictly causal mask
    o = o + MHA(q, k, v, allow_mask=allow_mask)
    dx = rearrange(o, 'btnd->bt(nd)') @ W_o
    dM = MWrite(RMSNorm(o, dim=-1), x, xw) if write_M else 0.
    return dx, dM

def ffn(x, write_M=True):
    xw = gelu(x @ W_w1)
    dx = _ffn_x(x)
    dM = MWrite(rearrange(_ffn_m(x), 'bt(nd)->btnd'), x, xw) if write_M else 0.
    return dx, dM

def loomformer(input_ids):
    x = embedding(input_ids)
    o = rearrange(x @ W_e, 'bt(nd)->btnd')
    M = MWrite(o, x, gelu(x @ W_w1))

    for l in range(L):
        write_M = l < L - 1
        # pairs are added element-wise: (x, M) + (dx, dM) = (x + dx, M + dM)
        (x, M) = (x, M) + loom_mha[l](ln_1[l](x), M, write_M=write_M)
        (x, M) = (x, M) + ffn[l](ln_2[l](x), write_M=write_M)
    return unembedding(ln_f(x))

Experimental Configurations, Baselines and Benchmarks

Model Configurations and Hyperparameters

Table 6 lists the architectural dimensions, peak learning rates and token budgets across all four LoomFormer scales (§ 5.1 and § 5.2). In blocks 0, . . . , L−2L - 2, FFNx_x and the FFNM_M write branch (FFNM_M plus its MWrite module) follow a 2:1 parameter ratio (rounded to multiples of 128 at 2.8B, giving 2.2:1), while block L−1L - 1 (last) omits unused writes to MLM_L and widens FFNx_x to match the baseline Transformer’s total parameter count. Table 7 lists the training hyperparameters for the scaling-law experiments (§ 5.1; weight decay is excluded on normalization scales and biases, including gate biases), while the 2.8B models (§ 5.2) follow Pythia-2.8B (Biderman et al., [2]). To improve training stability at the XL scale, LoomFormer-XL replaces SwiGLU in FFNx_x with Kimi K3’s bounded SiTU-GLU activation (Kimi Team, [28]) with β1=4\beta_1 = 4, β2=7\beta_2 = 7.

ModelParamsLLDDD/LD/LnnddDrD_rTfm FFNFFNx_x (last)FFNM_MLRTokens
Medium432M18120066.7167525632002510 (3904)11283.0e-47B
Large778M22153669.8169625640963317 (5083)15392.5e-414B
XL1.4B28192068.6209640051204048 (6277)18272.0e-426B
2.8B2.8B322560803280640102407808 (9984)29441.6e-4300B

Table 6. Model configurations across scales. dk=2nd_k = 2n; shared port-feature width Dr=ndk/2=n2D_r = nd_k/2 = n^2, capped at D/4=640D/4 = 640 at 2.8B.

HyperparameterValueHyperparameterValue
OptimizerAdamWSequence length4096
(β1,β2)(\beta_1, \beta_2)(0.9, 0.95)Batch size (seqs)128
ϵ\epsilon10−810^{-8}Vocab size50,432
Weight decay0.1Tied embeddingsFalse
Gradient clipping1.0Linear biasFalse
LR scheduleCosineNormalizationRMSNorm (ϵ=10−6\epsilon= 10^{-6})
Min LR ratio0.1FFN activationSwiGLU
Warmup fraction0.01Positional emb.RoPE (θ=10,000\theta= 10{,}000)
Dropout0.0PrecisionBF16

Table 7. Training hyperparameters for the scaling-law experiments (§ 5.1).

Port and gate initialization. Each gate projection in Eqs. (5)–(7) includes a learnable bias (omitted in § 3.2 for brevity) that sets its initial opening. Specifically, the gate projection weights are initialized to zero, with biases setting initial gate values to 0.05 on the dynamic read branch, 0.9 on the static read branch, 0.1 on the write branch, and 0.5 on MShift (zˉt\bar{z}_t). For the static queries qˉ∈Rdk\bar{q} \in\mathbb{R}^{d_k}, value reads vv are initialized from N(0,1/dk)\mathcal{N}(0, 1/d_k), whereas q~\tilde{q}, k~\tilde{k} and omo^m start at qˉ=0\bar{q} = 0 so memory-read Q/K coordinates and the output bypass grow in gradually.

Scaling-Law Baselines

All baselines in § 5.1 are trained in JAX/MaxText on the identical data order, tokenizer and schedule as LoomFormer:

  • Transformer++: Llama-style pre-norm Transformer (Touvron et al., [48]) with RoPE (Su et al., 2024), SwiGLU FFN (Shazeer, [43]), RMSNorm and no linear biases.

  • DHC: Dynamic Hyper-Connections with expansion rate dk=4d_k = 4 and tanh-bounded dynamic routing following Zhu et al. [63].

  • mHC: Manifold-constrained Hyper-Connections (dk=4d_k = 4 streams) projecting the stream-mixing matrix onto the Birkhoff polytope via Sinkhorn normalization (Xie et al., [57]).

  • AttnRes (full): Full Attention Residuals aggregating all preceding sub-layer outputs per sub-layer via learned depth-wise softmax queries (Kimi Team, [27]).

  • MUDDFormer: Multiway Dynamic Dense connections generating per-token depth-aggregation weights separately for the query, key, value and residual inputs of each block (Xiao et al., [55]).

Downstream Evaluation Benchmarks

In addition to the benchmarks used by Pythia (Biderman et al., [2])—LAMBADA (Paperno et al., [38]), PIQA (Bisk et al., [3]), WinoGrande (Sakaguchi et al., [41]), ARC-Easy/Challenge (Clark et al., [6]) and SciQ (Welbl et al., 2017)—we evaluate BoolQ (Clark et al., [5]) and HellaSwag (Zellers et al., [62]) for commonsense reasoning, and RACE-Middle/High (Lai et al., [29]) for reading comprehension (Table 2), all under LM Evaluation Harness (Gao et al., [19]) in zero-shot and five-shot settings.

Details of Complexity Analysis

We derive the forward-FLOP overhead in Table 3 under a matched parameter budget, following the counting convention of DCFormer (Xiao et al., [54]) and MUDDFormer (Xiao et al., [55]). Let LL be the number of layers, TT the sequence length, DD the model width, nn the number of heads, d=D/nd = D/n the head dimension, and M∈Rdk×dM \in\mathbb{R}^{d_k \times d} the matrix memory. We report FLOPs per sequence at two FLOPs per multiply-add, omitting the shared token embedding and unembedding as well as normalization, nonlinearities, biases and other elementwise operations (such as gate activations and the elementwise mixing in MSShift). Causal attention has approximately T2/2T^2/2 query–key pairs; using a strictly rather than inclusively causal mask changes only the lower-order diagonal terms.

Parameter budget and tokenwise projections. The reference Transformer has 4D24D^2 attention and 8D28D^2 FFN weights per layer, for a total of P0=12LD2P_0 = 12LD^2 (applying to both a GELU FFN of hidden width 4D4D and a SwiGLU FFN of hidden width 8D/38D/3). LoomFormer replaces the full Q/K/V projections with smaller RoPE projections and matrix reads, redistributing the saved parameter budget among the port generators, FFNx_x and FFNM_M, as well as the initial value projection WEW^E and embedding MWrite (Eq. (10)), so that PLoom=P0P_{\mathrm{Loom}} = P_0.

Every tokenwise dense matrix WW costs 2T∣W∣2T|W| FLOPs, where ∣W∣|W| is its number of entries. Consequently, to leading order, the combined projection and FFN cost is 2TP02TP_0 in both models. This includes both stages of the low-rank port generators, all projected gates (including WgSW^S_g in MShift), WEW^E, FFNx_x and FFNM_M; a shared projection is counted once. Adding the port-generation or FFNM_M FLOPs without subtracting the FFNx_x FLOPs that paid for their weights would double-count them. Static ports, learned normalization scales and biases give only lower-order corrections to this dense-weight relation, and for the same reason the bottleneck width DrD_r affects parameter allocation without entering the leading net FLOP overhead.

Reference Transformer FLOPs. In addition to the tokenwise projections and FFNs, each layer computes QKTQK^{\mathsf{T}} and attention-weighted values. Each costs 2nd⋅T2/2=DT22nd \cdot T^2/2 = DT^2 FLOPs under the causal approximation. The reference forward cost is therefore

F0=2TP0+2LDT2=2LDT(12D+T).(13)F_0 = 2TP_0 + 2LDT^2 = 2LDT(12D + T). \tag*{(13)}

Reading and writing the matrix memory. A single MRead contracts a dkd_k-dimensional port with M∈Rdk×dM \in\mathbb{R}^{d_k \times d}, at a cost of 2dkd2d_kd FLOPs per token. Its dynamic and static ports are summed before this contraction (Eq. (5)), so they do not require two separate reads. With four reads per head and nn heads, the LL layers cost

Fread=4⋅2Tnddk⋅L=8LTDdk.(14)F_{\mathrm{read}} = 4 \cdot2Tndd_k \cdot L = 8LTDd_k. \tag*{(14)}

For each writing sub-layer, MWrite sums nn outer products of shape dk×dd_k \times d, costing 2Tnddk=2TDdk2Tndd_k = 2TDd_k FLOPs. There are two such sub-layers per block, attention and FFNM_M, except in the last block, which does not write to MM. The embedding adds one initial write of the same size (Eq. (10)). Hence

Fwrite=4(L−1)TDdk+2TDdk,FM=Fread+Fwrite=(12L−2)TDdk≃12LTDdk.(15)\begin{aligned} F_{\mathrm{write}} &= 4(L-1)TDd_k + 2TDd_k,\\ F_M &= F_{\mathrm{read}} + F_{\mathrm{write}} = (12L-2)TDd_k \simeq12LTDd_k. \tag*{(15)} \end{aligned}

The last approximation neglects the small endpoint factor 1−1/(6L)1 - 1/(6L) multiplying the memory-overhead term. Since MM has a fixed size, the read/write cost per layer does not increase with depth.

Wider query and key. In the reference Transformer, Q, K and V each have dd coordinates per head. LoomFormer concatenates d/4d/4 RoPE coordinates to the dd coordinates of Q/K read from MM (Eq. (7)), while V retains width dd. Thus only the QKTQK^{\mathsf{T}} contraction is wider; the attention-weighted value contraction is unchanged. The extra cost is

ΔFQK=2Lnd4⋅T22=LDT24.(16)\Delta F_{QK} = 2Ln\frac{d}{4}\cdot\frac{T^2}{2} = \frac{LDT^2}{4}. \tag*{(16)}

Total overhead and scaling. Combining Eqs. (13)–(16) gives

RΔFLOPs≃12LTDdk+LDT2/42LDT(12D+T)=dk2D(1+ρ/12)+18(1+12/ρ).(17)R_{\Delta\mathrm{FLOPs}} \simeq\frac{12LTDd_k + LDT^2/4}{2LDT(12D+T)} = \frac{d_k}{2D(1+\rho/12)} + \frac{1}{8(1+12/\rho)}. \tag*{(17)}

where ρ=T/D\rho= T/D. With D=ndD = nd and dk=2nd_k = 2n, we have dk/(2D)=1/dd_k/(2D) = 1/d, giving the expression in § 6:

RΔFLOPs≃1d(1+ρ/12)⏟MRead/MWrite+18(1+12/ρ)⏟wider Q/K.(18)R_{\Delta\mathrm{FLOPs}} \simeq\underbrace{\frac{1}{d(1+\rho/12)}}_{\mathrm{MRead/MWrite}} + \underbrace{\frac{1}{8(1+12/\rho)}}_{\mathrm{wider\ Q/K}}. \tag*{(18)}

At fixed ρ\rho, the matrix read/write term scales as 1/d1/d while the wider-Q/K term is independent of dd; as ρ\rho grows, the first term falls from 1/d1/d toward 00 and the second rises toward 1/81/8, with both independent of LL at leading order. In Table 3 (d=75,96,96,80d = 75, 96, 96, 80 and ρ=T/D=3.41,2.67,2.13,0.80\rho= T/D = 3.41, 2.67, 2.13, 0.80 for Medium, Large, XL and 2.8B, using T=4096T = 4096 at Medium/Large/XL and T=2048T = 2048 at 2.8B; Table 6), Large, XL and 2.8B have integer d/4d/4 and follow Eq. (18) directly (3.13%, 2.77% and 1.95%), whereas Medium rounds its RoPE width d/4=75/4d/4 = 75/4 to ⌊d/4⌋=18\lfloor d/4 \rfloor= 18 in Eq. (16), giving 3.70% instead of Eq. (18)’s unrounded 3.81% (retaining 12L−212L - 2 in Eq. (15) changes every row by < 0.01 percentage points). For a backbone with a different FFN parameter ratio, one can retain the general denominator 2TP0+2LDT22TP_0 + 2LDT^2 instead of substituting P0=12LD2P_0 = 12LD^2. Wall-clock training and inference speeds are detailed in Section F.

Training and Inference Throughput Details

Training throughput. Table 8 reports paired training benchmarks in JAX/MaxText on TPU v5p pods at each model’s training configuration (§ 5.1 and § 5.2), with both Transformer and LoomFormer using Splash attention (1024-token blocks and fused backward). LoomFormer executes custom Pallas kernels (forward and backward) that fuse MShift, MNorm, port normalization and gating, and the four MReads of all nn heads into one per-token (4n×dk)×(dk×d)(4n \times d_k) \times(d_k \times d) MXU matrix multiplication in VMEM, and likewise fuse MWrite’s nn-head outer-product accumulation, avoiding intermediate HBM traffic on MM. We compare median XPlane device step time under full activation rematerialization on both sides (Table 3). At 2.8B, LoomFormer uses 512-token cross-entropy chunking to fit v5p-128 HBM whereas Pythia-2.8B does not, making the 2.8B ratio slightly conservative.

ModelPodTTBatch (seqs)Tfm (ms)Loom (ms)Relative speed
Mediumv5p-1640961281224135290.5%
Largev5p-324096128962107889.2%
XLv5p-3240961281590172392.3%
2.8Bv5p-128204810242988323392.4%

Table 8. TPU v5p training step time and relative throughput of LoomFormer (Loom) vs. Transformer (Tfm).

Inference throughput on NVIDIA A800. Table 9 reports BF16 inference throughput on a single NVIDIA A800-80GB PCIe GPU (torch 2.14 / triton 3.8 / cuDNN 9.24) using trained checkpoints at all four scales, taking the median over five measurements. LoomFormer executes one fused Triton kernel per layer covering the preceding write, the MShift read view, the four MReads, RoPE and cache updates, together with grouped decode GEMVs for the small port projections; prefill uses each model’s fastest SDPA backend (FlashAttention for Transformer; cuDNN SDPA for LoomFormer, whose Q/K head width 1.25d1.25d differs from V width dd). Prefill measures one uncached forward pass of B×TB \times T tokens, and decode measures single-token generation steps after a (T−64)(T - 64)-token prompt under torch.compile(mode="max-autotune") with CUDA graphs.

ModelPrefill bs 1Prefill bs 8Decode bs 1Decode bs 16Decode bs 64
Medium87.4% (148.9k/170.3k)90.4% (166.0k/183.5k)91.7% (565/616)89.2% (2109/2365)92.3% (2499/2709)
Large85.3% (95.3k/111.7k)86.2% (104.0k/120.6k)85.4% (438/513)87.8% (1916/2183)84.9% (2311/2721)
XL83.8% (50.8k/60.6k)85.3% (55.3k/64.9k)86.9% (272/313)84.6% (1245/1472)86.6% (1452/1677)
2.8B87.5% (30.4k/34.7k)90.5% (33.1k/36.6k)86.4% (171/198)87.6% (1248/1425)88.9% (1836/2066)

Table 9. BF16 inference throughput on one NVIDIA A800-80GB GPU, reported as relative throughput and absolute tokens/s (Loom / Tfm); T=4096T = 4096 for Medium, Large and XL, and T=2048T = 2048 for 2.8B.

Extended Ablation Studies

Table 10 reports the complete 18-variant ablation suite at the Medium scale (L=18L = 18, D=1200D = 1200, n=16n = 16, d=75d = 75, dk=32d_k = 32, Dr=256D_r = 256, RoPE dim ⌊d/4⌋=18\lfloor d/4 \rfloor= 18, T=4096T = 4096, 7B tokens), extending Table 4. In full LoomFormer, FFNM_M has SwiGLU hidden width 1128, and FFNX_X has width 2510 in blocks 0–16 and 3904 in block 17 (which omits unused writes to MLM_L). Whenever an ablation removes parameters, we widen FFNX_X uniformly across blocks 0–16 and absorb any embedding or integer-rounding residual in block 17, matching the 432.11M parameter budget within ±1.4K (< 0.0004%).

VariantSpecification (vs. full LoomFormer)Loss↓ΔLossGain
LoomFormer (full)†—2.266—100.0%
Transformer++ (baseline)†Standard MHA + SwiGLU FFN, no matrix stream MM2.443+0.1770.0%
Dynamic rewiring & write-port gating (Theorem 3.1)
Static LoomMHA kMmk_M^m, gatedStatic kMmk_M^m in LoomMHA; write gate σ(xWgW)\sigma(xW_g^W) kept2.2660.000100.0%
Static LoomMHA kMmk_M^mStatic kMmk_M^m in LoomMHA; write gate dropped (≡ 1)2.282+0.01691.1%
Static FFNM_M kmk^m, gatedStatic kmk^m in FFNM_M; write gate σ(xWgW)\sigma(xW_g^W) kept2.268+0.00199.3%
Static FFNM_M kmk^mStatic kmk^m in FFNM_M; write gate dropped (≡ 1)2.272+0.00696.6%
Static write keys (kmk^m), gatedStatic kmk^m in emb., LoomMHA, FFNM_M; write gates kept2.274+0.00895.6%
Static write keys (kmk^m)†Static kmk^m in emb., LoomMHA, FFNM_M; write gates dropped2.283+0.01790.3%
Static read queries (qmq^m)†Only static qˉ\bar q in MReadQ,K,V,O; all read gates dropped2.310+0.04375.4%
Static read & write (qm,kmq^m,k^m), gatedStatic qmq^m (no read gates), all kmk^m; write gates kept2.327+0.06065.8%
Static read & write (qm,kmq^m,k^m)†Static qmq^m, all kmk^m; port gates dropped (TfmK,Q + MShift)2.344+0.07856.0%
Static read & write (qm,kmq^m,k^m), − MShiftStatic qmq^m, all kmk^m; port gates, MShift dropped (Prop. 3.1(i))2.348+0.08253.6%
Port normalization & gating (Eqs. (5)–(6))
− dynamic port gates†σ(xWgR),σ(xWgW)≡1\sigma(xW_g^R),\sigma(xW_g^W)\equiv1; σ(xWgˉR)\sigma(xW_{\bar g}^R) and MShift kept2.277+0.01193.7%
− dynamic port Norm†Drop Norm on dynamic qm,kmq^m,k^m; Norm(oio_i), MNorm kept2.289+0.02387.1%
− dynamic port gates & Norm†Drop both σ(xWgR),σ(xWgW)\sigma(xW_g^R),\sigma(xW_g^W) and port Norm2.283+0.01790.3%
Sub-layer components (§ 3.2)
− FFNM_M write†Remove FFNM_M and its MWrite (Eq. (9))2.300+0.03480.7%
− output bypass omo^m†Drop MReadO^O; restore self-attention to current token (Eq. (8))2.299+0.03281.8%
− vector-stream RoPE WQ,KW^{Q,K}†Drop WQ,KW^{Q,K}; RoPE on 18 of 75 dims of q~,k~\tilde q,\tilde k (Eq. (7))2.286+0.02088.7%
− MShift†Set z[t]≡0z[t]\equiv0 in Eq. (7)2.277+0.01094.2%
− LoomMHA write Norm(oio_i)Drop Norm on oio_i in LoomMHA writes (Eq. (8))2.268+0.00298.8%

Table 10. Complete Medium-scale (432M) ablation suite of LoomFormer under a matched parameter budget (432.11M ± 1.4K). †Included in Table 4.

Write-port gating vs. slot selection, and reduction to TfmK,Q_{K,Q}. Fixing write keys kmk^m to learned static vectors while keeping their dynamic gates σ(xWgW)\sigma(xW_g^W) preserves nearly the full gain (100.0% for LoomMHA, 99.3% for FFNM_M, and 95.6% across all three write sites including the embedding). Dropping the gate on static kmk^m, however, hurts LoomMHA over three times as much as FFNM_M (100.0% → 91.1% vs. 99.3% → 96.6%): LoomMHA normalizes its head outputs Norm⁡(oi)\operatorname{Norm}(o_i) before writing (Eq. (8)), leaving the gate as the sole control of write magnitude (and whether a head is on), whereas FFNM_M writes unnormalized slices (Eq. (9)) whose norms can still modulate write strength per token. When both qmq^m and kmk^m are static, retaining dynamic write gates gives a node-gated circuit on fixed slots (65.8%), dropping those gates leaves TfmK,Q_{K,Q} with MShift (56.0%), and further removing MShift yields the exact TfmK,Q_{K,Q} of Theorem 3.1(i) (53.6%)—which has no token-dependent port or shift gates on MM, yet still outperforms all layer-wise dynamic baselines at the same scale (Figure 5, where MUDDFormer reaches 48.5% of LoomFormer’s gain).

Attention write-value normalization. Removing Norm(oio_i) from LoomMHA writes (Eq. (8)) loses only 1.2% of the gain (98.8% retained), as whole-matrix pre-normalization MNorm before reads (Eq. (7)) already bounds the scale of MM.

Mechanistic Analysis Details and Visualizations

Evaluation protocol and linear attribution. The statistics in § 5.3 and this section are computed on held-out Pile validation sequences of length T=2048T=2048 at the 300B-token checkpoints of Pythia-2.8B, mHC-Pythia-2.8B and LoomPythia-2.8B (evaluating token positions t≥64t\ge64 to avoid sequence-boundary transients). Because MShift and MNorm act linearly on the accumulated writes at each layer (Equation (7)), absorbing the per-slot shift gate z[t]z[t] (or 1−z[t]1-z[t]) and the scalar MNorm factor into cij=⟨qim,kjm⟩c_{ij}=\langle q_i^m,k_j^m\rangle decomposes every MRead output as uj=∑icijoiu_j=\sum_i c_{ij}o_i over all earlier writers (embedding, LoomMHA and FFNM_M writes at tt and t−1t-1; 0.4% median RMS difference from BF16 execution across layers). Projecting each term onto uju_j gives the additive writer attribution

aij=cij⟨oi,uj⟩∥uj∥2,∑iaij=1.(19)a_{ij}=\frac{c_{ij}\langle o_i,u_j\rangle}{\lVert u_j\rVert^2},\qquad\sum_i a_{ij}=1. \tag*{(19)}

Definitions for Figure 6. In Figure 6(a), to isolate dynamic port rewiring from both static virtual weights (Theorem 3.1(i)) and per-token scalar gate or writer-norm fluctuations, let q^jm(t)=qjm(t)/∥qjm(t)∥2\hat q_j^m(t)=q_j^m(t)/\lVert q_j^m(t)\rVert_2 and k^im(t)=kim(t)/∥kim(t)∥2∈Sdk−1\hat k_i^m(t)=k_i^m(t)/\lVert k_i^m(t)\rVert_2\in\mathbb{S}^{d_k-1} denote the unit port directions of reader jj and same-token writer ii, weighted by each writer’s corpus RMS norm ωˉi=Et[∥oi(t)∥2]\bar\omega_i=\sqrt{\mathbb{E}_t[\lVert o_i(t)\rVert^2]}. Cij(t)=ωˉi⟨q^jm(t),k^im(t)⟩C_{ij}(t)=\bar\omega_i\langle\hat q_j^m(t),\hat k_i^m(t)\rangle. We center across tokens, ΔC^(t)=C^(t)−Et′[C^(t′)]\Delta\hat C(t)=\hat C(t)-\mathbb{E}_{t'}[\hat C(t')], and report the energy effective rank exp⁡(−∑kpklog⁡pk)\exp(-\sum_k p_k\log p_k) with pk=σk2/∑k′σk′2p_k=\sigma_k^2/\sum_{k'}\sigma_{k'}^2, where the 3n=963n=96 Q/K/V readers of layer ll (or the n=32n=32 readers of a single Q, K or V input); under fixed-port TfmK,Q_{K,Q} with arbitrary positive scalar gates, ΔC^(t)=0\Delta\hat C(t)=0. In Figure 6(b), for each read port qjm(t)∈Rdkq_j^m(t) \in\mathbb{R}^{d_k} (q~,k~,v,om\tilde{q},\tilde{k},v,o^m) and write port kim(t)∈Rdkk_i^m(t) \in\mathbb{R}^{d_k} (LoomMHA and FFNM_M), we average 1−cos⁡(p(t1),p(t2))1-\cos(p(t_1),p(t_2)) over distinct token pairs t1≠t2t_1 \ne t_2 (t≥64t \ge64) and over the n=32n=32 heads of layer ll (embedding write ports remain near-static at 0.005, providing a sanity check). In Figure 6(c), following Xiao et al. (2025), a head is on at query position tt if arg⁡max⁡sαts\arg\max_s \alpha_{ts} falls neither in {0,1}\{0,1\} nor on a sink token (<|endoftext|>, ".", " .", "\n", "\n\n"); in layers 17–32, first-two-token sink mass drops from 26.4% (Pythia) and 27.2% (mHC) to 1.5% in LoomPythia while content-token attention mass rises from 22.7% and 31.2% to 65.4%, and masking the self-diagonal s=ts=t in Pythia and mHC to match LoomMHA’s strict causal mask (Equation (8)) leaves the gap unchanged (74.4% vs. 21.2% and 15.7%). In Figure 6(d), for each head hh in layers 3–32 and each pair among its four ports {q~h,k~h,vh,ohm}\{\tilde{q}_h,\tilde{k}_h,v_h,o_h^m\}, we compute from token-averaged positive attributions aˉij+=Et[max⁡(aij(t),0)]\bar{a}_{ij}^{+}=\mathbb{E}_t[\max(a_{ij}(t),0)] over same-token writers: (i) Pearson correlation after summing attributions by writer group (Emb, each earlier LoomMHA layer, each earlier FFNM_M layer), (ii) Pearson correlation across individual head/module writers, and (iii) ∣SA∩SB∣/32|S_A\cap S_B|/32 for the top-32 writer sets SA,SBS_A,S_B, reporting the median across heads (in slot space Rdk\mathbb{R}^{d_k}, same-token cosine similarity between ports of the same head averages 0.01–0.07 outside Q–K and 0.27 on Q–K).

Writer composition and depth-to-depth routing. Averaged over layers 2–32 in LoomPythia-2.8B, positive attribution mass max⁡(aij,0)\max(a_{ij},0) is shared across LoomMHA writes (53.4%–62.5% across q~,k~,v,om\tilde{q},\tilde{k},v,o^m), FFNM_M writes (27.5%–35.2%) and embedding writes (10.0%–11.7%), while previous-token MShift reads account for 13.7%–15.2% of ∑i∣aij∣\sum_i|a_{ij}| (Figure 8(a)). FFNM_M reaches its largest share (35.2%) on value reads vv, consistent with FFNM_M serving as the sole post-embedding channel from the vector stream into MM (Equation (9)) and with its large effect in Table 4. Plotted with writer sources on the vertical axis (bottom to top) and reader layers on the horizontal axis, the column-max normalized routing map (Figure 8(b)) combines local relay along the diagonal with persistent horizontal bands from hub writer sources—most prominently the embedding at early layers and writer layers 13–14 and 19 across all subsequent layers.

Figure 8. Matrix-stream routing in LoomPythia-2.8B across Pile validation sequences. (a) Share of positive attribution from Embedding, LoomMHA and FFNM_M writes, and share of ∣aij∣|a_{ij}| from previous-token MShift (Mt−1M_{t-1}). (b) Column-max normalized positive attribution from each writer source (vertical, bottom to top) to each reader layer ll (horizontal; gray upper triangle: causally unreachable).

Adjacent-token rewiring on an in-context prompt. Figure 9 shows the head-writer attribution submatrix [aij][a_{ij}] at hub layer 19 (selecting the top 6 readers per MRead arm and top 18 earlier LoomMHA head writers by peak ∣aij∣|a_{ij}| across the two tokens) on "France: Paris\nJapan: Tokyo\nChina: Beijing\nSpain: Madrid\nGermany:", where LoomPythia-2.8B predicts " Berlin" top-1 with probability 0.65. At "Germany" (Figure 9(a)), writers route selectively to distinct MRead arms—L13.H11 feeds key reads (k~\tilde{k}: K14,K23,K25) without feeding value or bypass reads, whereas L13.H12 and L08.H25 feed value and bypass reads (V10,O09,O22)—forming a non-rectangular within-token pattern (Theorem 2.3) that appears "Germany"’s horizontal keys, values and residual state. At the immediately following delimiter ":" (Figure 9(b)), LoomMHA’s strict causal mask (s<ts<t, Equation (8)) means that only q~\tilde{q} (attending back to "Germany" and the few-shot capitals) and omo^m affect the " Berlin" prediction, whereas k~\tilde{k} and vv at ":" serve only future tokens. Correspondingly, L13.H11 and L13.H12 switch off on layer 19, while layer 19 rewires its causal query reads q~\tilde{q} onto L18.H25, L15.H32 and L14.H01 (Q06,Q07,Q17,Q22) and its bypass outputs omo^m onto L14.H06, L16.H29 and L14.H19 (O16,O21); causally freezing layer 19’s dynamic read ports at ":" to those at "Germany" alone drops P("Berlin")P(" Berlin") from 0.65 to 0.54 (0.41 when frozen across all layers).

Attribution submatrices showing Layer 19 wiring and rewiring

Figure 9. Attribution submatrix [aij][a_{ij}] (rows: top-18 earlier head writers Ll.HhL_l.H_h; columns: top-6 layer-19 MRead outputs per arm q~,k~,v,om\tilde{q}, \tilde{k}, v, o^m) of LoomPythia-2.8B at two consecutive tokens of an in-context prompt (next-token top-1: " Berlin", p=0.65p = 0.65), showing non-rectangular within-token wiring at "Germany" (a) and per-token rewiring onto causal q~\tilde{q} and omo^m pathways at ":" (b; hatched k~,v~\tilde{k}, \tilde{v} columns affect only future tokens under s<ts < t).

References

  1. [1]with pathways. Journal of Machine Learning Research, 24(240):1–113, 2023.arxiv.org/abs/2204.02311
  2. [2]Biderman, S., Schoelkopf, H., Anthony, Q. G., Bradley, H., O’Brien, K., Hallahan, E., Khan, M. A., Purohit, S., Prashanth, U. S., Raff, E., et al. Pythia: A suite for analyzing large language models across training and scaling. In International Conference on Machine Learning (ICML), pp. 2397–2430. PMLR, 2023.arxiv.org/abs/2304.01373
  3. [3]Bisk, Y., Zellers, R., Gao, J., Choi, Y., et al. Piqa: Reasoning about physical commonsense in natural language. In Proceedings of the AAAI conference on artificial intelligence, volume 34, pp. 7432–7439, 2020.arxiv.org/abs/1911.11641
  4. [4]Brandon, W., Mishra, M., Nrusimha, A., Panda, R., and Kelly, J. R. Reducing transformer key-value cache size with cross-layer attention. arXiv preprint arXiv:2405.12981, 2024.arxiv.org/abs/2405.12981
  5. [5]Clark, C., Lee, K., Chang, M.-W., Kwiatkowski, T., Collins, M., and Toutanova, K. BoolQ: Exploring the surprising difficulty of natural yes/no questions. arXiv preprint arXiv:1905.10044, 2019.arxiv.org/abs/1905.10044
  6. [6]Clark, P., Cowhey, I., Etzioni, O., Khot, T., Sabharwal, A., Schoenick, C., and Tafjord, O. Think you have solved question answering? try arc, the ai2 reasoning challenge. arXiv preprint arXiv:1803.05457, 2018.arxiv.org/abs/1803.05457
  7. [7]Conmy, A., Mavor-Parker, A., Lynch, A., Heimersheim, S., and Garriga-Alonso, A. Towards automated circuit discovery for mechanistic interpretability. In Advances in Neural Information Processing Systems (NeurIPS), volume 36, pp. 16318–16352, 2023.arxiv.org/abs/2304.14997
  8. [8]Dai, D., Deng, C., Zhao, C., Xu, R., Gao, H., Chen, D., Li, J., Zeng, W., Yu, X., Wu, Y., et al. DeepSeekMoE: Towards ultimate expert specialization in mixture-of-experts language models. arXiv preprint arXiv:2401.06066, 2024.arxiv.org/abs/2401.06066
  9. [10]D’yachkov, A. G. and Rykov, V. V. Bounds on the length of disjunctive codes. Problemy Peredachi Informatsii, 18 (3):7–13, 1982.
  10. [11]Elhage, N., Neel, N., Olsson, C., et al. A mathematical framework for transformer circuits. Transformer Circuits Thread, 2020. URL https://transformer-circuits.pub/2021/framework/index.html.
  11. [12]Elhage, N., Hume, T., Olsson, C., Schiefer, N., Henighan, T., Kravec, S., Hatfield-Dodds, Z., Lasenby, R., Drain, D., Chen, C., et al. Toy models of superposition. Transformer Circuits Thread, 2022.arxiv.org/abs/2209.10652
  12. [13]ElNokrashy, M., AlKhamissi, B., and Diab, M. Depth-wise attention (dwatt): A layer fusion method for data-efficient classification. arXiv preprint arXiv:2209.15168, 2022.arxiv.org/abs/2209.15168
  13. [14]Erdős, P., Frankl, P., and Füredi, Z. Families of finite sets in which no set is covered by the union of others. Israel Journal of Mathematics, 51:79–89, 1985.
  14. [15]Fang, Y., Cai, Y., Chen, J., Zhao, J., Tian, G., and Li, G. Cross-layer retrospective retrieving via layer attention. arXiv preprint arXiv:2302.03985, 2023.arxiv.org/abs/2302.03985
  15. [16]Fedus, W., Zoph, B., and Shazeer, N. Switch transformers: Scaling to trillion parameter models with simple and efficient sparsity. The Journal of Machine Learning Research, 23(1):5232–5270, 2022.arxiv.org/abs/2101.03961
  16. [17]Füredi, Z. On r-cover-free families. Journal of Combinatorial Theory, Series A, 73(1):172–173, 1996.
  17. [18]Gao, L., Biderman, S., Black, S., Golding, L., Hoppe, T., Foster, C., Phang, J., He, H., Thite, A., Nabeshima, N., et al. The pile: An 800gb dataset of diverse text for language modeling. arXiv preprint arXiv:2101.00027, 2020.
  18. [19]Gao, L., Tow, J., Abbasi, B., Biderman, S., Black, S., DiPofi, A., Foster, C., Golding, L., Hsu, J., Le Noac’h, A., Li, H., McDonnell, K., Muennighoff, N., Ociepa, C., Phang, J., Reynolds, L., Schoelkopf, H., Skowron, A., Sutawika, L., Tang, E., Thite, A., Wang, B., Wang, K., and Zou, A. A framework for few-shot language model evaluation, 12 2023. URL https://zenodo.org/records/10256836.
  19. [21]Hanna, M., Pezzelle, S., and Belinkov, Y. Have faith in faithfulness: Going beyond circuit overlap when finding model mechanisms. In Proceedings of Conference on Language Modeling (COLM), 2024.
  20. [23]Hoffmann, J., Borgeaud, S., Mensch, A., Buchatskaya, E., Cai, T., Rutherford, E., de Las Casas, D., Hendricks, L. A., Welbl, J., Clark, A., et al. An empirical analysis of compute-optimal large language model training. Advances in Neural Information Processing Systems, 35:30016–30030, 2022.
  21. [24]Huang, G., Liu, Z., Van Der Maaten, L., and Weinberger, K. Q. Densely connected convolutional networks. In Proceedings of the IEEE conference on computer vision and pattern recognition (CVPR), pp. 4700–4708, 2017.arxiv.org/abs/1608.06993
  22. [25]Katharopoulos, A., Vyas, A., Pappas, N., and Fleuret, F. Transformers are RNNs: Fast autoregressive transformers with linear attention. In Proceedings of the 37th International Conference on Machine Learning (ICML), 2020.arxiv.org/abs/2006.16236
  23. [26]Kautz, W. H. and Singleton, R. C. Nonrandom binary superimposed codes. IEEE Transactions on Information Theory, 10(4):363–377, 1964.DOI
  24. [27]Kimi Team. Attention residuals. arXiv preprint arXiv:2603.15031, 2026a.
  25. [28]Kimi Team. Kimi K3: Open frontier intelligence. arXiv preprint arXiv:2607.24653, 2026b.
  26. [29]Lai, G., Xie, Q., Liu, H., Yang, Y., and Hovy, E. Race: Large-scale reading comprehension dataset from examinations. arXiv preprint arXiv:1704.04683, 2017.
  27. [31]Liu, A., Feng, B., Wang, B., Wang, B., Liu, B., Zhao, C., Deng, C., Ruan, C., Dai, D., Guo, D., et al. Deepseek-v2: A strong, economical, and efficient mixture-of-experts language model. arXiv preprint arXiv:2405.04434, 2024.
  28. [32]Longpre, S., Hou, L., Vu, T., Webson, A., Chung, H. W., Tay, Y., Zhou, D., Le, Q. V., Zoph, B., Wei, J., et al. The flan collection: Designing data and methods for effective instruction tuning. arXiv preprint arXiv:2301.13688, 2023.arxiv.org/abs/2301.13688
  29. [33]Mak, B. and Flanigan, J. Residual matrix transformers: Scaling the size of the residual stream. In Proceedings of the 42nd International Conference on Machine Learning (ICML), pp. 42712–42729, 2025.arxiv.org/abs/2506.22696
  30. [34]Merullo, J., Eickhoff, C., and Pavlick, E. Talking heads: Understanding inter-layer communication in transformer language models. arXiv preprint arXiv:2406.09519, 2024.arxiv.org/abs/2406.09519
  31. [36]Olsson, C., Elhage, N., Nanda, N., Joseph, N., DasSarma, N., Henighan, T., Mann, B., Askell, A., Bai, Y., Chen, A., et al. In-context learning and induction heads. Transformer Circuits Thread, 2022.arxiv.org/abs/2209.11895
  32. [37]Paglialdini, M., Mohtashami, A., Fleuret, F., and Jaggi, M. Denseformer: Enhancing information flow in transformers via depth weighted averaging. In Proceedings of the Thirty-Eighth Annual Conference on Neural Information Processing Systems (NeurIPS), 2024.
  33. [38]Paperno, D., Kruszewski, G., Lazaridou, A., Pham, Q. N., Bernardi, R., Pezzelle, S., Baroni, M., Boleda, G., and Fernández, R. The lambda dataset: Word prediction requiring a broad discourse context. arXiv preprint arXiv:1606.06031, 2016.
  34. [39]Peng, B., Goldstein, D., Anthony, Q., Albalak, A., Alcaide, E., Biderman, S., Cheah, E., Du, X., Ferdinan, T., Hou, H., et al. Eagle and finch: Rwkv with matrix-valued states and dynamic recurrence. arXiv preprint arXiv:2404.05892, 2024.arxiv.org/abs/2404.05892
  35. [40]Ruszinkó, M. On the upper bound of the size of the r-cover-free families. Journal of Combinatorial Theory, Series A, 66(2):302–310, 1994.
  36. [41]Sakaguchi, K., Bras, R. L., Bhagavatula, C., and Choi, Y. Winogrande: An adversarial winograd schema challenge at scale. Communications of the ACM, 64(9):99–106, 2021.arxiv.org/abs/1907.10641
  37. [42]Schlag, I., Irie, K., and Schmidhuber, J. Linear transformers are secretly fast weight programmers. In Proceedings of the 38th International Conference on Machine Learning (ICML), 2021.arxiv.org/abs/2102.11174
  38. [43]Shazeer, N. GLU variants improve transformer. arXiv preprint arXiv:2002.05202, 2020.arxiv.org/abs/2002.05202
  39. [44]Sperner, E. Ein satz über untermengen einer endlichen menge. Mathematische Zeitschrift, 27:544–548, 1928.DOI
  40. [45]Srivastava, R. K., Greff, K., and Schmidhuber, J. Training very deep networks. Advances in neural information processing systems, 28, 2015.arxiv.org/abs/1507.06228
  41. [47]Tay, Y., Dehghani, M., Aribandi, V., Gupta, J., Pham, P. M., Qin, Z., Bahri, D., Juan, D.-C., and Metzler, D. Omninet: Omnidirectional representations from transformers. In International Conference on Machine Learning (ICML), pp. 10193–10202. PMLR, 2021.
  42. [48]Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M.-A., Lacroix, T., Rozière, B., Goyal, N., Hambro, E., Azhar, F., et al. Llama: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971, 2023.arxiv.org/abs/2302.13971
  43. [49]Vig, J. and Belinkov, Y. Analyzing the structure of attention in a transformer language model. arXiv preprint arXiv:1906.04284, 2019.arxiv.org/abs/1906.04284
  44. [50]Wang, K., Variengien, A., Conmy, A., Shlegeris, B., and Steinhardt, J. Interpretability in the wild: a circuit for indirect object identification in gpt-2 small. In Proceedings of the Eleventh International Conference on Learning Representations (ICLR), 2023.arxiv.org/abs/2211.00593
  45. [51]Wang, K., Xia, X., Liu, J., Yi, Z., and He, T. Strengthening layer interaction via dynamic layer attention. arXiv preprint arXiv:2406.13392, 2024.arxiv.org/abs/2406.13392
  46. [52]Wang, Q., Li, B., Xiao, T., Zhu, J., Li, C., Wong, D. F., and Chao, L. S. Learning deep transformer models for machine translation. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (ACL), 2019.arxiv.org/abs/1906.01787
  47. [54]Xiao, D., Meng, Q., Li, S., and Yuan, X. Improving transformers with dynamically composable multi-head attention. 2024a.arxiv.org/abs/2405.08553
  48. [55]Xiao, D., Meng, Q., Li, S., and Yuan, X. MUDDFormer: Breaking residual bottlenecks in transformers via multiway dynamic dense connections. In Proceedings of the 42nd International Conference on Machine Learning (ICML), 2025.arxiv.org/abs/2502.12170
  49. [56]Xiao, G., Tian, Y., Chen, B., Han, S., and Lewis, M. Efficient streaming language models with attention sinks. In The Twelfth International Conference on Learning Representations (ICLR), 2024b.arxiv.org/abs/2309.17453
  50. [57]Xie, Z., Wei, Y., Cao, H., Zhao, C., Deng, C., Li, J., Dai, D., Gao, H., Chang, J., Yu, K., Zhao, L., Zhou, S., Xu, Z., Zhang, Z., Zeng, W., Hu, S., Wang, Y., Yuan, J., Wang, L., and Liang, W. mHC: Manifold-constrained hyper-connections. arXiv preprint arXiv:2512.24880, 2025.arxiv.org/abs/2512.24880
  51. [58]Yang, S., Wang, B., Shen, Y., Panda, R., and Kim, Y. Gated linear attention transformers with hardware-efficient training. In Proceedings of the 41st International Conference on Machine Learning (ICML), pp. 56501–56523, 2024a.arxiv.org/abs/2312.06635
  52. [59]Yang, S., Wang, B., Zhang, Y., Shen, Y., and Kim, Y. Parallelizing linear transformers with the delta rule over sequence length. In Proceedings of the Thirty-Eighth Annual Conference on Neural Information Processing Systems, 2024b.arxiv.org/abs/2406.06484
  53. [60]Yang, S., Kautz, J., and Hatamizadeh, A. Gated delta networks: Improving Mamba2 with delta rule. In Proceedings of the Thirteenth International Conference on Learning Representations (ICLR), 2025.arxiv.org/abs/2412.06464
  54. [62]Zellers, R., Holtzman, A., Bisk, Y., Farhadi, A., and Choi, Y. Can a machine really finish your sentence? arXiv preprint arXiv:1905.07830, 2019.arxiv.org/abs/1905.07830
  55. [63]Zhu, D., Huang, H., Huang, Z., Zeng, Y., Mao, Y., Wu, B., Min, Q., and Zhou, X. Hyper-connections. In Proceedings of the Thirteenth International Conference on Learning Representations (ICLR), 2025.arxiv.org/abs/2409.19606

Paper details

vlnc:W_2w8ej2rg
Version
v1 · latest
Published
Fresh — added to the Hub within the last 30 days
Added
License
CC BY 4.0
Usage

views · 0

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Computer Science

Not recorded for this paper

View statement
Looking for related papers…
Contents