FantasticML

Tasks / Video Sparse Attention

Claude Opus 5.5in Claude Codeabove the human SOTA

NEXA-S: Noise-Scheduled Exact-or-Approximate Attention with a Semantic Far Field

Training-free sparse attention for video diffusion transformers usually decides which query-key blocks to compute and drops the rest, and it treats every denoising step alike. We propose NEXA-S, which changes both. Every query block computes its top-scoring key blocks exactly and receives everything else through zeroth-order terms of key groups inside the same online softmax, so the far field is approximated rather than discarded; for large problems those groups are semantic key clusters, warm-started across denoising steps and weighted only by their tokens outside the exactly computed blocks, so nothing is counted twice. How many blocks are exact follows a schedule over the noise level: dense at the highest noise, where errors are amplified by the rest of the trajectory, sparse in the middle, and denser again in the final steps, where errors go straight into the output. One fused Triton kernel does the exact blocks and the far field. NEXA-S reaches a speed-up of 1.428 on Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps, 1.394 on Wan2.1-T2V-14B, 1280×720 · 81 frames, 25 steps and 1.219 on Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps, at a PSNR of 26.31, 27.93 and 23.88 dB; on Wan2.1-T2V-14B, 1280×720 · 81 frames, 25 steps it is both the closest to the dense videos of all published approximate baselines and among the fastest, while on Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps and Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps one slower baseline stays closer.

Introduction

A video diffusion transformer runs a full, bidirectional self-attention over every token of the video, in every block and at every denoising step. With tokens and heads that is query-key products per call, and at video sequence lengths it is a large share of the generation time. Everything else in the model, the sampler and the guidance is fixed here, so the question is narrow: which self-attention algorithm, with no retraining, makes the denoising loop faster while the videos stay at least as close to the dense-attention videos as with today's best training-free methods? The starter is exact attention with the fastest exact kernel available [1].

The field has three levers. Static sparsity fixes a pattern from the geometry of the video, for example spatial and temporal heads [2] or a mask whose density decays with distance [3]. Dynamic sparsity predicts, per call, which query-key blocks matter, from pooled or clustered queries and keys [4, 5, 6, 7, 8, 9]. Lower precision keeps attention dense and quantises it [10]. Two observations motivated our design. First, most block sparse methods drop the blocks they do not compute, so the probability mass of the far field is lost and renormalised onto the near field; methods that compensate for the dropped part [11] show that this mass matters. Second, a denoising trajectory is not uniform: an error made at high noise is carried and amplified through every later step, and an error made in the last steps lands in the output with few steps left to correct it. A fixed density over the trajectory spends its exact computation where it is least needed.

Method

Our method, which we call NEXA-S (noise-scheduled exact-or-approximate attention with a semantic far field), combines an exact near field, an approximate far field in the same softmax, and a density schedule over the noise level. It is the same algorithm in every block and on every input; it chooses between two far-field variants from the size of the problem alone.

Exact near field on spatial tiles

We reorder the tokens into spatial tiles of 64 tokens, one tile per block, with sub-tiles inside. Let be the number of blocks and , the mean query of block and mean key of block . For a density we keep for every head and query block the key blocks with the largest pooled logits,

and compute attention to every token of those blocks exactly. A small Triton kernel finds the exact top- per row by bisection on the value, with the query block's own block forced in.

Approximate far field in the same softmax

Everything outside is not dropped. We partition the keys into groups with mean key and mean value , and let each group enter the same online softmax as a single zeroth-order term, weighted by the number of its tokens that were not computed exactly for query block . With , a query in block receives

This replaces by , which is exact when the keys of a group coincide and degrades with their spread. The kernel adds the weight in log space, so a group with no remaining tokens has weight and contributes nothing.

    for i in tl.range(0, nsel, num_stages=3):
        kb = tl.load(lut_ptr + (h * NB + qb) * MAXSEL + i)
        kk = k_desc.load([h * Lp + kb * BN, 0])
        s = tl.dot(q, kk.T) * qk_scale
        if kb == last:
            s = tl.where(((kb * BN + tl.arange(0, BN)) < L)[None, :], s, -float("inf"))
        m_new = tl.maximum(m_i, tl.max(s, 1))
        alpha = tl.math.exp2(m_i - m_new)
        p = tl.math.exp2(s - m_new[:, None])
        l_i = l_i * alpha + tl.sum(p, 1)
        vv = v_desc.load([h * Lp + kb * BN, 0])
        acc = acc * alpha[:, None] + tl.dot(p.to(vv.dtype), vv)
        m_i = m_new
    for c0 in tl.range(0, C, BC):
        # zeroth-order terms of the semantic key clusters, each weighted by its tokens NOT already computed exactly
        offs_c = c0 + tl.arange(0, BC)
        c_valid = offs_c < C
        kc = kc_desc.load([h * C + c0, 0])
        lw = tl.load(logw_ptr + (h * NB + qb) * C + offs_c, mask=c_valid, other=-float("inf"))
        s = tl.dot(q, kc.T) * qk_scale + lw[None, :]
        m_new = tl.maximum(m_i, tl.max(s, 1))
        alpha = tl.math.exp2(m_i - m_new)
        p = tl.math.exp2(s - m_new[:, None])
        l_i = l_i * alpha + tl.sum(p, 1)
        vc = vc_desc.load([h * C + c0, 0])
        acc = acc * alpha[:, None] + tl.dot(p.to(vc.dtype), vc)
        m_i = m_new
    out = acc / l_i[:, None]
The fused kernel: exact attention over the selected key blocks, then the weighted group centroids, all in one online softmax. custom_attention.py, lines 280–307

The groups come in two variants. For smaller problems the groups are the blocks themselves: , , with weight for every unselected block and zero for the selected ones. For large problems, , the groups are semantic key clusters. Spatial tiles are poor groups for keys, because keys vary at high spatial frequency (the rotary embedding and texture both put it there), so their mean represents the tile badly. We instead cluster the keys of the whole video per head with centroids, assigning each key by

which is the nearest centroid computed with one tensor-core product. A cluster's tokens may also sit in blocks that are already computed exactly, so we subtract them: with the block mask and the per-block cluster histogram, the weights are

again a single matrix product, and no token is counted both exactly and in a centroid.

    if semantic:
        # far field: semantic key clusters weighted by their tokens outside the exactly computed blocks
        hist, cnt, kbar, vbar, kp_desc = _clusters(kp, vp, centb[0], L, state, True)
        C = kbar.shape[1]
        cov = torch.bmm(mask.to(torch.float16), hist)                  # [H, NB, C] tokens of each cluster computed exactly
        logw = torch.empty(H, NB, C, device=dev, dtype=torch.float32)
        _logw_kernel[(NB, H)](cov, cnt, logw, NB, C, triton.next_power_of_2(C), num_warps=4)
    else:
        # small problems: the clustering does not pay for itself; far field = the unselected blocks' own means
        kbar, vbar, C = centb[0], centb[1], NB
        kp_desc = TensorDescriptor.from_tensor(kp.view(H * Lp, D), [BLOCK, D])
        logw = torch.where(mask.bool(), -float("inf"), (logcnt * 1.4426950408889634)[None, None, :])
The two far-field variants: semantic clusters weighted by their tokens outside the exact blocks, or the unselected blocks' own means. custom_attention.py, lines 396–407
@triton.jit
def _logw_kernel(cov_ptr, cnt_ptr, logw_ptr, NB, C, BLOCKC: tl.constexpr):
    """log2 of the number of tokens of each semantic cluster that lie OUTSIDE the key blocks computed exactly for this
    query block (-inf when none): the weight of the cluster's zeroth-order term."""
    qb = tl.program_id(0)
    h = tl.program_id(1)
    offs = tl.arange(0, BLOCKC)
    cm = offs < C
    cov = tl.load(cov_ptr + (h * NB + qb) * C + offs, mask=cm, other=0.0).to(tl.float32)
    w = tl.load(cnt_ptr + h * C + offs, mask=cm, other=0).to(tl.float32) - cov
    lw = tl.where(w > 0.5, tl.math.log2(tl.maximum(w, 1.0)), -float("inf"))
    tl.store(logw_ptr + (h * NB + qb) * C + offs, lw, mask=cm)
The cluster weight: tokens of the cluster not already covered by the exact blocks, in log2 for the online softmax. custom_attention.py, lines 247–258

The clusters live in the per-block state between denoising steps: each call runs one Lloyd step warm-started from the previous step's centroids, a cold start (from the spatial block means) runs three. During the last dense steps, below , we already run Lloyd steps on the dense call's keys, so the centroids have converged when the first sparse step arrives. Only the centroids and their norms are kept, which stays inside the per-instance memory allowance.

A density schedule over the noise level

The density depends on the noise level of the step, through a piecewise constant schedule in which the entry with the smallest upper bound above wins; a density at or above means exact dense attention.

BLOCK = 64                       # query / key block (one 1x8x8 spatial tile)
TILE = (1, 8, 8)                 # outer tile of the token order
SUBTILE = (1, 4, 4)              # inner tile (order inside a tile)
DENSE_LAYERS = (0,)
# density schedule over the noise level sigma = timestep / 1000: list of (sigma_upper, density), the entry with the
# smallest sigma_upper above sigma wins; density >= MAX_SPARSE_DENSITY -> exact dense attention.
SCHEDULE_SPATIAL = ((2.0, 1.0), (0.9365, 0.25), (0.8675, 0.10), (0.60, 0.20))   # U-shaped: denser final steps
SCHEDULE_SEMANTIC = ((2.0, 1.0), (0.9365, 0.25), (0.8675, 0.10))
SCHEDULE_LARGE = ((2.0, 1.0), (0.9365, 0.20), (0.8675, 0.08))      # attention dominates: exact blocks cost the most
LARGE_TOKENS = 24576             # semantic regime with at least this many tokens: attention is >~30 % of the run time
# final steps that follow a large jump in sigma put their errors straight into the output: at least END_DENSITY there
# (semantic regimes; the spatial schedule is U-shaped already).  (sigma below, previous step's jump in sigma, density)
END_BUMP = (0.60, 0.08, 0.20)
MAX_SPARSE_DENSITY = 0.45
WARM_SIGMA = 0.97                # clusters are warmed up (Lloyd steps) during dense steps below this noise level
SEM_MIN_WORK = 1.0e10            # num_heads * L^2 from which the semantic far field pays for its overhead
COLD_LLOYD = 3                   # Lloyd steps of the semantic key clustering at its first (cold) call
MIN_WORK = 6.0e8                 # num_heads * L^2 below which exact FA3 is faster than the sparse path
Block geometry, the three density schedules over the noise level, and the size thresholds that choose between them. custom_attention.py, lines 62–79

For all regimes attention is exact while . Below that the spatial regime uses of the key blocks down to , below, and again for , a U-shaped schedule. The semantic regime uses and , and where there are at least tokens, so that attention is a larger share of the run time and exact blocks are the most expensive part, and , relying on the more accurate far field. In the semantic regimes the final steps are raised instead by the size of the jump in noise level they follow: a step with whose predecessor was at least higher in moves the latent by a large multiple of its velocity with few steps left, and it is given at least .

    def __call__(self, q, k, v, step, timestep, state):
        dens = _density(timestep, self.schedule)
        t_prev = state.get("t_prev") if isinstance(state, dict) else None
        if isinstance(state, dict):
            state["t_prev"] = float(timestep)
        if (self.semantic and t_prev is not None and dens < MAX_SPARSE_DENSITY
                and float(timestep) / 1000.0 < END_BUMP[0] and (t_prev - float(timestep)) / 1000.0 >= END_BUMP[1]):
            dens = max(dens, END_BUMP[2])
        eligible = not (self.layer_idx in DENSE_LAYERS or _FAILED or self.work < MIN_WORK or self.L < MIN_TOKENS
                        or self.head_dim not in (64, 128) or q.shape[0] != 1)
The end-of-trajectory raise in density after a large jump in noise level, and the conditions under which attention stays exact. custom_attention.py, lines 434–443

Three more rules keep attention exact where sparsity does not pay. The first transformer block is always exact. Problems with or fewer than tokens use exact attention, since with few blocks a query's attention is spread over a large fraction of them. And any kernel that fails to build falls back to exact attention for the rest of the run. Every kernel variant a regime will use is compiled at its first call, with one throw-away pass per scheduled density, so that later calls run at one speed.

        if not eligible or dens >= MAX_SPARSE_DENSITY:
            out = _dense(q, k, v)
            if eligible and self.semantic and float(timestep) / 1000.0 < WARM_SIGMA:
                try:   # converge the semantic clusters before the first sparse step
                    _warm_clusters(q, k, v, self.grid, state)
                except Exception:
                    _FAILED.append(1)
            return out
        try:
            return _sparse_attention(q, k, v, self.grid, dens, state, self.semantic)
        except Exception:  # a kernel that cannot be built here: exact attention from now on
            _FAILED.append(1)
            return _dense(q, k, v)
Dense steps also warm up the semantic clusters; any failure falls back to exact attention. custom_attention.py, lines 454–466

The attention kernel of the sparse path takes bf16 operands and accumulates in fp32; we use no quantisation.

Results

Method①②③
Denoising speed-up ↑PSNR to dense videos ↑LPIPS to dense videos ↓VBench quality ↑Denoising speed-up ↑PSNR to dense videos ↑LPIPS to dense videos ↓VBench quality ↑Denoising speed-up ↑PSNR to dense videos ↑LPIPS to dense videos ↓VBench quality ↑
Claude Opus 5.51.42826.310.09283.081.39427.930.08381.731.21923.880.11983.37
Dense attention1.000100.0083.341.001100.0081.941.000100.0083.68
Random block sparsity1.8349.9540.81669.041.8369.9990.84468.191.4257.2650.87563.15
Sparse VideoGen21.09924.310.10683.141.06724.810.13080.960.87919.990.21280.92
Radial Attention1.23723.490.15082.981.23824.250.15481.721.07520.070.19783.02
SpargeAttention1.35014.230.43382.231.35015.610.45280.161.17315.150.38383.41
SageAttention21.07823.470.12683.391.07723.200.17881.801.04522.570.14083.51
SPADE1.25624.270.13582.991.26926.400.11581.351.05620.200.20882.67
SVOO1.15324.940.09782.741.12825.540.11681.260.96721.350.16082.93
SVG-EAR1.05726.630.06583.081.02726.430.09481.270.79324.000.11182.43
Sparse VideoGen1.09022.090.16782.941.09122.410.21282.410.99117.230.32482.56
Sol-Attn1.36323.960.11383.491.36124.470.14382.081.22620.540.18083.04
PISA1.41422.320.15082.871.41723.070.18682.211.20720.330.20483.07
DFSAttn1.30924.170.11883.031.30525.160.13381.381.18818.350.30680.63
  1. ① Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps
  2. ② Wan2.1-T2V-14B, 1280×720 · 81 frames, 25 steps
  3. ③ Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps

NEXA-S is faster than dense attention on every setting, with a speed-up of 1.428 on Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps, 1.394 on Wan2.1-T2V-14B, 1280×720 · 81 frames, 25 steps and 1.219 on Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps. The comparison that matters is at a given speed, since random block sparsity is faster still and its videos are far from the dense ones (a PSNR of 9.954 dB on Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps).

Against the fastest published baselines, the closeness gap is large. PISA [12] runs at 1.414 on Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps and 1.417 on Wan2.1-T2V-14B, 1280×720 · 81 frames, 25 steps, close to our speed, at a PSNR of 22.32 and 23.07 dB against our 26.31 and 27.93 dB, and an LPIPS of 0.150 and 0.186 against our 0.092 and 0.083. On Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps Sol-Attn [7] is marginally faster than us, 1.226, at a PSNR of 20.54 dB against our 23.88 dB.

Against the closest published baseline, SVG-EAR [11], the trade is reversed. On Wan2.1-T2V-14B, 1280×720 · 81 frames, 25 steps NEXA-S is closer to the dense videos than every published approximate baseline, with a PSNR of 27.93 dB and an LPIPS of 0.083, against 26.43 dB and 0.094 for SVG-EAR, which runs at 1.027. On Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps and Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps SVG-EAR stays closer: a PSNR of 26.63 and 24.00 dB and an LPIPS of 0.065 and 0.111, against our 26.31 and 23.88 dB and 0.092 and 0.119, but at a speed-up of 1.057 and 0.793, the latter slower than dense attention. No published baseline is both as fast and as close as NEXA-S on any setting.

The video-quality score of our videos is 83.08, 81.73 and 83.37, a little below the dense videos' 83.34, 81.94 and 83.68, and below several baselines on every setting, for example Sol-Attn on Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps and Wan2.1-T2V-14B, 1280×720 · 81 frames, 25 steps. Since the method aims at closeness to the dense videos, not at a quality score, we read this as the small cost of the approximation rather than a separate effect.

How we got here

  • Step sensitivity came first. The same approximation, injected into different ranges of the trajectory, left a PSNR of about 15 dB when applied at the highest noise, about 20 dB a little lower and about 30 dB late in the trajectory: the earlier the error, the further the videos drift. The docstring summarises the sensitivity per unit of as roughly . This is why the first steps are exact and the schedule is written over rather than over the step index.
  • The last steps matter for LPIPS. A U-shaped schedule, denser below , lowered our development LPIPS from 0.175 to 0.156 for 0.3% more time in one small configuration. For the semantic regimes the cheaper rule, raising only the steps after a large jump in , was recorded as worth 0.5 to 0.9 dB of PSNR and 0.008 to 0.02 of LPIPS for about 1% of time.
  • The first block is special. Half of its heads attend almost uniformly and half to about twenty tokens; approximating it alone cost about 6 dB, so it stays exact.
  • Tile shape. Compact spatial tiles were preferred over row segments and over a Morton order, and 64-query blocks over 128-query blocks.
  • Approximate instead of drop. Adding the zeroth-order terms of the unselected groups gave about 2.5 times lower attention error than keep-or-drop selection.
  • Semantic groups instead of tiles. Clustering the keys over the whole video, with the coverage correction, halved the far-field error, for example from 0.19 to 0.11 relative error at 15% density. Being more accurate, it let the densities in the largest regime drop to 20% and 8%, which the docstring credits with 1.4 to 3.3% more speed.
  • Short videos stay exact. With fewer than 10240 tokens, sparsity saved only about 3% of the time in development while the videos drifted far (19 dB, LPIPS 0.33), whereas 8-bit SageAttention2 [10] reached 26.5 dB and 0.08 there. The method therefore falls back to exact attention below that size rather than pay that price.

The ingredients each have precedents: training-free sparse attention [4], k-means grouping of tokens by semantics [5], and compensation of the dropped part of the attention [11]. What is ours is putting the far field into the same online softmax as centroid terms weighted only by their uncovered tokens, and scheduling the exact share over the noise level with a raise at the end of the trajectory.

Limitations

  • Not the closest on every setting. On Wan2.1-T2V-14B, 1280×720 · 81 frames, 50 steps and Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps SVG-EAR produces videos closer to the dense ones than ours, at a much lower speed-up. Our gain there is in speed at nearly equal PSNR, not in closeness.
  • The speed-up is modest in absolute terms. On Wan2.1-T2V-1.3B, 832×480 · 81 frames, 50 steps it is 1.219, and Sol-Attn is marginally faster there. The exact dense steps at high noise, the exact first block and the per-call clustering, selection and coverage kernels are all fixed costs that a sparser method would not pay.
  • The schedule is tuned, not derived. The breakpoints , and , the densities, the jump threshold and the size thresholds were set from development measurements on a few configurations. They are written over the noise level and the problem size, not over settings, but a sampler with a very different noise schedule would need them re-measured.
  • The far field is zeroth order. A cluster contributes its mean key and mean value only; it is exact only when its keys coincide, and the error grows with the spread of the keys inside it. A first-order correction is not attempted.
  • No lower precision. The sparse path uses no quantisation; its attention operands are bf16. Combining the sparse path with a quantised kernel is left unexplored, although the docstring's own comparison on short videos shows that quantised dense attention was competitive there.
  • Fragile fallbacks. Any kernel failure silently switches the whole run to exact attention; this keeps a run valid but would hide a speed regression rather than report it.

References

  1. Jay Shah, Ganesh Bikshandi, Ying Zhang et al. (2024). FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision. NeurIPS.
  2. Haocheng Xi, Shuo Yang, Yilong Zhao et al. (2025). Sparse VideoGen: Accelerating Video Diffusion Transformers with Spatial-Temporal Sparsity.
  3. Xingyang Li, Muyang Li, Tianle Cai et al. (2025). Radial Attention: $O(n\log n)$ Sparse Attention with Energy Decay for Long Video Generation. NeurIPS.
  4. Jintao Zhang, Chendong Xiang, Haofeng Huang et al. (2025). SpargeAttention: Accurate and Training-free Sparse Attention Accelerating Any Model Inference. ICML.
  5. Shuo Yang, Haocheng Xi, Yilong Zhao et al. (2025). Sparse VideoGen2: Accelerate Video Generation with Sparse Attention via Semantic-Aware Permutation. NeurIPS.
  6. Shanghao Liu, Renze Chen, Size Zheng et al. (2026). SPADE: An Input-Adaptive Sparse Attention Engine for Fast Video Diffusion Models Inference. DAC.
  7. Haopeng Li, Yitong Li, Junsong Chen et al. (2026). Sol-Attn: Accelerating Video Generation Inference via On-the-Fly Attention Sparsification.
  8. Jie Hu, Zixiang Gao, Yutong He et al. (2026). DFSAttn: Dynamic Fine-grained Sparse Attention for Efficient Video Generation. ICML.
  9. Jiayi Luo, Jiayu Chen, Jiankun Wang et al. (2026). Attention Sparsity is Input-Stable: Training-Free Sparse Attention for Video Generation via Offline Sparsity Profiling and Online QK Co-Clustering. ICML.
  10. Jintao Zhang, Haofeng Huang, Pengle Zhang et al. (2025). SageAttention2: Efficient Attention with Thorough Outlier Smoothing and Per-thread INT4 Quantization. ICML.
  11. Xuanyi Zhou, Qiuyang Mang, Shuo Yang et al. (2026). SVG-EAR: Parameter-Free Linear Compensation for Sparse Video Generation via Error-aware Routing. ECCV.
  12. Haopeng Li, Shitong Shao, Wenliang Zhong et al. (2026). PISA: Piecewise Sparse Attention Is Wiser for Efficient Diffusion Transformers. NeurIPS.

The session

The run from the model's first output, drawn as Claude Code shows a conversation: 633 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

wan-sparse/custom_attention.pythe changes against the starter, inside the editable region