返回资讯中心
外部精选
软件工程
#开发者实时流

FLAT: Flash Linear Attention on TPUs

While the Transformer architecture [1] has gained immense adoption, recent production LLMs have adopted variants of Linear Attention [2]: Kimi K3 [3] uses Kimi Delta Attention [4], and Qwen 3.5 [5] interleaves Gated Del…

Hacker News 最新matt_d2026/10/15 · 2026/10/1530 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

While the Transformer architecture [1] has gained immense adoption, recent production LLMs have adopted variants of Linear Attention [2]: Kimi K3 [3] uses Kimi Delta Attention [4], and Qwen 3.5 [5] interleaves Gated DeltaNet [6] layers with full attention. A linear attention layer replaces attention’s KV-cache, which grows with the context, with a fixed-size recurrent state, so generating a token takes constant time and memory and training costs O(T)O(T)O(T) in the context length TTT.

While GPUs have fast kernels for these layers, such as FLA (flash-linear-attention) and Mamba’s CUDA kernels, Google’s TPUs [7, 8] do not. Recent TPU work targets inference [9, 10]; we know of no open-source kernels for training these layers on TPUs. We release FLAT: Flash Linear Attention on TPUs, Pallas implementations of Linear Attention [2], Mamba-2 [11], and Gated Linear Attention (GLA) [12] for TPUs, benchmarked on a TPU v6e (Trillium) chip. We also release a fast Pallas kernel for the short causal convolution that most linear attention layers apply before the recurrence. Counting the forward and backward together, FLAT on one TPU v6e chip is up to 3×3\times3× faster than FLA on an NVIDIA H100 (Figure ?): 1,982 µs against 6,106 µs for GLA, 1.6×1.6\times1.6× faster for Linear Attention and 1.5×1.5\times1.5× faster for Mamba-2. We use these kernels to train Rigel [13] on TPU chips.

Writing these kernels for a TPU turned out to be a different problem from writing them for a GPU (Section ?). Three things kept getting in our way:

Most of our speedups come from three ideas:

We aim to release training kernels for DeltaNet [14], Gated DeltaNet [6] and Kimi Delta Attention [4] soon.

GPUs are built from many streaming multiprocessors (SMs), 132 on an H100. Each SM runs many warps of SIMT threads and has tensor cores for matrix multiplies. Its hardware warp schedulers choose a ready warp every cycle, so when one warp stalls on memory, another runs in its place.

TPUs are built around the MXU, a large systolic array for matrix multiplies. A v6e chip has one TensorCore with two 256×256256 \times 256256×256 MXUs; everything else (elementwise math, reductions, data shuffling) runs on a vector unit, the VPU. There is no hardware scheduler: the compiler (XLA, or Mosaic for Pallas kernels) schedules the whole program ahead of time into a static VLIW instruction stream.

Each cycle, a v6e TensorCore issues one instruction bundle*NoteA bundle can be thought of as one wide instruction. with fixed slots: scalar, vector ALU (VPU), transcendental (EUP), cross-lane (rotates, transposes, lane reductions), VMEM loads and stores, and the MXU. A separate DMA engine copies data between HBM and VMEM in the background. Nothing is reordered at runtime, so two pieces of work overlap only if the kernel exposes them as independent.

GPU kernels for linear attention rely on hardware a TPU does not have, so they cannot simply be translated. The features above turn into three problems:

One property of the TPU works in our favor. A GPU kernel has to spread its work over many SMs, so FLA computes the chunk states in one kernel, writes them to HBM, and reads them back in a second kernel to produce the output. A v6e chip has a single core, and the kernel itself decides what stays in its VMEM, so our forward keeps the recurrent state in VMEM for the whole sequence and computes the states and the output in one kernel (Figure ?). Inferact’s megakernel relies on the same property to prefetch the next layer’s weights into VMEM while the current layer runs [9].

All our measurements are taken on a single TPU v6e chip and report device time. Per-op breakdowns sum each op’s device time from an XProf trace. Unless stated otherwise, inputs and outputs are in bf16 [15], and accumulations and reductions are in fp32.

We judge every kernel against the two ceilings of a roofline model [16].

A kernel’s arithmetic intensity, the FLOPs it does per byte it moves, decides which ceiling applies. On the MXU the crossover is about 918/1.638≈560918 / 1.638 \approx 560918/1.638≈560 FLOP/byte, and on the VPU it is about 7.091/1.638≈4.37.091 / 1.638 \approx 4.37.091/1.638≈4.3 FLOP/byte.

Linear Attention [2] has a recurrent form, used for autoregressive inference, with qt,kt∈RKq_t, k_t \in \mathbb{R}^{K}qt​,kt​∈RK, vt∈RVv_t \in \mathbb{R}^{V}vt​∈RV and state Ht∈RK×V\mathbf{H}_t \in \mathbb{R}^{K \times V}Ht​∈RK×V:

and a chunkwise form, used for training, that turns most of the work into matrix multiplies. With chunks of CCC positions, Q[i],K[i],V[i]\mathbf{Q}{[i]}, \mathbf{K}{[i]}, \mathbf{V}_{[i]}Q[i]​,K[i]​,V[i]​ the rows of chunk iii, and MC\mathbf{M}_CMC​ the C×CC \times CC×C lower-triangular causal mask:

RetNet [18] adds a scalar forget gate to Linear Attention, a constant that does not depend on the input xtx_txt​. Mamba-2 [11] reformulates the selective state-space model introduced by Mamba [17] as an instance of structured state-space duality (SSD), which expresses the SSM recurrence as a form of linear attention with a data-dependent, scalar state-transition gate. Gated Linear Attention (GLA) [12] goes further with a diagonal, channel-wise forget gate. The table lists the recurrent and chunkwise forms of each:

Notation: Ft=∏s≤tfsF_t = \prod_{s \le t} f_sFt​=∏s≤t​fs​ is the cumulative decay (a scalar for Mamba-2, a vector for GLA), F[i]\boldsymbol F_{[i]}F[i]​ stacks it over chunk iii, and for RetNet (Lf)mn=fm−n(\mathbf{L}f){mn} = f^{m-n}(Lf​)mn​=fm−n for m≥nm \ge nm≥n and 0 otherwise. Divisions are elementwise. RetNet is Mamba-2 with a constant gate, so it runs on the Mamba-2 kernels.

On GPUs, FLA splits the forward into a state-passing kernel and an output kernel to expose enough parallelism for over a hundred SMs. A TPU chip has a single TensorCore, so we fuse both into one kernel.

Differentiating the recurrence gives a recurrence for the state gradient that runs backwards in time:

It has the same form as the forward recurrence, with qtq_tqt​ and ∇ytL\nabla_{y_t}\mathcal{L}∇yt​​L in the roles of ktk_tkt​ and vtv_tvt​, so the backward of linear attention is itself a linear attention run in reverse. The input gradients read off the two states:

Chunkwise, with the chunks visited in reverse order i=⌈S/C⌉−1,…,0i = \lceil S/C \rceil{-}1, \ldots, 0i=⌈S/C⌉−1,…,0:

The gated variants follow the same equations, with the gate also scaling the state gradient at every step, and they have one more output, the gradient of the forget gate. For GLA [12] it is the state gradient times the previous state, summed over the value dimension: ∇ftL=(∇HtL⊙Ht−1)1V\nabla_{f_t}\mathcal{L} = \left(\nabla_{\mathbf{H}t}\mathcal{L} \odot \mathbf{H}{t-1}\right)\mathbf{1}_V∇ft​​L=(∇Ht​​L⊙Ht−1​)1V​. RetNet [18] and Mamba-2 [11] follow the same pattern with a scalar gate, and their chunkwise forms follow the same derivation.

Our kernels never materialize ∇HtL\nabla_{\mathbf{H}t}\mathcal{L}∇Ht​​L and Ht−1\mathbf{H}{t-1}Ht−1​ one timestep at a time to get ∇ftL\nabla_{f_t}\mathcal{L}∇ft​​L. The forward already writes every fff-dependent ratio as an exponentiated chunk-local prefix sum of log⁡f\log flogf, so the backward differentiates that prefix sum instead. The adjoint of a prefix sum is a suffix sum, so the gradient kernel accumulates qt⊙∇qtL−kt⊙∇ktLq_t \odot \nabla_{q_t}\mathcal{L} - k_t \odot \nabla_{k_t}\mathcal{L}qt​⊙∇qt​​L−kt​⊙∇kt​​L at every position and suffix-sums it within the chunk, plus a boundary term from HiC⊙∇H(i+1)CL\mathbf{H}{iC} \odot \nabla{\mathbf{H}{(i+1)C}}\mathcal{L}HiC​⊙∇H(i+1)C​​L. The result is ∇log⁡ftL=ft ∇ftL\nabla{\log f_t}\mathcal{L} = f_t , \nabla_{f_t}\mathcal{L}∇logft​​L=ft​∇ft​​L: the same quantity as above, reached by differentiating the log-space form instead of the one-step recurrence.

In practice the backward runs as two kernels. A state-passing kernel reruns the forward recurrence to recompute HiC\mathbf{H}{iC}HiC​ at the start of every chunk and stores it in HBM. A gradient kernel then walks the chunks in reverse, carrying ∇HL\nabla{\mathbf{H}}\mathcal{L}∇H​L, and computes the gradients of the queries, keys, values and gate (Section ?).

We implement the TPU forward pass in Pallas as a fused, chunkwise recurrence. Our first implementation tiled the batch, the sequence and the value head dimension, with a program grid of (B, ceil(V / BLOCK_SIZE_V), ceil(S / BLOCK_SIZE_S)). The current kernel tiles only the batch and the sequence: with BLOCK_SIZE_S = 256 the grid is (B, ceil(S / BLOCK_SIZE_S)), and every program covers all heads and the full value width of its chunk. Every per-head tensor arrives flattened to (B, S, N·K), the layout a projection produces, so a head is a lane-aligned column slice of a block, and a value tile spanning all heads would not be a rectangular block. The batch axis is parallel, while the sequence axis is sequential because each chunk needs the state produced by the previous one. This maps well to a TPU: with a single TensorCore, the batch axis alone keeps the chip busy, and a program can carry the recurrent state in VMEM across the whole sequence instead of writing every intermediate state to HBM (Section ?).

Each program keeps the recurrent state of all NNN heads in VMEM as an fp32 (N,K,V)(N, K, V)(N,K,V) tile. It initializes the state from the optional input state (or zero) and then walks the sequence one chunk at a time. Within a chunk it loads Q[i]\mathbf{Q}{[i]}Q[i]​, K[i]\mathbf{K}{[i]}K[i]​ and V[i]\mathbf{V}{[i]}V[i]​, computes the causal intra-chunk term (Q[i]K[i]⊤⊙MC)V[i](\mathbf{Q}{[i]} \mathbf{K}{[i]}^\top \odot \mathbf{M}C) \mathbf{V}{[i]}(Q[i]​K[i]⊤​⊙MC​)V[i]​, adds the readout of the carried state Q[i]HiC\mathbf{Q}{[i]} \mathbf{H}{iC}Q[i]​HiC​, writes the output, and updates the state with the chunk’s K[i]⊤V[i]\mathbf{K}{[i]}^\top \mathbf{V}_{[i]}K[i]⊤​V[i]​. State passing and output readout thus happen in the same Pallas program instead of two separate kernels; we call this the fused block-recurrent kernel.

Mamba-2 [11] uses a scalar, data-dependent forget gate ftf_tft​. All terms involving the cumulative product of the forget values (Ft=∏s≤tfs)\left( F_t = \prod_{s \leq t} f_s \right)(Ft​=∏s≤t​fs​) in the architecture table can then be evaluated in log space for numerical stability as:

In the current implementation, a separate XLA op computes this chunk-local prefix sum before the Mamba-2 Pallas kernel runs, as a multiplication by a triangular matrix of ones (the same trick GLA uses inside its kernel, described next). On a per-head gate this matmul takes 6 µs, where XLA’s jnp.cumsum takes 86 µs. The kernel then exponentiates the prefix where the recurrence needs it.

GLA [12] replaces the scalar gate with a diagonal one: every key channel has its own forget value, so ft∈RKf_t \in \mathbb{R}^Kft​∈RK and Ft=∏s≤tfsF_t = \prod_{s \leq t} f_sFt​=∏s≤t​fs​ is taken elementwise. Our first GLA kernels were the Mamba-2 kernels with the gate widened to KKK channels. The cumsum then had KKK times as many elements, became bound by VPU throughput, and noticeably slowed down end-to-end training.

A prefix sum is a linear map, though, so the MXU can compute it instead. For a chunk of CCC positions following position jjj (so i=j+Ci = j + Ci=j+C), all CCC prefix sums come from a single multiplication by a lower-triangular matrix of ones:

​log(Fj​Fj+1​​)log(Fj​Fj+2​​)⋮log(Fj​Fi​​)​​=MC​(lower-triangular prefix-sum matrix)​11⋮1​01⋮1​⋯⋯⋱⋯​00⋮1​​​​​logfj+1​logfj+2​⋮logfi​​​. The final entry gives log⁡(Fi/Fj)\log(F_i/F_j)log(Fi​/Fj​); exponentiating it gives the desired ratio. In the optimized GLA path, the Pallas program takes the raw log decays and multiplies them by MC\mathbf{M}CMC​ on the MXU, accumulating in fp32. The resulting prefix is exponentiated only where needed to scale Q[i]\mathbf{Q}{[i]}Q[i]​, K[i]\mathbf{K}_{[i]}K[i]​, or the carried state. This keeps the scan inside the fused custom kernel and avoids a separate prefix-scan kernel.

The kernels accept any sha

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →