DWSLM-256M-Base / dwslm /kernels.py
dwsdubey's picture
DWSLM-256M release v1.0: weights, config, tokenizer, reference code, model card
ca76ef5 verified
Raw History Blame Contribute Delete
45.3 kB
"""Kernel driver for the model: the only module touching raw kernel APIs.
layers.py ──► kernels.py ──┬─► torch varlen_attn (FA2) global + SWA attention (G2)
├─► fla causal_conv1d fwd/bwd short conv + SiLU, as an opaque torch.library op
├─► fla chunk_gated_delta_rule GDN, gates fused in-kernel
├─► fla chunk_kda fwd/bwd KDA, gate in-kernel (CLAMP: torch), a torch.library op
├─► fla rms_norm_gated GDN/KDA output norm x gate
├─► Triton route fwd/bwd MHAR softmax over sources, a torch.library op
├─► torch._scaled_mm FP8 MLP GEMMs, rowwise or tensorwise (G1)
└─► compiled head + softcap + CE (G4)
Packed varlen layout throughout: (tokens, heads, head_dim) for attention,
fla's (1, tokens, ...) for the delta rule, segment offsets in `cu`.
"""
from __future__ import annotations
import torch
import torch.nn.functional as F
import triton
import triton.language as tl
from fla.modules.causal_conv1d.ops import causal_conv1d, causal_conv1d_bwd, causal_conv1d_fwd
from fla.modules.norm.fused_norm_gate import rms_norm_gated
from fla.modules.norm.l2norm import l2norm_bwd, l2norm_fwd
from fla.ops.common.gate import fused_beta_sigmoid_bwd, fused_beta_sigmoid_fwd
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
from fla.ops.kda import chunk_kda
from fla.ops.kda.chunk_bwd import chunk_kda_bwd
from fla.ops.kda.chunk_fwd import chunk_kda_fwd
from fla.ops.utils.index import prepare_chunk_indices
from torch import Tensor
from torch.nn.attention import SDPBackend, sdpa_kernel
from torch.nn.attention.varlen import varlen_attn
from dwslm.config import AttnKernel, KdaBwd, KdaGate, Prec
GLOBAL = None # window: full causal
_SDPA = {AttnKernel.FLASH: SDPBackend.FLASH_ATTENTION, AttnKernel.CUDNN: SDPBackend.CUDNN_ATTENTION}
GDN_GATE = "swish" # output-gate activations, fla's layer defaults
KDA_GATE = "sigmoid"
NORM_EPS = 1e-6
KDA_LOWER_BOUND = -5.0 # safe gate: fla's recommended and lowest allowed bound (per-step decay ≥ e^-5)
KDA_CHUNK = 32 # same math as fla's default 64, 1.32x faster fwd+bwd on sm_103 (kernels fall back to mma.sync)
_BETA_SCALE = 1.0 # fla's beta = scale·sigmoid(b); 2 only with allow_neg_eigval, which we leave off
E4M3 = torch.float8_e4m3fn
E4M3_MAX = torch.finfo(E4M3).max
E5M2 = torch.float8_e5m2 # grads: one mantissa bit traded for range (max 57344 vs 448)
AMAX_FLOOR = 1e-12 # keeps all-zero slices from dividing by zero
_OPS = "dwslm" # torch.library namespace
CONV_ACT = "silu"
CONV_CHUNK = 64 # fla causal_conv1d's own tile length
_BWD_ROWS = 256 # rows per bwd program: dw partials are (T/256, D, W) fp32, 25 MB at the main shape
# (BLOCK_T, BLOCK_D, num_warps). Every bwd BLOCK_T must divide _BWD_ROWS, or strips overlap and dw double-counts
_FWD_TILES = ((32, 128, 4), (64, 128, 4), (128, 128, 8), (64, 256, 8))
# bwd tiles: wide along D. Pass 1 keeps 4 shifted x tiles live, so mostly 16 elements/thread; pass 2 is lighter
_DZ_TILES = ((8, 256, 4), (8, 512, 8), (16, 512, 8), (8, 1024, 8))
_DX_TILES = ((16, 512, 8), (32, 256, 4), (32, 512, 8), (16, 1024, 8))
_BWD_STAGES = (1, 2, 3) # autotuned: cp.async pipelining skips L1, which the 3-row halo re-reads lean on
_DZ_DTYPE = torch.bfloat16 # bwd pass 1 → 2 handoff: half fp32's traffic, dx rel err ~1e-3 (TOL 1e-2)
_NO_PIPELINE = 1 # num_stages: the bwd loop's ~24 tile loads per step won't fit pipelined in shared memory
ROUTE_SOURCES = 6 # route's pointer slots: 1 + 5 groups at 20 layers; net._route falls back to torch past it
_SRC_PAD = triton.next_power_of_2(ROUTE_SOURCES) # route bwd keeps per-source row vectors as (BLOCK_T, 8) columns
_ROUTE_ROWS = 256 # rows per route bwd program: dqw partials are (T/256, d) fp32, 2 MB at the main shape
# (BLOCK_T, num_warps). Every route bwd BLOCK_T must divide _ROUTE_ROWS, or strips overlap and dqw double-counts
_ROUTE_FWD_TILES = ((16, 4), (32, 4), (64, 4), (64, 8))
_ROUTE_BWD_TILES = ((16, 4), (32, 4), (32, 8), (64, 8))
def attend(q: Tensor, k: Tensor, v: Tensor, cu: Tensor, max_len: int, window: int | None,
scale: float | None = None, kernel: AttnKernel = AttnKernel.FLASH) -> Tensor:
"""Causal GQA attention inside segments. `window` = visible keys including self; `scale` None = 1/√d."""
# flash's left bound excludes self: (511, 0) = 512 visible keys
left = -1 if window is GLOBAL else window - 1
# torch's cuDNN varlen path takes causal only; banded (SWA) layers stay on flash
backend = _SDPA[kernel] if window is GLOBAL else SDPBackend.FLASH_ATTENTION
with sdpa_kernel([backend]):
return varlen_attn(q, k, v, cu, cu, max_len, max_len, window_size=(left, 0), enable_gqa=True, scale=scale)
def short_conv(x: Tensor, weight: Tensor, cu64: Tensor, cu_host: Tensor) -> Tensor:
"""Depthwise causal conv + SiLU within segments, x (1, T, D), weight (D, W): fla's kernels, one opaque op.
y_t = silu(Σ_j weight[:, W-1-j] · x_{t-j}), taps reaching before the segment start dropped
fla's entry point graph-breaks (its chunk indexing has a data-dependent shape); inside a custom op dynamo
never looks, so the layer stays one graph and keeps fla's speed. The Triton (short_conv_triton) and torch
(short_conv_torch) versions match it but run 1.6x / 2.3x slower on sm_103 (model.bench.conv_check).
"""
return _fla_conv(x, weight, cu64, cu_host)
def _chunks(cu64: Tensor, cu_host: Tensor) -> Tensor:
return prepare_chunk_indices(cu64, CONV_CHUNK, cu_seqlens_cpu=cu_host)
@torch.library.custom_op(f"{_OPS}::fla_conv", mutates_args=())
def _fla_conv(x: Tensor, weight: Tensor, cu64: Tensor, cu_host: Tensor) -> Tensor:
y, _state = causal_conv1d_fwd(x=x, weight=weight, bias=None, residual=None, activation=CONV_ACT,
cu_seqlens=cu64, cu_seqlens_cpu=cu_host, chunk_indices=_chunks(cu64, cu_host),
chunk_size=CONV_CHUNK)
return y
@_fla_conv.register_fake
def _fla_conv_fake(x: Tensor, weight: Tensor, cu64: Tensor, cu_host: Tensor) -> Tensor:
return torch.empty_like(x)
@torch.library.custom_op(f"{_OPS}::fla_conv_bwd", mutates_args=())
def _fla_conv_bwd(dy: Tensor, x: Tensor, weight: Tensor, cu64: Tensor, cu_host: Tensor) -> tuple[Tensor, Tensor]:
dx, dw, _db, _dr, _dh0 = causal_conv1d_bwd(x=x, dy=dy.contiguous(), dht=None, weight=weight, bias=None,
residual=None, activation=CONV_ACT, cu_seqlens=cu64,
cu_seqlens_cpu=cu_host, chunk_indices=_chunks(cu64, cu_host),
chunk_size=CONV_CHUNK)
return dx, dw
@_fla_conv_bwd.register_fake
def _fla_conv_bwd_fake(dy: Tensor, x: Tensor, weight: Tensor, cu64: Tensor, cu_host: Tensor) -> tuple[Tensor, Tensor]:
return torch.empty_like(x), torch.empty_like(weight)
def _fla_conv_setup(ctx, inputs: tuple[Tensor, Tensor, Tensor, Tensor], output: Tensor) -> None:
x, weight, cu64, cu_host = inputs
ctx.save_for_backward(x, weight, cu64)
ctx.cu_host = cu_host # host tensor: kept as is, never moved
def _fla_conv_grad(ctx, dy: Tensor) -> tuple[Tensor, Tensor, None, None]:
x, weight, cu64 = ctx.saved_tensors
dx, dw = _fla_conv_bwd(dy, x, weight, cu64, ctx.cu_host)
return dx, dw, None, None
_fla_conv.register_autograd(_fla_conv_grad, setup_context=_fla_conv_setup)
def short_conv_triton(x: Tensor, weight: Tensor, pos: Tensor) -> Tensor:
"""Triton fwd + bwd as a torch.library op, varlen via pos: matches fla, kept as a reference."""
return _conv_fwd(x, weight, pos)
def short_conv_torch(x: Tensor, weight: Tensor, pos: Tensor) -> Tensor:
"""Plain-torch short_conv, the reference the Triton op is checked against.
Plain torch so inductor fuses it into the layer: fla's kernel ran ~5x off bandwidth on sm_103, and its
data-dependent chunk indexing graph-broke every layer. Matches fla's causal_conv1d (model.bench.conv_check).
"""
W = weight.shape[1]
xs = x[0].float()
y = xs * weight[:, W - 1]
for j in range(1, W):
back = F.pad(xs[:-j], (0, 0, j, 0)) # x_{t-j}, zeros before the row start
y = y + torch.where((pos >= j)[:, None], back, 0.0) * weight[:, W - 1 - j]
return F.silu(y).to(x.dtype)[None]
def short_conv_fla(x: Tensor, weight: Tensor, cu64: Tensor, cu_host: Tensor) -> Tensor:
"""fla's depthwise causal conv + SiLU within segments: the reference short_conv is checked against."""
y, _state = causal_conv1d(x, weight, activation="silu", cu_seqlens=cu64, cu_seqlens_cpu=cu_host)
return y
# Triton short conv. x, y, dy, dx are (T, D) row-major; weight (D, W) with W a power of 2.
#
# fwd one (BLOCK_T, BLOCK_D) tile per program, reading x rows t-3..t (3-row halo above)
# z_t = Σ_j w[:, W-1-j] · x_{t-j} · [pos_t ≥ j] y_t = silu(z_t)
#
# bwd two passes, one (_BWD_ROWS, BLOCK_D) strip per program, BLOCK_T rows per step
# 1 x (3-row halo above), dy ──► dz_t = dy_t · σ(z_t)(1 + z_t(1 - σ(z_t))), z recomputed ──► dz (bf16)
# part[strip, :, W-1-j] = Σ_t dz_t · x_{t-j} · [pos_t ≥ j] from fp32 dz, x tiles already loaded
# 2 dz (3-row halo below) ──► dx_t = Σ_j w[:, W-1-j] · dz_{t+j} · [pos_{t+j} ≥ j]
# dw = part.sum(0): no atomics. Each pass reads every row once from DRAM, the halo comes from cache.
def _configs(tiles: tuple[tuple[int, int, int], ...], **launch) -> list[triton.Config]:
return [triton.Config({"BLOCK_T": t, "BLOCK_D": d}, num_warps=w, **launch) for t, d, w in tiles]
def _staged(tiles: tuple[tuple[int, int, int], ...]) -> list[triton.Config]:
"""Every tile at every depth in _BWD_STAGES. STAGES goes to tl.range: a loop without tl.dot only pipelines
when the loop itself asks."""
return [triton.Config({"BLOCK_T": t, "BLOCK_D": d, "STAGES": s}, num_warps=w, num_stages=s)
for s in _BWD_STAGES for t, d, w in tiles]
@triton.jit
def _offs(rows, d, D):
"""Element offsets of rows x channels; int64 so T*D may pass 2^31."""
return rows.to(tl.int64)[:, None] * D + d[None, :]
@triton.jit
def _weights(w, d, d_in, W: tl.constexpr):
"""weight rows d as one (BLOCK_D, W) fp32 tile: a single contiguous load per program."""
k = tl.arange(0, W)
return tl.load(w + d[:, None] * W + k[None, :], mask=d_in[:, None], other=0.0).to(tl.float32)
@triton.jit
def _tap_w(wt, W: tl.constexpr, j: tl.constexpr):
"""weight[:, W-1-j], the tap applied to x_{t-j}, picked from the tile. Pure, so loops hoist it."""
k = tl.arange(0, W)
return tl.sum(tl.where(k[None, :] == W - 1 - j, wt, 0.0), axis=1)
@triton.jit
def _tap_x(x, t, d, p, live, d_in, D, j: tl.constexpr):
"""x_{t-j} in fp32, zero where the tap reaches before the segment start (j > pos_t) or row 0."""
rows = t - j
keep = live & (p >= j) & (rows >= 0)
return tl.load(x + _offs(rows, d, D), mask=keep[:, None] & d_in[None, :], other=0.0).to(tl.float32)
@triton.jit
def _tap_dz(dz, pos, t, d, d_in, T, D, j: tl.constexpr):
"""dz_{t+j} in fp32, zero past the row end or where row t+j's window stops short of t (pos_{t+j} < j)."""
r = t + j
r_in = r < T
keep = r_in & (tl.load(pos + r, mask=r_in, other=0) >= j)
return tl.load(dz + _offs(r, d, D), mask=keep[:, None] & d_in[None, :], other=0.0).to(tl.float32)
@triton.jit
def _taps(x, wt, t, d, p, live, d_in, D, W: tl.constexpr, BLOCK_T: tl.constexpr, BLOCK_D: tl.constexpr):
"""z at rows t, fp32; taps summed j = 0 first, like short_conv_torch."""
z = tl.zeros((BLOCK_T, BLOCK_D), dtype=tl.float32)
for j in tl.static_range(W):
z += _tap_x(x, t, d, p, live, d_in, D, j) * _tap_w(wt, W, j)[None, :]
return z
@triton.jit
def _dw_taps(x, t, d, p, live, d_in, dz, D, W: tl.constexpr, BLOCK_D: tl.constexpr):
"""sum_t dz_t * x_{t-j} over rows t as a (BLOCK_D, W) tile laid out like weight: tap j in column W-1-j."""
k = tl.arange(0, W)
acc = tl.zeros((BLOCK_D, W), dtype=tl.float32)
for j in tl.static_range(W):
col = tl.sum(dz * _tap_x(x, t, d, p, live, d_in, D, j), axis=0)
acc += tl.where(k[None, :] == W - 1 - j, col[:, None], 0.0)
return acc
@triton.autotune(configs=_configs(_FWD_TILES), key=["D"])
@triton.jit
def _fwd_kernel(x, w, pos, y, T, D, W: tl.constexpr, BLOCK_T: tl.constexpr, BLOCK_D: tl.constexpr):
"""y = silu(z) on one tile."""
t = tl.program_id(0) * BLOCK_T + tl.arange(0, BLOCK_T)
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
t_in = t < T
d_in = d < D
p = tl.load(pos + t, mask=t_in, other=0)
z = _taps(x, _weights(w, d, d_in, W), t, d, p, t_in, d_in, D, W, BLOCK_T, BLOCK_D)
out = (z * tl.sigmoid(z)).to(y.dtype.element_ty)
tl.store(y + _offs(t, d, D), out, mask=t_in[:, None] & d_in[None, :])
@triton.autotune(configs=_staged(_DZ_TILES), key=["D"])
@triton.jit
def _dz_kernel(x, w, pos, dy, dz, part, T, D, W: tl.constexpr, ROWS: tl.constexpr,
BLOCK_T: tl.constexpr, BLOCK_D: tl.constexpr, STAGES: tl.constexpr):
"""Bwd pass 1 over one strip of ROWS rows: dz = dy * silu'(z), z recomputed, plus the strip's dw partial."""
strip = tl.program_id(0)
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
d_in = d < D
wt = _weights(w, d, d_in, W)
acc = tl.zeros((BLOCK_D, W), dtype=tl.float32)
for start in tl.range(strip * ROWS, tl.minimum(strip * ROWS + ROWS, T), BLOCK_T, num_stages=STAGES):
t = start + tl.arange(0, BLOCK_T)
t_in = t < T
tile = t_in[:, None] & d_in[None, :]
p = tl.load(pos + t, mask=t_in, other=0)
z = _taps(x, wt, t, d, p, t_in, d_in, D, W, BLOCK_T, BLOCK_D)
s = tl.sigmoid(z)
g = tl.load(dy + _offs(t, d, D), mask=tile, other=0.0).to(tl.float32) * s * (1 + z * (1 - s))
# dw before the dz store: no write between its x loads and _taps' identical ones, so CSE can merge them
acc += _dw_taps(x, t, d, p, t_in, d_in, g, D, W, BLOCK_D)
tl.store(dz + _offs(t, d, D), g.to(dz.dtype.element_ty), mask=tile)
k = tl.arange(0, W)
tl.store(part + strip * D * W + d[:, None] * W + k[None, :], acc, mask=d_in[:, None])
@triton.autotune(configs=_staged(_DX_TILES), key=["D"])
@triton.jit
def _dx_kernel(dz, w, pos, dx, T, D, W: tl.constexpr, ROWS: tl.constexpr,
BLOCK_T: tl.constexpr, BLOCK_D: tl.constexpr, STAGES: tl.constexpr):
"""Bwd pass 2 over one strip of ROWS rows: dx_t = sum_j w[:, W-1-j] * dz_{t+j}, masked by pos_{t+j} >= j."""
strip = tl.program_id(0)
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
d_in = d < D
wt = _weights(w, d, d_in, W)
for start in tl.range(strip * ROWS, tl.minimum(strip * ROWS + ROWS, T), BLOCK_T, num_stages=STAGES):
t = start + tl.arange(0, BLOCK_T)
g = tl.zeros((BLOCK_T, BLOCK_D), dtype=tl.float32)
for j in tl.static_range(W):
g += _tap_dz(dz, pos, t, d, d_in, T, D, j) * _tap_w(wt, W, j)[None, :]
tl.store(dx + _offs(t, d, D), g.to(dx.dtype.element_ty), mask=(t < T)[:, None] & d_in[None, :])
@torch.library.triton_op(f"{_OPS}::short_conv", mutates_args=())
def _conv_fwd(x: Tensor, weight: Tensor, pos: Tensor) -> Tensor:
"""short_conv's fwd launch. Also its fake impl: under FakeTensor only the allocation runs."""
x, weight, pos = x.contiguous(), weight.contiguous(), pos.contiguous()
T, D = x.shape[1], x.shape[2]
y = torch.empty_like(x)
def grid(meta: dict) -> tuple[int, int]:
return triton.cdiv(T, meta["BLOCK_T"]), triton.cdiv(D, meta["BLOCK_D"])
torch.library.wrap_triton(_fwd_kernel)[grid](x, weight, pos, y, T, D, W=weight.shape[1])
return y
@torch.library.triton_op(f"{_OPS}::short_conv_bwd", mutates_args=())
def _conv_bwd(dy: Tensor, x: Tensor, weight: Tensor, pos: Tensor) -> tuple[Tensor, Tensor]:
"""(dx like x, dweight fp32): pass 1 writes dz and per-strip dw partials, pass 2 dx; torch sums the partials."""
dy, x, weight, pos = dy.contiguous(), x.contiguous(), weight.contiguous(), pos.contiguous()
T, D, W = x.shape[1], x.shape[2], weight.shape[1]
strips = triton.cdiv(T, _BWD_ROWS)
dz = torch.empty_like(x, dtype=_DZ_DTYPE)
dx = torch.empty_like(x)
part = x.new_empty((strips, D, W), dtype=torch.float32)
def grid(meta: dict) -> tuple[int, int]:
return strips, triton.cdiv(D, meta["BLOCK_D"])
torch.library.wrap_triton(_dz_kernel)[grid](x, weight, pos, dy, dz, part, T, D, W=W, ROWS=_BWD_ROWS)
torch.library.wrap_triton(_dx_kernel)[grid](dz, weight, pos, dx, T, D, W=W, ROWS=_BWD_ROWS)
return dx, part.sum(0)
def _conv_setup(ctx, inputs: tuple[Tensor, Tensor, Tensor], output: Tensor) -> None:
"""Saves x, weight, pos: the bwd recomputes z instead of keeping it."""
ctx.save_for_backward(*inputs)
def _conv_grad(ctx, dy: Tensor) -> tuple[Tensor, Tensor, None]:
dx, dw = _conv_bwd(dy, *ctx.saved_tensors)
return dx, dw, None
_conv_fwd.register_autograd(_conv_grad, setup_context=_conv_setup)
def route(values: list[Tensor], scales: list[Tensor], qw: Tensor, heads: int) -> Tensor:
"""MHAR routing as one fused Triton fwd + bwd op. Up to ROUTE_SOURCES sources (T, d), bf16 or fp32 each.
per token, head h: α_i = softmax_i(r_i · (qw_h · x_i,h)), out_h = Σ_i α_i · x_i,h out (T, d) fp32
Matches net._route_torch (model.bench.route_check)."""
return _route_fwd(values, scales, qw, heads)
# Triton route. Sources x_i, out and dout are (T, d) row-major, scales r_i (T, 1), qw (d,) = H heads x HD.
# The S sources ride in fixed pointer slots x0..x5 (S constexpr); pad slots point at an input and are never touched.
#
# fwd one (BLOCK_T, HD) tile of head h per program, online softmax over sources: each read once
# logit_i = r_i · (q_h · x_i) α = softmax_i(logit) out = Σ_i α_i x_i
#
# bwd one (_ROUTE_ROWS, HD) strip of head h per program, BLOCK_T rows per step; α recomputed, never saved
# pass 1 logit_i, q_h·x_i, g·x_i one column per source of a (BLOCK_T, 8) tile
# dlogit_i = α_i (g·x_i − Σ_k α_k g·x_k)
# pass 2 dx_i = α_i g + dlogit_i r_i q_h stored in x_i's dtype
# drp[h, i] = dlogit_i · (q_h·x_i) → dr = drp.sum(0) over heads
# part[strip, h] = Σ_t dlogit_i r_i x_i → dqw = part.sum(0) over strips, no atomics
def _route_cfgs(tiles: tuple[tuple[int, int], ...], **launch) -> list[triton.Config]:
return [triton.Config({"BLOCK_T": t}, num_warps=w, **launch) for t, w in tiles]
@triton.jit
def _slot(i: tl.constexpr, p0, p1, p2, p3, p4, p5):
"""Pointer slot i of ROUTE_SOURCES, picked at compile time."""
if i == 0:
p = p0
elif i == 1:
p = p1
elif i == 2:
p = p2
elif i == 3:
p = p3
elif i == 4:
p = p4
else:
p = p5
return p
@triton.jit
def _tile(src, t, c, t_in, D):
"""(BLOCK_T, HD) tile at rows t, head columns c, in fp32; rows past T read 0."""
return tl.load(src + _offs(t, c, D), mask=t_in[:, None], other=0.0).to(tl.float32)
@triton.jit
def _scale(r, t, t_in):
"""Per-token inverse RMS at rows t."""
return tl.load(r + t, mask=t_in, other=0.0)
@triton.jit
def _put(m, k, i: tl.constexpr, v):
"""m with column i set to v: S row vectors kept as one tile, since a kernel can't hold a list."""
return tl.where(k[None, :] == i, v[:, None], m)
@triton.jit
def _col(m, k, i: tl.constexpr):
"""Column i of m."""
return tl.sum(tl.where(k[None, :] == i, m, 0.0), axis=1)
@triton.autotune(configs=_route_cfgs(_ROUTE_FWD_TILES), key=["D", "S"])
@triton.jit
def _route_fwd_kernel(x0, x1, x2, x3, x4, x5, r0, r1, r2, r3, r4, r5, qw, out, T, D,
S: tl.constexpr, HD: tl.constexpr, BLOCK_T: tl.constexpr):
"""out on one (BLOCK_T, HD) tile of head h."""
t = tl.program_id(0) * BLOCK_T + tl.arange(0, BLOCK_T)
c = tl.program_id(1) * HD + tl.arange(0, HD)
t_in = t < T
q = tl.load(qw + c).to(tl.float32)
# source 0 seeds the running max, normalizer and weighted sum
x = _tile(x0, t, c, t_in, D)
top = _scale(r0, t, t_in) * tl.sum(x * q[None, :], axis=1)
den = tl.full((BLOCK_T,), 1.0, tl.float32)
acc = x
# a source that raises the max rescales everything summed before it
for i in tl.static_range(1, S):
x = _tile(_slot(i, x0, x1, x2, x3, x4, x5), t, c, t_in, D)
logit = _scale(_slot(i, r0, r1, r2, r3, r4, r5), t, t_in) * tl.sum(x * q[None, :], axis=1)
new_top = tl.maximum(top, logit)
old, w = tl.exp(top - new_top), tl.exp(logit - new_top)
den = den * old + w
acc = acc * old[:, None] + x * w[:, None]
top = new_top
tl.store(out + _offs(t, c, D), acc / den[:, None], mask=t_in[:, None])
@triton.autotune(configs=_route_cfgs(_ROUTE_BWD_TILES, num_stages=_NO_PIPELINE), key=["D", "S"])
@triton.jit
def _route_bwd_kernel(x0, x1, x2, x3, x4, x5, r0, r1, r2, r3, r4, r5, dx0, dx1, dx2, dx3, dx4, dx5,
qw, dout, drp, part, T, D, S: tl.constexpr, SP: tl.constexpr, HD: tl.constexpr,
ROWS: tl.constexpr, BLOCK_T: tl.constexpr):
"""Every dx_i over one strip of head h, plus head h's dr partial and the strip's dqw partial."""
strip, h = tl.program_id(0), tl.program_id(1)
c = h * HD + tl.arange(0, HD)
k = tl.arange(0, SP)
q = tl.load(qw + c).to(tl.float32)
dq = tl.zeros((BLOCK_T, HD), dtype=tl.float32)
for start in range(strip * ROWS, tl.minimum(strip * ROWS + ROWS, T), BLOCK_T):
t = start + tl.arange(0, BLOCK_T)
t_in = t < T
g = _tile(dout, t, c, t_in, D)
# pass 1: logit, key dot and g·x per source; pad columns stay -inf, so their α is 0
logit = tl.full((BLOCK_T, SP), float("-inf"), tl.float32)
key = tl.zeros((BLOCK_T, SP), dtype=tl.float32)
gx = tl.zeros((BLOCK_T, SP), dtype=tl.float32)
for i in tl.static_range(S):
x = _tile(_slot(i, x0, x1, x2, x3, x4, x5), t, c, t_in, D)
s = tl.sum(x * q[None, :], axis=1)
logit = _put(logit, k, i, _scale(_slot(i, r0, r1, r2, r3, r4, r5), t, t_in) * s)
key = _put(key, k, i, s)
gx = _put(gx, k, i, tl.sum(x * g, axis=1))
# softmax backward: dlogit_i = α_i (g·x_i − Σ_k α_k g·x_k)
e = tl.exp(logit - tl.max(logit, axis=1)[:, None])
a = e / tl.sum(e, axis=1)[:, None]
dlogit = a * (gx - tl.sum(a * gx, axis=1)[:, None])
# pass 2: x_i is re-read for dqw only, a tile this program just loaded, so it comes from cache
for i in tl.static_range(S):
dl = _col(dlogit, k, i)
dlr = dl * _scale(_slot(i, r0, r1, r2, r3, r4, r5), t, t_in)
tl.store(drp + (h * S + i) * T + t, dl * _col(key, k, i), mask=t_in)
dq += _tile(_slot(i, x0, x1, x2, x3, x4, x5), t, c, t_in, D) * dlr[:, None]
dx = _col(a, k, i)[:, None] * g + dlr[:, None] * q[None, :]
dst = _slot(i, dx0, dx1, dx2, dx3, dx4, dx5)
tl.store(dst + _offs(t, c, D), dx.to(dst.dtype.element_ty), mask=t_in[:, None])
tl.store(part + strip * D + c, tl.sum(dq, axis=0))
def _dense(ts: list[Tensor]) -> list[Tensor]:
return [t.contiguous() for t in ts]
def _slots(ts: list[Tensor], spare: Tensor) -> list[Tensor]:
"""ts padded to ROUTE_SOURCES kernel slots with `spare`: a read-only input, so inductor never sees a pad
as a written output (and clones it)."""
return [*ts, *[spare] * (ROUTE_SOURCES - len(ts))]
@torch.library.triton_op(f"{_OPS}::route", mutates_args=())
def _route_fwd(values: list[Tensor], scales: list[Tensor], qw: Tensor, heads: int) -> Tensor:
"""route's fwd launch. Also its fake impl: under FakeTensor only the allocation runs."""
xs, rs = _dense(values), _dense(scales)
T, D = xs[0].shape
out = xs[0].new_empty((T, D), dtype=torch.float32)
def grid(meta: dict) -> tuple[int, int]:
return triton.cdiv(T, meta["BLOCK_T"]), heads
torch.library.wrap_triton(_route_fwd_kernel)[grid](*_slots(xs, xs[0]), *_slots(rs, rs[0]), qw.contiguous(), out,
T, D, S=len(xs), HD=D // heads)
return out
@torch.library.triton_op(f"{_OPS}::route_bwd", mutates_args=())
def _route_bwd(dout: Tensor, values: list[Tensor], scales: list[Tensor], qw: Tensor,
heads: int) -> tuple[list[Tensor], Tensor, Tensor]:
"""(dx like each source, dr (S, T) fp32, dqw fp32): the kernel writes dx and the per-head dr and per-strip
dqw partials, torch sums the partials."""
dout, xs, rs, qw = dout.contiguous(), _dense(values), _dense(scales), qw.contiguous()
T, D = dout.shape
S, strips = len(xs), triton.cdiv(T, _ROUTE_ROWS)
dxs = [torch.empty_like(x) for x in xs]
drp = dout.new_empty((heads, S, T), dtype=torch.float32)
part = dout.new_empty((strips, D), dtype=torch.float32)
def grid(meta: dict) -> tuple[int, int]:
return strips, heads
torch.library.wrap_triton(_route_bwd_kernel)[grid](
*_slots(xs, xs[0]), *_slots(rs, rs[0]), *_slots(dxs, dout), qw, dout, drp, part, T, D,
S=S, SP=_SRC_PAD, HD=D // heads, ROWS=_ROUTE_ROWS)
return dxs, drp.sum(0), part.sum(0)
def _route_setup(ctx, inputs: tuple[list[Tensor], list[Tensor], Tensor, int], output: Tensor) -> None:
"""Saves sources, scales and qw: the bwd recomputes logits and α instead of keeping them."""
values, scales, qw, heads = inputs
ctx.save_for_backward(*values, *scales, qw)
ctx.sources, ctx.heads = len(values), heads
def _route_grad(ctx, dout: Tensor) -> tuple[list[Tensor], list[Tensor], Tensor, None]:
"""Grads shaped like the inputs: lists for the sources and the (T, 1) scales."""
S, saved = ctx.sources, ctx.saved_tensors
dxs, dr, dqw = _route_bwd(dout, list(saved[:S]), list(saved[S:2 * S]), saved[-1], ctx.heads)
# independent (T, 1) tensors, not unbind views of one buffer: aliased grads from a custom op are the
# prime suspect for the op's drift on trained weights (K33)
return dxs, [d[..., None].clone() for d in dr], dqw, None
_route_fwd.register_autograd(_route_grad, setup_context=_route_setup)
def gated_delta(q: Tensor, k: Tensor, v: Tensor, a: Tensor, b: Tensor, a_log: Tensor, dt_bias: Tensor,
cu64: Tensor, cu_host: Tensor) -> Tensor:
"""GDN within segments. q/k L2-normed, decay = -exp(a_log)·softplus(a + dt_bias), beta = sigmoid(b): all in-kernel."""
o, _state = chunk_gated_delta_rule(
q, k, v, a, b,
use_qk_l2norm_in_kernel=True, use_beta_sigmoid_in_kernel=True, use_gate_in_kernel=True,
A_log=a_log, dt_bias=dt_bias, state_v_first=True,
cu_seqlens=cu64, cu_seqlens_cpu=cu_host,
) # fmt: skip
return o
def kimi_delta(q: Tensor, k: Tensor, v: Tensor, f: Tensor, b: Tensor, a_log: Tensor, dt_bias: Tensor,
cu64: Tensor, cu_host: Tensor, gate: KdaGate = KdaGate.SOFTPLUS,
bwd: KdaBwd = KdaBwd.RECOMPUTE) -> Tensor:
"""KDA within segments, f (1, T, H, K); gate (see KdaGate), beta and q/k L2 norm all in-kernel.
fla's chunk_kda is compiler-disabled, so every KDA layer graph-broke there. Its internals run here as one
opaque op instead: same kernels, same order, so o and every grad match kimi_delta_fla bit for bit
(model.bench.kda_check). SAVE stays on fla's entry point: its saved chunk states have a data-dependent shape.
CLAMP computes the gate in torch and runs a sibling op on fla's precomputed-gate safe path.
"""
if bwd is KdaBwd.SAVE:
return kimi_delta_fla(q, k, v, f, b, a_log, dt_bias, cu64, cu_host, gate, bwd)
# inductor fuses the gate into the layer; autograd carries its a_log and dt_bias grads, fla only sees g
if gate is KdaGate.CLAMP:
return _kda_clamp_fwd(q, k, v, _clamped_gate(f, a_log, dt_bias), b, cu64, cu_host)[0]
return _kda_fwd(q, k, v, f, b, a_log, dt_bias, cu64, cu_host, gate.value)[0]
def _clamped_gate(f: Tensor, a_log: Tensor, dt_bias: Tensor) -> Tensor:
"""CLAMP's gate: fla's in-kernel softplus gate (fla.ops.kda.gate) in fp32 torch, clamped to its safe range.
g = max(-exp(a_log_h)·softplus(f + dt_bias), KDA_LOWER_BOUND) f, g (1, T, H, K); a_log (H,); dt_bias (H·K,)
Only gates under the bound change (per-step decay < e^-5, state all but wiped either way), and their grads go
to 0. fp32 on purpose: fla cumsums g as given, so a bf16 g would round every step's decay before the sum.
"""
H, K = f.shape[-2:]
x = f.float() + dt_bias.float().view(H, K)
g = -a_log.float().exp().view(H, 1) * F.softplus(x) # softplus threshold 20, as fla's
return g.clamp(min=KDA_LOWER_BOUND)
def _kda_args(q: Tensor, a_log: Tensor, dt_bias: Tensor, cu64: Tensor, cu_host: Tensor, gate: str) -> dict:
"""What fla's ChunkKDAFunction passes both chunk_kda_fwd and chunk_kda_bwd under our flags. Everything left
out sits at fla's default: no initial or final state, no context parallel, no graph-static chunk lists."""
safe = gate == KdaGate.SAFE
return {
"scale": q.shape[-1] ** -0.5, "state_v_first": True, "cu_seqlens": cu64,
"chunk_indices": prepare_chunk_indices(cu64, KDA_CHUNK, cu_seqlens_cpu=cu_host), "chunk_size": KDA_CHUNK,
"safe_gate": safe, "lower_bound": KDA_LOWER_BOUND if safe else None,
"use_gate_in_kernel": True, "A_log": a_log, "dt_bias": dt_bias, "disable_recompute": False,
} # fmt: skip
# o, then what ChunkKDAFunction saves for backward under RECOMPUTE: L2-normed q and k with their 1/‖·‖ rows,
# sigmoid(b) and the intra-chunk Aqk, Akk. The gate cumsum, w, u and chunk states are rebuilt in backward.
_KdaOut = tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]
_KdaGrads = tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor] # q, k, v, f, b, a_log, dt_bias
@torch.library.custom_op(f"{_OPS}::kda_fwd", mutates_args=())
def _kda_fwd(q: Tensor, k: Tensor, v: Tensor, f: Tensor, b: Tensor, a_log: Tensor, dt_bias: Tensor,
cu64: Tensor, cu_host: Tensor, gate: str) -> _KdaOut:
# ChunkKDAFunction.forward line for line; contiguous like its input_guard
q, k, v, f, b = (t.contiguous() for t in (q, k, v, f, b))
q, q_rstd = l2norm_fwd(q)
k, k_rstd = l2norm_fwd(k)
beta = fused_beta_sigmoid_fwd(b, _BETA_SCALE)
# RECOMPUTE: the final state, gate cumsum, w, u, qg, kg, v_new, h and initial state all come back None
o, _final, _g, Aqk, Akk, *_rebuilt = chunk_kda_fwd(q=q, k=k, v=v, g=f, beta=beta, initial_state=None,
output_final_state=False, cu_seqlens_cpu=cu_host,
**_kda_args(q, a_log, dt_bias, cu64, cu_host, gate))
return o.type_as(q), q, q_rstd, k, k_rstd, beta, Aqk, Akk
@_kda_fwd.register_fake
def _kda_fwd_fake(q: Tensor, k: Tensor, v: Tensor, f: Tensor, b: Tensor, a_log: Tensor, dt_bias: Tensor,
cu64: Tensor, cu_host: Tensor, gate: str) -> _KdaOut:
# fla's allocations, all contiguous: o zeros_like(v) then type_as(q); l2norm_fwd's rstd (1, T, H) fp32;
# fused_beta_sigmoid_fwd's fp32 beta; chunk_kda_fwd_intra's Aqk, Akk (1, T, HV, chunk) in k's dtype
tiles = (*f.shape[:-1], KDA_CHUNK)
return (v.new_empty(v.shape, dtype=q.dtype),
q.new_empty(q.shape), q.new_empty(q.shape[:-1], dtype=torch.float32),
k.new_empty(k.shape), k.new_empty(k.shape[:-1], dtype=torch.float32),
b.new_empty(b.shape, dtype=torch.float32), k.new_empty(tiles), k.new_empty(tiles))
@torch.library.custom_op(f"{_OPS}::kda_bwd", mutates_args=())
def _kda_bwd(do: Tensor, q: Tensor, q_rstd: Tensor, k: Tensor, k_rstd: Tensor, v: Tensor, f: Tensor, b: Tensor,
beta: Tensor, a_log: Tensor, dt_bias: Tensor, Aqk: Tensor, Akk: Tensor, cu64: Tensor, cu_host: Tensor,
gate: str) -> _KdaGrads:
# ChunkKDAFunction.backward line for line: q, k arrive L2-normed, no state flows in or out
do, v, f, b = (t.contiguous() for t in (do, v, f, b))
dq, dk, dv, db, df, _dh0, da, dbias = chunk_kda_bwd(q=q, k=k, v=v, beta=beta, Aqk=Aqk, Akk=Akk,
initial_state=None, do=do, dht=None, g_org=f,
**_kda_args(q, a_log, dt_bias, cu64, cu_host, gate))
# back through the in-kernel L2 norms and beta sigmoid
dq = l2norm_bwd(q, q_rstd, dq)
dk = l2norm_bwd(k, k_rstd, dk)
db = fused_beta_sigmoid_bwd(x=b, dy=db, scale=_BETA_SCALE)
return dq.to(q), dk.to(k), dv.to(v), df.to(f), db.to(b), da, dbias
@_kda_bwd.register_fake
def _kda_bwd_fake(do: Tensor, q: Tensor, q_rstd: Tensor, k: Tensor, k_rstd: Tensor, v: Tensor, f: Tensor,
b: Tensor, beta: Tensor, a_log: Tensor, dt_bias: Tensor, Aqk: Tensor, Akk: Tensor, cu64: Tensor,
cu_host: Tensor, gate: str) -> _KdaGrads:
# each grad as its input, contiguous: .to(input) in ChunkKDAFunction, type_as / .to in kda_gate_bwd
return tuple(t.new_empty(t.shape) for t in (q, k, v, f, b, a_log, dt_bias))
def _kda_setup(ctx, inputs: tuple, output: _KdaOut) -> None:
_q, _k, v, f, b, a_log, dt_bias, cu64, cu_host, gate = inputs
ctx.save_for_backward(v, f, b, a_log, dt_bias, cu64, *output[1:]) # raw q, k unsaved, as in fla
ctx.cu_host, ctx.gate = cu_host, gate # host tensor kept as is, never moved
ctx.set_materialize_grads(False) # the saved outputs' grads are never read: don't zero-fill them
def _kda_grad(ctx, do: Tensor, *_saved_grads: Tensor) -> tuple[Tensor | None, ...]:
v, f, b, a_log, dt_bias, cu64, q, q_rstd, k, k_rstd, beta, Aqk, Akk = ctx.saved_tensors
grads = _kda_bwd(do, q, q_rstd, k, k_rstd, v, f, b, beta, a_log, dt_bias, Aqk, Akk, cu64, ctx.cu_host, ctx.gate)
return *grads, None, None, None
_kda_fwd.register_autograd(_kda_grad, setup_context=_kda_setup)
def _clamp_args(q: Tensor, cu64: Tensor, cu_host: Tensor) -> dict:
"""SAFE's flags with a precomputed gate: fla only cumsums g (scale 1/ln 2), so no A_log or dt_bias, and
lower_bound is dead (fla reads it only to build the gate, never in the intra-chunk kernels)."""
return _kda_args(q, None, None, cu64, cu_host, KdaGate.SAFE) | {"use_gate_in_kernel": False, "lower_bound": None}
# CLAMP's op pair: as above, plus the gate cumsum. With a precomputed gate fla keeps it from the forward (only
# use_gate_in_kernel drops it), and its backward reads it instead of rebuilding the gate. Grads: q, k, v, g, b
_KdaClampOut = tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]
_KdaClampGrads = tuple[Tensor, Tensor, Tensor, Tensor, Tensor]
@torch.library.custom_op(f"{_OPS}::kda_clamp_fwd", mutates_args=())
def _kda_clamp_fwd(q: Tensor, k: Tensor, v: Tensor, g: Tensor, b: Tensor, cu64: Tensor,
cu_host: Tensor) -> _KdaClampOut:
# _kda_fwd with g in place of f: chunk_kda_fwd cumsums it, and the cumsum comes back instead of None
q, k, v, g, b = (t.contiguous() for t in (q, k, v, g, b))
q, q_rstd = l2norm_fwd(q)
k, k_rstd = l2norm_fwd(k)
beta = fused_beta_sigmoid_fwd(b, _BETA_SCALE)
o, _final, g_cum, Aqk, Akk, *_rebuilt = chunk_kda_fwd(q=q, k=k, v=v, g=g, beta=beta, initial_state=None,
output_final_state=False, cu_seqlens_cpu=cu_host,
**_clamp_args(q, cu64, cu_host))
return o.type_as(q), q, q_rstd, k, k_rstd, beta, g_cum, Aqk, Akk
@_kda_clamp_fwd.register_fake
def _kda_clamp_fwd_fake(q: Tensor, k: Tensor, v: Tensor, g: Tensor, b: Tensor, cu64: Tensor,
cu_host: Tensor) -> _KdaClampOut:
# _kda_fwd_fake's allocations, plus chunk_local_cumsum's g_cum: like g, fp32 (its output_dtype default)
tiles = (*g.shape[:-1], KDA_CHUNK)
return (v.new_empty(v.shape, dtype=q.dtype),
q.new_empty(q.shape), q.new_empty(q.shape[:-1], dtype=torch.float32),
k.new_empty(k.shape), k.new_empty(k.shape[:-1], dtype=torch.float32),
b.new_empty(b.shape, dtype=torch.float32), g.new_empty(g.shape, dtype=torch.float32),
k.new_empty(tiles), k.new_empty(tiles))
@torch.library.custom_op(f"{_OPS}::kda_clamp_bwd", mutates_args=())
def _kda_clamp_bwd(do: Tensor, q: Tensor, q_rstd: Tensor, k: Tensor, k_rstd: Tensor, v: Tensor, g_cum: Tensor,
b: Tensor, beta: Tensor, Aqk: Tensor, Akk: Tensor, cu64: Tensor,
cu_host: Tensor) -> _KdaClampGrads:
# ChunkKDAFunction.backward with g = the saved cumsum, g_org None: no gate bwd, dg is d(loss)/d(precomputed g)
do, v, b = (t.contiguous() for t in (do, v, b))
dq, dk, dv, db, dg, _dh0, _da, _dbias = chunk_kda_bwd(q=q, k=k, v=v, beta=beta, Aqk=Aqk, Akk=Akk,
initial_state=None, do=do, dht=None, g=g_cum, g_org=None,
**_clamp_args(q, cu64, cu_host))
# back through the in-kernel L2 norms and beta sigmoid
dq = l2norm_bwd(q, q_rstd, dq)
dk = l2norm_bwd(k, k_rstd, dk)
db = fused_beta_sigmoid_bwd(x=b, dy=db, scale=_BETA_SCALE)
return dq.to(q), dk.to(k), dv.to(v), dg.to(g_cum), db.to(b)
@_kda_clamp_bwd.register_fake
def _kda_clamp_bwd_fake(do: Tensor, q: Tensor, q_rstd: Tensor, k: Tensor, k_rstd: Tensor, v: Tensor, g_cum: Tensor,
b: Tensor, beta: Tensor, Aqk: Tensor, Akk: Tensor, cu64: Tensor,
cu_host: Tensor) -> _KdaClampGrads:
# each grad as its input, contiguous; dg fp32 like g and g_cum
return tuple(t.new_empty(t.shape) for t in (q, k, v, g_cum, b))
def _kda_clamp_setup(ctx, inputs: tuple, output: _KdaClampOut) -> None:
_q, _k, v, _g, b, cu64, cu_host = inputs
ctx.save_for_backward(v, b, cu64, *output[1:]) # g itself unsaved: backward reads its cumsum
ctx.cu_host = cu_host # host tensor kept as is, never moved
ctx.set_materialize_grads(False) # the saved outputs' grads are never read: don't zero-fill them
def _kda_clamp_grad(ctx, do: Tensor, *_saved_grads: Tensor) -> tuple[Tensor | None, ...]:
v, b, cu64, q, q_rstd, k, k_rstd, beta, g_cum, Aqk, Akk = ctx.saved_tensors
grads = _kda_clamp_bwd(do, q, q_rstd, k, k_rstd, v, g_cum, b, beta, Aqk, Akk, cu64, ctx.cu_host)
return *grads, None, None
_kda_clamp_fwd.register_autograd(_kda_clamp_grad, setup_context=_kda_clamp_setup)
def kimi_delta_fla(q: Tensor, k: Tensor, v: Tensor, f: Tensor, b: Tensor, a_log: Tensor, dt_bias: Tensor,
cu64: Tensor, cu_host: Tensor, gate: KdaGate = KdaGate.SOFTPLUS,
bwd: KdaBwd = KdaBwd.RECOMPUTE) -> Tensor:
"""fla's public chunk_kda (a graph break per call): the reference kimi_delta is checked against."""
if gate is KdaGate.CLAMP:
return _kda_clamp_fla(q, k, v, f, b, a_log, dt_bias, cu64, cu_host, bwd)
safe = gate is KdaGate.SAFE
o, _state = chunk_kda(
q, k, v, f, b,
use_qk_l2norm_in_kernel=True, use_beta_sigmoid_in_kernel=True, use_gate_in_kernel=True,
A_log=a_log, dt_bias=dt_bias, state_v_first=True,
cu_seqlens=cu64, cu_seqlens_cpu=cu_host,
safe_gate=safe, lower_bound=KDA_LOWER_BOUND if safe else None, chunk_size=KDA_CHUNK,
disable_recompute=bwd is KdaBwd.SAVE,
) # fmt: skip
return o
def _kda_clamp_fla(q: Tensor, k: Tensor, v: Tensor, f: Tensor, b: Tensor, a_log: Tensor, dt_bias: Tensor,
cu64: Tensor, cu_host: Tensor, bwd: KdaBwd) -> Tensor:
"""CLAMP through chunk_kda: the same torch gate, handed in precomputed on fla's safe path."""
o, _state = chunk_kda(
q, k, v, _clamped_gate(f, a_log, dt_bias), b,
use_qk_l2norm_in_kernel=True, use_beta_sigmoid_in_kernel=True, use_gate_in_kernel=False,
state_v_first=True, cu_seqlens=cu64, cu_seqlens_cpu=cu_host,
safe_gate=True, chunk_size=KDA_CHUNK, disable_recompute=bwd is KdaBwd.SAVE,
) # fmt: skip
return o
def gated_norm(x: Tensor, gate: Tensor, weight: Tensor, act: str) -> Tensor:
"""RMSNorm(x)·weight·act(gate) over the last dim (per head); act is GDN_GATE (g·σ(g)) or KDA_GATE (σ(g)).
Plain torch, fp32 inside, so it fuses into the layer instead of graph-breaking (model.bench.conv_check)."""
y = F.rms_norm(x.float(), (x.shape[-1],), weight, NORM_EPS)
g = gate.float()
a = torch.sigmoid(g) if act == KDA_GATE else F.silu(g)
return (y * a).to(x.dtype)
def gated_norm_fla(x: Tensor, gate: Tensor, weight: Tensor, act: str) -> Tensor:
"""fla's fused gated RMSNorm: the reference gated_norm is checked against."""
return rms_norm_gated(x, gate, weight, None, activation=act, eps=NORM_EPS)
@torch.compile(dynamic=False)
def head_nll(h: Tensor, w: Tensor, y: Tensor, mult: float, softcap: float) -> Tensor:
"""Per-token CE (nats) of softcap·tanh(mult·(h @ w.T) / softcap); inductor fuses the softcap into CE."""
z = (h @ w.t()).float() * mult
z = softcap * torch.tanh(z / softcap)
return F.cross_entropy(z, y, reduction="none")
def _quant(x: Tensor, dim: int) -> tuple[Tensor, Tensor]:
"""e4m3 with one scale per slice along `dim`. Returns (fp8, inverse scale)."""
amax = x.abs().amax(dim=dim, keepdim=True).float().clamp(min=AMAX_FLOOR)
scale = E4M3_MAX / amax
return (x.float() * scale).to(E4M3), scale.reciprocal()
def _gemm8(a: Tensor, b: Tensor) -> Tensor:
"""a (M,K) @ b (K,N) in FP8: a scaled per row, b per column. cuBLASLt wants a row-major, b column-major."""
qa, sa = _quant(a, dim=1)
qb, sb = _quant(b, dim=0)
qa = qa.contiguous()
qb = qb.t().contiguous().t()
return torch._scaled_mm(qa, qb, scale_a=sa, scale_b=sb, out_dtype=torch.bfloat16)
class _Fp8Linear(torch.autograd.Function):
"""y = x @ w.T, all three GEMMs in FP8 (day-0: 1.51x on the MLP); requantizes in backward."""
@staticmethod
def forward(ctx, x: Tensor, w: Tensor) -> Tensor:
ctx.save_for_backward(x, w)
return _gemm8(x, w.t())
@staticmethod
def backward(ctx, gy: Tensor) -> tuple[Tensor, Tensor]:
x, w = ctx.saved_tensors
gx = _gemm8(gy, w) # (M,N) @ (N,K)
gw = _gemm8(gy.t(), x) # (N,M) @ (M,K)
return gx.to(x.dtype), gw.to(w.dtype)
def _quant_tw(t: Tensor, fp8: torch.dtype) -> tuple[Tensor, Tensor]:
"""Row-major `fp8` with one scale for the whole tensor. Returns (fp8, inverse scale), the scale 0-dim fp32."""
amax = t.abs().amax().float().clamp(min=AMAX_FLOOR)
scale = torch.finfo(fp8).max / amax
return (t.contiguous().float() * scale).to(fp8), scale.reciprocal()
def _col_major(t: Tensor) -> Tensor:
"""Same (rows, cols) values, column-major: the layout cuBLASLt wants for _scaled_mm's mat2."""
return t.t().contiguous().t()
class _Fp8TwLinear(torch.autograd.Function):
"""y = x @ w.T, all three GEMMs in tensorwise FP8: e4m3 x and w, e5m2 grads (B300: 1.5-2x bf16 per GEMM).
Shapes: x (M,K), w (N,K), y and gy (M,N). cuBLASLt takes mat1 row-major, mat2 column-major, never e5m2 x e5m2.
Keeps the fp8 x and w for backward: 1 byte each, and no second quant pass.
"""
@staticmethod
def forward(ctx, x: Tensor, w: Tensor) -> Tensor:
x8, sx = _quant_tw(x, E4M3)
w8, sw = _quant_tw(w, E4M3)
ctx.save_for_backward(x8, w8, sx, sw)
ctx.dtypes = x.dtype, w.dtype
# (M,K) @ (K,N): w8.t() of the row-major weight is already column-major, no copy
return torch._scaled_mm(x8, w8.t(), scale_a=sx, scale_b=sw, out_dtype=torch.bfloat16)
@staticmethod
def backward(ctx, gy: Tensor) -> tuple[Tensor, Tensor]:
x8, w8, sx, sw = ctx.saved_tensors
x_dtype, w_dtype = ctx.dtypes
g8, sg = _quant_tw(gy, E5M2)
# dgrad (M,N) @ (N,K): e5m2 x e4m3, w8 copied column-major (N·K bytes, small)
gx = torch._scaled_mm(g8, _col_major(w8), scale_a=sg, scale_b=sw, out_dtype=torch.bfloat16)
# wgrad (N,M) @ (M,K), reduced over tokens: both operands need M innermost, so both are transposed copies
gw = torch._scaled_mm(g8.t().contiguous(), _col_major(x8), scale_a=sg, scale_b=sx, out_dtype=torch.bfloat16)
return gx.to(x_dtype), gw.to(w_dtype)
@torch.compile(dynamic=False)
def relu2_mlp(x: Tensor, up: Tensor, down: Tensor, prec: Prec) -> Tensor:
"""ReLU² MLP: down(relu(up(x))²), GEMMs in BF16, rowwise FP8 or tensorwise FP8."""
linear = F.linear
if prec is Prec.FP8:
linear = _Fp8Linear.apply
if prec is Prec.FP8_TW:
linear = _Fp8TwLinear.apply
return linear(F.relu(linear(x, up)).square(), down)