say hi
A build log · correctness before speed

Write the kernel
that no library
ships for you.

A step-by-step path to a fused selective scan — the recurrence at the heart of Mamba — written in Triton, from a five-line hello-world kernel through a hand-derived backward pass, benchmarked on an RTX 5090. Matmul goes to cuBLAS and attention goes to FlashAttention; this is the kernel you actually have to write yourself.

Triton · Python DSL RTX 5090 · sm_120 fused O(BLD) recurrence tl.associative_scan hand-derived backward

00 · Orientation

Why this kernel, and not a matmul

Nearly every Triton tutorial teaches you to write a matmul, then benchmarks it against cuBLAS and loses. That is not a lesson about Triton — it is a lesson about how many engineer-years NVIDIA has spent on GEMM. The honest case for Triton is the opposite one: kernels that no library ships, because they are too specific to your model to be worth a vendor's time.

The selective scan is exactly that kernel. It is the linear recurrence at the core of Mamba and every S6-style state-space model:

◈The recurrence

hℓ  =  Āℓ ⊙ hℓ−1  +  B̄ℓ · uℓ
yℓ  =  ⟨ Cℓ , hℓ ⟩  +  D ⊙ uℓ

with Āℓ = exp(Δℓ A) and B̄ℓ = Δℓ Bℓ. The whole trick of S6 is that Δ, B and C are functions of the input — which is what makes the model expressive, and simultaneously what makes it impossible to fold into a convolution or a matmul the way S4 could.

Āk = exp(kΔA) — what Δ actually controls
—

The state's memory of a token decays geometrically. Δ is the only thing the network gets to choose per token, and it sets the horizon: small Δ means ignore this token, keep what you have; large Δ means reset and absorb. Selectivity is this slider, predicted from the input.

That input-dependence is the source of the engineering problem. Because Δ varies per timestep and per channel, the discretised Ā has shape (B, L, D, N) — a four-dimensional tensor with one entry per batch, timestep, channel and state dimension. Write it out naively and you move gigabytes through VRAM that you never needed. Keep the state in registers instead, and the same computation touches O(B·L·D) memory.

This is the same argument FlashAttention makes about the attention matrix, and it is the argument that justifies writing a kernel at all. Speed is a side effect; the primary result is that the model fits.

PartWhat we buildWhy it exists
01Triton's execution modelPrograms, not threads. What the compiler takes away from you, and what it hands back.
02Hello kernel — a fused softplus for ΔProve the toolchain works; learn the debug loop before the kernel gets hard.
03Reference scan in PyTorchCorrect, slow, and out of memory. The baseline every later version is checked against.
04Fused forward kernelState in registers, sequential over L. The memory win, measured.
05tl.associative_scanParallelise across time. Sometimes a win — and we work out exactly when.
06Backward passDerived by hand, with recomputation. The part every Triton tutorial skips.
07AutotuningBLOCK_D, num_warps, num_stages — and which of them actually move the needle here.
08Where Triton endsAn honest list of what you cannot express, and the signals that mean "drop to CUDA".
09Benchmarks & gatesAgainst the reference and against the official CUDA kernel, with a roofline to judge them by.
⌥Prerequisites

You need to know what a state-space model is — the discretisation, the HiPPO initialisation of A, why selectivity was introduced. This page does not re-derive any of that; it treats the recurrence as given and spends its whole budget on making it run. If the equations above are unfamiliar, read the model first and come back.

You do not need CUDA experience. Triton is Python, and the parts of the GPU it exposes are introduced as we hit them.

!One machine, deliberately

Everything here targets a single RTX 5090 (Blackwell, sm_120). No second backend, no Apple comparison — Triton has no Metal backend. It targets NVIDIA and AMD; Apple silicon is not on the list, and the CPU backend is experimental. If you want the same recurrence on an M-series Mac, that is a different toolchain and a different page.

01 · The programming model

Programs, not threads

CUDA hands you a thread and makes you responsible for everything: which element it touches, whether the warp's loads coalesce, when to stage through shared memory, where to put __syncthreads(). Triton raises the unit of programming by one level. You write code for one program — roughly a thread block — and inside that program you manipulate whole tensors whose shapes are known at compile time.

CUDA conceptIn Triton
thread, threadIdxDoes not exist. You never index a thread.
block, blockIdxtl.program_id(axis) — the one index you do control.
gridA tuple you pass at launch: kernel[grid](...).
shared memoryAllocated and staged by the compiler. No __shared__.
__syncthreads()Inserted by the compiler. You cannot call it.
coalescingThe compiler's job, given a contiguous tl.arange.
registers per threadImplied by your block shapes and num_warps.
warp shufflesNot exposed. tl.sum, tl.max, tl.reduce instead.

The trade is explicit: you give up the ability to hand-place data, and in return the compiler handles vectorisation, coalescing, shared-memory staging and software pipelining. For kernels whose access pattern is dense and regular — which the selective scan is — that trade is very good. For kernels that need irregular gathers, sorting or cross-block communication, it is bad, and part 08 is about recognising that boundary early.

Three rules that govern everything

◈Shapes are compile-time constants

Every tensor inside a kernel has a shape fixed at compile time, and every dimension must be a power of two. Anything variable — the sequence length, the channel count — enters as a runtime scalar and is handled with mask= on loads and stores. A parameter annotated tl.constexpr becomes part of the compilation key: change it and Triton compiles a new kernel, transparently and at some cost.

◈Pointers are tensors too

There is no array indexing. You build a tensor of addresses by arithmetic — ptr + offs_row[:, None] * stride_row + offs_col[None, :] * stride_col — and hand it to tl.load. Strides come in as runtime arguments, which is why every kernel signature below is longer than you expect. Getting a stride wrong is the single most common way to produce a kernel that runs, returns numbers, and is silently incorrect.

◈The launch grid is a Python lambda

grid = lambda meta: (triton.cdiv(n, meta['BLOCK']),). The lambda receives the autotuner's chosen config, so the grid can depend on a block size the autotuner is still deciding. This is why grids are callables rather than plain tuples.

One consequence worth internalising now: because state lives in registers and registers are per-program, a Triton program cannot talk to another program. No grid-wide sync, no cooperative groups, no cluster-level distributed shared memory. Any algorithm you write must be decomposable into programs that never need to look at each other's intermediate results. The selective scan decomposes that way along batch and channels; it does not along time, which is what makes part 05 interesting.

02 · Hello, Triton

A kernel small enough to debug

Before writing anything hard, write something trivial and learn how it fails. Our hello-world is not a vector add — it is a real piece of the model: the softplus that turns the raw Δ projection into a positive step size.

bash environment
# Blackwell needs a recent CUDA toolkit and a torch built against it.
# Triton ships inside the PyTorch wheel; you do not install it separately.
python -c "import torch, triton; print(torch.__version__, triton.__version__)"
python -c "import torch; print(torch.cuda.get_device_capability())"   # -> (12, 0) on a 5090

# Sanity: the GPU arch Triton will compile for
python -c "import triton; print(triton.runtime.driver.active.get_current_target())"
!Version pinning is not optional

Triton's Python API has broken across minor versions more than once — tl.associative_scan, tensor descriptors and the autotuner's pruning hooks have all moved. Pin torch exactly, record the triton.__version__ your numbers came from, and re-read the signatures against the version you actually have rather than against any tutorial, this one included.

python ssm/hello.py
import torch
import triton
import triton.language as tl


@triton.jit
def softplus_kernel(x_ptr, y_ptr, n_elements, BLOCK: tl.constexpr):
    pid = tl.program_id(axis=0)
    offs = pid * BLOCK + tl.arange(0, BLOCK)     # a *tensor* of indices
    mask = offs < n_elements                      # tail guard, always

    x = tl.load(x_ptr + offs, mask=mask, other=0.0).to(tl.float32)
    # softplus, with the standard large-x branch to avoid exp overflow
    y = tl.where(x > 20.0, x, tl.log(1.0 + tl.exp(x)))
    tl.store(y_ptr + offs, y, mask=mask)


def softplus(x: torch.Tensor) -> torch.Tensor:
    y = torch.empty_like(x, dtype=torch.float32)
    n = x.numel()
    grid = lambda meta: (triton.cdiv(n, meta["BLOCK"]),)
    softplus_kernel[grid](x, y, n, BLOCK=1024)
    return y


if __name__ == "__main__":
    x = torch.randn(1_000_003, device="cuda", dtype=torch.float32) * 8
    torch.testing.assert_close(softplus(x), torch.nn.functional.softplus(x),
                               rtol=1e-5, atol=1e-5)
    print("ok")

Three things in that kernel matter more than the arithmetic. offs is a tensor, not a scalar — the entire block is expressed at once. mask exists because n_elements is almost never a multiple of BLOCK, and an unmasked load past the end of a tensor reads whatever memory follows it. And .to(tl.float32) is there because the moment you feed this bfloat16 activations, you want the exponential evaluated in fp32 regardless of what the tensor is stored as.

The debug loop

A Triton kernel is compiled machine code, which means it fails the way machine code fails: no stack trace, no print, just wrong numbers or an illegal memory access. Two escape hatches make this bearable.

bash debugging
# 1. Run the kernel in a Python interpreter instead of on the GPU.
#    Slow, but `print()` works inside @triton.jit and shapes are checked.
TRITON_INTERPRET=1 python ssm/hello.py

# 2. Make illegal accesses fail at the point of the access, not later.
CUDA_LAUNCH_BLOCKING=1 compute-sanitizer python ssm/hello.py

# Inspect what the compiler actually produced
TRITON_PRINT_AUTOTUNING=1 python ssm/bench.py        # chosen configs
TRITON_CACHE_DIR=./ttcache python ssm/bench.py       # .ptx / .ttgir land here
✓Gate

assert_close against the PyTorch op passes, and TRITON_INTERPRET=1 runs the same file to the same result. If the interpreted and compiled results differ, the bug is in your masking or your strides — that divergence is the most useful signal you will get all page.

03 · The reference

Correct, slow, and out of memory

Write the recurrence in plain PyTorch first. It will be the thing every kernel is checked against, and — more usefully — it will fail in exactly the way that motivates the kernel.

python ssm/reference.py
import torch


def selective_scan_ref(u, delta, A, B, C, D):
    """
    u     : (b, d, l)   input, already gated and conv'd
    delta : (b, d, l)   positive step size, per channel per timestep
    A     : (d, n)      negative real, A = -exp(A_log)
    B, C  : (b, n, l)   input-dependent, shared across channels
    D     : (d,)        skip connection
    returns y : (b, d, l)
    """
    b, d, l = u.shape

    #  ---- the two tensors that end the experiment ----
    dA = torch.exp(delta.unsqueeze(-1) * A)                       # (b, d, l, n)
    dB = delta.unsqueeze(-1) * B.permute(0, 2, 1).unsqueeze(1)    # (b, d, l, n)

    x = torch.zeros(b, d, A.shape[1], device=u.device, dtype=torch.float32)
    ys = []
    for i in range(l):                       # a Python loop over 4096 timesteps
        x = dA[:, :, i] * x + dB[:, :, i] * u[:, :, i, None]
        ys.append((x * C[:, None, :, i]).sum(-1))

    return torch.stack(ys, dim=-1) + u * D[None, :, None]

This is correct and it is the only version on this page you can read and immediately believe. It is also unusable, for two independent reasons.

Reason one — the launch overhead

The Python loop issues on the order of five CUDA kernels per timestep. At L = 4096 that is twenty thousand launches per forward pass, each with its own overhead, none of which can overlap because each depends on the previous. The GPU spends most of its time idle waiting for the CPU.

Reason two — the tensors

dA and dB each hold B·L·D·N elements. Autograd then keeps both alive for the backward pass. Drag the sliders:

materialised Ā and B̄ — VRAM cost
—

Naive = one (B,L,D,N) fp32 tensor for Ā plus one for B̄, both kept for backward. Fused = the tensors that actually cross VRAM: u, Δ, y at (B,D,L) and B, C at (B,N,L), in bf16. Both curves are dominated by their leading term, so the gap scales with N.

At the default configuration — batch 8, L = 4096, D = 4096, N = 16 — a single one of those tensors is 8.6 GB in fp32. Two of them plus the saved states do not fit in the 5090's 32 GB, and that is before the rest of the model exists. The recurrence is not compute-bound, not bandwidth-bound in any interesting sense; it is bound by a tensor nobody wanted.

◈The whole thesis of the page

The state h has shape (B, D, N) — no L. If the loop over time lives inside the kernel, h stays in registers, Ā and B̄ are computed and consumed within one iteration, and nothing of size (B, L, D, N) ever exists. Memory drops by more than an order of magnitude — the gap grows linearly in N — and the twenty thousand launches collapse into one.

✓Gate

Keep selective_scan_ref forever. Run it in float64 on small shapes (b=2, d=8, l=64, n=16) and treat that as ground truth for every kernel below. A kernel that matches fp64 reference to rtol=1e-4 in bf16 is fine; one that matches only its own fp32 sibling is not tested.

04 · v1 — fused forward

Put the state in registers

One program per (batch, block of channels). Each program holds a (BLOCK_D, N) tile of state in registers and walks the sequence itself. Nothing about the time axis is parallel yet — that is deliberate, and part 05 asks whether it needs to be.

python ssm/fwd.py
import torch
import triton
import triton.language as tl


@triton.jit
def _scan_fwd(
    U, DELTA, A, Bm, Cm, Dv, Y, HOUT,
    stride_ub, stride_ud, stride_ul,          # u, delta, y : (b, d, l)
    stride_bb, stride_bn, stride_bl,          # B, C        : (b, n, l)
    stride_hb, stride_hd,                     # h_out       : (b, d, n)
    DIM, L,
    BLOCK_D: tl.constexpr, N: tl.constexpr,
):
    pid_b = tl.program_id(0)
    pid_d = tl.program_id(1)

    offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)
    offs_n = tl.arange(0, N)
    mask_d = offs_d < DIM

    # A is (d, n) and time-invariant: load it once, outside the loop.
    a = tl.load(A + offs_d[:, None] * N + offs_n[None, :],
                mask=mask_d[:, None], other=0.0).to(tl.float32)
    dskip = tl.load(Dv + offs_d, mask=mask_d, other=0.0).to(tl.float32)

    # base pointers for timestep 0
    u_ptr = U     + pid_b * stride_ub + offs_d * stride_ud
    t_ptr = DELTA + pid_b * stride_ub + offs_d * stride_ud
    y_ptr = Y     + pid_b * stride_ub + offs_d * stride_ud
    b_ptr = Bm    + pid_b * stride_bb + offs_n * stride_bn
    c_ptr = Cm    + pid_b * stride_bb + offs_n * stride_bn

    h = tl.zeros((BLOCK_D, N), dtype=tl.float32)      # <- lives in registers

    for i in range(L):
        u  = tl.load(u_ptr + i * stride_ul, mask=mask_d, other=0.0).to(tl.float32)
        dt = tl.load(t_ptr + i * stride_ul, mask=mask_d, other=0.0).to(tl.float32)
        bv = tl.load(b_ptr + i * stride_bl).to(tl.float32)     # (N,)
        cv = tl.load(c_ptr + i * stride_bl).to(tl.float32)     # (N,)

        dA  = tl.exp(dt[:, None] * a)                          # (BLOCK_D, N)
        dBu = (dt * u)[:, None] * bv[None, :]                  # (BLOCK_D, N)

        h = dA * h + dBu
        y = tl.sum(h * cv[None, :], axis=1) + dskip * u        # (BLOCK_D,)

        tl.store(y_ptr + i * stride_ul, y, mask=mask_d)

    tl.store(HOUT + pid_b * stride_hb + offs_d[:, None] * stride_hd + offs_n[None, :],
             h, mask=mask_d[:, None])


def selective_scan_fwd(u, delta, A, B, C, D, BLOCK_D=64):
    b, d, l = u.shape
    n = A.shape[1]
    y = torch.empty_like(u)
    h_out = torch.empty(b, d, n, device=u.device, dtype=torch.float32)
    grid = (b, triton.cdiv(d, BLOCK_D))
    _scan_fwd[grid](
        u, delta, A, B, C, D, y, h_out,
        *u.stride(), *B.stride(), *h_out.stride()[:2],
        d, l, BLOCK_D=BLOCK_D, N=n, num_warps=4,
    )
    return y, h_out

What the compiler is doing for you here

h is a (BLOCK_D, N) fp32 tile — with BLOCK_D=64, N=16 that is 1024 floats, 4 KB, comfortably in registers. Because it is never stored, the loop body reads 2·BLOCK_D + 2N values and writes BLOCK_D. The tl.sum over axis=1 becomes a warp-level reduction the compiler picks the shape of. You wrote none of that.

!The exponential is not free

tl.exp lowers to the SFU, which on every recent NVIDIA architecture runs at a small fraction of FMA throughput. This kernel evaluates BLOCK_D × N exponentials per timestep — for a state size of 16, the exponentials can cost more than every multiply-add in the loop combined.

The fix is one line: fold log₂e into A once, at load time, and use tl.exp2, which maps to a single hardware instruction with no pre-multiply. a = a * 1.4426950408889634 immediately after the tl.load, then tl.exp2(dt[:, None] * a). Measure it before and after — on a memory-bound shape it will do nothing, and on a compute-bound one it is worth double digits.

!N must be a power of two

tl.arange(0, N) rejects anything else. Mamba's default d_state=16 is fine; a model with d_state=24 needs padding to 32 and a mask on the state axis, which costs you a third of the register file for nothing. This is a real constraint on model configuration that comes purely from the kernel language.

◈Where the parallelism comes from

The grid is (B, ⌈D/BLOCK_D⌉). With B=8, D=4096, BLOCK_D=64 that is 512 programs against the 5090's ~170 SMs — three waves, enough to hide latency. The time axis being serial costs nothing here, because there is already more parallel work than the GPU has places to put it.

Change to B=1, as in autoregressive decoding, and the grid collapses to 64 programs on 170 SMs. Now most of the machine is idle and the serial time loop is the entire problem. Hold that thought.

✓Gate

Against the fp64 reference at (b=2, d=8, l=64, n=16): max absolute error below 1e-5 in fp32. Then run b=8, d=4096, l=4096 and watch torch.cuda.max_memory_allocated() — it should be tens of megabytes where the reference asked for tens of gigabytes.

05 · Parallelising time

tl.associative_scan, and when it loses

The recurrence looks inherently serial. It is not. A first-order linear recurrence is a composition of affine maps, and affine maps compose associatively — which means the whole sequence can be resolved in log₂L parallel rounds instead of L serial ones.

◈The combine operator

Write each timestep as the map fℓ(h) = aℓh + bℓ. Composing the earlier map f₁ with the later f₂:

f₂(f₁(h)) = a₂(a₁h + b₁) + b₂ = (a₁a₂)·h + (a₂b₁ + b₂)

So the pair (a, b) composes as (a₁a₂, a₂b₁ + b₂) — associative, but not commutative. Getting the argument order wrong produces a kernel that is subtly, plausibly wrong: correct at L=1, correct on constant inputs, wrong everywhere interesting.

python ssm/scan.py — chunked, per channel
@triton.jit
def _combine(a_l, b_l, a_r, b_r):
    """left = earlier in time, right = later. Order matters."""
    return a_l * a_r, a_r * b_l + b_r


@triton.jit
def _scan_chunk(..., CHUNK: tl.constexpr, N: tl.constexpr):
    offs_l = tl.arange(0, CHUNK)
    offs_n = tl.arange(0, N)

    # (CHUNK, N) tiles for one channel
    dt = tl.load(t_ptr + offs_l * stride_ul)                    # (CHUNK,)
    bv = tl.load(b_ptr + offs_l[:, None] * stride_bl
                       + offs_n[None, :] * stride_bn)           # (CHUNK, N)
    uu = tl.load(u_ptr + offs_l * stride_ul)                    # (CHUNK,)

    log_dA = dt[:, None] * a[None, :]                           # <= 0 elementwise
    dA     = tl.exp(log_dA)
    dBu    = (dt * uu)[:, None] * bv

    # log2(CHUNK) rounds instead of CHUNK serial steps
    cum_a, h = tl.associative_scan((dA, dBu), axis=0, combine_fn=_combine)

    # fold in the state carried from the previous chunk
    h = h + cum_a * h_prev[None, :]
!Cumulative products underflow, and that is fine — until you divide

Because A < 0 and Δ > 0, every Ā is in (0, 1), so cum_a is a product of hundreds of sub-unit numbers. At CHUNK=256 it will flush to zero. That is numerically correct — the true influence of the chunk's first token on its last really is nil.

It becomes a bug the moment you try to recover an intermediate prefix by dividing: cum_a[j] / cum_a[i] is 0/0. Never do that. Work with the cumulative sum of log_dA and take differences — exp(cs[j] − cs[i]) for j ≥ i has a non-positive exponent by construction and is always in (0, 1]. This shows up again in the backward pass, where the temptation to divide is much stronger.

The honest part: it is often slower

The scan replaces L serial steps with log₂L rounds, but it pays for that by materialising a (CHUNK, N) tile in registers where the serial version held (BLOCK_D, N). Register pressure forces BLOCK_D down, often to 1, which cuts the number of resident programs — the exact resource the serial kernel had in surplus.

RegimePrograms availableWhich form wins
Training, B=8, D=4096512, on ~170 SMsSerial. The machine is already full; parallelising time buys nothing and costs registers.
Small batch, B=1, D=409664, on ~170 SMsScan. Two thirds of the GPU is otherwise idle.
Decoding, L=1—Neither. There is no scan to do; write a separate one-step update kernel.
⌥Why the official kernel still chunks

Mamba's CUDA implementation uses a chunked scan even for large batches. It is not contradicting the table above: it chunks to bound register usage and to create clean recomputation boundaries for the backward pass, not primarily to expose parallelism. The chunk structure earns its keep in part 06 whether or not you use associative_scan inside it.

✓Gate

Same fp64 reference, plus one specific test: a sequence long enough that cum_a underflows (L ≥ 512 with typical Δ) must still match. If your scan is correct at L=64 and wrong at L=1024, you are dividing by a cumulative product somewhere.

06 · The part everyone skips

Backward, by hand

A forward kernel is a demo. A kernel you can train with needs a backward pass, and the backward pass of a fused recurrence is where the interesting problems live: it needs the forward states you deliberately threw away.

The equations

Differentiating hℓ = Āℓhℓ−1 + B̄ℓuℓ and yℓ = ⟨Cℓ, hℓ⟩ + Duℓ gives a second recurrence, running backwards in time:

◈The adjoint recurrence

dhℓ  =  Cℓ·dyℓ  +  Āℓ+1 ⊙ dhℓ+1

Note which Ā appears: the one from timestep ℓ+1. Off-by-one here is the classic bug, and it produces gradients that are wrong by a factor that looks like a learning-rate problem.

GradientExpressionReduced over
dCℓ,nΣd hℓ,d,n · dyℓ,dchannels — needs a cross-program reduction
dBℓ,nΣd Δℓ,d uℓ,d · dhℓ,d,nchannels — same problem
duℓ,dΣn Δℓ,d Bℓ,n dhℓ,d,n + Dd dyℓ,dstate — local, free
dΔℓ,dΣn dhℓ,d,n(Ad,n Āℓ,d,n hℓ−1,d,n + Bℓ,n uℓ,d)state — local
dAd,nΣb,ℓ Δℓ,d Āℓ,d,n hℓ−1,d,n dhℓ,d,nbatch and time — accumulate then atomic

Every row in that table contains hℓ or hℓ−1. The forward pass stored exactly one state — the final one. This is the central tension of the whole design, and it has a standard resolution.

Recomputation

◈Store boundaries, recompute interiors

Split the sequence into chunks of CHUNK timesteps. The forward pass saves only the state at each chunk boundary: (B, L/CHUNK, D, N). With CHUNK=256 that is 256× less than saving every state — back to about 34 MB on our reference shape, not the 8.6 GB from part 03.

The backward pass then handles one chunk at a time: replay the forward recurrence from the stored boundary state to rebuild the interior states in registers, then run the adjoint recurrence backwards through the same chunk. You pay one extra forward pass of arithmetic and save a factor of CHUNK in memory. On a kernel this memory-bound, the arithmetic is close to free.

python ssm/bwd.py — structure
@triton.jit
def _scan_bwd(..., CHUNK: tl.constexpr, BLOCK_D: tl.constexpr, N: tl.constexpr):
    pid_b, pid_d, pid_c = tl.program_id(0), tl.program_id(1), tl.program_id(2)

    # --- pass 1: replay forward inside this chunk, keep states in registers ---
    h = tl.load(HBOUND + boundary_offset(pid_b, pid_d, pid_c))   # (BLOCK_D, N)
    h_hist = tl.zeros((CHUNK, BLOCK_D, N), dtype=tl.float32)     # register budget!
    for i in range(CHUNK):
        ...
        h = dA * h + dBu

    # --- pass 2: adjoint recurrence, backwards through the same chunk ---
    dh = tl.load(DHBOUND + ...)                # carried in from the *later* chunk
    for i in range(CHUNK - 1, -1, -1):
        dy = tl.load(DY + ...)
        dh = dh + cv[None, :] * dy[:, None]

        # local gradients: free, reduced over the state axis
        du = tl.sum(dh * (dt[:, None] * bv[None, :]), axis=1) + dskip * dy

        # cross-channel gradients: not free
        tl.atomic_add(DC + ..., tl.sum(h_prev * dy[:, None], axis=0))
        tl.atomic_add(DB + ..., tl.sum(dh * (dt * uu)[:, None], axis=0))

        dh = dA * dh                            # step the adjoint state back
    tl.store(DHBOUND + ..., dh)                 # hand off to the earlier chunk
!The register budget is the real constraint

h_hist as written above is CHUNK × BLOCK_D × N floats. At CHUNK=64, BLOCK_D=32, N=16 that is 32768 floats — 128 KB, out of a 256 KB register file per SM (65536 32-bit registers, shared across every warp resident there). Half the SM's entire register budget, spent on one tensor, before a, dskip and the rest of the loop's live values are even counted. The compiler will spill to local memory and your kernel will be slower than the reference.

The practical answer is to not keep the history at all: interleave the two passes by recomputing forward from the boundary inside the backward loop, or shrink BLOCK_D until the tile fits. Check with kernel.n_regs and kernel.n_spills on the compiled handle — a non-zero spill count is the number you are optimising against.

!Atomics make your gradients non-deterministic

B and C are shared across all D channels, so their gradients are sums over channel-blocks that live in different programs. tl.atomic_add is the easy answer, and it makes bitwise reproducibility impossible: floating-point addition is not associative and the order is a race.

The alternative is to write per-program partials to a (num_blocks_d, ...) buffer and reduce with .sum(0) in PyTorch. It costs one extra pass over a small tensor and gives you a run-to-run identical gradient. Take the deterministic version while you are still debugging convergence; you cannot tell a kernel bug from a seed difference otherwise.

python ssm/op.py — wiring it into autograd
class SelectiveScan(torch.autograd.Function):
    @staticmethod
    def forward(ctx, u, delta, A, B, C, D, chunk=256):
        y, h_bounds = selective_scan_fwd(u, delta, A, B, C, D, chunk=chunk)
        ctx.save_for_backward(u, delta, A, B, C, D, h_bounds)
        ctx.chunk = chunk
        return y

    @staticmethod
    def backward(ctx, dy):
        return (*selective_scan_bwd(dy, *ctx.saved_tensors, chunk=ctx.chunk), None)


selective_scan = SelectiveScan.apply
✓Gate

torch.autograd.gradcheck in float64 on a deliberately tiny shape (b=2, d=4, l=16, n=4) — it is slow and it will find the off-by-one in the adjoint that no allclose test catches. Then a convergence smoke test: overfit fifty steps on a hundred-token sequence and confirm the loss goes to zero. A backward that is wrong by a constant factor still trains, just badly, and only the gradcheck will tell you.

07 · Tuning

Which knobs actually move

Triton's autotuner will happily search a hundred configurations and cost you ten minutes per shape. Most of them do nothing for this kernel. It is worth knowing which ones matter before handing the machine a search space.

python ssm/fwd.py — autotuned
@triton.autotune(
    configs=[
        triton.Config({"BLOCK_D": bd}, num_warps=w, num_stages=s)
        for bd in (16, 32, 64, 128)
        for w  in (2, 4, 8)
        for s  in (1, 2)
    ],
    key=["DIM", "L", "N"],          # recompile+research when these change
)
@triton.jit
def _scan_fwd(...):
    ...
KnobWhat it controlsEffect here
BLOCK_Dchannels per programLarge. Sets both register pressure and grid size — the two things this kernel is actually limited by.
num_warpsthreads per programLarge. Fewer warps means more registers each, which is what the state tile wants; too few and the tl.sum reduction narrows.
num_stagessoftware pipelining depthNear zero. Pipelining hides load latency behind independent work — and iteration i+1 depends on i. There is nothing to overlap.
CHUNKrecomputation granularityBackward only. Trades saved-state memory against recompute arithmetic.

num_stages is the instructive one. It is the first knob most people reach for because it dominates matmul tuning, and it is useless here for a structural reason: a serial recurrence has no independent loads to prefetch. Drop it from the search space and your autotuning time halves for free. Tuning is not a generic procedure — it follows from the dependency structure of the loop you wrote.

!The autotune key is a footgun

key=["DIM", "L", "N"] means a new search on every new sequence length. Feed that kernel variable-length batches and you will re-tune constantly, on the critical path, in the middle of training. Either bucket your lengths, or drop L from the key and accept a config tuned for one length — usually the right call, since L barely affects the optimum for this kernel.

python reading the compiled artefact
k = _scan_fwd.warmup(..., grid=(1,))     # compile without launching
print(k.n_regs, k.n_spills)              # spills > 0 => shrink BLOCK_D
print(k.asm["ttgir"][:2000])             # Triton GPU IR: layouts, pipelining
print(k.asm["ptx"][:2000])               # what the SM will actually run
✓Gate

n_spills == 0 for the chosen config, and TRITON_PRINT_AUTOTUNING=1 shows the winner is not at the edge of your search space. If the best BLOCK_D is the largest one you offered, you did not offer enough.

08 · Boundaries

Where Triton stops, and what that costs

Triton buys productivity by removing control. For this kernel the trade is overwhelmingly favourable. It is worth being precise about what was removed, because the same list tells you when a different kernel will not work out.

Not expressible in TritonConsequence
Cross-program communication — no grid sync, no cooperative groups, no thread-block clusters or distributed shared memoryAny reduction across programs goes through global memory: atomics or a second kernel. On Blackwell, cluster-level DSM is simply unavailable to you.
Sorting and irregular gathersNo CUB equivalent. Do the sort in PyTorch and give Triton only the dense inner loop. Spatial data structures, sparse formats and top-k routing all belong on the PyTorch side of the boundary.
Explicit shared-memory placementYou cannot choose a swizzle to dodge a bank conflict. Usually the compiler's choice is fine; when it is not, there is no lever.
Warp-level primitives — shuffles, votes, ballotsOnly the reductions Triton exposes. There is an inline-asm escape hatch, which is a signal you have outgrown the language.
Non-power-of-two tile dimensionsPad and mask, and pay for the padding in registers.
Apple GPUsNo Metal backend. NVIDIA and AMD only.
⌥Moving targets

Some of the above is being actively eroded: tensor-descriptor / TMA support and limited warp specialisation have landed for recent architectures in successive Triton releases, in forms that have changed more than once. Treat this table as accurate for the version you pinned in part 02 and check the release notes before assuming a limitation still holds.

The signals that mean "write CUDA"

  • You need programs to see each other's partial results during the kernel — a persistent kernel with grid-wide synchronisation, or a cluster sharing DSM.
  • Your access pattern is data-dependent and irregular, and the PyTorch-side preprocessing that would make it dense costs more than the kernel saves.
  • You are reading PTX to work out what the compiler did, and then changing Triton code to coax it somewhere. At that point you are writing CUDA through a translator.
  • You need a specific instruction — a particular MMA shape, an async-copy variant — rather than a particular result.

None of these apply to the selective scan, which is precisely why it is a good Triton kernel. It decomposes cleanly across batch and channels, its inner loop is dense and regular, and its only cross-program reduction (dB, dC) is small enough to hand to atomics or a cheap second pass. When you are choosing what to write in Triton, look for that shape.

09 · Measurement

Benchmarks, gates, and a roofline to judge them by

A number without a bound is not a measurement. Before benchmarking, work out what "good" would be — otherwise you have no way to know whether a 2× speedup means you succeeded or means you left 5× on the table.

The bound

Per element of u, the fused kernel moves u, Δ and y — six bytes in bf16, ignoring B and C, which are amortised across all D channels. It performs roughly 6N flops: one exponential, one FMA and one dot-product contribution per state dimension. At N=16 that is about 16 flops per byte.

The 5090's ridge point — peak fp32 throughput over peak GDDR7 bandwidth — is several times that. The kernel is therefore memory-bound, and the only meaningful score is achieved bandwidth as a fraction of peak. A kernel at 80% of peak bandwidth is finished; no amount of arithmetic tuning will help it. Compute the ridge point for your own card and put it at the top of the benchmark output, so every later number is read against it.

python ssm/bench.py
import torch, triton

CONFIGS = [(8, 4096, 4096, 16), (1, 8192, 4096, 16), (32, 1024, 2048, 16)]


def bytes_moved(b, l, d, n, itemsize=2):
    return (3 * b * d * l + 2 * b * n * l) * itemsize   # u, delta, y + B, C


for (b, l, d, n) in CONFIGS:
    u     = torch.randn(b, d, l, device="cuda", dtype=torch.bfloat16)
    delta = torch.rand (b, d, l, device="cuda", dtype=torch.bfloat16) * 0.1
    A     = -torch.rand(d, n, device="cuda").float()
    B     = torch.randn(b, n, l, device="cuda", dtype=torch.bfloat16)
    C     = torch.randn(b, n, l, device="cuda", dtype=torch.bfloat16)
    D     = torch.randn(d, device="cuda").float()

    ms = triton.testing.do_bench(lambda: selective_scan(u, delta, A, B, C, D))
    gbs = bytes_moved(b, l, d, n) / (ms * 1e-3) / 1e9
    print(f"b={b:3d} l={l:5d} d={d:5d}  {ms:8.3f} ms   {gbs:7.1f} GB/s")
⌥No numbers here on purpose

This page does not print a scoreboard, because a scoreboard copied from someone else's machine is decoration. Run bench.py on your own card, against your own pinned torch and triton, and record the versions next to the numbers. The three comparisons worth having are: the PyTorch reference (where it fits at all), this Triton kernel, and mamba_ssm's official CUDA kernel — the last one being the honest yardstick, since it is what a well-funded hand-written implementation achieves on the same problem.

The gates, collected

GateShapeCriterion
Forward vs fp64 referenceb2 d8 l64 n16max abs err < 1e-5 (fp32), < 1e-2 (bf16)
Long-sequence stabilityb2 d8 l4096 n16same tolerance — catches cumulative-product division
gradcheckb2 d4 l16 n4, fp64passes — catches the adjoint off-by-one
Determinismanytwo runs bitwise identical, in the non-atomic build
Memoryb8 d4096 l4096 n16max_memory_allocated below 1 GB
Register spillschosen confign_spills == 0
Convergencetiny modeloverfits 100 tokens to ~0 loss in 50 steps
bash the tree
ssm/
├── hello.py       # 02 — first kernel, debug loop
├── reference.py   # 03 — fp64 ground truth, kept forever
├── fwd.py         # 04 — fused forward + autotune config
├── scan.py        # 05 — associative-scan variant
├── bwd.py         # 06 — adjoint + recomputation
├── op.py          # 06 — autograd.Function wrapper
├── bench.py       # 09 — timings and achieved bandwidth
└── test_gates.py  # 09 — every row of the table above

pytest ssm/test_gates.py -q && python ssm/bench.py

The order of that list is the order to build in, and each file should be green before the next one is written. The temptation on a kernel like this is to write the fused forward first because it is the interesting part — and then to spend two days unable to tell whether the discrepancy is in the strides, the discretisation, the masking or the reduction. The reference costs twenty minutes and removes that entire class of afternoon.