Independent scholarship · Open accessThe monthly digest

Full manuscript · browser edition

Interaction Order in Self-Attention

Continuous, single-column reading. Equations, tables, proofs, references and appendices stay in document order.

Contents · 26 sections

AUTHOR REVIEW COPY / INTENDED FOR HIGHER CATEGORICAL SEMANTICS

Interaction Order in Self-Attention

Weighted spans, exact streaming, and scaling from pairs to quintuples

Anonymous December 2026


Abstract. Dense self-attention compares each query with each key. Replacing the key by an ordered tuple of p−1p-1 keys gives npn^p scores on nn tokens. We give a bicategorical semantics of these operators through finite weighted spans and characterize when normalizing a composite agrees with composing normalized kernels. Finite pushforward gives exact streaming and, for tied roles, an exact reduction to multisets. A Gaussian calculation gives an order- and multiplicity-dependent extension of the usual logit scaling. In a fixed-width ordered CPU kernel, the measured sequence-length exponents at orders two through five were 1.99,2.95,3.94,4.851.99,2.95,3.94,4.85. In five-fold experiments with matched parameter counts, cubic attention improved Wine accuracy from 89.89%89.89\% to 93.82%93.82\%. On four-patch Digits the corresponding order-two through order-five accuracies were 91.21%,89.37%,86.70%,85.42%91.21\%,89.37\%,86.70\%,85.42\%. A Boolean-cube calculation identifies tasks on which increasing the maximum available order strictly decreases the optimal error of a specified readout. Interaction order therefore has an exact combinatorial cost and a task-dependent statistical benefit.

The question of order

For a sequence of nn vectors, one dense self-attention head assigns a distribution on nn keys to each of nn queries. A score for an image patch can depend directly on one other patch through a dot product. A cubic head can instead score a pair of patches jointly for the same query. The numerical cost of the extra slot is elementary. The statistical question is whether joint scoring improves prediction under a specified distribution, representation, and budget.

Three independent variables enter this question. Sequence length nn determines the number of candidate tuples. Interaction order pp counts the query and the key slots in a single score. Training-set size mm counts labeled examples. A quadratic arithmetic bound in nn says nothing by itself about the degree of the input–output function or the slope of test loss against mm. Even at p=2p=2, exponentiation and the softmax denominator make a single output depend nonlinearly on the entire key set. Successive layers can also combine information from several tokens.

The ordinary head is due to Vaswani et al. [1]. Clift et al. introduced 2-simplicial attention using an unsigned scalar triple product and tensor-valued interactions [2]. Alman and Song defined the column-wise Kronecker tensor-softmax family used here and analyzed fast approximation and conditional hardness [3]. Roy et al. implemented efficient cubic attention in Triton and reported gains for language models on a fixed token budget [4]. Graph transformers acting on tuple states form another family. Pairwise self-attention over nkn^k such states already has n2kn^{2k} ordered pairs [5]. One-layer limitations for particular relational tasks also depend on assumptions on width, precision, and architecture [6].

Our contribution concerns normalized weighted spans for these heads, exact simplifications and their obstructions, score variance under tied roles, and controlled measurements from order two through five. The fitted exponents below apply to an identified algorithm or an identified finite data range.

From one key to a tuple

Let II be a nonempty finite set with ∣I∣=n|I|=n, r=p−1r=p-1, and X=(xi)i∈I∈(RD)IX=(x_i)_{i\in I}\in(\mathbb R^D)^I. For each role aa put kja=WKaxj∈Rdk^a_j=W^a_K x_j\in\mathbb R^d, vja=WVaxj∈Rdvv^a_j=W^a_V x_j\in\mathbb R^{d_v}, and let qi=WQxi∈Rdq_i=W_Qx_i\in\mathbb R^d. A legal relation E⊆I×IrE\subseteq I\times I^r specifies the tuple support EiE_i. Assume every EiE_i is nonempty. For J=(j1,…,jr)J=(j_1,\ldots,j_r) put KJ=⨀a=1rkjaa,UJ=⨀a=1rvjaa,siJ=d−1/2⟨qi,KJ⟩+biJ,Zi=∑J∈EiesiJ,Ap(X)i=Zi−1∑J∈EiesiJUJ.\begin{aligned} K_J &= \bigodot_{a=1}^r k^a_{j_a},& U_J &= \bigodot_{a=1}^r v^a_{j_a}, \\ s_{iJ} &= d^{-1/2}\langle q_i,K_J\rangle+b_{iJ},& Z_i &=\sum_{J\in E_i} e^{s_{iJ}},\\ A_p(X)_i &= Z_i^{-1}\sum_{J\in E_i} e^{s_{iJ}}U_J . \end{aligned} The product is coordinatewise. The classifier uses tied role maps, b=0b=0, all ordered tuples, and sampling with replacement. A repeated index is legal, including a key index equal to the query. For p=3p=3, a score contains terms qihkjh1kℓh2q_{ih}k^1_{jh}k^2_{\ell h}. The normalization ranges over the joint pair (j,ℓ)(j,\ell). Two independently normalized pairwise heads would generally give a different distribution.

For r=1r=1 the dense formula is exactly softmax⁡(QK⊤/d)V\operatorname{softmax}(QK^\top/\sqrt d)V, with row-wise softmax. Heads with different parameters can be concatenated and composed with a pointwise output projection. Adding a residual connection, tokenwise normalization and a feedforward block gives an encoder layer. The general construction permits role-specific tensors, relative biases, sparse relations, and multiple heads. The experiments below fix a smaller class so that order can vary with exactly the same parameter count within a dataset.

Proposition 1 (Adding an unused slot). In the role-specific dense family with a constant feature, an order-pp head is realizable at order p+1p+1.

Proof. Set the extra key and value projections to the all-ones vectors and pull the bias back along the projection forgetting the extra key. Each original term occurs nn times in the numerator and denominator of (3). Their ratio is unchanged. On masked supports the same calculation holds for positive constant extension multiplicity on each query fiber. ◻

This gives weak inclusion of the corresponding function classes. Strict improvement in optimal risk requires a target that separates them. In the tied family an individual extra slot cannot in general be assigned a separate constant map. Even for nested classes, finite-sample estimates and finite-time optimization can reverse their population ordering.

A bicategory for normalized attention

Weighted spans and linearization

Write S\mathcal S for the bicategory with finite sets as objects and a weighted span A←ℓS→uB,w:S⟶R≥0A\xleftarrow{\ell} S\xrightarrow{u}B,\qquad w:S\longrightarrow\mathbb R_{\geq 0} as a 1-cell. A 2-cell is a weight-preserving bijection of apices commuting with both legs. Horizontal composition with a span of apex TT uses S×BTS\times_B T and weight w(s)v(t)w(s)v(t). Identities are diagonal spans of weight one. The associator sends ((s,t),u)((s,t),u) to (s,(t,u))(s,(t,u)). Both sides of the pentagon send a composable four-tuple to the same rebracketing. Cartesian product of spans gives the symmetric monoidal structure. This is a locally groupoidal bicategory, or a (2,1)(2,1)-category. Attention order pp and categorical dimension are separate parameters.

Define a nonnegative matrix by finite pushforward, L(S)(a,b)=∑ℓ(s)=a, u(s)=bw(s).L(S)(a,b)= \sum_{\ell(s)=a,\ u(s)=b} w(s). Summing first over the common index in the pullback gives L(S×BT)=L(S)L(T)L(S\times_B T)=L(S)L(T). Products of spans give Kronecker products of matrices. Thus LL descends through 2-isomorphisms to a symmetric monoidal linearization into nonnegative matrices, viewed as a locally discrete bicategory. Span constructions and polynomial indexing over locally cartesian closed categories supply the general background [7, 8].

At fixed XX, use the span I←E→IrI\leftarrow E\rightarrow I^r, with the query and tuple projections and weights esiJe^{s_{iJ}}. Dividing by the positive mass ZiZ_i on each source fiber gives a stochastic matrix PXP_X. Equation (3) is PXUXP_X U_X. Real-valued and vector-valued observables can have either sign. The weights remain nonnegative. Changing XX changes both the kernel and the observable. Composing two neural layers therefore includes recomputing the second layer’s scores on the first layer’s output.

Naturality and a topos of token families

Let B\mathcal B be a small skeleton of finite sets and bijections. In the presheaf topos E=SetBop\mathcal E=\mathbf{Set}^{\mathcal B^{\rm op}}, put T(I)=IT(I)=I, with inverse transport along a bijection, and FD(I)=(RD)IF_D(I)=(\mathbb R^D)^I, with reindexing by precomposition. The polynomial indexing operation T↦TrT\mapsto T^r assigns the set of key tuples. A natural mask is a subobject of T×TrT\times T^r. Coordinates, masks, and any positional data must travel with their tokens.

Theorem 2 (Base change for normalized sums). Suppose finite fibers, scores, and observables are transported along a pullback square. At each source point with positive mass, transport of the normalized pushforward equals the normalized pushforward of the transported data. In particular ApA_p is a natural transformation from FDF_D to FdvF_{d_v} when the data in (3) are natural in token bijections.

Proof. For a map π:E→I\pi:E\to I and a reindexing u:I′→Iu:I'\to I, the fiber of I′×IE→I′I'\times_I E\to I' over i′i' is canonically Eu(i′)E_{u(i')}. The two numerator sums agree term by term, as do the masses. Division gives the claim. For token bijections the maps on tuples are the componentwise bijections J↦urJJ\mapsto u^rJ, with the same argument on each query. ◻

For example, reordering both pixel patches and their position embeddings permutes the encoder outputs. Reordering only the pixel data while keeping the embeddings at their old positions changes the input assignment. Rebuilding a full tuple set after a nonbijective change of tokens can also change normalized attention. At constant score with values 0,10,1, duplicating the zero-valued key changes the average from 1/21/2 to 1/31/3. An actual pullback of an existing score fiber and a change of its counting measure are different operations.

A parameterized layer is a pair (Θ,f)(\Theta,f) with f:Θ‾×FD→FD′f:\underline{\Theta}\times F_D\to F_{D'} natural, where Θ‾\underline{\Theta} is the constant parameter object. A reparameterization ρ:Θ→Θ′\rho:\Theta\to\Theta' is a 2-cell when f=f′∘(ρ×id)f=f'\circ(\rho\times\mathrm{id}). Layers compose by product of parameter spaces and substitution. Canonical product associators give the coherence maps. Shared role weights arise by precomposing the role-specific family with the diagonal on parameter spaces. This uses the parametric approach to learning [9, 10] with set-valued maps that include the nonlinear normalization. A learned position table for a fixed length is an additional input of type FD(I)F_D(I), or a parameter transported in the indexed family at that length.

Homotopy fibers and symmetric tuples

There is a higher analogue in the ∞\infty-category of spaces. Let each homotopy fiber EihE_i^h of E→IE\to I be π\pi-finite, with finitely many components and finite homotopy groups, trivial in sufficiently high degree. For a component represented by ee, put ω(e)=∏k≥1∣πk(Eih,e)∣(−1)k.\omega(e)=\prod_{k\ge1}|\pi_k(E_i^h,e)|^{(-1)^k}. For weights w>0w>0 and vector observations UU constant on components of the fibers and compatible with transport, define Ai=∑[e]∈π0Eihω(e)w(e)U(e)∑[e]∈π0Eihω(e)w(e).\mathcal A_i= \frac{\sum_{[e]\in\pi_0 E_i^h}\omega(e)w(e)U(e)} {\sum_{[e]\in\pi_0 E_i^h}\omega(e)w(e)}. The sums use homotopy cardinality [11]. On nonempty fibers any homotopy pullback preserves this value because it induces an equivalence between the corresponding fibers and transports their weights and observables. For a map of discrete sets the formula is Theorem 2.

An application gives an algebraic reason for the multiplicity correction in symmetric heads. For role-invariant scores and values, take the action groupoid Ir//SrI^r\mathbin{/\mkern-6mu/} S_r as the fiber. The component of a multiset with counts cjc_j has automorphism group ∏jScj\prod_j S_{c_j}. Its homotopy weight is 1/∏jcj!1/\prod_j c_j!, exactly 1/r!1/r! times the number of its ordered representatives. The common factor cancels in the normalized sum. With two keys a,ba,b, two roles and zero scores, the resulting probabilities of aa,ab,bbaa,ab,bb are 1/4,1/2,1/41/4,1/2,1/4. A uniform measure on the three coarse classes gives 1/31/3 apiece. Automorphisms thus have a numerically observable effect.

An obstruction to flattening layers

For a positive matrix WW, write Norm⁡W\operatorname{Norm}W for row normalization. Composable stochastic matrices compose in the usual way. Normalizing two factors introduces intermediate row masses.

Proposition 3 (Path-normalization obstruction). Fix a source ii, first-stage weights Wij>0W_{ij}>0 on its support, and second-stage weights Vjk≥0V_{jk}\geq0 with zj=∑kVjk>0z_j=\sum_k V_{jk}>0. The joint law of paths (j,k)(j,k) formed by successive row normalizations equals the single normalization of WijVjkW_{ij}V_{jk} exactly when zjz_j is constant on the reachable intermediate states.

Proof. Let si=∑jWijs_i=\sum_j W_{ij} and ti=∑jWijzjt_i=\sum_j W_{ij}z_j. At a positive path the two masses are WijVjk/(sizj)W_{ij}V_{jk}/(s_i z_j) and WijVjk/tiW_{ij}V_{jk}/t_i. Equality for every such path is equivalent to zj=ti/siz_j=t_i/s_i for each reachable jj. ◻

For equal first-stage weights and disjoint deterministic terminal states with outgoing masses 1 and 2, successive normalization gives terminal probabilities 1/2,1/21/2,1/2. A single normalization gives 1/3,2/31/3,2/3. Marginalization can hide a path discrepancy if distinct paths share a terminal state. The equivalence above is for the joint path law. At fixed scores, subtracting log⁡zj\log z_j from the joint path score restores successive normalization. This supplies an explicit obstruction to replacing depth by an uncorrected higher-order softmax.

Cost laws and exact implementations

Sequence length and support

For fixed p,d,dvp,d,d_v, a direct dense forward pass evaluates npn^p scalar scores per head and example. Generating each product KJ,UJK_J,U_J once and sharing it across queries costs O(rnr(d+dv))O(r n^r(d+d_v)). The matrix of scores and its action on values cost Θ(nr+1(d+dv))\Theta(n^{r+1}(d+d_v)) for the direct dot products and reductions. With head width proportional to model width DD and fixed head count, projection and feedforward work add O(nD2+nDDff)O(nD^2+nD D_{\rm ff}). Thus even the dominant term in whole-encoder cost depends on length and width. Multiplying batch size or the number of independent heads multiplies the corresponding attention work.

Score evaluations per head and example. There are r=p−1r=p-1 key slots. Repeated key indices are allowed unless a support restriction removes them.
Support or evaluation Score count
Ordered dense npn^p
All keys in the query prefix ∑i=1nir\sum_{i=1}^n i^r
At most ww keys per slot ≤nwr\le n w^r
Symmetric dense, one per orbit n(n+r−1r)n\binom{n+r-1}{r}
Arbitrary legal tuples ∑i∣Ei∣\sum_i |E_i|

Doubling nn multiplies dense score count by 4,8,16,324,8,16,32 at p=2,3,4,5p=2,3,4,5. Increasing pp by one at fixed nn multiplies it by nn. For a causal prefix the leading count is np/p+O(np−1)n^p/p+O(n^{p-1}). One new query at prefix length nn costs np−1n^{p-1} scores if the per-token projections are cached. At a fixed score budget CC, the maximum dense length is ⌊C1/p⌋\lfloor C^{1/p}\rfloor. These counts are for explicit enumeration.

Proposition 4 (Oracle lower bound). If an algorithm has only pointwise access to arbitrary independent logits and must return exact normalized means for all logits, a dense pp-ary head requires npn^p queries in the worst case, for n≥2n\ge2.

Proof. Choose binary tuple values with both values represented. Answer every logit query by zero. The mean in every row lies strictly between zero and one. Altering any unqueried logit in a row changes its mean, since that tuple’s value differs from the original mean. An exact deterministic algorithm must therefore inspect every logit in every row. ◻

Structured scores such as (1) do not supply independent oracle entries. In the structured setting Alman and Song give bounded-entry approximation algorithms and conditional hardness results in specified parameter regimes [3]. Proposition 4 does not transfer a lower bound to these structured algorithms.

FlashAttention and exact streaming

A materialized forward pass needs space for npn^p scores, apart from inputs and outputs. FlashAttention computes the ordinary dense softmax by tiling, maintaining online row normalizers, and recomputing intermediates during backpropagation [12, 13, 14]. In the original two-level model with d≤M≤ndd\le M\le nd on-chip words and equal head and value widths, the analyzed pairwise kernel transfers Θ(n2d2/M)\Theta(n^2d^2/M) words to or from high-bandwidth memory. Its explicit arithmetic remains quadratic in nn. FlashAttention-2 refines block and warp work partitioning [15]. FlashAttention-3 overlaps operations on Hopper GPUs and includes a low-precision variant [16]. FlashAttention-4 adapts the pipelines and exponential calculation to Blackwell hardware [17]. Mathematical equality uses exact arithmetic. Finite precision and low-precision variants have their own numerical errors.

The same reduction applies to disjoint blocks of any finite tuple fiber. For a nonempty block B⊆EiB\subseteq E_i define mB=max⁡J∈BsiJ,  zB=∑J∈BesiJ−mB,  uB=∑J∈BesiJ−mBUJ.m_B=\max_{J\in B}s_{iJ},\ \ z_B=\sum_{J\in B}e^{s_{iJ}-m_B},\ \ u_B=\sum_{J\in B}e^{s_{iJ}-m_B}U_J . For disjoint blocks with summaries (m,z,u),(m′,z′,u′)(m,z,u),(m',z',u'), their combined maximum is h=max⁡(m,m′)h=\max(m,m') and the combined denominator and numerator are (z′′,u′′)=em−h(z,u)+em′−h(z′,u′).(z'',u'')=e^{m-h}(z,u)+e^{m'-h}(z',u'). Treat an empty block as a separate identity element, so that no subtraction of two infinities is needed.

Theorem 5 (Invariance under tile refinement). Block combination is associative and commutative on valid summaries in exact arithmetic. Every partition and every merge tree returns (3) as u/zu/z.

Proof. The combined maximum is the maximum over the union. A term from the first block contributes em−hes−m=es−he^{m-h}e^{s-m}=e^{s-h}, and the same identity holds for the second block. The combined summary is therefore the unique summary defined by the union. Associativity and commutativity follow from finite union and addition. The diagonal scaling cancels in the final ratio. ◻

With fixed query and tuple tile sizes Bq,BtB_q,B_t, forward working storage including projections and outputs is O ⁣(nr(d+dv)+Bt(d+dv)+BqBt)O\!\left(nr(d+d_v)+B_t(d+d_v)+B_qB_t\right) for fixed pp, with an additional O(Btr)O(B_t r) if tuple indices are stored explicitly. Factored supports and biases are assumed to be generated on demand. A dense bias supplied as input has its own npn^p storage cost. For reverse mode one can save the output and log partition per query and regenerate weights. For an upstream vector gig_i, ∂L∂siJ=PX(i,J) ⟨gi,UJ−Ap(X)i⟩.\frac{\partial L}{\partial s_{iJ}} =P_X(i,J)\,\langle g_i,U_J-A_p(X)_i\rangle . This identity follows by differentiating a row softmax and permits streamed gradient accumulation. The reference C++ kernel below implements ordered forward streaming. The NumPy training implementation instead stores the smaller orbit-level activations. Neither a higher-order GPU I/O bound nor a GPU speedup is inferred from the CPU timings. A hardware-optimized cubic kernel is already available [4].

Two exact simplifications

Proposition 6 (Quotient by role permutations). Suppose support, scores, and values are invariant under the action of SrS_r permuting the key roles. For the full product IrI^r, replace a tuple by its count vector c=(c1,…,cn)c=(c_1,\ldots,c_n) with ∑jcj=r\sum_j c_j=r. With hc=r!/∏jcj!h_c=r!/\prod_j c_j!, (3) equals a softmax over (n+r−1r)\binom{n+r-1}{r} representatives per query with logits sic+log⁡hcs_{ic}+\log h_c.

Proof. All tuples in one orbit have identical score and observable, and the stabilizer has size ∏jcj!\prod_j c_j!. In the numerator and denominator their total weight is hcesich_c e^{s_{ic}}. Weak compositions of rr into nn parts index the orbits. ◻

The orbit map is a finite pushforward. Treating every representative as equally frequent would change the counting measure. For fixed rr this quotient preserves the leading exponent and divides the leading score count by r!r!. At n=4n=4, ordered per-query counts 4,16,64,2564,16,64,256 become 4,10,20,354,10,20,35. Independent role maps generally break the invariance.

A second simplification can lower the exponent. Suppose on the full Cartesian support the positive kernel itself has a supplied decomposition W(i,J)=∑h=1H∏a=1rwha(i,ja),wha≥0.W(i,J)=\sum_{h=1}^{H}\prod_{a=1}^{r} w_{ha}(i,j_a), \qquad w_{ha}\geq0 . Then finite distributivity gives the exact denominator and numerator Zi=∑h∏a∑jwha(i,j),Ni=∑h⨀a(∑jwha(i,j)vja).\begin{aligned} Z_i &=\sum_h\prod_a\sum_j w_{ha}(i,j),\\ N_i &=\sum_h\bigodot_a\left(\sum_j w_{ha}(i,j)v^a_j\right). \end{aligned} For bounded H,rH,r and widths, evaluating all factors costs O(Hrn2)O(Hr n^2) for all queries if each factor is available at constant cost. Additive slot scores s(i,J)=∑asa(i,ja)s(i,J)=\sum_a s_a(i,j_a) give H=1H=1. Conversely a low-rank multilinear expression for the logit does not give a bounded-rank decomposition of its exponential. Kernelized linear attention exploits related algebraic reordering for a different choice or approximation of kernel [18]. Thus neither semantic arity nor low-rank logits alone determine an arithmetic exponent.

Logit scaling and statistical order

Repeated indices change the variance

The factor 1/d1/\sqrt d scales a sum across coordinates. In an idealized untied head, if all query and role-key coordinates used in a score are independent, centered, and have unit variance, the product in each coordinate has variance one. The sum of dd such terms divided by d\sqrt d again has variance one at every order. Tied roles with repeated indices require a different calculation.

Theorem 7 (Gaussian multiplicity law). Assume the qhq_h and kjhk_{jh} are independent standard Gaussians across tokens and coordinates, with the same kk reused across key slots and with zero bias. Conditional on a fixed tuple with counts cc, the score in (2) has mean zero and variance σc2=∏j:cj>0(2cj−1)!!.\sigma_c^2=\prod_{j:c_j>0}(2c_j-1)!! . For independent uniform key indices, the variance averaged over tuples is V(n,r)=∏a=0r−1(1+2an).V(n,r)=\prod_{a=0}^{r-1}\left(1+\frac{2a}{n}\right).

Proof. Centering follows from the independent query. Distinct coordinates have zero covariance. Each second moment factors into the even Gaussian moments Ek2c=(2c−1)!!\mathbb Ek^{2c}=(2c-1)!!, so the normalized coordinate sum has variance σc2\sigma_c^2. Given the keys in one coordinate, the expected product of their squares over uniform tuples is (n−1∑jkj2)r(n^{-1}\sum_j k_j^2)^r. Its expectation is the rr-th moment of χn2/n\chi_n^2/n, which is the product in (4). ◻

At n=4n=4, VV is 1,1.5,3,7.51,1.5,3,7.5 for the four orders. For four identical key indices the conditional variance is 7!!=1057!!=105. Dividing the bias-free logit by σc\sigma_c gives unit variance on each orbit under these assumptions. The orbit mass correction log⁡hc\log h_c is then added after rescaling. A check with 2202^{20} independent Gaussian key vectors, integrating over the query and index choices, gave 0.9992,1.4973,2.9902,7.45710.9992,1.4973,2.9902,7.4571. The experiment below tests this temperature as a model change. Learned query and key projections of a common input can violate independence and Gaussianity.

A target with a strict higher-order gain

Let xjx_j be independent uniform signs. Mask out repeated key indices, set all scores to zero, and use scalar values vj=xjv_j=x_j. Up to a known constant each query returns the same degree-rr symmetric Walsh observable ϕr(x)=(nr)−1/2∑S⊆I∣S∣=r∏j∈Sxj.\phi_r(x)=\binom{n}{r}^{-1/2} \sum_{\substack{S\subseteq I\\|S|=r}}\prod_{j\in S}x_j . Indeed every unordered subset occurs r!r! times, so multiplying the uniform attention mean by (nr)\sqrt{\binom nr} gives ϕr\phi_r.

Proposition 8 (Exact order threshold for a linear readout). Let 1≤s≤n1\le s\le n. For target ϕs\phi_s and readout space span(1,ϕ1,…,ϕk)\mathrm{span}(1,\phi_1,\ldots,\phi_k), the minimum population mean squared error is 1 for k<sk<s and 0 for k≥sk\ge s.

Proof. In the Walsh basis [19], two distinct sign monomials have zero inner product because some sign occurs exactly once in their product. Each monomial has squared norm one. The normalized sums in (5) are therefore orthonormal, including the constant ϕ0=1\phi_0=1. Orthogonal projection of ϕs\phi_s onto the stated space is either zero or ϕs\phi_s. ◻

Exhaustive least squares on all 28=2562^8=256 sign vectors for s,k=1,…,4s,k=1,\ldots,4 reproduced the sixteen entries of this error matrix to 3×10−153\times10^{-15}. For instance adding a quintic head exposes the degree-four target directly. This is a strict benefit for a specified family of uniform masked heads and a linear readout. A deeper pairwise network or a nonlinear readout belongs to another class. Even the cost of this particular target can be reduced using the elementary-symmetric recurrence ej(t)=ej(t−1)+xtej−1(t−1)e_j^{(t)}=e_j^{(t-1)}+x_t e_{j-1}^{(t-1)}, starting with e0=1e_0=1 and ej>0=0e_{j>0}=0. Its O(nr)O(nr) scalar work further separates feature order from enumeration cost.

Experimental design

Four classification datasets

We used the bundled scikit-learn versions of four UCI datasets [20, 21, 22, 23, 24]. Iris contains 150 examples, four features and three classes. Wine contains 178 examples, 13 features and three classes. Wisconsin Diagnostic Breast Cancer (WDBC) contains 569 examples, 30 features and two classes. The bundled Digits dataset contains 1,797 examples, 8×88\times 8 pixels and ten classes, drawn from the test portion of the original UCI release. All reported partitions are new partitions within each bundled dataset. WDBC is used solely for a benchmark comparison.

The primary design used four tokens per example. For tabular data we standardized each original feature using only the current training subset, padded the final feature group with zeros, and split the original feature order into four consecutive groups of equal size. Iris therefore has one feature per token, Wine four after padding, and WDBC eight. For Digits we standardized the 64 pixel positions separately and used the four 4×44\times4 quadrants in raster order. An additional experiment used eight row tokens of eight pixels each. With four tokens some order-five interactions must repeat a token if the query is counted. With eight tokens all five indices can be distinct.

Five shuffled stratified outer folds assigned every example to one held-out fold. Within each remaining 80%80\%, we reserved a stratified 20%20\% for validation. Thus the training, validation, and test fractions were approximately 64%,16%,20%64\%,16\%,20\%. We used the same partitions and initialization seed within a fold across interaction orders. For the Digits learning curves, one random permutation per class within each fold supplied nested training subsets at 1/8,1/4,1/2,11/8,1/4,1/2,1 of the training pool. Each subset had its own fitted standardization. No test score entered checkpoint selection.

Trainable encoders and controls

Each encoder has one head and one residual block of width D=d=dv=16D=d=d_v=16. For input patches xx, learned positional vectors PP, a shared linear embedding WeW_e, and parameter-free feature LayerNorm ℓ\ell with ϵ=10−5\epsilon=10^{-5}, the computations are Z=xWe+P,H=Z+Ap(ℓ(Z))WO,F=H+ReLU(ℓ(H)W1+b1)W2+b2,z^=meani∈I(Fi)WC+bC.\begin{aligned} Z &= xW_e+P,\\ H &= Z+A_p(\ell(Z))W_O,\\ F &= H+\mathrm{ReLU}(\ell(H)W_1+b_1)W_2+b_2,\\ \hat z &= \mathrm{mean}_{i\in I}(F_i)W_C+b_C . \end{aligned} The feedforward inner width is 32. All query, key, value, embedding, output and classifier matrices are trained jointly. Every order has 2,227 trainable parameters for Iris, 2,275 for Wine, 2,322 for WDBC, 2,586 for four-patch Digits and 2,522 for eight-row Digits.

We minimized multiclass cross-entropy for 60 epochs with Adam [25], learning rate 0.003, default moments 0.9,0.9990.9,0.999, batch size 32, and global gradient-norm clipping at 5. Training used float32, a shared initialization scheme, and identical per-fold minibatch permutations across orders. We used no weight decay or dropout. The main test prediction is from the eligible epoch with the smallest validation cross-entropy, taking the earliest minimizer. A standardized-feature logistic regression with C=1C=1, trained on the same training records, gives a conventional baseline. The fixed hyperparameters specify a controlled comparison. A separate search per architecture would answer a different question.

Three resource comparisons are reported. The first gives each architecture 60 training epochs and selects its checkpoint by validation. The second caps per-example training scores in the implemented multiset representation. For Mp=(n+p−2p−1)M_p=\binom{n+p-2}{p-1} representatives per query, the eligible epochs are Epscore=⌊60 nMp⌋.E_p^{\rm score}=\left\lfloor 60\,\frac{n}{M_p}\right\rfloor. At n=4n=4 this yields 60,24,12,660,24,12,6 epochs. The last value uses 87.5%87.5\% of the budget because only completed epochs are eligible. The cap counts forward scores corresponding to training examples. Projection, feedforward, validation, and memory traffic are outside that count.

The third comparison fixes measured training CPU time per fold on four-patch Digits. On one pinned core we replayed the same training trajectories, timed forward, backward and Adam updates with process CPU time, and used the 60-epoch pairwise time of that fold as its budget. Validation and testing were outside the clock. An epoch crossing the limit was ineligible. Recording its time established the boundary. The five reference budgets ranged from 0.931 to 1.148 process CPU seconds in this environment. Eligible validation histories agreed with the original runs to 10−610^{-6}. The artifact retains the measured durations and fold-specific budgets.

Out-of-fold accuracy and cross-entropy with four tokens. Each example receives one prediction from its outer test fold. Attention models use tied roles and a common 60-epoch training allowance. LR denotes logistic regression on the original standardized features.
Accuracy (%, larger is better) Cross-entropy (nats, smaller is better)
2-6(lr)7-11 Dataset LR p=2p=2 p=3p=3 p=4p=4 p=5p=5 LR p=2p=2 p=3p=3 p=4p=4 p=5p=5
tables/main.tex

Kernel benchmark and numerical checks

A separate serial C++17 kernel evaluated every ordered tuple with float64 arithmetic, d=dv=8d=d_v=8, one head, one example and a tile of 64 key tuples. The kernel forms tile-local key and value products once, then streams all query rows over the tile. Timing includes temporary allocation and reduction, starting with projected inputs. Each case used a warm-up forward pass. Nine randomized rounds each visited six lengths per order. Each timed block repeated full forward calls until at least 25 milliseconds had elapsed. We regressed log median seconds against log length across the six sizes per order. The host reported an AMD EPYC 9V74 CPU. The process was pinned to one logical CPU, using GCC 14.2 with -O3 and -std=c++17. The trainer uses multiset enumeration. The C++ reference evaluates the same tied-role function on ordered tuples with the original logit scale.

We compared dense Cartesian NumPy evaluation with multiset evaluation and four streaming tile sizes. Maximum absolute forward discrepancies over the four orders were below 2.4×10−142.4\times10^{-14} in float64. The maximum full-encoder directional derivative error was 2.3×10−92.3\times10^{-9}, and that for the attention input derivatives was 3.1×10−93.1\times10^{-9}. Reindexing including repeated keys agreed to 7.2×10−157.2\times10^{-15}. The compiled kernel agreed with the independent Cartesian oracle to 1.0×10−141.0\times10^{-14} on 12 combinations of nn and pp. The orbit-temperature variant passed a separate dense-oracle and derivative check. These are numerical consistency tests on specified inputs.

Measured scaling and predictive performance

Length scaling of explicit enumeration

Fitted runtime exponent βp\beta_p in Tp(n)=apnβpT_p(n)=a_p n^{\beta_p} for the ordered CPU forward kernel. The range is the minimum and maximum slope after deleting one length. R2R^2 is on log scales.
pp nn range βp\beta_p Delete-one range R2R^2
tables/timing.tex

The fitted exponent increases from 1.986 at p=2p=2 to 4.852 at p=5p=5 (Table 3). The lengths intentionally differ across orders to keep the number of tuple evaluations in a comparable range. Roughly the same 18–21 ms took 1,536 tokens at order two and 19 tokens at order five at the largest respective measurements. The quintic fit is below five throughout the delete-one-size analysis. Tuple generation, short rows and tile boundaries contribute finite-size terms to this implementation. The exact count is n5n^5 at every length regardless of the wall-time slope.

Ordered forward time on one CPU core. Points are nine-round medians, vertical lines give the 10th–90th percentile across rounds, and solid lines are power-law fits. Each order has its own measured length interval.

Fixed exposure on the four datasets

The pairwise head attained the highest attention-model accuracy on Iris, WDBC, and Digits (Table 2). Cubic attention had the highest attention-model accuracy on Wine. Of 178 Wine cases, eleven classified incorrectly by the pairwise model were correct under the cubic model, and four changed in the opposite direction. The net difference is seven cases or 3.933.93 percentage points. The paired fold differences ranged from 0.00.0 to 11.411.4 points, with three favorable folds and two ties. Logistic regression classified 176 cases correctly on that dataset, compared with 167 for cubic attention.

On Digits, the quintic head corrected 70 of the pairwise head’s errors and lost 174 of its correct predictions. The net change was −104/1797-104/1797, or −5.79-5.79 points. All five fold differences were negative, from −8.1-8.1 to −2.8-2.8 points. In WDBC the cubic head had slightly lower cross-entropy than the pairwise head despite slightly lower accuracy. Accuracy and cross-entropy therefore give different orderings even for a fixed set of predictions. The number of folds is small and their training sets overlap. These differences describe paired observations on the specified partitions.

Digits accuracy (%) by budget and tokenization. The first three columns after pp use four patches. Parentheses give eligible epochs or their five-fold range. The row-token comparison uses 60 epochs.
pp 60 epochs Score cap CPU cap 8 rows
tables/budget.tex

The observed CPU cap admitted the validation-selected checkpoint in every four-patch Digits run, so it returned the same predictions as the 60-epoch comparison. The score cap reduced quintic accuracy to 82.80%82.80\% (Table 4). Whole-encoder CPU time varies more slowly with order at four tokens because the trainer shares tuple products and also computes embeddings, a feedforward block, and gradient updates. Equal attention-score counts and equal elapsed training resources define different comparisons.

With eight row tokens, quintic accuracy rose to 87.81%87.81\% and exceeded quartic accuracy. Pairwise accuracy was again 91.21%91.21\%. Rows change the spatial decomposition, input projection, position table and available tuple set together. Thus the improvement between these two quintic runs cannot be assigned to sequence length alone.

Finite-sample learning curves

Digits cross-entropy (nats) by mean training-set size mm per fold. Validation and test membership are fixed across the four nested sizes in each fold.
mm p=2p=2 p=3p=3 p=4p=4 p=5p=5
tables/curve.tex
Four-patch Digits learning curves. Points are pooled held-out cross-entropies at the four nested training sizes. Dashed lines fit log⁡Lp(m)=ap−αplog⁡m\log L_p(m)=a_p-\alpha_p\log m to the four points of each order.

For every tested order, held-out cross-entropy fell as the number of training examples increased (Table 5). Fitting a zero-floor power law separately in each order gave αp=0.495,0.477,0.474,0.516\alpha_p=0.495,0.477,0.474,0.516. The range 0.470.47–0.520.52 describes local slopes. It is consistent with similar rates over these four sizes and different loss levels. A larger fitted exponent alone does not imply lower error at any tested size. Quintic attention had the largest fitted exponent and the largest loss at every size.

Learning-curve fits. The range spans five separate fold slopes. The last two columns give the largest-size loss predicted using only the three smaller sizes and the measured largest-size loss.
pp αp\alpha_p Fold range Predicted Observed
tables/learn.tex

As a check on extrapolation, fits to the first three sizes overpredicted the loss at the fourth by 26.7%,5.1%,1.8%,15.1%26.7\%,5.1\%,1.8\%,15.1\% (Table 6). The overlapping per-fold slope ranges and the sensitivity to omitting one size leave the asymptotic slope and loss floor unidentified. At fixed epochs, larger training subsets supply more gradient updates, so these curves measure the joint effect of data and this training protocol. They do not estimate a language-model scaling law.

Sensitivity to orbit temperature

Accuracy (%) after Gaussian variance rescaling by orbit, with 60 epochs and four tokens. At p=2p=2 every scale equals one, hence the first column is the original pairwise accuracy.
Dataset p=2p=2 p=3p=3 p=4p=4 p=5p=5
tables/temperature.tex

The intervention from Theorem 7 raised four-patch quintic accuracy from 85.42%85.42\% to 87.81%87.81\% on Digits and from 87.08%87.08\% to 90.45%90.45\% on Wine. Cubic Digits accuracy fell from 89.37%89.37\% to 87.48%87.48\% under the same rule. Table 7 gives all four datasets. The variance law is an exact initialization-model calculation. Its effect on classification remains empirical.

When does another slot pay for itself?

Increasing order permits a direct statistic of more keys. It strictly improves the specified Walsh readout exactly when the target has a previously unavailable component. A dense pairwise head can already attain the optimum on targets in its class, and a larger function class cannot improve on the Bayes risk. For example, if a balanced binary label is independent of the input, every classifier has expected accuracy 1/21/2 at every order. Expressivity gives a route to a gain under particular assumptions, with no distribution-free guarantee of a positive gain.

For an explicit dense kernel the extra slot multiplies the per-query and total score counts by nn. Role symmetry removes redundant permutations, streaming limits auxiliary storage, and separability or a task-specific recurrence can change the arithmetic exponent. The practical choice depends on the support, the kernel, and the target. In these tests a cubic head improved on pairwise attention on Wine, while Digits favored the pairwise head under fixed epochs, a score allowance, and a measured CPU budget. Logistic regression surpassed every tested encoder on three of the four primary datasets. A claim about the best possible order for language, high-resolution vision or long-context training would require experiments in those regimes.

Reproducibility and authorship

The accompanying source archive includes the NumPy encoder and gradients, C++ kernel, raw outer-fold logits and split indices, validation histories, process CPU timings, checksums of source data arrays, numerical oracles, and scripts for the figures and tables. There are 220 encoder fits and 20 logistic fits, plus 20 CPU-budget replays. Data load from scikit-learn 1.8.0. The experiment environment used Python 3.12.16, NumPy 2.3.5, SciPy 1.17.0 and Matplotlib 3.10.8. The archive records the remaining build details. The research question and review direction were supplied by the requester. An AI assistant developed the formalization, wrote and executed the experiments, and drafted the manuscript. The anonymous draft is supplied for author review.

References

  1. A. Vaswani et al. Attention Is All You Need. NeurIPS, 2017. arXiv:1706.03762.

  2. J. Clift, D. Doryn, D. Murfet and J. Wallbridge. Logic and the 2-Simplicial Transformer. ICLR, 2020. arXiv:1909.00668.

  3. J. Alman and Z. Song. How to Capture Higher-Order Correlations? Generalizing Matrix Softmax Attention to Kronecker Computation. ICLR, 2024. arXiv:2310.04064.

  4. A. Roy et al. Fast and Simplex: 2-Simplicial Attention in Triton. 2025. arXiv:2507.02754.

  5. C. Zhou, R. Yu and Y. Wang. On the Theoretical Expressive Power and the Design Space of Higher-Order Graph Transformers. AISTATS, 2024. PMLR 238, 2179–2187.

  6. C. Sanford, D. Hsu and M. Telgarsky. Representational Strengths and Limitations of Transformers. NeurIPS, 2023. arXiv:2306.02896.

  7. N. Gambino and J. Kock. Polynomial Functors and Polynomial Monads. Math. Proc. Camb. Phil. Soc. 154, 153–192, 2013. arXiv:0906.4931.

  8. J. C. Baez, A. E. Hoffnung and C. D. Walker. Higher-Dimensional Algebra VII: Groupoidification. arXiv:0908.4305.

  9. G. S. H. Cruttwell, B. Gavranović, N. Ghani, P. Wilson and F. Zanasi. Categorical Foundations of Gradient-Based Learning. ESOP, 2022. arXiv:2103.01931.

  10. C. O’Neill. Self-Attention as a Parametric Endofunctor: A Categorical Framework for Transformer Architectures. 2025. arXiv:2501.02931.

  11. I. Gálvez-Carrillo, J. Kock and A. Tonks. Homotopy Linear Algebra. Proc. Roy. Soc. Edinburgh Sect. A, 148, 293–325, 2018. arXiv:1602.05082.

  12. M. Milakov and N. Gimelshein. Online Normalizer Calculation for Softmax. 2018. arXiv:1805.02867.

  13. M. N. Rabe and C. Staats. Self-Attention Does Not Need O(n2)O(n^2) Memory. 2021. arXiv:2112.05682.

  14. T. Dao, D. Y. Fu, S. Ermon, A. Rudra and C. Ré. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS, 2022. arXiv:2205.14135.

  15. T. Dao. FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. ICLR, 2024. arXiv:2307.08691.

  16. J. Shah, G. Bikshandi, Y. Zhang, V. Thakkar, P. Ramani and T. Dao. FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-Precision. 2024. arXiv:2407.08608.

  17. T. Zadouri et al. FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling. MLSys, 2026. Conference paper.

  18. A. Katharopoulos, A. Vyas, N. Pappas and F. Fleuret. Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention. ICML, 2020. PMLR 119, 5156–5165.

  19. R. O’Donnell. Analysis of Boolean Functions. Cambridge University Press, 2014, corrected edition 2021. arXiv:2105.10386.

  20. Scikit-learn developers. Toy datasets. The experiment uses the dataset loaders and array order shipped with scikit-learn 1.8.0. Dataset documentation.

  21. R. A. Fisher. Iris. UCI Machine Learning Repository. Dataset 53.

  22. S. Aeberhard and M. Forina. Wine. UCI Machine Learning Repository. Dataset 109.

  23. W. Wolberg, O. Mangasarian, N. Street and W. Street. Breast Cancer Wisconsin (Diagnostic). UCI Machine Learning Repository. Dataset 17.

  24. E. Alpaydin and C. Kaynak. Optical Recognition of Handwritten Digits. UCI Machine Learning Repository. Dataset 80. Bundled subset.

  25. D. P. Kingma and J. Ba. Adam: A Method for Stochastic Optimization. ICLR, 2015. arXiv:1412.6980.

Complete flattened LaTeX source
\documentclass[10pt,twocolumn]{article}

\usepackage[letterpaper,top=.80in,bottom=.78in,left=.76in,right=.76in,columnsep=.27in,headheight=13pt,headsep=14pt,footskip=26pt]{geometry}

\usepackage{amsmath,amssymb,amsthm,graphicx,booktabs,array,mathpazo,xcolor,fancyhdr,caption,flushend}

\usepackage[T1]{fontenc}

\usepackage[colorlinks=true,linkcolor=tealblue,citecolor=tealblue,urlcolor=tealblue]{hyperref}

\definecolor{tealblue}{HTML}{23546B}
\definecolor{ink}{HTML}{23303B}
\definecolor{muted}{HTML}{4D6068}
\usepackage{titlesec}

\titleformat{\section}{\normalfont\large\bfseries\color{ink}}{\thesection}{.52em}{}
\titleformat{\subsection}{\normalfont\normalsize\bfseries\color{ink}}{\thesubsection}{.5em}{}
\titlespacing*{\section}{0pt}{2.3ex plus .5ex minus .25ex}{.8ex}
\titlespacing*{\subsection}{0pt}{1.7ex plus .4ex minus .2ex}{.5ex}
\captionsetup{font=small,labelfont=bf,labelsep=period,justification=raggedright,singlelinecheck=false}
\setlength{\parindent}{1em}
\setlength{\tabcolsep}{3pt}
\setlength{\textfloatsep}{12pt plus 3pt minus 3pt}
\setlength{\dbltextfloatsep}{13pt plus 3pt minus 3pt}
\setlength{\floatsep}{10pt}
\setlength{\emergencystretch}{1.5em}
\setcounter{topnumber}{3}
\renewcommand{\topfraction}{.92}
\renewcommand{\textfraction}{.08}
\renewcommand{\dbltopfraction}{.92}
\raggedbottom
\pagestyle{fancy}
\fancyhf{}
\lhead{\footnotesize\textsc{Interaction order in self-attention}}
\rhead{\footnotesize Research manuscript}
\cfoot{\small\thepage}
\renewcommand{\headrulewidth}{.25pt}
\newtheoremstyle{compact}{.85ex}{.55ex}{\normalfont}{}{\bfseries}{.}{.4em}{}
\theoremstyle{compact}
\newtheorem{theorem}{Theorem}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{corollary}[theorem]{Corollary}
\newcommand{\R}{\mathbb R}
\newcommand{\N}{\mathbb N}
\newcommand{\E}{\mathbb E}
\newcommand{\Var}{\operatorname{Var}}
\newcommand{\soft}{\operatorname{softmax}}
\newcommand{\normop}{\operatorname{Norm}}
\newcommand{\id}{\mathrm{id}}
\newcommand{\Set}{\mathbf{Set}}
\newcommand{\Span}{\mathbf{Span}}
\newcommand{\Mat}{\mathbf{Mat}}
\newcommand{\B}{\mathcal B}
\newcommand{\catE}{\mathcal E}
\hypersetup{pdftitle={Interaction Order in Self-Attention},pdfauthor={Anonymous},pdfsubject={Higher-categorical semantics, exact attention algorithms, and finite-sample scaling}}

\makeatletter
\let\readtablerows\@@input
\makeatother


\begin{document}
\twocolumn[{
\raggedright
{\footnotesize\sffamily\bfseries\color{tealblue} AUTHOR REVIEW COPY \quad / \quad INTENDED FOR HIGHER CATEGORICAL SEMANTICS\par}
\vspace{.55em}
{\fontsize{27}{31}\selectfont\bfseries\color{ink} Interaction Order in Self-Attention\par}
\vspace{.25em}
{\large Weighted spans, exact streaming, and scaling from pairs to quintuples\par}
\vspace{.55em}
{\small Anonymous \hfill December 2026\par}
\vspace{.7em}
{\color{tealblue}\hrule height .65pt}
\vspace{.7em}
\begin{minipage}{\textwidth}
\small
\textbf{Abstract.}
Dense self-attention compares each query with each key. Replacing the key by an ordered tuple of \(p-1\) keys gives \(n^p\) scores on \(n\) tokens. We give a bicategorical semantics of these operators through finite weighted spans and characterize when normalizing a composite agrees with composing normalized kernels. Finite pushforward gives exact streaming and, for tied roles, an exact reduction to multisets. A Gaussian calculation gives an order- and multiplicity-dependent extension of the usual logit scaling. In a fixed-width ordered CPU kernel, the measured sequence-length exponents at orders two through five were \(1.99,2.95,3.94,4.85\). In five-fold experiments with matched parameter counts, cubic attention improved Wine accuracy from \(89.89\%\) to \(93.82\%\). On four-patch Digits the corresponding order-two through order-five accuracies were \(91.21\%,89.37\%,86.70\%,85.42\%\). A Boolean-cube calculation identifies tasks on which increasing the maximum available order strictly decreases the optimal error of a specified readout. Interaction order therefore has an exact combinatorial cost and a task-dependent statistical benefit.
\end{minipage}
\vspace{.8em}
}]
\thispagestyle{plain}

\section{The question of order}

For a sequence of \(n\) vectors, one dense self-attention head assigns a distribution on \(n\) keys to each of \(n\) queries. A score for an image patch can depend directly on one other patch through a dot product. A cubic head can instead score a pair of patches jointly for the same query. The numerical cost of the extra slot is elementary. The statistical question is whether joint scoring improves prediction under a specified distribution, representation, and budget.

Three independent variables enter this question. Sequence length \(n\) determines the number of candidate tuples. Interaction order \(p\) counts the query and the key slots in a single score. Training-set size \(m\) counts labeled examples. A quadratic arithmetic bound in \(n\) says nothing by itself about the degree of the input--output function or the slope of test loss against \(m\). Even at \(p=2\), exponentiation and the softmax denominator make a single output depend nonlinearly on the entire key set. Successive layers can also combine information from several tokens.

The ordinary head is due to Vaswani et al.~\cite{vaswani}. Clift et al.\ introduced 2-simplicial attention using an unsigned scalar triple product and tensor-valued interactions~\cite{clift}. Alman and Song defined the column-wise Kronecker tensor-softmax family used here and analyzed fast approximation and conditional hardness~\cite{alman}. Roy et al.\ implemented efficient cubic attention in Triton and reported gains for language models on a fixed token budget~\cite{roy}. Graph transformers acting on tuple \emph{states} form another family. Pairwise self-attention over \(n^k\) such states already has \(n^{2k}\) ordered pairs~\cite{zhou}. One-layer limitations for particular relational tasks also depend on assumptions on width, precision, and architecture~\cite{sanford}.

Our contribution concerns normalized weighted spans for these heads, exact simplifications and their obstructions, score variance under tied roles, and controlled measurements from order two through five. The fitted exponents below apply to an identified algorithm or an identified finite data range.

\section{From one key to a tuple}
\label{sec:tuple}

Let \(I\) be a nonempty finite set with \(|I|=n\), \(r=p-1\), and \(X=(x_i)_{i\in I}\in(\R^D)^I\). For each role \(a\) put \(k^a_j=W^a_K x_j\in\R^d\), \(v^a_j=W^a_V x_j\in\R^{d_v}\), and let \(q_i=W_Qx_i\in\R^d\). A legal relation \(E\subseteq I\times I^r\) specifies the tuple support \(E_i\). Assume every \(E_i\) is nonempty. For \(J=(j_1,\ldots,j_r)\) put
\begin{align}
 K_J &= \bigodot_{a=1}^r k^a_{j_a},&
 U_J &= \bigodot_{a=1}^r v^a_{j_a}, \label{eq:prod}\\
 s_{iJ} &= d^{-1/2}\langle q_i,K_J\rangle+b_{iJ},&
 Z_i &=\sum_{J\in E_i} e^{s_{iJ}},\label{eq:score}\\
 A_p(X)_i &= Z_i^{-1}\sum_{J\in E_i} e^{s_{iJ}}U_J .\label{eq:attention}
\end{align}
The product is coordinatewise. The classifier uses tied role maps, \(b=0\), all ordered tuples, and sampling with replacement. A repeated index is legal, including a key index equal to the query. For \(p=3\), a score contains terms \(q_{ih}k^1_{jh}k^2_{\ell h}\). The normalization ranges over the joint pair \((j,\ell)\). Two independently normalized pairwise heads would generally give a different distribution.

For \(r=1\) the dense formula is exactly \(\soft(QK^\top/\sqrt d)V\), with row-wise softmax. Heads with different parameters can be concatenated and composed with a pointwise output projection. Adding a residual connection, tokenwise normalization and a feedforward block gives an encoder layer. The general construction permits role-specific tensors, relative biases, sparse relations, and multiple heads. The experiments below fix a smaller class so that order can vary with exactly the same parameter count within a dataset.

\begin{proposition}[Adding an unused slot]\label{prop:lift}
In the role-specific dense family with a constant feature, an order-\(p\) head is realizable at order \(p+1\).
\end{proposition}
\begin{proof}
Set the extra key and value projections to the all-ones vectors and pull the bias back along the projection forgetting the extra key. Each original term occurs \(n\) times in the numerator and denominator of \eqref{eq:attention}. Their ratio is unchanged. On masked supports the same calculation holds for positive constant extension multiplicity on each query fiber.
\end{proof}
This gives weak inclusion of the corresponding function classes. Strict improvement in optimal risk requires a target that separates them. In the tied family an individual extra slot cannot in general be assigned a separate constant map. Even for nested classes, finite-sample estimates and finite-time optimization can reverse their population ordering.

\section{A bicategory for normalized attention}
\label{sec:semantics}

\subsection{Weighted spans and linearization}

Write \(\mathcal S\) for the bicategory with finite sets as objects and a weighted span
\[
 A\xleftarrow{\ell} S\xrightarrow{u}B,\qquad
 w:S\longrightarrow\R_{\geq 0}
\]
as a 1-cell. A 2-cell is a weight-preserving bijection of apices commuting with both legs. Horizontal composition with a span of apex \(T\) uses \(S\times_B T\) and weight \(w(s)v(t)\). Identities are diagonal spans of weight one. The associator sends \(((s,t),u)\) to \((s,(t,u))\). Both sides of the pentagon send a composable four-tuple to the same rebracketing. Cartesian product of spans gives the symmetric monoidal structure. This is a locally groupoidal bicategory, or a \((2,1)\)-category. Attention order \(p\) and categorical dimension are separate parameters.

Define a nonnegative matrix by finite pushforward,
\[
 L(S)(a,b)=
 \sum_{\ell(s)=a,\ u(s)=b} w(s).
\]
Summing first over the common index in the pullback gives \(L(S\times_B T)=L(S)L(T)\). Products of spans give Kronecker products of matrices. Thus \(L\) descends through 2-isomorphisms to a symmetric monoidal linearization into nonnegative matrices, viewed as a locally discrete bicategory. Span constructions and polynomial indexing over locally cartesian closed categories supply the general background~\cite{gambino,baez}.

At fixed \(X\), use the span \(I\leftarrow E\rightarrow I^r\), with the query and tuple projections and weights \(e^{s_{iJ}}\). Dividing by the positive mass \(Z_i\) on each source fiber gives a stochastic matrix \(P_X\). Equation \eqref{eq:attention} is \(P_X U_X\). Real-valued and vector-valued observables can have either sign. The weights remain nonnegative. Changing \(X\) changes both the kernel and the observable. Composing two neural layers therefore includes recomputing the second layer's scores on the first layer's output.

\subsection{Naturality and a topos of token families}

Let \(\B\) be a small skeleton of finite sets and bijections. In the presheaf topos \(\catE=\Set^{\B^{\rm op}}\), put \(T(I)=I\), with inverse transport along a bijection, and \(F_D(I)=(\R^D)^I\), with reindexing by precomposition. The polynomial indexing operation \(T\mapsto T^r\) assigns the set of key tuples. A natural mask is a subobject of \(T\times T^r\). Coordinates, masks, and any positional data must travel with their tokens.

\begin{theorem}[Base change for normalized sums]\label{thm:base}
Suppose finite fibers, scores, and observables are transported along a pullback square. At each source point with positive mass, transport of the normalized pushforward equals the normalized pushforward of the transported data. In particular \(A_p\) is a natural transformation from \(F_D\) to \(F_{d_v}\) when the data in \eqref{eq:attention} are natural in token bijections.
\end{theorem}
\begin{proof}
For a map \(\pi:E\to I\) and a reindexing \(u:I'\to I\), the fiber of \(I'\times_I E\to I'\) over \(i'\) is canonically \(E_{u(i')}\). The two numerator sums agree term by term, as do the masses. Division gives the claim. For token bijections the maps on tuples are the componentwise bijections \(J\mapsto u^rJ\), with the same argument on each query.
\end{proof}

For example, reordering both pixel patches and their position embeddings permutes the encoder outputs. Reordering only the pixel data while keeping the embeddings at their old positions changes the input assignment. Rebuilding a full tuple set after a nonbijective change of tokens can also change normalized attention. At constant score with values \(0,1\), duplicating the zero-valued key changes the average from \(1/2\) to \(1/3\). An actual pullback of an existing score fiber and a change of its counting measure are different operations.

A parameterized layer is a pair \((\Theta,f)\) with \(f:\underline{\Theta}\times F_D\to F_{D'}\) natural, where \(\underline{\Theta}\) is the constant parameter object. A reparameterization \(\rho:\Theta\to\Theta'\) is a 2-cell when \(f=f'\circ(\rho\times\id)\). Layers compose by product of parameter spaces and substitution. Canonical product associators give the coherence maps. Shared role weights arise by precomposing the role-specific family with the diagonal on parameter spaces. This uses the parametric approach to learning~\cite{cruttwell,oneill} with set-valued maps that include the nonlinear normalization. A learned position table for a fixed length is an additional input of type \(F_D(I)\), or a parameter transported in the indexed family at that length.

\subsection{Homotopy fibers and symmetric tuples}

There is a higher analogue in the \(\infty\)-category of spaces. Let each homotopy fiber \(E_i^h\) of \(E\to I\) be \(\pi\)-finite, with finitely many components and finite homotopy groups, trivial in sufficiently high degree. For a component represented by \(e\), put
\[
 \omega(e)=\prod_{k\ge1}|\pi_k(E_i^h,e)|^{(-1)^k}.
\]
For weights \(w>0\) and vector observations \(U\) constant on components of the fibers and compatible with transport, define
\[
 \mathcal A_i=
 \frac{\sum_{[e]\in\pi_0 E_i^h}\omega(e)w(e)U(e)}
      {\sum_{[e]\in\pi_0 E_i^h}\omega(e)w(e)}.
\]
The sums use homotopy cardinality~\cite{homotopy}. On nonempty fibers any homotopy pullback preserves this value because it induces an equivalence between the corresponding fibers and transports their weights and observables. For a map of discrete sets the formula is Theorem~\ref{thm:base}.

An application gives an algebraic reason for the multiplicity correction in symmetric heads. For role-invariant scores and values, take the action groupoid \(I^r\mathbin{/\mkern-6mu/} S_r\) as the fiber. The component of a multiset with counts \(c_j\) has automorphism group \(\prod_j S_{c_j}\). Its homotopy weight is \(1/\prod_j c_j!\), exactly \(1/r!\) times the number of its ordered representatives. The common factor cancels in the normalized sum. With two keys \(a,b\), two roles and zero scores, the resulting probabilities of \(aa,ab,bb\) are \(1/4,1/2,1/4\). A uniform measure on the three coarse classes gives \(1/3\) apiece. Automorphisms thus have a numerically observable effect.

\subsection{An obstruction to flattening layers}

For a positive matrix \(W\), write \(\normop W\) for row normalization. Composable stochastic matrices compose in the usual way. Normalizing two factors introduces intermediate row masses.

\begin{proposition}[Path-normalization obstruction]\label{prop:obstruction}
Fix a source \(i\), first-stage weights \(W_{ij}>0\) on its support, and second-stage weights \(V_{jk}\geq0\) with \(z_j=\sum_k V_{jk}>0\). The joint law of paths \((j,k)\) formed by successive row normalizations equals the single normalization of \(W_{ij}V_{jk}\) exactly when \(z_j\) is constant on the reachable intermediate states.
\end{proposition}
\begin{proof}
Let \(s_i=\sum_j W_{ij}\) and \(t_i=\sum_j W_{ij}z_j\). At a positive path the two masses are \(W_{ij}V_{jk}/(s_i z_j)\) and \(W_{ij}V_{jk}/t_i\). Equality for every such path is equivalent to \(z_j=t_i/s_i\) for each reachable \(j\).
\end{proof}
For equal first-stage weights and disjoint deterministic terminal states with outgoing masses 1 and 2, successive normalization gives terminal probabilities \(1/2,1/2\). A single normalization gives \(1/3,2/3\). Marginalization can hide a path discrepancy if distinct paths share a terminal state. The equivalence above is for the joint path law. At fixed scores, subtracting \(\log z_j\) from the joint path score restores successive normalization. This supplies an explicit obstruction to replacing depth by an uncorrected higher-order softmax.

\section{Cost laws and exact implementations}
\label{sec:cost}

\subsection{Sequence length and support}

For fixed \(p,d,d_v\), a direct dense forward pass evaluates \(n^p\) scalar scores per head and example. Generating each product \(K_J,U_J\) once and sharing it across queries costs \(O(r n^r(d+d_v))\). The matrix of scores and its action on values cost \(\Theta(n^{r+1}(d+d_v))\) for the direct dot products and reductions. With head width proportional to model width \(D\) and fixed head count, projection and feedforward work add \(O(nD^2+nD D_{\rm ff})\). Thus even the dominant term in whole-encoder cost depends on length and width. Multiplying batch size or the number of independent heads multiplies the corresponding attention work.

\begin{table}[t]
\caption{Score evaluations per head and example. There are \(r=p-1\) key slots. Repeated key indices are allowed unless a support restriction removes them.}
\label{tab:counts}
\centering\small
\begin{tabular}{@{}ll@{}}
\toprule Support or evaluation & Score count \\ \midrule
Ordered dense & \(n^p\)\\
All keys in the query prefix & \(\sum_{i=1}^n i^r\)\\
At most \(w\) keys per slot & \(\le n w^r\)\\
Symmetric dense, one per orbit & \(n\binom{n+r-1}{r}\)\\
Arbitrary legal tuples & \(\sum_i |E_i|\)\\
\bottomrule
\end{tabular}
\end{table}

Doubling \(n\) multiplies dense score count by \(4,8,16,32\) at \(p=2,3,4,5\). Increasing \(p\) by one at fixed \(n\) multiplies it by \(n\). For a causal prefix the leading count is \(n^p/p+O(n^{p-1})\). One new query at prefix length \(n\) costs \(n^{p-1}\) scores if the per-token projections are cached. At a fixed score budget \(C\), the maximum dense length is \(\lfloor C^{1/p}\rfloor\). These counts are for explicit enumeration.

\begin{proposition}[Oracle lower bound]\label{prop:oracle}
If an algorithm has only pointwise access to arbitrary independent logits and must return exact normalized means for all logits, a dense \(p\)-ary head requires \(n^p\) queries in the worst case, for \(n\ge2\).
\end{proposition}
\begin{proof}
Choose binary tuple values with both values represented. Answer every logit query by zero. The mean in every row lies strictly between zero and one. Altering any unqueried logit in a row changes its mean, since that tuple's value differs from the original mean. An exact deterministic algorithm must therefore inspect every logit in every row.
\end{proof}
Structured scores such as \eqref{eq:prod} do not supply independent oracle entries. In the structured setting Alman and Song give bounded-entry approximation algorithms and conditional hardness results in specified parameter regimes~\cite{alman}. Proposition~\ref{prop:oracle} does not transfer a lower bound to these structured algorithms.

\subsection{FlashAttention and exact streaming}

A materialized forward pass needs space for \(n^p\) scores, apart from inputs and outputs. FlashAttention computes the ordinary dense softmax by tiling, maintaining online row normalizers, and recomputing intermediates during backpropagation~\cite{online,rabe,flash}. In the original two-level model with \(d\le M\le nd\) on-chip words and equal head and value widths, the analyzed pairwise kernel transfers \(\Theta(n^2d^2/M)\) words to or from high-bandwidth memory. Its explicit arithmetic remains quadratic in \(n\). FlashAttention-2 refines block and warp work partitioning~\cite{flash2}. FlashAttention-3 overlaps operations on Hopper GPUs and includes a low-precision variant~\cite{flash3}. FlashAttention-4 adapts the pipelines and exponential calculation to Blackwell hardware~\cite{flash4}. Mathematical equality uses exact arithmetic. Finite precision and low-precision variants have their own numerical errors.

The same reduction applies to disjoint blocks of any finite tuple fiber. For a nonempty block \(B\subseteq E_i\) define
\[
 m_B=\max_{J\in B}s_{iJ},\ \
 z_B=\sum_{J\in B}e^{s_{iJ}-m_B},\ \
 u_B=\sum_{J\in B}e^{s_{iJ}-m_B}U_J .
\]
For disjoint blocks with summaries \((m,z,u),(m',z',u')\), their combined maximum is \(h=\max(m,m')\) and the combined denominator and numerator are
\[
 (z'',u'')=e^{m-h}(z,u)+e^{m'-h}(z',u').
\]
Treat an empty block as a separate identity element, so that no subtraction of two infinities is needed.

\begin{theorem}[Invariance under tile refinement]\label{thm:tile}
Block combination is associative and commutative on valid summaries in exact arithmetic. Every partition and every merge tree returns \eqref{eq:attention} as \(u/z\).
\end{theorem}
\begin{proof}
The combined maximum is the maximum over the union. A term from the first block contributes \(e^{m-h}e^{s-m}=e^{s-h}\), and the same identity holds for the second block. The combined summary is therefore the unique summary defined by the union. Associativity and commutativity follow from finite union and addition. The diagonal scaling cancels in the final ratio.
\end{proof}

With fixed query and tuple tile sizes \(B_q,B_t\), forward working storage including projections and outputs is
\[
 O\!\left(nr(d+d_v)+B_t(d+d_v)+B_qB_t\right)
\]
for fixed \(p\), with an additional \(O(B_t r)\) if tuple indices are stored explicitly. Factored supports and biases are assumed to be generated on demand. A dense bias supplied as input has its own \(n^p\) storage cost. For reverse mode one can save the output and log partition per query and regenerate weights. For an upstream vector \(g_i\),
\[
 \frac{\partial L}{\partial s_{iJ}}
   =P_X(i,J)\,\langle g_i,U_J-A_p(X)_i\rangle .
\]
This identity follows by differentiating a row softmax and permits streamed gradient accumulation. The reference C++ kernel below implements ordered \emph{forward} streaming. The NumPy training implementation instead stores the smaller orbit-level activations. Neither a higher-order GPU I/O bound nor a GPU speedup is inferred from the CPU timings. A hardware-optimized cubic kernel is already available~\cite{roy}.

\subsection{Two exact simplifications}

\begin{proposition}[Quotient by role permutations]\label{prop:orbit}
Suppose support, scores, and values are invariant under the action of \(S_r\) permuting the key roles. For the full product \(I^r\), replace a tuple by its count vector \(c=(c_1,\ldots,c_n)\) with \(\sum_j c_j=r\). With \(h_c=r!/\prod_j c_j!\), \eqref{eq:attention} equals a softmax over \(\binom{n+r-1}{r}\) representatives per query with logits \(s_{ic}+\log h_c\).
\end{proposition}
\begin{proof}
All tuples in one orbit have identical score and observable, and the stabilizer has size \(\prod_j c_j!\). In the numerator and denominator their total weight is \(h_c e^{s_{ic}}\). Weak compositions of \(r\) into \(n\) parts index the orbits.
\end{proof}
The orbit map is a finite pushforward. Treating every representative as equally frequent would change the counting measure. For fixed \(r\) this quotient preserves the leading exponent and divides the leading score count by \(r!\). At \(n=4\), ordered per-query counts \(4,16,64,256\) become \(4,10,20,35\). Independent role maps generally break the invariance.

A second simplification can lower the exponent. Suppose on the full Cartesian support the \emph{positive kernel itself} has a supplied decomposition
\[
 W(i,J)=\sum_{h=1}^{H}\prod_{a=1}^{r} w_{ha}(i,j_a),
 \qquad w_{ha}\geq0 .
\]
Then finite distributivity gives the exact denominator and numerator
\begin{align*}
 Z_i &=\sum_h\prod_a\sum_j w_{ha}(i,j),\\
 N_i &=\sum_h\bigodot_a\left(\sum_j w_{ha}(i,j)v^a_j\right).
\end{align*}
For bounded \(H,r\) and widths, evaluating all factors costs \(O(Hr n^2)\) for all queries if each factor is available at constant cost. Additive slot scores \(s(i,J)=\sum_a s_a(i,j_a)\) give \(H=1\). Conversely a low-rank multilinear expression for the \emph{logit} does not give a bounded-rank decomposition of its exponential. Kernelized linear attention exploits related algebraic reordering for a different choice or approximation of kernel~\cite{linear}. Thus neither semantic arity nor low-rank logits alone determine an arithmetic exponent.

\section{Logit scaling and statistical order}
\label{sec:scaling}

\subsection{Repeated indices change the variance}

The factor \(1/\sqrt d\) scales a sum across coordinates. In an idealized untied head, if all query and role-key coordinates used in a score are independent, centered, and have unit variance, the product in each coordinate has variance one. The sum of \(d\) such terms divided by \(\sqrt d\) again has variance one at every order. Tied roles with repeated indices require a different calculation.

\begin{theorem}[Gaussian multiplicity law]\label{thm:variance}
Assume the \(q_h\) and \(k_{jh}\) are independent standard Gaussians across tokens and coordinates, with the same \(k\) reused across key slots and with zero bias. Conditional on a fixed tuple with counts \(c\), the score in \eqref{eq:score} has mean zero and variance
\[
 \sigma_c^2=\prod_{j:c_j>0}(2c_j-1)!! .
\]
For independent uniform key indices, the variance averaged over tuples is
\begin{equation}
 V(n,r)=\prod_{a=0}^{r-1}\left(1+\frac{2a}{n}\right).
 \label{eq:var}
\end{equation}
\end{theorem}
\begin{proof}
Centering follows from the independent query. Distinct coordinates have zero covariance. Each second moment factors into the even Gaussian moments \(\E k^{2c}=(2c-1)!!\), so the normalized coordinate sum has variance \(\sigma_c^2\). Given the keys in one coordinate, the expected product of their squares over uniform tuples is \((n^{-1}\sum_j k_j^2)^r\). Its expectation is the \(r\)-th moment of \(\chi_n^2/n\), which is the product in \eqref{eq:var}.
\end{proof}

At \(n=4\), \(V\) is \(1,1.5,3,7.5\) for the four orders. For four identical key indices the conditional variance is \(7!!=105\). Dividing the bias-free logit by \(\sigma_c\) gives unit variance on each orbit under these assumptions. The orbit mass correction \(\log h_c\) is then added \emph{after} rescaling. A check with \(2^{20}\) independent Gaussian key vectors, integrating over the query and index choices, gave \(0.9992,1.4973,2.9902,7.4571\). The experiment below tests this temperature as a model change. Learned query and key projections of a common input can violate independence and Gaussianity.

\subsection{A target with a strict higher-order gain}

Let \(x_j\) be independent uniform signs. Mask out repeated \emph{key} indices, set all scores to zero, and use scalar values \(v_j=x_j\). Up to a known constant each query returns the same degree-\(r\) symmetric Walsh observable
\begin{equation}
 \phi_r(x)=\binom{n}{r}^{-1/2}
             \sum_{\substack{S\subseteq I\\|S|=r}}\prod_{j\in S}x_j .
 \label{eq:walsh}
\end{equation}
Indeed every unordered subset occurs \(r!\) times, so multiplying the uniform attention mean by \(\sqrt{\binom nr}\) gives \(\phi_r\).

\begin{proposition}[Exact order threshold for a linear readout]\label{prop:walsh}
Let \(1\le s\le n\). For target \(\phi_s\) and readout space \(\mathrm{span}(1,\phi_1,\ldots,\phi_k)\), the minimum population mean squared error is 1 for \(k<s\) and 0 for \(k\ge s\).
\end{proposition}
\begin{proof}
In the Walsh basis~\cite{walsh}, two distinct sign monomials have zero inner product because some sign occurs exactly once in their product. Each monomial has squared norm one. The normalized sums in \eqref{eq:walsh} are therefore orthonormal, including the constant \(\phi_0=1\). Orthogonal projection of \(\phi_s\) onto the stated space is either zero or \(\phi_s\).
\end{proof}
Exhaustive least squares on all \(2^8=256\) sign vectors for \(s,k=1,\ldots,4\) reproduced the sixteen entries of this error matrix to \(3\times10^{-15}\). For instance adding a quintic head exposes the degree-four target directly. This is a strict benefit for a specified family of uniform masked heads and a linear readout. A deeper pairwise network or a nonlinear readout belongs to another class. Even the cost of this particular target can be reduced using the elementary-symmetric recurrence \(e_j^{(t)}=e_j^{(t-1)}+x_t e_{j-1}^{(t-1)}\), starting with \(e_0=1\) and \(e_{j>0}=0\). Its \(O(nr)\) scalar work further separates feature order from enumeration cost.

\section{Experimental design}
\label{sec:methods}

\subsection{Four classification datasets}

We used the bundled scikit-learn versions of four UCI datasets~\cite{skdata,iris,wine,wdbc,digits}. Iris contains 150 examples, four features and three classes. Wine contains 178 examples, 13 features and three classes. Wisconsin Diagnostic Breast Cancer (WDBC) contains 569 examples, 30 features and two classes. The bundled Digits dataset contains 1,797 examples, \(8\times 8\) pixels and ten classes, drawn from the test portion of the original UCI release. All reported partitions are new partitions within each bundled dataset. WDBC is used solely for a benchmark comparison.

The primary design used four tokens per example. For tabular data we standardized each original feature using only the current training subset, padded the final feature group with zeros, and split the original feature order into four consecutive groups of equal size. Iris therefore has one feature per token, Wine four after padding, and WDBC eight. For Digits we standardized the 64 pixel positions separately and used the four \(4\times4\) quadrants in raster order. An additional experiment used eight row tokens of eight pixels each. With four tokens some order-five interactions must repeat a token if the query is counted. With eight tokens all five indices can be distinct.

Five shuffled stratified outer folds assigned every example to one held-out fold. Within each remaining \(80\%\), we reserved a stratified \(20\%\) for validation. Thus the training, validation, and test fractions were approximately \(64\%,16\%,20\%\). We used the same partitions and initialization seed within a fold across interaction orders. For the Digits learning curves, one random permutation per class within each fold supplied nested training subsets at \(1/8,1/4,1/2,1\) of the training pool. Each subset had its own fitted standardization. No test score entered checkpoint selection.

\subsection{Trainable encoders and controls}

Each encoder has one head and one residual block of width \(D=d=d_v=16\). For input patches \(x\), learned positional vectors \(P\), a shared linear embedding \(W_e\), and parameter-free feature LayerNorm \(\ell\) with \(\epsilon=10^{-5}\), the computations are
\begin{align*}
 Z &= xW_e+P,\\
 H &= Z+A_p(\ell(Z))W_O,\\
 F &= H+\mathrm{ReLU}(\ell(H)W_1+b_1)W_2+b_2,\\
 \hat z &= \mathrm{mean}_{i\in I}(F_i)W_C+b_C .
\end{align*}
The feedforward inner width is 32. All query, key, value, embedding, output and classifier matrices are trained jointly. Every order has 2,227 trainable parameters for Iris, 2,275 for Wine, 2,322 for WDBC, 2,586 for four-patch Digits and 2,522 for eight-row Digits.

We minimized multiclass cross-entropy for 60 epochs with Adam~\cite{adam}, learning rate 0.003, default moments \(0.9,0.999\), batch size 32, and global gradient-norm clipping at 5. Training used float32, a shared initialization scheme, and identical per-fold minibatch permutations across orders. We used no weight decay or dropout. The main test prediction is from the eligible epoch with the smallest validation cross-entropy, taking the earliest minimizer. A standardized-feature logistic regression with \(C=1\), trained on the same training records, gives a conventional baseline. The fixed hyperparameters specify a controlled comparison. A separate search per architecture would answer a different question.

Three resource comparisons are reported. The first gives each architecture 60 training epochs and selects its checkpoint by validation. The second caps per-example training scores in the \emph{implemented multiset representation}. For \(M_p=\binom{n+p-2}{p-1}\) representatives per query, the eligible epochs are
\[
 E_p^{\rm score}=\left\lfloor 60\,\frac{n}{M_p}\right\rfloor.
\]
At \(n=4\) this yields \(60,24,12,6\) epochs. The last value uses \(87.5\%\) of the budget because only completed epochs are eligible. The cap counts forward scores corresponding to training examples. Projection, feedforward, validation, and memory traffic are outside that count.

The third comparison fixes measured training CPU time per fold on four-patch Digits. On one pinned core we replayed the same training trajectories, timed forward, backward and Adam updates with process CPU time, and used the 60-epoch pairwise time of that fold as its budget. Validation and testing were outside the clock. An epoch crossing the limit was ineligible. Recording its time established the boundary. The five reference budgets ranged from 0.931 to 1.148 process CPU seconds in this environment. Eligible validation histories agreed with the original runs to \(10^{-6}\). The artifact retains the measured durations and fold-specific budgets.

\begin{table*}[t]
\caption{Out-of-fold accuracy and cross-entropy with four tokens. Each example receives one prediction from its outer test fold. Attention models use tied roles and a common 60-epoch training allowance. LR denotes logistic regression on the original standardized features.}
\label{tab:main}
\centering\small
\setlength{\tabcolsep}{5.1pt}
\begin{tabular}{@{}lrrrrr@{\hspace{1.4em}}rrrrr@{}}
\toprule
 & \multicolumn{5}{c}{Accuracy (\%, larger is better)} & \multicolumn{5}{c}{Cross-entropy (nats, smaller is better)}\\
\cmidrule(lr){2-6}\cmidrule(lr){7-11}
Dataset & LR & \(p=2\)&\(p=3\)&\(p=4\)&\(p=5\)& LR &\(p=2\)&\(p=3\)&\(p=4\)&\(p=5\)\\\midrule
\readtablerows tables/main.tex
\bottomrule
\end{tabular}
\end{table*}

\subsection{Kernel benchmark and numerical checks}

A separate serial C++17 kernel evaluated every ordered tuple with float64 arithmetic, \(d=d_v=8\), one head, one example and a tile of 64 key tuples. The kernel forms tile-local key and value products once, then streams all query rows over the tile. Timing includes temporary allocation and reduction, starting with projected inputs. Each case used a warm-up forward pass. Nine randomized rounds each visited six lengths per order. Each timed block repeated full forward calls until at least 25 milliseconds had elapsed. We regressed log median seconds against log length across the six sizes per order. The host reported an AMD EPYC 9V74 CPU. The process was pinned to one logical CPU, using GCC 14.2 with \texttt{-O3} and \texttt{-std=c++17}. The trainer uses multiset enumeration. The C++ reference evaluates the same tied-role function on ordered tuples with the original logit scale.

We compared dense Cartesian NumPy evaluation with multiset evaluation and four streaming tile sizes. Maximum absolute forward discrepancies over the four orders were below \(2.4\times10^{-14}\) in float64. The maximum full-encoder directional derivative error was \(2.3\times10^{-9}\), and that for the attention input derivatives was \(3.1\times10^{-9}\). Reindexing including repeated keys agreed to \(7.2\times10^{-15}\). The compiled kernel agreed with the independent Cartesian oracle to \(1.0\times10^{-14}\) on 12 combinations of \(n\) and \(p\). The orbit-temperature variant passed a separate dense-oracle and derivative check. These are numerical consistency tests on specified inputs.

\section{Measured scaling and predictive performance}

\subsection{Length scaling of explicit enumeration}

\begin{table}[t]
\caption{Fitted runtime exponent \(\beta_p\) in \(T_p(n)=a_p n^{\beta_p}\) for the ordered CPU forward kernel. The range is the minimum and maximum slope after deleting one length. \(R^2\) is on log scales.}
\label{tab:time}
\centering\small
\begin{tabular}{@{}rrrrr@{}}
\toprule \(p\)&\(n\) range&\(\beta_p\)&Delete-one range&\(R^2\)\\\midrule
\readtablerows tables/timing.tex
\bottomrule
\end{tabular}
\end{table}

The fitted exponent increases from 1.986 at \(p=2\) to 4.852 at \(p=5\) (Table~\ref{tab:time}). The lengths intentionally differ across orders to keep the number of tuple evaluations in a comparable range. Roughly the same 18--21 ms took 1,536 tokens at order two and 19 tokens at order five at the largest respective measurements. The quintic fit is below five throughout the delete-one-size analysis. Tuple generation, short rows and tile boundaries contribute finite-size terms to this implementation. The exact count is \(n^5\) at every length regardless of the wall-time slope.

\begin{figure}[t]
\centering\includegraphics[width=\linewidth]{figures/time.pdf}
\caption{Ordered forward time on one CPU core. Points are nine-round medians, vertical lines give the 10th--90th percentile across rounds, and solid lines are power-law fits. Each order has its own measured length interval.}
\label{fig:time}
\end{figure}

\subsection{Fixed exposure on the four datasets}



The pairwise head attained the highest attention-model accuracy on Iris, WDBC, and Digits (Table~\ref{tab:main}). Cubic attention had the highest attention-model accuracy on Wine. Of 178 Wine cases, eleven classified incorrectly by the pairwise model were correct under the cubic model, and four changed in the opposite direction. The net difference is seven cases or \(3.93\) percentage points. The paired fold differences ranged from \(0.0\) to \(11.4\) points, with three favorable folds and two ties. Logistic regression classified 176 cases correctly on that dataset, compared with 167 for cubic attention.

On Digits, the quintic head corrected 70 of the pairwise head's errors and lost 174 of its correct predictions. The net change was \(-104/1797\), or \(-5.79\) points. All five fold differences were negative, from \(-8.1\) to \(-2.8\) points. In WDBC the cubic head had slightly lower cross-entropy than the pairwise head despite slightly lower accuracy. Accuracy and cross-entropy therefore give different orderings even for a fixed set of predictions. The number of folds is small and their training sets overlap. These differences describe paired observations on the specified partitions.

\begin{table}[htb]
\caption{Digits accuracy (\%) by budget and tokenization. The first three columns after \(p\) use four patches. Parentheses give eligible epochs or their five-fold range. The row-token comparison uses 60 epochs.}
\label{tab:budget}
\centering\footnotesize
\setlength{\tabcolsep}{2.1pt}
\begin{tabular}{@{}rrrrr@{}}
\toprule \(p\)&60 epochs&Score cap&CPU cap&8 rows\\\midrule
\readtablerows tables/budget.tex
\bottomrule
\end{tabular}
\end{table}

The observed CPU cap admitted the validation-selected checkpoint in every four-patch Digits run, so it returned the same predictions as the 60-epoch comparison. The score cap reduced quintic accuracy to \(82.80\%\) (Table~\ref{tab:budget}). Whole-encoder CPU time varies more slowly with order at four tokens because the trainer shares tuple products and also computes embeddings, a feedforward block, and gradient updates. Equal attention-score counts and equal elapsed training resources define different comparisons.

With eight row tokens, quintic accuracy rose to \(87.81\%\) and exceeded quartic accuracy. Pairwise accuracy was again \(91.21\%\). Rows change the spatial decomposition, input projection, position table and available tuple set together. Thus the improvement between these two quintic runs cannot be assigned to sequence length alone.

\subsection{Finite-sample learning curves}

\begin{table}[htb]
\caption{Digits cross-entropy (nats) by mean training-set size \(m\) per fold. Validation and test membership are fixed across the four nested sizes in each fold.}
\label{tab:curve}
\centering\small
\begin{tabular}{@{}rrrrr@{}}
\toprule \(m\)&\(p=2\)&\(p=3\)&\(p=4\)&\(p=5\)\\\midrule
\readtablerows tables/curve.tex
\bottomrule
\end{tabular}
\end{table}

\begin{figure}[t]
\centering\includegraphics[width=\linewidth]{figures/learning.pdf}
\caption{Four-patch Digits learning curves. Points are pooled held-out cross-entropies at the four nested training sizes. Dashed lines fit \(\log L_p(m)=a_p-\alpha_p\log m\) to the four points of each order.}
\label{fig:learning}
\end{figure}

For every tested order, held-out cross-entropy fell as the number of training examples increased (Table~\ref{tab:curve}). Fitting a zero-floor power law separately in each order gave \(\alpha_p=0.495,0.477,0.474,0.516\). The range \(0.47\)--\(0.52\) describes local slopes. It is consistent with similar rates over these four sizes and different loss levels. A larger fitted exponent alone does not imply lower error at any tested size. Quintic attention had the largest fitted exponent and the largest loss at every size.

\begin{table}[htb]
\caption{Learning-curve fits. The range spans five separate fold slopes. The last two columns give the largest-size loss predicted using only the three smaller sizes and the measured largest-size loss.}
\label{tab:learn}
\centering\small
\begin{tabular}{@{}rrrrr@{}}
\toprule \(p\)&\(\alpha_p\)&Fold range&Predicted&Observed\\\midrule
\readtablerows tables/learn.tex
\bottomrule
\end{tabular}
\end{table}

As a check on extrapolation, fits to the first three sizes overpredicted the loss at the fourth by \(26.7\%,5.1\%,1.8\%,15.1\%\) (Table~\ref{tab:learn}). The overlapping per-fold slope ranges and the sensitivity to omitting one size leave the asymptotic slope and loss floor unidentified. At fixed epochs, larger training subsets supply more gradient updates, so these curves measure the joint effect of data and this training protocol. They do not estimate a language-model scaling law.

\subsection{Sensitivity to orbit temperature}

\begin{table}[htb]
\caption{Accuracy (\%) after Gaussian variance rescaling by orbit, with 60 epochs and four tokens. At \(p=2\) every scale equals one, hence the first column is the original pairwise accuracy.}
\label{tab:temp}
\centering\small
\begin{tabular}{@{}lrrrr@{}}
\toprule Dataset&\(p=2\)&\(p=3\)&\(p=4\)&\(p=5\)\\\midrule
\readtablerows tables/temperature.tex
\bottomrule
\end{tabular}
\end{table}

The intervention from Theorem~\ref{thm:variance} raised four-patch quintic accuracy from \(85.42\%\) to \(87.81\%\) on Digits and from \(87.08\%\) to \(90.45\%\) on Wine. Cubic Digits accuracy fell from \(89.37\%\) to \(87.48\%\) under the same rule. Table~\ref{tab:temp} gives all four datasets. The variance law is an exact initialization-model calculation. Its effect on classification remains empirical.

\section{When does another slot pay for itself?}

Increasing order permits a direct statistic of more keys. It strictly improves the specified Walsh readout exactly when the target has a previously unavailable component. A dense pairwise head can already attain the optimum on targets in its class, and a larger function class cannot improve on the Bayes risk. For example, if a balanced binary label is independent of the input, every classifier has expected accuracy \(1/2\) at every order. Expressivity gives a route to a gain under particular assumptions, with no distribution-free guarantee of a positive gain.

For an explicit dense kernel the extra slot multiplies the per-query and total score counts by \(n\). Role symmetry removes redundant permutations, streaming limits auxiliary storage, and separability or a task-specific recurrence can change the arithmetic exponent. The practical choice depends on the support, the kernel, and the target. In these tests a cubic head improved on pairwise attention on Wine, while Digits favored the pairwise head under fixed epochs, a score allowance, and a measured CPU budget. Logistic regression surpassed every tested encoder on three of the four primary datasets. A claim about the best possible order for language, high-resolution vision or long-context training would require experiments in those regimes.

\subsection*{Reproducibility and authorship}

The accompanying source archive includes the NumPy encoder and gradients, C++ kernel, raw outer-fold logits and split indices, validation histories, process CPU timings, checksums of source data arrays, numerical oracles, and scripts for the figures and tables. There are 220 encoder fits and 20 logistic fits, plus 20 CPU-budget replays. Data load from scikit-learn 1.8.0. The experiment environment used Python 3.12.16, NumPy 2.3.5, SciPy 1.17.0 and Matplotlib 3.10.8. The archive records the remaining build details. The research question and review direction were supplied by the requester. An AI assistant developed the formalization, wrote and executed the experiments, and drafted the manuscript. The anonymous draft is supplied for author review.


\begin{thebibliography}{25}\small
\bibitem{vaswani} A. Vaswani et al. \emph{Attention Is All You Need}. NeurIPS, 2017. \href{https://arxiv.org/abs/1706.03762}{arXiv:1706.03762}.
\bibitem{clift} J. Clift, D. Doryn, D. Murfet and J. Wallbridge. \emph{Logic and the 2-Simplicial Transformer}. ICLR, 2020. \href{https://arxiv.org/abs/1909.00668}{arXiv:1909.00668}.
\bibitem{alman} J. Alman and Z. Song. \emph{How to Capture Higher-Order Correlations? Generalizing Matrix Softmax Attention to Kronecker Computation}. ICLR, 2024. \href{https://arxiv.org/abs/2310.04064}{arXiv:2310.04064}.
\bibitem{roy} A. Roy et al. \emph{Fast and Simplex: 2-Simplicial Attention in Triton}. 2025. \href{https://arxiv.org/abs/2507.02754}{arXiv:2507.02754}.
\bibitem{zhou} C. Zhou, R. Yu and Y. Wang. \emph{On the Theoretical Expressive Power and the Design Space of Higher-Order Graph Transformers}. AISTATS, 2024. \href{https://proceedings.mlr.press/v238/zhou24a.html}{PMLR 238, 2179--2187}.
\bibitem{sanford} C. Sanford, D. Hsu and M. Telgarsky. \emph{Representational Strengths and Limitations of Transformers}. NeurIPS, 2023. \href{https://arxiv.org/abs/2306.02896}{arXiv:2306.02896}.
\bibitem{gambino} N. Gambino and J. Kock. \emph{Polynomial Functors and Polynomial Monads}. Math. Proc. Camb. Phil. Soc. 154, 153--192, 2013. \href{https://arxiv.org/abs/0906.4931}{arXiv:0906.4931}.
\bibitem{baez} J. C. Baez, A. E. Hoffnung and C. D. Walker. \emph{Higher-Dimensional Algebra VII: Groupoidification}. \href{https://arxiv.org/abs/0908.4305}{arXiv:0908.4305}.
\bibitem{cruttwell} G. S. H. Cruttwell, B. Gavranovi\'c, N. Ghani, P. Wilson and F. Zanasi. \emph{Categorical Foundations of Gradient-Based Learning}. ESOP, 2022. \href{https://arxiv.org/abs/2103.01931}{arXiv:2103.01931}.
\bibitem{oneill} C. O'Neill. \emph{Self-Attention as a Parametric Endofunctor: A Categorical Framework for Transformer Architectures}. 2025. \href{https://arxiv.org/abs/2501.02931}{arXiv:2501.02931}.
\bibitem{homotopy} I. G\'alvez-Carrillo, J. Kock and A. Tonks. \emph{Homotopy Linear Algebra}. Proc. Roy. Soc. Edinburgh Sect. A, 148, 293--325, 2018. \href{https://arxiv.org/abs/1602.05082}{arXiv:1602.05082}.
\bibitem{online} M. Milakov and N. Gimelshein. \emph{Online Normalizer Calculation for Softmax}. 2018. \href{https://arxiv.org/abs/1805.02867}{arXiv:1805.02867}.
\bibitem{rabe} M. N. Rabe and C. Staats. \emph{Self-Attention Does Not Need \(O(n^2)\) Memory}. 2021. \href{https://arxiv.org/abs/2112.05682}{arXiv:2112.05682}.
\bibitem{flash} T. Dao, D. Y. Fu, S. Ermon, A. Rudra and C. R\'e. \emph{FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness}. NeurIPS, 2022. \href{https://arxiv.org/abs/2205.14135}{arXiv:2205.14135}.
\bibitem{flash2} T. Dao. \emph{FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning}. ICLR, 2024. \href{https://arxiv.org/abs/2307.08691}{arXiv:2307.08691}.
\bibitem{flash3} J. Shah, G. Bikshandi, Y. Zhang, V. Thakkar, P. Ramani and T. Dao. \emph{FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-Precision}. 2024. \href{https://arxiv.org/abs/2407.08608}{arXiv:2407.08608}.
\bibitem{flash4} T. Zadouri et al. \emph{FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling}. MLSys, 2026. \href{https://proceedings.mlsys.org/paper_files/paper/2026/hash/ae8b0b5838ba510daff1198474e7b984-Abstract-Conference.html}{Conference paper}.
\bibitem{linear} A. Katharopoulos, A. Vyas, N. Pappas and F. Fleuret. \emph{Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention}. ICML, 2020. \href{https://proceedings.mlr.press/v119/katharopoulos20a.html}{PMLR 119, 5156--5165}.
\bibitem{walsh} R. O'Donnell. \emph{Analysis of Boolean Functions}. Cambridge University Press, 2014, corrected edition 2021. \href{https://arxiv.org/abs/2105.10386}{arXiv:2105.10386}.
\bibitem{skdata} Scikit-learn developers. \emph{Toy datasets}. The experiment uses the dataset loaders and array order shipped with scikit-learn 1.8.0. \href{https://scikit-learn.org/stable/datasets/toy_dataset.html}{Dataset documentation}.
\bibitem{iris} R. A. Fisher. \emph{Iris}. UCI Machine Learning Repository. \href{https://archive.ics.uci.edu/dataset/53/iris}{Dataset 53}.
\bibitem{wine} S. Aeberhard and M. Forina. \emph{Wine}. UCI Machine Learning Repository. \href{https://archive.ics.uci.edu/dataset/109/wine}{Dataset 109}.
\bibitem{wdbc} W. Wolberg, O. Mangasarian, N. Street and W. Street. \emph{Breast Cancer Wisconsin (Diagnostic)}. UCI Machine Learning Repository. \href{https://archive.ics.uci.edu/dataset/17/breast+cancer+wisconsin+diagnostic}{Dataset 17}.
\bibitem{digits} E. Alpaydin and C. Kaynak. \emph{Optical Recognition of Handwritten Digits}. UCI Machine Learning Repository. \href{https://archive.ics.uci.edu/dataset/80/optical+recognition+of+handwritten+digits}{Dataset 80}. \href{https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html}{Bundled subset}.
\bibitem{adam} D. P. Kingma and J. Ba. \emph{Adam: A Method for Stochastic Optimization}. ICLR, 2015. \href{https://arxiv.org/abs/1412.6980}{arXiv:1412.6980}.
\end{thebibliography}


\end{document}

End of manuscript · Back to top ↑