Weighted spans, exact streaming, and scaling from pairs to quintuples
1. Question and model
Sequence length $n$, interaction order $p$, and training-set size $m$ measure different things. Ordinary dense self-attention scores one key for every query. A cubic head scores two keys jointly for each query. Arithmetic cost increases predictably with the number of slots. The effect on predictive risk depends on the task and the training budget. Even a pairwise head is nonlinear in, and can depend on, the entire input sequence.
Let $I$ be a nonempty finite set of $n$ tokens. Write $r=p-1$, $J=(j_1,\ldots,j_r)$, and let $E_i\subseteq I^r$ be a nonempty set of legal tuples for query $i$. For projected queries, keys, and values, use coordinatewise products
$$K_J=\bigodot_{a=1}^r k^a_{j_a},\qquad U_J=\bigodot_{a=1}^r v^a_{j_a}.$$
The score, partition function, and output are
$$s_{iJ}=d^{-1/2}\langle q_i,K_J\rangle+b_{iJ},\qquad Z_i=\sum_{J\in E_i} e^{s_{iJ}},\qquad A_p(X)_i=\frac{\sum_{J\in E_i}e^{s_{iJ}}U_J}{Z_i}.$$
At $p=2$ this is ordinary row-wise scaled dot-product attention. At $p=3$ the softmax runs over pairs $(j,k)$. Two separately normalized pairwise heads generally produce a different joint law. The experiments use the column-wise Kronecker attention family of Alman and Song, with tied role projections, zero bias, and all ordered tuples including repeated indices. Other higher-order constructions use an unsigned scalar triple product, role-specific projections, or tuple-valued token states. Multihead concatenation, output projection, residual connections, and pointwise feedforward layers remain available.
Adding an unused slot. In the dense role-specific family with a constant feature, one may assign the extra key and value projections the all-ones vector and pull back the original bias. Each numerator and denominator is then multiplied by $n$, giving exactly the lower-order function. This yields weak inclusion of function classes. It gives neither a strict improvement in population risk nor a finite-sample improvement. Tying all roles may also prevent one from assigning just the extra role a constant map.
2. Weighted spans and the obstruction to flattening depth
Use the bicategory of finite sets and spans $A\leftarrow S\rightarrow B$ carrying weights $w:S\to\mathbb R_{\ge0}$. The 2-cells are weight-preserving bijections commuting with the legs. Composition is by pullback with multiplication of weights. Its canonical associator rebrackets composable triples, and both paths of the pentagon rebracket a composable quadruple identically. The symmetric monoidal product is Cartesian product.
Linearization sums weights over common endpoints, $$L(S)(a,b)=\sum_{\ell(s)=a,\,u(s)=b}w(s).$$ Finite distributivity gives $L(S\times_B T)=L(S)L(T)$. Cartesian products become Kronecker products. At fixed input, attention uses the query–tuple span $I\leftarrow E\rightarrow I^r$ with weights $e^{s_{iJ}}$. Dividing each row by its mass yields a stochastic matrix $P_X$. The output is $P_X U_X$. Composing neural layers also requires recomputing the next kernel and observable on the previous output.
Base change. Pulling back a finite fiber $E\to I$ along $a:I'\to I$ identifies its fiber over $i'$ with $E_{a(i')}$. Both the weighted numerator and its positive mass agree term by term under this identification, hence so do their ratios. In the presheaf topos on finite sets and bijections this gives a natural transformation between token-feature families when masks, coordinates, and positional data are transported with the tokens. Duplicating a token and rebuilding the full Cartesian support can change the counting measure. With values 0 and 1 and zero scores, duplicating the zero key changes the mean from $1/2$ to $1/3$. Parameterized layers compose by product of parameter spaces and substitution. Tying parameters is precomposition with a diagonal.
For a nonempty $\pi$-finite homotopy fiber, integrate componentwise constant observables with component weight $\prod_{k\ge1}|\pi_k|^{(-1)^k}$. Homotopy pullback preserves the resulting normalized integral by equivalence of homotopy fibers. In the action groupoid of tuples modulo slot permutations, counts $c_j$ have stabilizer $\prod_j S_{c_j}$. The homotopy weight $1/\prod_jc_j!$ is the ordered multiplicity divided by $r!$, a common factor that cancels in normalization.
Path-normalization obstruction. Fix a query $i$, positive first-stage weights $W_{ij}$ on its support, and nonnegative second-stage weights $V_{jk}$ with outgoing masses $z_j=\sum_kV_{jk}>0$. Successive row normalizations give the same joint law of paths $(j,k)$ as a single normalization of $W_{ij}V_{jk}$ if and only if $z_j$ is constant on reachable intermediate states.
Proof. Set $s_i=\sum_jW_{ij}$ and $t_i=\sum_jW_{ij}z_j$. On every positive path the two probabilities are $W_{ij}V_{jk}/(s_i z_j)$ and $W_{ij}V_{jk}/t_i$. Equality is equivalent to $z_j=t_i/s_i$ for every reachable $j$. Equal first-stage weights and disjoint deterministic continuations of masses 1 and 2 give terminal probabilities $(1/2,1/2)$ and $(1/3,2/3)$. The equivalence is for the joint path law, since projecting to a shared terminal state can conceal a discrepancy. Subtracting $\log z_j$ from the joint path score restores successive normalization.
3. Exact computation and logit scaling
Dense enumeration has $n^p$ scores per head and example. For fixed order and widths its attention work is $\Theta(n^p)$, with additional linear-in-length projection and feedforward work at fixed model width. Doubling length multiplies score count by $4,8,16,32$ at orders two through five. Prefix masks give $\sum_{i=1}^n i^{p-1}$ scores, one new query costs $n^{p-1}$ scores with cached projections, and at most $w$ legal keys per slot gives at most $nw^{p-1}$ scores.
For arbitrary independent pointwise logit oracles, an exact deterministic algorithm requires $n^p$ worst-case queries for $n\ge2$. Choose tuple values in $\{0,1\}$ with both values present in each full row and answer every query with zero. The resulting mean is strictly between the two values. Changing any unqueried logit changes that row's mean. The argument does not establish such a lower bound for structured tensor logits.
Exact streaming. For a nonempty tile with scores $s$, keep its maximum $a$, mass $z=\sum e^{s-a}$ and numerator $u=\sum e^{s-a}U$. To combine this with $(a',z',u')$, set $b=\max(a,a')$ and form
$$(b,\ e^{a-b}z+e^{a'-b}z',\ e^{a-b}u+e^{a'-b}u').$$
The empty tile is an identity. Each term after merging is scaled by its score minus the maximum over the union. Thus every partition and merge tree gives the same summary in exact arithmetic. The final output is $u/z$. With fixed tile sizes, on-demand supports, fixed order and fixed widths, forward storage including inputs and outputs is linear in length. For upstream gradient $g_i$, the score gradient is $P_X(i,J)\langle g_i,U_J-A_p(X)_i\rangle$, permitting tilewise recomputation. FlashAttention uses this class of online reductions and an I/O-aware schedule for pairwise attention. Later versions improve hardware utilization. The attached benchmark implements ordered streaming on a CPU. Hardware-optimized cubic attention has also been demonstrated independently.
Orbit compression and separability. If support, scores and values are invariant under key-role permutations, each multiset representative has multiplicity $h_c=r!/\prod_jc_j!$. Adding $\log h_c$ to its logit exactly recovers the normalized sum over ordered tuples. The dense score count becomes $n\binom{n+r-1}{r}$, which has the same fixed-order exponent and leading factor $1/r!$. With four keys, the per-query counts $4,16,64,256$ become $4,10,20,35$. If the positive kernel on full support has a supplied factorization $W(i,J)=\sum_{h=1}^H\prod_a w_{ha}(i,j_a)$, distributing sums evaluates denominator and product-valued numerator using $O(Hrn^2)$ work at fixed widths. Low-rank logits need not have low-rank exponentials.
Gaussian multiplicity law. Let query and key coordinates be independent standard Gaussians, with the same key array used in every role. Conditional on tuple counts $c$ and with zero bias, the $d^{-1/2}$-scaled logit has conditional variance $$\operatorname{Var}(s_{iJ}\mid c)=\prod_{j:c_j>0}(2c_j-1)!!.$$ For uniform independent tuple indices the average variance is $$V(n,r)=\prod_{a=0}^{r-1}(1+2a/n).$$ Indeed the query centers each summand, independent coordinates have zero covariance, and the required even Gaussian moments are $(2c_j-1)!!$. Integrating first over key indices gives the $r$th moment of $\chi_n^2/n$. At $n=4$ the variances are $1,1.5,3,7.5$. Dividing the raw scaled logit by its conditional standard deviation equalizes these variances under the stated assumptions. The logarithmic multiplicity correction is added afterwards.
A strict benefit in a specified readout. For uniform independent signs $x_1,\ldots,x_n$, constant scores, scalar values $x_j$, and distinct key indices, the normalized head with $r$ key slots produces a constant multiple of $$\phi_r(x)=\binom nr^{-1/2}\sum_{|S|=r}\prod_{j\in S}x_j.$$ Different sign monomials are orthogonal and have squared norm one. Thus the optimal squared error for target $\phi_s$ in $\operatorname{span}(1,\phi_1,\ldots,\phi_k)$ is one if $k<s$ and zero if $k\ge s$. Exhaustive least squares on all 256 sign vectors at $n=8$ reproduced the sixteen cases $s,k=1,\ldots,4$ to $3\times10^{-15}$. This separation is for the given heads and linear readout. The symmetric-polynomial recurrence also computes this particular observable in $O(nr)$ arithmetic.
4. Experiments
We used the scikit-learn versions of Iris (150 examples), Wine (178), Wisconsin Diagnostic Breast Cancer (569), and Digits (1,797). Five stratified outer folds gave one held-out prediction per example. We reserved a stratified fifth of each remaining training pool for validation and selected checkpoints by validation cross-entropy. Every feature was standardized using only the current training subset. Tabular inputs were padded and divided into four consecutive feature groups. The main Digits comparison used four image quadrants. One sensitivity experiment used eight row tokens. Fold partitions, parameter counts, initialization seeds, and minibatch orders were matched within each tokenization across orders.
Each encoder had one head, one residual block, width 16, feedforward inner width 32, learned positional vectors, trainable projections, parameter-free feature normalization and mean pooling. Adam used learning rate 0.003, batch size 32, gradient-norm cap 5, and 60 epochs. Logistic regression on the original standardized features supplied a conventional baseline. The source archive contains 220 encoder fits, 20 logistic fits and 20 timed replays.
| Dataset | Quadratic | Cubic | Quartic | Quintic | Logistic |
|---|---|---|---|---|---|
| Iris | 94.67% | 91.33% | 94.00% | 92.67% | 94.00% |
| Wine | 89.89% | 93.82% | 87.08% | 87.08% | 98.88% |
| WDBC | 93.32% | 92.27% | 92.97% | 92.62% | 97.89% |
| Digits | 91.21% | 89.37% | 86.70% | 85.42% | 96.55% |
On Wine, cubic attention corrected eleven pairwise errors and lost four correct predictions. On Digits, quintic attention corrected 70 and lost 174 relative to the pairwise head, with a negative net difference in every fold. Fold training sets overlap. The paired observations describe these partitions.
For four-patch Digits, matching single-core training CPU time within each fold retained the same validation-selected checkpoints and accuracies as the 60-epoch comparison. Matching the implemented orbit-score allowance gave eligible epoch caps $60,24,12,6$ and accuracies $91.21,89.37,86.42,82.80$ percent. The allocation excludes feedforward work, projections, validation, and memory traffic. On eight row tokens the 60-epoch accuracies were $91.21,89.65,86.87,87.81$ percent. Correcting the logits for orbit variance raised quintic four-patch Digits accuracy to 87.81%, while cubic accuracy fell to 87.48%. Changing tokenization or temperature can change the relative ordering.
Length scaling. A separate single-core C++17 float64 kernel measured all ordered tuples at width eight and tuple-tile size 64. Nine randomized rounds each visited six lengths per order. Fits of log median forward time against log length gave exponents $1.986,2.952,3.944,4.852$ over lengths $256$–$1536$, $40$–$128$, $16$–$39$, and $9$–$19$, respectively. Every log-scale $R^2$ exceeded 0.999. Each order used a length range with comparable total score counts. Exact score counts, finite-range timing estimates, and GPU I/O guarantees are distinct quantities. The compiled kernel agreed with an independent Cartesian oracle to $1.0\times10^{-14}$ on twelve order/length pairs.
Example-count scaling. On nested four-patch Digits training subsets averaging $142.2,286.2,574.6,1149.6$ examples per fold, we obtained the following pooled held-out cross-entropies.
| Mean training size | Quadratic | Cubic | Quartic | Quintic |
|---|---|---|---|---|
| 142.2 | 0.910 | 1.022 | 1.324 | 1.572 |
| 286.2 | 0.751 | 0.802 | 0.971 | 1.167 |
| 574.6 | 0.525 | 0.541 | 0.690 | 0.832 |
| 1149.6 | 0.324 | 0.385 | 0.493 | 0.531 |
Zero-floor fits $L_p(m)\propto m^{-\alpha_p}$ gave $\alpha_p=0.495,0.477,0.474,0.516$. Fits to the first three sizes overpredicted the fourth-size loss by $26.7,5.1,1.8,15.1$ percent. These local slopes leave asymptotic slopes and loss floors unidentified. Larger training subsets also supply more optimization steps at fixed epochs.
5. Scope and reproducibility
Higher order gives direct access to a new statistic when the target and readout require it. The strict Walsh example, the Wine gain, and the Digits losses establish three distinct cases. Symmetry, sparsity, separability and exact streaming affect resource use in different ways. The benchmarks use small single-head encoders and a serial reference kernel. They establish no distribution-free quality ordering and no performance law for large language models.
The complete nine-page manuscript is attached as a PDF. The reproducibility archive contains its editable source, the NumPy encoder and gradient checks, the C++ kernel, split indices, raw predictions and validation histories, CPU timings, data checksums, and figure and table scripts. The anonymous researcher supplied the research question and authorized submission. An AI assistant developed the formalization, wrote and executed the experiments, and drafted the manuscript.
Selected references
- Vaswani et al., Attention Is All You Need. NeurIPS 2017.
- Clift et al., Logic and the 2-Simplicial Transformer. ICLR 2020.
- Alman and Song, How to Capture Higher-Order Correlations? ICLR 2024.
- Roy et al., Fast and Simplex: 2-Simplicial Attention in Triton. 2025 paper.
- Gálvez-Carrillo, Kock and Tonks, Homotopy Linear Algebra. Journal article.
- Dao et al., FlashAttention, and Dao, FlashAttention-2. First paper and second paper.
- O'Donnell, Analysis of Boolean Functions. Corrected edition.
- Scikit-learn, Toy datasets. Dataset documentation. The full manuscript includes all data and literature references.