Manuscript Offprint
arXiv:2609.35349Quasi Linear Kernel Attention with Infinite Capacity
ABSTRACT
The evaluation cost of transformers with softmax attention scales quadratically with sequence length. Kernel attention addresses this by replacing softmax with a more general kernel function. In this paper, we aim to identify kernels that retain the expressivity of attention while enabling quasi linear computation. To quantify expressivity, we introduce a capacity for each kernel, measuring the maximum sequence length for which the attention matrix can approximate the identity. A higher capacity thus indicates greater expressivity. We show that expressive kernels like softmax, Gauss, and Laplace have infinite capacity. In contrast, common quasi linear kernels, such as those derived from finite dimensional feature maps, exhibit finite capacity. As a solution, we propose additive kernels constructed from univariate spline and polynomial exponential kernels. We prove that these maintain infinite capacity while allowing quasi linear computation via sorting. Finally, we implement additive sorting kernels efficiently and benchmark them against modern softmax backends, demonstrating advantages for long sequences.
1 INTRODUCTION
Transformers (Vaswani et al., 2017) are the dominant architecture in language processing (Brown et al., 2020) and computer vision (Dosovitskiy et al., 2021). Their central building block is attention, which computes for query vectors , key vectors , and value vectors the attention vectors as
Most implementations use the softmax kernel with inverse temperature , which acts as similarity score between the vectors and . For , the computational effort scales quadratically with the sequence length . This has become the main computational bottleneck in practice. Current models are trained and deployed with context windows of 128k tokens and beyond (Llama Team, AI @ Meta, 2024), which involves substantial engineering effort (Dao et al., 2022; Dao, 2024). There have been several attempts to escape the quadratic complexity through approximations and windowed attention patterns; see Tay et al. (2022) for an overview.
In this paper, we focus on exact subquadratic attention, where the structure of the kernel allows the computation of (1) in quasi linear time (Tsai et al., 2019). Within this class, Katharopoulos et al. (2020) achieved linear complexity by choosing kernels that factor over a finite feature map (FFM) , i.e., . This construction yields symmetric positive definite (spd) kernels, which can be evaluated in linear time. However, for small , these approaches have been shown to admit only limited expressivity compared to softmax attention, see Schlag et al. (2021). At the same time, the cost of evaluating the finite feature map increases linearly with .
On the other hand, there exist several univariate kernels (namely ), for which the corresponding kernel sums can be evaluated exactly via quasi linear sorting algorithms. Examples are polynomial exponential kernels like the Laplace kernel (Hofmeyr, 2021) and piecewise linear kernels (Hertrich, 2024; Hertrich et al., 2024; Vialard & Boufadène, 2025). However, most of these algorithms do not generalize to higher dimensions. An exception is the Laplace kernel, for which the sums can be evaluated in quasi linear time for arbitrary D, see Langrené & Warin (2021), but the complexity depends exponentially on D, making the approach practically infeasible for D > 6.
Contribution Our goal is to identify kernels such that the attention (1) is both expressive and computable in quasi linear time. To this end, we introduce the capacity of a kernel. Its definition is inspired by the associative recall experiment of Schlag et al. (2021) and measures up to which sequence length the identity can be approximated by the attention algorithm. Intuitively, this corresponds to the number of tokens that can be distinguished. Consequently, a higher capacity indicates higher expressivity. We prove that common choices have infinite capacity, including the softmax, Gauss, and Laplace kernels. This resembles the observation that their associated attention is expressive in practice. For kernels based on an FFM, we prove that the capacity is upper-bounded by the number L of considered features, reflecting their limited expressivity.
In order to achieve quasi linear attention with infinite capacity, we consider additive kernels of the form , where is a univariate kernel with quasi linear attention. For the univariate Laplace kernel and the bump kernel , we prove that the capacity of both and is infinite, so that we obtain quasi linear attention with infinite capacity. We verify our findings in numerical experiments and provide an efficient CUDA implementation. For sequence lengths , our implementation is faster than conventional single-precision PyTorch attention, which offers a comparable level of numerical precision and code optimization. Compared to the highly optimized half-precision FlashAttention, we reach the break-even point for . Thanks to the quasi linear complexity of our algorithm, the advantage increases rapidly with the sequence length.
Related work Several works reduce the quadratic cost of attention by approximation, either through sparse and windowed attention patterns (Kitaev et al., 2020; Beltagy et al., 2020; Zaheer et al., 2020), or through low-rank approximations of the attention matrix (Wang et al., 2020; Xiong et al., 2021). For an extensive overview, see Tay et al. (2022). The FFM idea was refined by Choromanski et al. (2021); Peng et al. (2021); Qin et al. (2022) with feature maps tailored to the softmax kernel and by Schlag et al. (2021), who increased the feature dimension L after recognizing that it caps the attention capacity. Lower bounds on the recurrent state size required for multi-query associative recall were proven by Arora et al. (2024a). Building on this, Arora et al. (2024b) combine linear attention with sliding windows, while gated linear attention (Yang et al., 2024a) and DeltaNet (Yang et al., 2024b) use data-dependent gating and delta-rule updates of the recurrent state, respectively, to better use a fixed-size state. These models are recurrent and go beyond the normalized kernel sums considered in (1). Alternative notions of expressivity for attention mechanisms were considered in Yun et al. (2020); Furuya et al. (2025). Our proposed bump and Laplace variants have been previously considered in different contexts: Feng et al. (2026) approximate the Laplace kernel attention via a finite feature map/Nyström approach, and Vialard & Boufadène (2025) combine the univariate bump kernel with a linear or MLP layer before each attention module to project onto a single dimension. Finally, the additive kernels are related to kernel slicing, see also Appendix B.
Definition of Capacity For a kernel , keys and queries , we define the Gram matrix and the attention matrix by
For in , the attention mechanism can be rewritten as the matrix-vector multiplication for . We denote the capacity of as the largest sequence length such that there exist keys and queries for which , where is the identity matrix. Formally, we define
In other words, if the sequence length N is larger than , the attention mechanism is no longer able to represent the identity, which indicates a lack of expressiveness.
Kernels with Infinite Capacity A kernel is stationary if for some function . If is continuous and fulfills as , we call a stationary kernel.
Theorem 1. Let be a stationary kernel with , then it holds .
The theorem applies in particular to the Gauss kernel and many others including Laplace and Matérn kernels. Even though the softmax kernel is not stationary, we can exploit its close relation to the Gauss kernel to show that .
Proposition 2. For and , we have .
Upper Bounding the Capacity Next, we derive a criterion which upper bounds the capacity of an spd kernel by the dimension of the corresponding reproducing kernel Hilbert space (RKHS). To define the RKHS, we consider the space with the bilinear form
Then, the RKHS is defined as the completion of with respect to the norm induced by . The columns of the Gram matrix can be seen as functions evaluated at queries . Therefore, the rank of can be bounded via
As the attention matrix arises from by rescaling the rows, we also find that . In particular, we have for any and by the Eckart-Young theorem (Eckart & Young, 1936) that
Thus, the left hand side can only be zero if such that . We summarize this result in the following theorem.
Theorem 3. Let be an spd kernel, then it holds .
The reverse statement is not true. More precisely, we show in Proposition 8 that there exist kernels such that , but .
3 CAPACITY OF QUASI LINEAR ATTENTION
In Theorem 1, we have derived a large class of kernels which admits infinite capacity, indicating a high expressivity. However, the computation of the attention mechanism requires generally operations, which is a major computational bottleneck. Therefore, we now focus on kernels for which the attention mechanism can be computed exactly in quasi linear time, i.e., in operations for some . We will mainly analyze the complexity of computing the kernel sums
for queries , keys and values . In fact, from a computational viewpoint, considering the kernel sums is equivalent to considering the attention mechanism, as the normalization can be computed in operations. In practice, the time of computing this normalization is dominated by the cost of reading the data.
Laplace Langrené & Warin (2021) propose an algorithm based on (Bentley, 1980) with quasi linear complexity to compute kernel sums for the Laplace kernel , which fulfills by Theorem 1. However, the algorithm relies on a decomposition of the Laplace kernel sum into generalized empirical cumulative distribution functions. In particular, the complexity depends exponentially on the dimension. Thus, for an exemplary head dimension of , the quasi linear implementation is only expected to be faster than brute-force for sequence lengths larger than , which makes it a theoretical advance rather than a practical method.
3.1 FINITE FEATURE MAPS
Following the idea of random Fourier features (Rahimi & Recht, 2007), several works (Peng et al., 2021; Choromanski et al., 2021; Katharopoulos et al., 2020; Schlag et al., 2021) proposed linear attention algorithms by using finite feature maps (FFMs) . The main idea is to choose , for which the kernel sum can be computed as
The inner sum no longer depends on such that all together can be computed in linear complexity . Schlag et al. (2021) uses the feature dimension as a measure of capacity. This is reasonable because
Since the completion of a finite dimensional space is the space itself, we also obtain , which has at most dimension . Corollary 4 gives the connection to Schlag et al. (2021) as an immediate consequence of Theorem 3.
Corollary 4. Let with FFM , then .
By Corollary 4 the capacity is bounded through the feature dimension L. At the same time, the computational complexity scales linearly with L such that FFMs with more features are slower to evaluate. The next proposition verifies that the assumptions of Theorem 1 are indeed violated for FFMs in the sense that most FFMs are not stationary and the only stationary FFMs are not .
Proposition 5. Let be a continuous and stationary kernel. Then, it holds , where and for . In particular, we have that is a stationary kernel if and only if .
3.2 QUASI LINEAR ATTENTION WITH INFINITE CAPACITY IN ONE DIMENSION
There exist several univariate kernels , for which kernel sums can be computed in quasi linear time via sorting. This involves the Laplace kernel (Hofmeyr, 2021; Langrené & Warin, 2021), the distance kernel (Hertrich, 2024; Hertrich et al., 2024; Teuber et al., 2011) and polynomial exponential kernels for some polynomial (Hofmeyr, 2021). Using that any continuous piecewise linear function can be represented as the composition of constants, linear terms and absolute values (Streubel et al., 2014), the sorting algorithm for the distance kernel can be deployed for any kernel .
Proposition 6. Let be piecewise linear with finitely many nodes, then is quasi linear.
This includes the bump kernel with alternative expressivity results by Vialard & Boufadène (2025, Thm. 3.2). Both bump and Laplace have infinite capacity, see Theorem 1.
Corollary 7. Both the bump kernel and the Laplace kernel are quasi linear and have infinite capacity.
On the other hand, the Riesz kernel is an example for a kernel with infinite dimensional RKHS and finite capacity. Since the RKHS of can be identified with the infinite dimensional homogeneous Beppo Levi space (Wendland, 2004, Prop. 10.39), its attention matrix has no bound on its rank. Yet, its global structure does not allow to approximate the identity.
Proposition 8. For the Riesz kernel with , we have .
Algorithm 1 Weighted absolute value sum
| # | Step | Work | Memory |
|---|---|---|---|
| 1 | Input , and | - | |
| 2 | Output | - | |
| 3 | s.t. | ||
| 4 | for | ||
| 5 | \text{pref}_t_n := \sum_{j=1}^n t_{\sigma(j)} v_{\sigma(j)} \in \mathbb{R}^C for | ||
| 6 | for | ||
| 7 | for | ||
| 8 | for | ||
| 9 | return |
Weighted Absolute Value Sums For the Riesz and spline kernels, the difficult part is to compute , where and . This sum can be computed in by Algorithm 1. A similar algorithm can be applied for the one dimensional Laplace kernel. The core idea is that after sorting, the keys below and above separate:
The last line (10) depends on the prefix sums over and , which can be computed with work. Once the prefix sums have been computed, the entry at position needs to be extracted, resulting in another operations. The total work of the one dimensional absolute value sum reduces to operations. In short, we pay to then be able to compute the rest in instead of .
Appendix C explains how we implement Algorithm 1 efficiently on the GPU. For the multivariate case, a naive PyTorch implementation needs to build huge temporary tensors in steps 5 to 8. Meanwhile, we compute steps 5 to 8 in a single CUDA kernel and allocate the intermediate tensors pref_v and pref_t on the fly. This ensures a low memory profile with good parallelism.
3.3 ADDITIVE KERNELS FOR QUASI LINEAR ATTENTION WITH INFINITE CAPACITY
In order to carry over the one dimensional algorithms from the previous subsection to higher dimensions, we propose to use additive kernels of the form
for some univariate kernel . Similar kernels were considered in Hertrich et al. (2025) as quasi-Monte Carlo design for the kernel slicing algorithm; more details are given in Appendix B. By definition, the kernel sums for such kernels can be computed as
which has quasi linear complexity if and only if the kernel sum with respect to the univariate kernel has quasi linear complexity. Even though additive kernels will never be (unless ), we prove in the next theorem that implies that .
Table 1: For additive kernels, we state the univariate . dpfp is described in Appendix A and the remaining kernels are defined for . All kernels except tri are nonnegative. riesz and add_riesz use and are partially stationary, i.e., stationary up to terms depending only on or only on . The last column is the best known kernel sum complexity in .
| Name | Formula | dim | stationary | additive | capacity | complexity |
|---|---|---|---|---|---|---|
| softmax | ∞ | no | no | ∞ | quadratic | |
| gauss | ∞ | yes | no | ∞ | quadratic | |
| laplace | ∞ | yes | no | ∞ | quasi linear | |
| riesz | ∞ | partially | no | - | quadratic | |
| add_riesz | ∞ | partially | yes | ≥2D | quasi linear | |
| add_laplace | ∞ | yes | yes | ∞ | quasi linear | |
| add_bump | ∞ | yes | yes | ∞ | quasi linear | |
| tri | 2D | yes | yes | ≤2D | linear | |
| relu | ReLU(s)ReLU(t) | D | no | yes | ≤D | linear |
| elu | D | no | yes | ≤D | linear | |
| dpfp | Appendix A | 6D | no | no | ≤6D | linear |
Theorem 9. Let be an additive kernel corresponding to some . Then, we have that . Moreover, the properties spd, quasi linear and stationary carry over from to . For the Riesz kernel , we have .
We now combine Corollary 7 with the arguments in this section to get our main result.
Corollary 10. The additive- Laplace and bump kernel defined by with and fulfill and corresponding kernel sums can be computed in quasi linear complexity.
4 IMPLEMENTATION AND EXPERIMENTS
Next, we investigate our findings numerically by three experiments. The first one in Section 4.1 aims to verify theoretical claims from the previous sections. To this end, we perform an associative-recall experiment, which numerically computes the capacity of the considered kernels. The second experiment in Section 4.2 investigates the computation time. To complement theoretical complexity analysis of the proposed quasi linear kernels, we investigate the “break-even” point. This describes the minimal sequence length N such that our attention algorithm is faster than softmax attention. In this part, we also comment on possible implementations of attention. Finally, the third experiment in Section 4.3 evaluates the performance of the kernels based on the text embedding transformer nomic-embed-text-v1 by Nussbaum et al. (2025). We include a similar experiment for a vision transformer in Appendix E. Table 1 gives an overview of the kernels evaluated in this section.
All experiments use PyTorch 2.13.0+cu129 and KeOps 2.3. While training runs on a multi GPU cluster, all time measurements (Table 2 & 5 and Figure 2) were taken on a single NVIDIA GeForce RTX 5090. The code corresponding to our experiments is available on GitHub .
Bandwidth The bandwidth is set via , with as default for softmax, gauss and tri. Since both text and vision transformer use head dimension , we use . We also tested other bandwidths but found to be near optimal in both the text and vision transformer. Similarly, for add_bump, for add_laplace and for laplace work well on both tasks. For , the kernels riesz, add_riesz, relu and dpfp are scale invariant, i.e., for all and some . Therefore, the scale cancels out within attention and for it merely rescales , so no tuning is necessary. As the only not nonnegative kernel, tri causes numerical instability during training. To stabilize this, we clamp the attention normalization at and use gradient clipping to avoid overshooting.
4.1 ASSOCIATIVE RECALL CAPACITY
Here, we assess the capacity of various kernels by an associative-recall experiment similar to Schlag et al. (2021, Sec. 6.1). More precisely, we start with learnable tokens and define
https://github.com/Nicolaj-Rux/quasi-linear-kernel-attention

Figure 1: Associative-recall: Trained full-batch with Adam (lr 0.03) for at most 120k steps, stopping early once the loss falls below , , where the tokens are initialized as standard normal and . Curves show the best loss over 3 seeds. Scale in brackets behind kernel name.
keys and queries as and for learnable matrices . Then, for values chosen as the unit vectors, we minimize the loss function
where with is the attention vector as defined in (1) and and are uniformly randomly drawn permutations. The loss does not depend on and as the following lemma shows.
Lemma 11. For all permutations and it holds
While Schlag et al. (2021) phrase this as a retrieval task, we show in Appendix F that it can be related to our capacity notion in the sense that
In particular, we have that only if .
In Figure 1, we plot the minimal value of after 120k optimization steps on , and for the kernels of Table 1. We observe that all FFM kernels roughly achieve a loss of zero for sequence lengths and end up with a strictly positive loss for . This matches Corollary 4 stating that . On the other hand, the stationary kernels gauss and laplace succeed in this task as predicted by Theorem 1. In alignment with Corollary 10, add_laplace and add_bump also pass the task up to . While Theorem 9 guarantees for add_riesz, the optimization already fails around , and riesz performs worst throughout.
4.2 IMPLEMENTATIONS AND SPEED BENCHMARKS
Now, we compare the runtime of the different backends of the attention algorithm. We already know that for softmax attention has complexity , while our kernels have complexity . Hence, for long enough sequence lengths, quasi linear kernels should eventually become faster. Thus, we are interested in the “break-even” point, i.e., the minimal number such that the quasi linear algorithms are faster than the standard softmax attention. For the quasi linear algorithms, we provide backends for add_laplace and the distance kernel. The latter can be used to compute all spline kernels and we choose add_riesz as a simple representative. Here, we consider the following backends.
Table 2: Forward-pass of kernel attention (1) with runtime in milliseconds, mean over 10 runs after 5 warm-up iterations. Relative standard deviations are below for , below at and below for . Bold marks the fastest method overall; underline marks the fastest among the five fp32 methods. Shape: , , , , .
| N | add_laplace fp32 | add_riesz fp32 | softmax | |||||
|---|---|---|---|---|---|---|---|---|
| GLOBAL | GLOBAL | FUSED | KEOPS | MEM_EFF32 | MEM_EFF16 | FLASH16 | CUDNN16 | |
| 128 | 0.442 | 0.455 | 0.305 | 0.381 | 0.029 | 0.021 | 0.021 | 0.023 |
| 256 | 0.575 | 0.539 | 0.353 | 0.425 | 0.058 | 0.031 | 0.022 | 0.030 |
| 512 | 0.824 | 0.694 | 0.478 | 0.688 | 0.144 | 0.058 | 0.041 | 0.043 |
| 1024 | 1.305 | 1.014 | 0.719 | 1.648 | 0.431 | 0.152 | 0.093 | 0.119 |
| 2048 | 2.260 | 1.690 | 1.278 | 4.754 | 1.645 | 0.537 | 0.266 | 0.265 |
| 4096 | 4.472 | 3.583 | 2.991 | 17.14 | 6.219 | 1.948 | 1.016 | 1.001 |
| 8192 | 9.109 | 7.336 | - | 63.94 | 24.12 | 7.424 | 3.780 | 3.726 |
| 16384 | 20.31 | 16.86 | - | 249.1 | 94.95 | 29.57 | 14.99 | 14.90 |
| 32768 | 42.07 | 34.88 | - | 985.6 | 379.4 | 118.8 | 59.79 | 60.11 |
| 65536 | 86.94 | 73.76 | - | 3877 | 1523 | 478.1 | 239.2 | 241.3 |
| 131072 | 190.1 | 200.0 | - | 15608 | 6118 | 1930 | 968.8 | 972.1 |
-
GLOBAL: Sorting and computing the prefix sums involves two separate CUDA kernels. Same structure is implemented for both add_riesz and add_laplace.
-
FUSED: all operations are in a single kernel; this is limited by memory to .
-
KEOPS: a GPU-friendly reference (Charlier et al., 2021).
We provide implementation details in Appendix C. All backends of the quasi linear attention algorithm run with fp32 precision. While an fp16 implementation is algorithmically possible and can lead to further speedups, it requires substantial code engineering, which goes beyond the scope of this paper. We comment in Appendix C.4 on this issue. We compare the evaluation times of this kernel attention with the standard softmax attention. Here, we consider the softmax backends:
-
MEM_EFF32 and MEM_EFF16 (Lefaudeux et al., 2022) in fp32 and fp16 precision.
-
FLASH16 and CUDNN16 (Dao, 2024) using fp16 precision.
Our weighted_abs_sum supports gradients and padding, such that all spline kernels can be used in both training and inference. Quasi linear causal attention is possible and explained in Appendix C.4 but not implemented. The add_laplace is forward only.
We report the runtime of a forward pass of (1) in Table 2. Appendix C covers the backward-pass with similar conclusions. At equal precision FUSED becomes faster than MEM_EFF32 at . For , GLOBAL is roughly faster. The fp16 backends are faster than their fp32 counterparts, so the break-even against FLASH16 occurs slightly beyond . We view this as an engineering rather than a conceptual gap: the fp16 backends exploit tensor cores and years of kernel tuning, whereas a flash-style fp16 tiling of the quadratic regime combined with our quasi linear kernel is possible in principle and would move the crossover accordingly. Regarding memory, our backend allocates roughly the forward peak memory of MEM_EFF32, as it must hold sorted copies of the queries, keys and their sorting permutations. Unlike a naive PyTorch implementation of Algorithm 1, which must materialize the prefix sums of size , we compute the prefix sums on the fly, such that the overhead reduces to .
4.3 TEXT EMBEDDING TRANSFORMER
Finally, we evaluate the performance of the quasi linear kernels on a text embedding transformer. To this end, we consider the sentence embedder nomic-embed-text-v1 (Nussbaum et al., 2025) (12 layers, 12 heads, , rotary positional embeddings (RoPE)).
Setup and Training To avoid the computationally expensive and hyperparameter-sensitive training procedure, we start with a pretrained teacher model using softmax attention and distill student models using other kernels from this teacher model. Here, we proceed in three phases:
-
Initialization: We initialize the student model by copying the weights of the teacher model.
-
Layer-by-layer distillation: For each attention layer, we match the MSE between the softmax teacher and the student.
Table 3: Results after full two-stage distillation for MTEB and LoCo. Best performance among quasi linear kernels is underlined.
| Kernel | scale | MTEB | LoCo (nDCG@10) | ||
|---|---|---|---|---|---|
| 2048 | 4096 | 8192 | |||
| softmax (teacher) | 2.828 | 64.41 | 0.873 | 0.882 | 0.883 |
| gauss | 2.828 | 64.41 | 0.875 | 0.884 | 0.886 |
| laplace | 6.0 | 64.38 | 0.885 | 0.891 | 0.887 |
| riesz | 1.0 | 61.69 | 0.805 | 0.839 | 0.858 |
| add_riesz | 1.0 | 61.72 | 0.769 | 0.813 | 0.832 |
| add_laplace | 0.5 | 62.12 | 0.830 | 0.845 | 0.858 |
| add_bump | 1.5 | 62.12 | 0.829 | 0.843 | 0.859 |
| tri | 2.828 | 61.53 | 0.829 | 0.838 | 0.851 |
| relu | 1.0 | 62.29 | 0.472 | 0.516 | 0.556 |
| elu | 1.0 | 61.55 | 0.699 | 0.773 | 0.794 |
| dpfp | 1.0 | 63.42 | 0.681 | 0.811 | 0.823 |

Figure 2: LoCo retrieval quality against encoding cost at 8192 and 16384 tokens. Each point is one kernel: is the mean nDCG@10 over five LoCo tasks, is GPU time per document.
- End-to-end distillation: We minimize the MSE between the end-to-end application of the teacher and student model.
For both distillations, we use nomic-ai/nomic-embed-unsupervised-data, specifically the reddit_title_body split. Texts are truncated to 512 tokens, batched in groups of 16, and decorated with one of the task prefixes classification, clustering, search_document and search_query, sampled with probabilities 0.45, 0.1, 0.35 and 0.1. In the first distillation, each layer is trained for 10,000 steps with Adam, with a learning rate cosine-annealed from to . In the second distillation, all parameters are trained for 10,000 steps with Adam, with a linear warmup over the first of steps to , followed by cosine annealing to .
Evaluation and Results We evaluate on two regimes: the MTEB(eng, v2) benchmark (Muennighoff et al., 2023), an average over 41 datasets whose documents are short (), and LoCo long-context retrieval (Saad-Falcon et al., 2024) (nDCG@10, averaged over 5 subsets) at lengths 2048, 4096 and 8192, well beyond the training length of 512.
We observe that gauss and laplace fully recover the teacher. The Riesz kernel and the quasi linear kernels moderately lose performance. The FFM kernels work well for the short sequences from the MTEB benchmark, but mostly degrade in performance for the LoCo. Only the tri kernel achieves reasonable results. On the other hand, the infinite capacity kernels add_bump and add_laplace remain close to the softmax teacher model. Moreover, on LoCo, stationary kernels tend to extrapolate better than non-stationary ones. This may be due to RoPE (with NTK scaling), which is designed for rotation-invariant kernels such as softmax. While laplace, tri and our additive kernels are not rotation invariant, they remain stationary, whereas the FFM kernels relu, elu and dpfp are neither. For this retrieval task, which relies on few relevant tokens and mean pooling, stationarity appears to matter more for extrapolation than capacity.
Further, we evaluate the time-performance trade-off. More precisely, we plot in Figure 2 the performance on LoCo versus the required evaluation time for each kernel. We consider both sequence lengths of 8192 and 16384, where longer sequences are truncated and shorter sequences are padded. We can see that for long sequences the tri and add_laplace kernels both significantly improve the computation time compared to the softmax kernel with a moderate loss of performance. Here, the tri kernel is slightly faster while the add_laplace kernel has a slightly better performance.
5 CONCLUSIONS, LIMITATIONS AND FUTURE WORK
We analyzed kernel attention to identify kernels that are both expressive and enable quasi linear computation. Expressivity is measured through the maximum sequence length for which the attention matrix can approximate the identity (capacity). We showed that expressive kernels such as softmax, Gauss and Laplace have infinite capacity while finite feature map kernels saturate. By leveraging additive kernels and one dimensional sorting, we identified a class of kernels with infinite capacity and quasi linear complexity. Experiments confirm that our CUDA-based kernel attention is faster than softmax attention for sequence lengths exceeding 2048 elements in fp32.
While our capacity metric provides a rigorous theoretical framework for comparing kernel attention, it captures only one aspect of expressiveness. Theoretically, kernel attention with higher capacity can represent classes of functions that cannot be represented with lower capacity. However, the full expressive power of transformers is influenced by additional properties beyond capacity, such as stationarity and locality. In the long term, an fp16 implementation, leveraging tensor cores and optimized memory access patterns, could yield significant additional speedups, particularly for long sequences. Further, we intend to extend our implementation to causal attention and to evaluate our method on larger-scale benchmarks to validate its scalability and performance.
AI USE STATEMENT
We did not use generative AI for any tasks with required disclosure: all research ideas, methodology, experimental design, and interpretation of results are the authors' own work, as is the design of the GPU implementation, including the parallelization strategy, the memory and thread layout and the kernel fusion; synthetic data generation, translation, and dataset cleaning are not applicable. Starting from a complete, author-written implementation of this design, we used generative AI tools to extend and clean up the code and repository, to unify naming and structure, and to apply hardware-specific low-level optimizations; these changes affect how the computation is executed on the device rather than the algorithm itself, they did improve performance, and the runtimes we report are those of the resulting code. We also used generative AI tools to identify related work and candidate citations. All AI-modified code was reviewed by the authors and verified for numerical agreement with the author-written reference implementation before being re-tested and re-benchmarked, and all AI-suggested references were verified against the original sources. The paper was written by the authors, with generative AI used to polish wording. We take responsibility for the final content of this work, including text, claims or artifacts produced with the aid of generative AI.
REPRODUCIBILITY STATEMENT
All required datasets and models are openly available from the literature. The source code for our experiments is available at:
https://github.com/Nicolaj-Rux/quasi-linear-kernel-attention
ACKNOWLEDGMENTS
JH acknowledges funding from the German Research Foundation (DFG) within project no 530824055 and 572825596. NR acknowledges funding from the European Union and the Free State of Saxony through the European Social Fund (ESF). We are grateful to Michel Steuwer, Nicole Thalia Heinimann, and Dominic Arne Stöcker for their guidance on the CUDA implementation, and to Paul Hagemann for valuable advice on model training.
REFERENCES
Simran Arora, Sabri Eyuboglu, Aman Timalsina, Isys Johnson, Michael Poli, James Zou, Atri Rudra, and Christopher Ré. Zoology: Measuring and improving recall in efficient language models. In Int. Conf. Learn. Represent., 2024a. URL https://openreview.net/forum?id=LY3ukUANko.
Simran Arora, Sabri Eyuboglu, Michael Zhang, Aman Timalsina, Silas Alberti, James Zou, Atri Rudra, and Christopher Ré. Simple linear attention language models balance the recall-throughput tradeoff. In Ruslan Salakhutdinov, Zico Kolter, Katherine Heller, Adrian Weller, Nuria Oliver, Jonathan Scarlett, and Felix Berkenkamp (eds.), Int. Conf. Mach. Learn., pp. 1763–1840, 2024b. URL https://proceedings.mlr.press/v235/arora24a.html.
Iz Beltagy, Matthew E. Peters, and Arman Cohan. Longformer: The long-document transformer. arXiv preprint arXiv:2004.05150, 2020.
Jon Louis Bentley. Multidimensional divide-and-conquer. Commun. ACM, 23(4):214–229, 1980. doi: 10.1145/358841.358850.
Siwan Boufadene, François-Xavier Vialard, and Jean Feydy. Fast large deformation matching with the energy distance kernel. arXiv preprint arXiv:2505.03342, 2025.
Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D. Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, Tom Henighan, Rewon Child, Aditya Ramesh, Daniel Ziegler, Jeffrey Wu, Clemens Winter, Chris Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, and Dario Amodei. Language models are few-shot learners. In Adv. Neural Inf. Process. Syst., pp. 1877–1901, 2020. URL https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf.
Benjamin Charlier, Jean Feydy, Joan Alexis Glaunès, François-David Collin, and Ghislain Durif. Kernel operations on the GPU, with autodiff, without memory overflows. J. Mach. Learn. Res., 22(74):1–6, 2021. URL http://jmlr.org/papers/v22/20-275.html.
Krzysztof Marcin Choromanski, Valerii Likhosherstov, David Dohan, Xingyou Song, Andreea Gane, Tamás Sarlós, Peter Hawkins, Jared Quincy Davis, Afroz Mohiuddin, Łukasz Kaiser, David Benjamin Belanger, Lucy J. Colwell, and Adrian Weller. Rethinking attention with Performers. In Int. Conf. Learn. Represent., 2021. URL https://openreview.net/forum?id=Ua6zuk0WRH.
Tri Dao. FlashAttention-2: Faster attention with better parallelism and work partitioning. In Int. Conf. Learn. Represent., 2024. URL https://openreview.net/forum?id=mZn2Xyh9Ec.
Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, and Christopher Ré. FlashAttention: Fast and memory-efficient exact attention with IO-awareness. In Adv. Neural Inf. Process. Syst., pp. 16344–16359, 2022. doi: 10.52202/068431-1189.
Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, and Neil Houlsby. An image is worth words: Transformers for image recognition at scale. In Int. Conf. Learn. Represent., 2021. URL https://openreview.net/forum?id=YicbFdNTTy.
Carl Eckart and Gale Young. The approximation of one matrix by another of lower rank. Psychometrika, 1(3):211–218, 1936. doi: 10.1007/BF02288367.
Zhe Feng, Sen Lian, Changwei Wang, Muyang Zhang, Tianlong Tan, Rongtao Xu, Weiliang Meng, and Xiaopeng Zhang. LaplacianFormer: Rethinking linear attention with Laplacian kernel. In Int. Conf. Learn. Represent., 2026. URL https://openreview.net/forum?id=bJZExGYWqx.
Takashi Furuya, Maarten V. de Hoop, and Gabriel Peyré. Transformers are universal in-context learners. In Int. Conf. Learn. Represent., 2025. URL https://openreview.net/forum?id=6S4WQD1LZR.
Johannes Hertrich. Fast kernel summation in high dimensions via slicing and Fourier transforms. SIAM J. Math. Data Sci., 6(4):1109–1137, 2024. doi: 10.1137/24M1632085.
Johannes Hertrich, Christian Wald, Fabian Altekrüger, and Paul Hagemann. Generative sliced MMD flows with Riesz kernels. In Int. Conf. Learn. Represent., 2024. URL https://openreview.net/forum?id=VdkGRV1vcf.
Johannes Hertrich, Tim Jahn, and Michael Quellmalz. Fast summation of radial kernels via QMC slicing. In Int. Conf. Learn. Represent., 2025. URL https://openreview.net/forum?id=iNmVX91x91.
David P. Hofmeyr. Fast exact evaluation of univariate kernel sums. IEEE Trans. Pattern Anal. Mach. Intell., 43(2):447–458, 2021. doi: 10.1109/TPAMI.2019.2930501.
Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, and François Fleuret. Transformers are RNNs: Fast autoregressive transformers with linear attention. In Hal Daumé III and Aarti Singh (eds.), Int. Conf. Mach. Learn., pp. 5156–5165, 2020. URL https://proceedings.mlr.press/v119/katharopoulos20a.html.
Nikita Kitaev, Łukasz Kaiser, and Anselm Levskaya. Reformer: The efficient transformer. In Int. Conf. Learn. Represent., 2020. URL https://openreview.net/forum?id=rkgNKkHtvB.
Nicolas Langrené and Xavier Warin. Fast multivariate empirical cumulative distribution function with connection to kernel density estimation. Comput. Stat. Data Anal., 162:107267, 2021. doi:10.1016/j.csda.2021.107267.
Benjamin Lefaudeux, Francisco Massa, Diana Liskovich, Wenhan Xiong, Vittorio Caggiano, Sean Naren, Min Xu, Jieru Hu, Marta Tintore, Susan Zhang, Patrick Labatut, Daniel Haziza, Luca Wehrstedt, Jeremy Reizenstein, and Grigory Sizov. xFormers: A modular and hackable Transformer modelling library. https://github.com/facebookresearch/xformers, 2022.
Llama Team, AI @ Meta. The Llama 3 herd of models. arXiv preprint arXiv:2407.21783, 2024.
Niklas Muennighoff, Nouamane Tazi, Loic Magne, and Nils Reimers. MTEB: Massive text embedding benchmark. In Andreas Vlachos and Isabelle Augenstein (eds.), Conf. Eur. Chapter Assoc. Comput. Linguist., pp. 2014–2037, Dubrovnik, Croatia, 2023. doi: 10.18653/v1/2023.eacl-main.148.
Zach Nussbaum, John Xavier Morris, Andriy Mulyar, and Brandon Duderstadt. Nomic Embed: Training a reproducible long context text embedder. Trans. Mach. Learn. Res., 2025. URL https://openreview.net/forum?id=IPmzyQSiQE.
Hao Peng, Nikolaos Pappas, Dani Yogatama, Roy Schwartz, Noah A. Smith, and Lingpeng Kong. Random feature attention. In Int. Conf. Learn. Represent., 2021. URL https://openreview.net/forum?id=QtTKTdVrFBB.
Zhen Qin, Weixuan Sun, Hui Deng, Dongxu Li, Yunshen Wei, Baohong Lv, Junjie Yan, Lingpeng Kong, and Yiran Zhong. cosFormer: Rethinking softmax in attention. In Int. Conf. Learn. Represent., 2022. URL https://openreview.net/forum?id=B18CQrx2Up4.
Ali Rahimi and Benjamin Recht. Random features for large-scale kernel machines. In Adv. Neural Inf. Process. Syst., pp. 1177–1184, 2007. URL https://proceedings.neurips.cc/paper/2007/file/013a006f03dbc5392effeb8f18fda755-Paper.pdf.
Nicolaj Rux, Johannes Hertrich, and Sebastian Neumayer. Numerical methods for kernel slicing. arXiv preprint arXiv:2510.11478, 2025.
Jon Saad-Falcon, Daniel Y. Fu, Simran Arora, Neel Guha, and Christopher Ré. Benchmarking and building long-context retrieval models with LoCo and M2-BERT. In Ruslan Salakhutdinov, Zico Kolter, Katherine Heller, Adrian Weller, Nuria Oliver, Jonathan Scarlett, and Felix Berkenkamp (eds.), Int. Conf. Mach. Learn., pp. 42918–42946, 2024. URL https://proceedings.mlr.press/v235/saad-falcon24a.html.
Imanol Schlag, Kazuki Irie, and Jürgen Schmidhuber. Linear transformers are secretly fast weight programmers. In Marina Meila and Tong Zhang (eds.), Int. Conf. Mach. Learn., pp. 9355–9366, 2021. URL https://proceedings.mlr.press/v139/schlag21a.html.
M. A. Shubin. Almost periodic functions and partial differential operators. Russian Math. Surveys, 33(2):1–52, 1978. doi: 10.1070/RM1978v033n02ABEH002303.
Ingo Steinwart and Andreas Christmann. Support Vector Machines. Information Science and Statistics. Springer, New York, 2008. doi: 10.1007/978-0-387-77242-4.
Tom Streubel, Andreas Griewank, Manuel Radons, and Jens-Uwe Bernt. Representation and analysis of piecewise linear functions in abs-normal form. In Christian Pötzsche, Clemens Heuberger, Barbara Kaltenbacher, and Franz Rendl (eds.), Syst. Model. Optim., pp. 327–336, Klagenfurt, Austria, 2014. doi: 10.1007/978-3-662-45504-3_32.
Yi Tay, Mostafa Dehghani, Dara Bahri, and Donald Metzler. Efficient transformers: A survey. ACM Comput. Surv., 55(6):109:1–109:28, 2022. doi: 10.1145/3530811.
Tanja Teuber, Gabriele Steidl, Pascal Gwosdek, Christian Schmaltz, and Joachim Weickert. Dithering by differences of convex functions. SIAM J. Imaging Sci., 4(1):79–108, 2011. doi:10.1137/100790197.
Yao-Hung Hubert Tsai, Shaojie Bai, Makoto Yamada, Louis-Philippe Morency, and Ruslan Salakhutdinov. Transformer dissection: An unified understanding for transformer's attention via the lens of kernel. In Kentaro Inui, Jing Jiang, Vincent Ng, and Xiaojun Wan (eds.), Conf. Empir. Methods Nat. Lang. Process. and Int. Jt. Conf. Nat. Lang. Process., pp. 4344–4353, Hong Kong, China, 2019. doi: 10.18653/v1/D19-1443.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Adv. Neural Inf. Process. Syst., pp. 5998–6008, 2017. URL https://proceedings.neurips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf.
François-Xavier Vialard and Siwan Boufadène. Sliced ReLU attention: Quasi-linear contextual expressivity via sorting. arXiv preprint arXiv:2512.11411, 2025.
Sinong Wang, Belinda Z. Li, Madian Khabsa, Han Fang, and Hao Ma. Linformer: Self-attention with linear complexity. arXiv preprint arXiv:2006.04768, 2020.
Holger Wendland. Scattered Data Approximation, volume 17 of Cambridge Monographs on Applied and Computational Mathematics. Cambridge University Press, Cambridge, 2004. doi: 10.1017/CBO9780511617539.
Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, and Vikas Singh. Nyströmformer: A Nyström-based algorithm for approximating self-attention. Proc. AAAI Conf. Artif. Intell., 35(16):14138–14148, 2021. doi: 10.1609/aaai.v35i16.17664.
Songlin Yang, Bailin Wang, Yikang Shen, Rameswar Panda, and Yoon Kim. Gated linear attention transformers with hardware-efficient training. In Ruslan Salakhutdinov, Zico Kolter, Katherine Heller, Adrian Weller, Nuria Oliver, Jonathan Scarlett, and Felix Berkenkamp (eds.), Int. Conf. Mach. Learn., pp. 56501–56523, 2024a. URL https://proceedings.mlr.press/v235/yang24ab.html.
Songlin Yang, Bailin Wang, Yu Zhang, Yikang Shen, and Yoon Kim. Parallelizing linear transformers with the delta rule over sequence length. In Adv. Neural Inf. Process. Syst., pp. 115491–115522, 2024b. doi: 10.52202/079017-3668.
Chulhee Yun, Srinadh Bhojanapalli, Ankit Singh Rawat, Sashank Reddi, and Sanjiv Kumar. Are transformers universal approximators of sequence-to-sequence functions? In Int. Conf. Learn. Represent., 2020. URL https://openreview.net/forum?id=ByxRM0Ntvr.
Manzil Zaheer, Guru Guruganesh, Kumar Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, and Amr Ahmed. Big Bird: Transformers for longer sequences. In Adv. Neural Inf. Process. Syst., pp. 17283–17297, 2020. URL https://papers.neurips.cc/paper/2020/file/c8512d142a2d849725f31a9a7a361ab9-Paper.pdf.
A BACKGROUND ON FFMs
Here, we discuss the feature maps proposed by Katharopoulos et al. (2020); Choromanski et al. (2021); Peng et al. (2021); Schlag et al. (2021). In Katharopoulos et al. (2020), the feature map with is used. Later, Peng et al. (2021) used Bochner's theorem to construct a feature map that approximates the Gauss kernel via
where are sampled i.i.d. The associated kernel is then given as
Now, Bochner's theorem implies for the relation
This idea is due to Rahimi & Recht (2007), who also establish error estimates. The kernel induced by this feature map is not nonnegative anymore, which can lead to numerical instability.
In Peng et al. (2021), they resample during training, but keep them fixed at test time, as they did not notice any change of behavior when resampling. Moreover, they use exactly directions. Attention generates the queries , keys and values by multiplying a token with three separate matrices . The linear projections can be fused with the matrices and to and , and we can assume instead the form with . Therefore, we interpret the resampling during training as a training mechanism rather than a property of the kernel or attention.
Choromanski et al. (2021) use a similar argument to directly approximate the softmax kernel with the feature map . With the same argument for from the previous paragraph we omit the random projections. In contrast to , their FFM is nonnegative, but not stationary, see Proposition 5. Among the FFMs introduced by Choromanski et al. (2021), they found to generally perform best, which is why we use during the numerical comparison.
Table 4 summarizes the previous FFMs of Katharopoulos et al. (2020); Choromanski et al. (2021); Peng et al. (2021), which all are of the form
Table 4: Examples of FFMs of the form (19).
| Paper | J | ||
|---|---|---|---|
| Katharopoulos et al. (2020) | 1 | ||
| Peng et al. (2021) | 2 | ||
| Choromanski et al. (2021) | 1 |
Note that all FFM of the form (19) are additive kernels over , because
However, their univariate kernel is a FFM with of dimension 1 or 2, while the Laplace, Riesz and bump kernel have infinite dimension.
Schlag et al. (2021) replaces the random features proposed by Choromanski et al. (2021); Peng et al. (2021) with deterministic parameter-free projection (DPFP): Let with and . The DPFP feature map is with for and , where the indices are taken modulo 2D. This differs from the general form (19). Here, we require , so that the components of are linearly independent. In fact, is wasteful, as it does not increase the dimension of the RKHS anymore. In practice, we follow Schlag et al. (2021) and use with , so that .
B CONNECTION TO SLICING
Additive kernels can be seen as a deterministic slicing of radial kernels. Given a univariate kernel , the sliced kernel identity by Hertrich (2024) expresses a radial kernel on as an expectation over uniformly random directions,
where is obtained from by the Riemann Liouville transform , see also Rux et al. (2025, Eq. (10)). The fast summation of Hertrich (2024) estimates (21) by drawing directions and applying a one dimensional fast summation along each of them, which costs and converges at the Monte Carlo rate . Replacing the random directions by the fixed coordinate axes yields, up to the factor , exactly the additive kernel,
The two constructions therefore share the same one dimensional primitive. Choosing for the directions can further be interpreted as quasi-Monte Carlo design for the integration of the sphere, which sometimes achieves better error rates than the previously mentioned standard estimate for Monte Carlo methods. We refer to Hertrich et al. (2025) for details.
In the special case of Riesz, the sliced multivariate Riesz kernel yields the univariate Riesz kernel. Therefore, additive Riesz can be seen as a Monte Carlo approximation of the multivariate Riesz kernel . However, the additive Laplace kernel does not appear as Monte Carlo approximation neither of Laplace nor of Laplace. Instead additive Laplace is the Monte Carlo approximation of a power series given in Hertrich (2024, Table. 1). For more background on slicing see Hertrich (2024); Rux et al. (2025). Applications of the slicing algorithm were also presented in Hertrich et al. (2024); Boufadene et al. (2025).
C FAST COMPUTATION OF SPLINE-KERNEL ATTENTION
In most transformer architectures, the head dimension is either 32, 64 or 128, and the number of channels usually equals , or if the values are extended by a row of constant ones for normalization. We are interested in the case where the sequence lengths satisfy and . Let , and . We focus on the efficient computation of absolute value sums
The naive computation of the absolute value sum requires operations and would be the computational bottleneck if and are both large. Instead, it is possible to reduce the complexity to . Simply, rewrite
Each inner sum is of the type , where and . The absolute value sum in can be computed in by Algorithm 1. By Proposition 6 all spline kernels with finitely many nodes, can be computed in quasi linear time, by calling Algorithm 1 on each node. More details are given inside the proof of Proposition 6
C.1 PARALLELIZATION AND MEMORY OVERHEAD
In practice, an efficient scalable implementation is often worth more than theoretical runtime asymptotics. Although flash attention (Dao et al., 2022) did not change the asymptotic work, it had significant impact. While (23) can be computed asymptotically fast, two questions must be answered simultaneously for both the forward and the backward pass: (i) Can the implementation be parallelized? and (ii) Can we handle memory efficiently? Without a parallel implementation, this method cannot compete against massively parallel algorithms such as flash attention. Even a parallel implementation will not convince in practice if it is not memory efficient.
In practice, each tensor has an additional batch dimension , namely , and . If we implement Algorithm 1 via PyTorch primitives, then the prefix sums are materialized for each and each batch , resulting in memory costs. This is a known issue that has been attacked already by Dao et al. (2022); Charlier et al. (2021) for certain expand-reduce computations. Of course, we could instead serialize over and compute each part independently or in a smaller batch, but then again we pay with parallelism for memory. Yet, there is a way to parallelize completely over , and , staying serial only in , without materializing any huge intermediates. The idea is to sort as well and never materialize the entire prefix sums. Instead, for each , we scan through the sorted keys and values for , compute the prefix sums on the fly and write the result for query as soon as the scan reaches position . Since we also sort , the positions are monotonically increasing, which ensures that no previous values are needed again. In the end, we correct the result with the total sum. In practice, we use a grid of size and block size . Since a warp always works in 32 threads, our implementation favors being a multiple of 32 and , which is usually satisfied. The fused scan kernel has no thread divergence and data independent runtime. One disadvantage is that the final reduction over cannot be performed within a block, so atomic stores are needed. This is the main bottleneck of our implementation.
C.2 GRADIENTS AND AUTODIFF
Since our implementation is in CUDA, we need to implement the gradient for autograd ourselves. All gradients of our method can be computed in , such that both forward and backward run subquadratic in . The subgradient of the absolute value is sign, and within the gradients it is necessary to compute sums of the form
(25)
Again, these sums can be computed with work.
Let be the output of (23) and the upstream gradient. In the following, we compute the vector Jacobian products (VJP) of . The VJP w.r.t. is
This gradient can be computed just like the forward pass by swapping and replacing by . The VJP w.r.t. reads
In theory, the tensor pref_v could be passed from the forward to the backward pass. However, as we compute it on the fly, we need to recompute it during the backward pass. Lastly, the VJP w.r.t.
Table 5: Forward+backward of kernel attention (1) with runtime in milliseconds, mean over 10 runs after 5 warm-up iterations, with forward and backward timed together in a single region. Relative standard deviations are below for , below at and below for . Bold marks the fastest method overall; underline marks the fastest among the four fp32 methods. Shape: , , , , .
| N | add.riesz fp32 | softmax | |||||
|---|---|---|---|---|---|---|---|
| GLOBAL | FUSED | KEOPS | MEM_EFF32 | MEM_EFF16 | FLASH16 | CUDNN16 | |
| 128 | 1.066 | 0.913 | 1.598 | 0.098 | 0.071 | 0.059 | 0.057 |
| 256 | 1.329 | 1.147 | 2.424 | 0.233 | 0.104 | 0.067 | 0.069 |
| 512 | 1.832 | 1.620 | 4.087 | 0.609 | 0.231 | 0.132 | 0.143 |
| 1024 | 2.950 | 2.664 | 11.96 | 1.923 | 0.634 | 0.324 | 0.363 |
| 2048 | 5.283 | 4.927 | 40.33 | 7.360 | 2.262 | 0.978 | 1.050 |
| 4096 | 11.19 | 10.66 | 140.5 | 27.95 | 8.363 | 3.731 | 4.029 |
| 8192 | 23.18 | - | 520.9 | 109.0 | 31.72 | 13.90 | 14.99 |
| 16384 | 50.03 | - | 2007 | 433.4 | 129.8 | 54.35 | 57.88 |
| 32768 | 103.8 | - | 7903 | 1729 | 503.6 | 214.9 | 228.6 |
| 65536 | 219.1 | - | 31550 | 6905 | 1990 | 856.9 | 913.2 |
| 131072 | 600.6 | - | 125800 | 27730 | 8008 | 3442 | 3666 |
is given via
Both sign sums have a reduction over , which is our block dimension. Therefore, this reduction can be performed within a block and no atomics are needed anymore.
Table 5 measures the speed of our additive Riesz attention versus softmax backend. For FUSED, only the forward pass is fused: the backward walk reuses the sorted tensors, which the fused forward does not materialize, so it runs on the GLOBAL backward. The break even points are slightly better than the forward computation in Table 2, as GLOBAL even beats FLASH16 before . This has a simple reason: We measure the elapsed time for the forward and the and -backwards. Usually, those are 4 equally sized computations. For example, FLASH16's forward+backward at is 3442 and about larger than its forward 968.8 in Table 2. However, GLOBAL's presort of and , can be reused during the three backwards leading to a factor of 3 from 200 to 600.6. Similarly, the relative memory overhead between GLOBAL and fp32 softmax backend is around 1.5, while the forward was around 3 times larger.
C.3 PADDING
Consider a batch of samples with sequence lengths , , and maximal length . Padding extends the queries , keys and values of sample to and with
Since the padded values vanish, the kernel sums (7) are unchanged, for , so the weighted absolute value sums of Algorithm 1 are applied to the padded tensors without any modification. Only the normalization counts every padded key with weight one and hence contains the additional term . In order to fix the normalization, we compute this correction for all queries in operations, which is negligible compared to the kernel sums. Then, we obtain for that
while the outputs of the padded queries are discarded. Thus, we can pad samples of different length to a common length in order to process inputs of different sizes in one batch, which is necessary, for example, for text models.
Algorithm 2 Sorting algorithm for causal masked kernel sums
1 Input , and
2 Output given by
3 Denote by Sorting() the application of Algorithm 1
4 If :
5 compute naively
6 Else:
7 compute
8 compute
9 compute
10 set for
11 return
C.4 CAUSAL MASKING

visible masked
Causal mask
causal sorting of smaller size
sorting of smaller size zero
Decomposition in Step 1
causal sorting of smaller size
sorting of smaller size zero
processed in previous iteration
Decomposition in Step 2
Final decomposition
Figure 3: Illustration of the causal mask and of Algorithm 2 for computing the kernel summation with causal mask in quasi linear time. From left to right: causal mask applied to the kernel matrix; block decomposition in the first step of Algorithm 2; block decomposition in the second step; the resulting block partition after the full recursion.
Many current transformers use causal masking. That is, the kernel sum (7) is replaced by for . We refer to Figure 3 for an illustration of the mask. In this setting, Algorithm 1 is not directly applicable, since every query now sees a different set of keys. Nevertheless, we can overcome this issue by a divide-and-conquer algorithm outlined in Algorithm 2. For simplicity, we assume that the sequence lengths and are powers of two. The main idea of the algorithm (for ) is that we split the masked kernel matrix into four blocks. Each diagonal block corresponds to a kernel sum with causal masking with sequence length . The upper right off-diagonal block is zero (since the mask is zero). The lower left off-diagonal block is a standard kernel sum without masking and can be computed by Algorithm 1 (or the equivalent algorithm for the one dimensional Laplace kernel).
To verify the quasi linear complexity (simply assuming that ), we note that for each length for , we call times Algorithm 1 with sequence length . In particular, we have for each the cost . So in total, we obtain the complexity . In effect, Algorithm 2 decomposes the triangular mask into blocks, see the final decomposition in Figure 3, which it traverses serially by the recursion. This order is not required, however: all blocks can be computed independently, since synchronization is only needed in line 10, which can be resolved by atomic additions accumulating into the output tensor.
Algorithm 3 Weighted Laplace sum
| # | Step | Work | Memory |
|---|---|---|---|
| 1 | Input , and | - | |
| 2 | Output = | - | |
| 3 | s.t. | ||
| 4 | for | ||
| 5 | for | ||
| 6 | for , | ||
| 7 | for , | ||
| 8 | for | ||
| 9 | return |
C.5 AUTOREGRESSIVE DECODING
During autoregressive decoding, tokens are generated one at a time. With causal attention, the keys and values of previous tokens do not change and are stored in a KV cache of size . For each new query, softmax attention reads the full cache at cost , so decoding is memory-bound rather than compute-bound. This procedure does not depend on the softmax structure and can be done for any kernel.
D WEIGHTED LAPLACE SUMS
For the Laplace kernel the difficult part is to compute , where and . Splitting at as in (10) gives , so the same prefix-sum idea applies. The individual factors and , however, overflow in floating point as soon as the inputs leave a small range, even though their product is bounded by one. Algorithm 3 avoids this by expressing the prefix sums relative to the current node instead of the origin, which costs as well.
By induction, and , so that with for and for the last line indeed equals , where empty terms are read as zero.
Every exponent occurring in Algorithm 3 is non-positive: by sorting, and by the definition of . Hence, all exponentials lie in , and induction gives and for every channel , so that . All intermediate quantities are thus bounded by the same quantity as the exact sum itself, independently of the magnitude of and .
In weighted_laplace_sum we provide a parallel implementation following the structure of the weighted_abs_sum. Gradients and masking are out of scope.
E VISION TRANSFORMER
We train a small vision transformer (Dosovitskiy et al., 2021) for classification on CIFAR-10: 12 layers, 3 heads of dimension , hidden dimension 192, patch size 4, hence sequence length 64. Since the sequence length does not exceed the head dimension, even a 64-dimensional RKHS suffices to separate all tokens and the capacity mechanism of the previous section cannot bind. This experiment is therefore deliberately a controlled sanity check: any remaining quality differences must come from properties other than dimension.
Each model is trained once from scratch with random initialization, as well as being distilled from a softmax teacher model (96.57% accuracy) in three stages: The student shares the architecture of the teacher and differs only in the kernel, so that stage copy simply utilizes the teacher weights.
Layer-by-layer then finetunes one student attention module at a time to minimize the MSE to the teacher's attention output at that layer, and end-to-end finally finetunes all parameters against the teacher logits with temperature-scaled KL. This distillation setup is identical to the text transformer with the single difference of using the KL divergence instead of the MSE loss for end-to-end.
Training from scratch uses AdamW, cosine annealing with 100 warmup epochs, weight decay 0.1, 1000 epochs, batch size 128, RandAugment, MixUp/CutMix and label smoothing 0.1. In both the vision and text transformers, the layer-by-layer stage runs 10k steps per layer. The end-to-end stage runs 50k steps with KL temperature for the vision transformer, and 10k steps with the MSE loss for the text transformer (Section 4.3).
Table 6: CIFAR-10 test accuracy (%). Training from scratch as well as piecewise distillation.
| Kernel | scale | scratch | distillation from softmax | ||
|---|---|---|---|---|---|
| copy | +layerwise | +end-to-end | |||
| softmax (teacher) | 2.828 | 96.57 | — | — | — |
| gauss | 2.828 | 96.70 | 96.10 | 96.56 | 96.55 |
| laplace | 6.0 | 96.71 | 94.92 | 96.57 | 96.64 |
| riesz | 1.0 | 94.14 | 58.12 | 95.61 | 95.83 |
| add_riesz | 1.0 | 93.68 | 55.93 | 95.84 | 96.21 |
| add_laplace | 0.5 | 93.94 | 43.67 | 95.96 | 96.40 |
| add_bump | 1.5 | 94.56 | 43.33 | 96.13 | 96.26 |
| tri | 2.828 | 94.63 | 39.47 | 96.01 | 96.13 |
| relu | 1.0 | 95.08 | 62.40 | 96.12 | 95.91 |
| elu | 1.0 | 95.17 | 43.17 | 96.17 | 96.35 |
| dpfp | 1.0 | 95.15 | 75.84 | 96.39 | 96.41 |
Table 6 supports three conclusions. First, as predicted, no capacity gap appears: all kernels train to within accuracy of softmax after full distillation. Second, the softmax-Gauss correspondence (32) is not merely formal, as the copy stage Gauss student already reaches , so the reweighting argument holds numerically, not just algebraically. Interestingly, laplace with also reaches without any finetuning, while all other kernels lie at least below. Third, distillation matches or improves training from scratch for all kernels, in both accuracy and training time; the layer-by-layer stage does most of the work and end-to-end adds less than .
F ASSOCIATIVE RECALL
Schlag et al. (2021, Sec. 6.1 & 6.2) introduce associative recall in order to verify the capacity limits. They start with a set of tokens and a learnable embedding . Two random permutations of are sampled and the sequence of embedded tokens with is built. To each token a one-hot value is assigned. The keys are computed via with a learnable . To recall the value of token , a query with learnable is built and the value is retrieved as with , and from (2). The loss is
where is the value assigned to token , and it is evaluated for all . The loss is (up to a factor of ) exactly the inner term of (13), so that Lemma 11 also yields the form with the Frobenius norm. We differ only in the key matrix: we use and , as in the standard transformer. Our setting is contained in that of Schlag et al. (2021) by extending with a zero matrix .
G PROOFS
Proof of Theorem 1. By assumption, there exists some function with . Now, for arbitrary , let be a collection of points with . Then, we have by definition for all with that the Gram matrix fulfills
and as since . This yields that and for all such that for all and thus . While many transformers normalize the tokens , the keys and queries are obtained via and , where are weight matrices. Choosing recovers from the proof.
Proof of Proposition 2. For the Gauss kernel , we have that . In particular, if , the attention matrices with respect to and coincide, since
Thus, we obtain by the same proof as for Theorem 1 that , provided that we choose for all in that proof, which is possible because the sphere for has infinitely many points.
Proof of Proposition 5. As is continuous and stationary there is continuous with . Since has a FFM expansion we know that is spd and has RKHS . By Bochner's theorem, there is a real nonnegative Borel measure such that . Since is real symmetric , is symmetric too and . A feature space of is given by , where and denote the even and odd function classes of . A feature map of is , because
By Steinwart & Christmann (2008, Thm. 4.21) the map given by is surjective. For with and , this operator is given by
(34)
As the Fourier transformation is injective implies and thus and . Therefore, , vanish -almost everywhere and is injective. Since has FFM : , it holds . Since is a linear bijection, is finite dimensional, which renders to be finite dimensional. This implies supp to be a finite set and hence for and . By Bochner's theorem, we thus obtain
The function is a trigonometric polynomial, hence almost periodic. Its mean value satisfies unless , by the orthogonality of characters (Shubin, 1978, Prop. 1.5). Since implies (Shubin, 1978, Prop. 1.8) we conclude .
Proof of Proposition 6. Any continuous piecewise linear function with finitely many nodes can be expressed in terms of absolute values (Streubel et al., 2014, p. 328) as
Let , and . Inserting (36) into the kernel sum yields
The constant and linear part can be computed in operations. For each , we shift the keys to and compute by the fast summation of the distance kernel applied to , and . Each call costs operations, which results in a total of . Note that the sorting of is the same as that of and does not need to be repeated for each node. Further, can be sorted once to avoid the repeated bisection. Therefore, the complexity can be improved to .
Note that the statement extends to the noncontinuous case: every piecewise linear function with finitely many nodes decomposes into a continuous piecewise linear function and a piecewise constant function. The latter only requires the evaluation of which can be solved in quasi linear time as explained in (25).
Proof of Proposition 8. For the Riesz kernel let and be arbitrary points with . Further, let and denote the attention matrix of given and . Fix and . The map is monotone for all , hence the maximum is attained at where . For all it holds and thus
Since we have . For we can choose and . Then it holds as , so the capacity is exactly 2.
Proof of Theorem 9. To distinguish the Gram and attention matrices with respect to and , we denote them by and or and , respectively. Now let and . Then, we know that there exist such that . Define by and . Then, we obtain by definition that and therefore . In particular, we have . Since this works for any , we obtain that and .
Let be the Riesz kernel. For arbitrary and , we can choose for and for . Then it holds for , that and for , . Hence, we get as , so the capacity is at least .
Symmetry and translation invariance clearly carry over from to . If is positive definite, then for all and it holds
so is positive definite. Now, let be quasi linear and let , and . Rearranging the kernel sum yields
Since is quasi linear, each of the inner sums can be computed in quasi linear time for all simultaneously. Summing the results over costs another operations, hence is computed in quasi linear time for every fixed .
Proof of Lemma 11. Since the normalization in (2) sums over all keys, we have . With this gives , and thus
(41)
The second equality uses that is an orthonormal basis, and the third substitutes and .