Inkling-2-Mini-DFly2 / reference_kernels.py
确定下推自动机
Add Inkling-2-Mini DFly2-KV on-policy step 956 BF16 weights, config, handoff, and evals
09185f4 verified
Raw History Blame Contribute Delete
36.5 kB
"""
High-throughput Blackwell (sm_103) Triton & torch.compile kernels for Inkling-2-Mini:
- Doc-aware W=4 static & dynamic short causal convs (zero cross-doc leakage, exact scales 5^-0.5 & 9^-0.5)
- Fused Inkling2 standard RMSNorm, L2-clipping (Q/K/R), Value RMSNorm (no gamma), log-scaling tau
- Compiled AttnRes block mixing & cross-pass controller blend+RMSNorm
- Compiled softcapped interleaved SiTU activation & exact Inkling2 router
"""
import math
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
try:
import triton
import triton.language as tl
except ImportError:
triton = None
class _DummyTL:
constexpr = int
tl = _DummyTL
_INV_SQRT5 = 5.0 ** -0.5
_INV_SQRT9 = 1.0 / 3.0
def _maybe_triton_jit(fn):
return triton.jit(fn) if triton is not None else fn
@_maybe_triton_jit
def _doc_sconv_static_kernel(
X_ptr, W_ptr, DOC_ptr, OUT_ptr, ADD_ptr, RES_ptr,
T, C,
stride_xt, stride_xc,
stride_wc, stride_wk,
stride_ot, stride_oc,
HAS_ADD: tl.constexpr,
HAS_RES: tl.constexpr,
SCALE: tl.constexpr,
BL: tl.constexpr,
BC: tl.constexpr,
):
pid_t = tl.program_id(0).to(tl.int64)
pid_c = tl.program_id(1).to(tl.int64)
offs_t = pid_t * BL + tl.arange(0, BL).to(tl.int64)
offs_c = pid_c * BC + tl.arange(0, BC).to(tl.int64)
t_m = offs_t < T
c_m = offs_c < C
m = t_m[:, None] & c_m[None, :]
d0 = tl.load(DOC_ptr + offs_t, mask=t_m, other=-2)
valid_doc = d0 >= 0
# Static weights [C, 4]: k=0..3 corresponds to lag = 3-k (k=3 is lag 0, k=0 is lag 3)
w0 = tl.load(W_ptr + offs_c * stride_wc + 0 * stride_wk, mask=c_m, other=0.0).to(tl.float32)
w1 = tl.load(W_ptr + offs_c * stride_wc + 1 * stride_wk, mask=c_m, other=0.0).to(tl.float32)
w2 = tl.load(W_ptr + offs_c * stride_wc + 2 * stride_wk, mask=c_m, other=0.0).to(tl.float32)
w3 = tl.load(W_ptr + offs_c * stride_wc + 3 * stride_wk, mask=c_m, other=0.0).to(tl.float32)
x0 = tl.load(X_ptr + offs_t[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m, other=0.0).to(tl.float32)
acc = x0 * (1.0 + w3[None, :])
# lag 1 -> k=2
t1 = offs_t - 1
ok1 = t_m & (t1 >= 0) & valid_doc
d1 = tl.load(DOC_ptr + tl.maximum(t1, 0), mask=ok1, other=-3)
m1 = (ok1 & (d1 == d0))[:, None] & c_m[None, :]
x1 = tl.load(X_ptr + tl.maximum(t1, 0)[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m1, other=0.0).to(tl.float32)
acc += x1 * w2[None, :]
# lag 2 -> k=1
t2 = offs_t - 2
ok2 = t_m & (t2 >= 0) & valid_doc
d2 = tl.load(DOC_ptr + tl.maximum(t2, 0), mask=ok2, other=-3)
m2 = (ok2 & (d2 == d0))[:, None] & c_m[None, :]
x2 = tl.load(X_ptr + tl.maximum(t2, 0)[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m2, other=0.0).to(tl.float32)
acc += x2 * w1[None, :]
# lag 3 -> k=0
t3 = offs_t - 3
ok3 = t_m & (t3 >= 0) & valid_doc
d3 = tl.load(DOC_ptr + tl.maximum(t3, 0), mask=ok3, other=-3)
m3 = (ok3 & (d3 == d0))[:, None] & c_m[None, :]
x3 = tl.load(X_ptr + tl.maximum(t3, 0)[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m3, other=0.0).to(tl.float32)
acc += x3 * w0[None, :]
y = acc * SCALE
if HAS_ADD:
y = y + tl.load(ADD_ptr + offs_t[:, None] * stride_ot + offs_c[None, :] * stride_oc, mask=m, other=0.0).to(tl.float32)
if HAS_RES:
y = y + tl.load(RES_ptr + offs_t[:, None] * stride_ot + offs_c[None, :] * stride_oc, mask=m, other=0.0).to(tl.float32)
tl.store(OUT_ptr + offs_t[:, None] * stride_ot + offs_c[None, :] * stride_oc, y.to(OUT_ptr.dtype.element_ty), mask=m)
def triton_doc_sconv_static(
x: torch.Tensor, # [T, C]
weight: torch.Tensor, # [C, 4]
doc_ids: torch.Tensor, # [T] int32
out: Optional[torch.Tensor] = None,
addend: Optional[torch.Tensor] = None,
residual: Optional[torch.Tensor] = None,
out_dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
T, C = x.shape
if out is None:
out = torch.empty((T, C), dtype=out_dtype or x.dtype, device=x.device)
if not x.is_cuda:
# Exact CPU reference
xf = x.float()
wf = weight.float()
acc = xf * (1.0 + wf[:, 3][None, :])
for lag, k in ((1, 2), (2, 1), (3, 0)):
if lag < T:
same = ((doc_ids[lag:] >= 0) & (doc_ids[lag:] == doc_ids[:-lag])).float()[:, None]
acc[lag:] = acc[lag:] + xf[:-lag] * wf[:, k][None, :] * same
y = acc * _INV_SQRT5
if addend is not None:
y = y + addend.float()
if residual is not None:
y = y + residual.float()
out.copy_(y.to(out.dtype))
return out
# Accept strided x directly (stride(1) == 1) without .contiguous() copy!
x_c = x if x.stride(1) == 1 else x.contiguous()
w_c = weight.contiguous()
d_c = doc_ids.contiguous()
add_c = addend if (addend is not None and addend.stride(1) == 1) else (addend.contiguous() if addend is not None else out)
res_c = residual if (residual is not None and residual.stride(1) == 1) else (residual.contiguous() if residual is not None else out)
BL, BC = 32, 256
grid = (triton.cdiv(T, BL), triton.cdiv(C, BC))
_doc_sconv_static_kernel[grid](
x_c, w_c, d_c, out, add_c, res_c,
T, C,
x_c.stride(0), x_c.stride(1),
w_c.stride(0), w_c.stride(1),
out.stride(0), out.stride(1),
HAS_ADD=(addend is not None),
HAS_RES=(residual is not None),
SCALE=_INV_SQRT5,
BL=BL, BC=BC, num_warps=4,
)
return out
@_maybe_triton_jit
def _doc_sconv_dynamic_kernel(
X_ptr, SW_ptr, DYN_ptr, DOC_ptr, OUT_ptr,
T, C,
stride_xt, stride_xc,
stride_sw0, stride_sw1,
stride_dt, stride_dc,
stride_ot, stride_oc,
HEAD_DIM: tl.constexpr,
SCALE: tl.constexpr,
BL: tl.constexpr,
BC: tl.constexpr,
):
pid_t = tl.program_id(0).to(tl.int64)
pid_c = tl.program_id(1).to(tl.int64)
offs_t = pid_t * BL + tl.arange(0, BL).to(tl.int64)
offs_c = pid_c * BC + tl.arange(0, BC).to(tl.int64)
t_m = offs_t < T
c_m = offs_c < C
m = t_m[:, None] & c_m[None, :]
heads = offs_c // HEAD_DIM
d0 = tl.load(DOC_ptr + offs_t, mask=t_m, other=-2)
valid_doc = d0 >= 0
# Dynamic weights: lag = 0..3 -> static_w[lag, c] + dyn[t, head*4 + lag]
x0 = tl.load(X_ptr + offs_t[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m, other=0.0).to(tl.float32)
sw0 = tl.load(SW_ptr + 0 * stride_sw0 + offs_c * stride_sw1, mask=c_m, other=0.0).to(tl.float32)
dy0 = tl.load(DYN_ptr + offs_t[:, None] * stride_dt + (heads * 4 + 0)[None, :] * stride_dc, mask=m, other=0.0).to(tl.float32)
acc = x0 * (1.0 + sw0[None, :] + dy0)
# lag 1
t1 = offs_t - 1
ok1 = t_m & (t1 >= 0) & valid_doc
d1 = tl.load(DOC_ptr + tl.maximum(t1, 0), mask=ok1, other=-3)
m1 = (ok1 & (d1 == d0))[:, None] & c_m[None, :]
x1 = tl.load(X_ptr + tl.maximum(t1, 0)[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m1, other=0.0).to(tl.float32)
sw1 = tl.load(SW_ptr + 1 * stride_sw0 + offs_c * stride_sw1, mask=c_m, other=0.0).to(tl.float32)
dy1 = tl.load(DYN_ptr + offs_t[:, None] * stride_dt + (heads * 4 + 1)[None, :] * stride_dc, mask=m, other=0.0).to(tl.float32)
acc += x1 * (sw1[None, :] + dy1)
# lag 2
t2 = offs_t - 2
ok2 = t_m & (t2 >= 0) & valid_doc
d2 = tl.load(DOC_ptr + tl.maximum(t2, 0), mask=ok2, other=-3)
m2 = (ok2 & (d2 == d0))[:, None] & c_m[None, :]
x2 = tl.load(X_ptr + tl.maximum(t2, 0)[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m2, other=0.0).to(tl.float32)
sw2 = tl.load(SW_ptr + 2 * stride_sw0 + offs_c * stride_sw1, mask=c_m, other=0.0).to(tl.float32)
dy2 = tl.load(DYN_ptr + offs_t[:, None] * stride_dt + (heads * 4 + 2)[None, :] * stride_dc, mask=m, other=0.0).to(tl.float32)
acc += x2 * (sw2[None, :] + dy2)
# lag 3
t3 = offs_t - 3
ok3 = t_m & (t3 >= 0) & valid_doc
d3 = tl.load(DOC_ptr + tl.maximum(t3, 0), mask=ok3, other=-3)
m3 = (ok3 & (d3 == d0))[:, None] & c_m[None, :]
x3 = tl.load(X_ptr + tl.maximum(t3, 0)[:, None] * stride_xt + offs_c[None, :] * stride_xc, mask=m3, other=0.0).to(tl.float32)
sw3 = tl.load(SW_ptr + 3 * stride_sw0 + offs_c * stride_sw1, mask=c_m, other=0.0).to(tl.float32)
dy3 = tl.load(DYN_ptr + offs_t[:, None] * stride_dt + (heads * 4 + 3)[None, :] * stride_dc, mask=m, other=0.0).to(tl.float32)
acc += x3 * (sw3[None, :] + dy3)
y = acc * SCALE
tl.store(OUT_ptr + offs_t[:, None] * stride_ot + offs_c[None, :] * stride_oc, y.to(OUT_ptr.dtype.element_ty), mask=m)
def triton_doc_sconv_dynamic(
x: torch.Tensor, # [T, C]
static_w: torch.Tensor, # [4, C]
dyn: torch.Tensor, # [T, H_kv * 4]
doc_ids: torch.Tensor, # [T] int32
head_dim: int = 128,
) -> torch.Tensor:
T, C = x.shape
out = torch.empty_like(x)
if not x.is_cuda:
xf = x.float()
sw = static_w.float()
H = C // head_dim
df = dyn.float().view(T, H, 4)
acc = xf.clone()
for lag in range(4):
w_eff = sw[lag][None, :] + df[:, :, lag].repeat_interleave(head_dim, dim=-1)
if lag == 0:
acc = acc + xf * w_eff
elif lag < T:
same = ((doc_ids[lag:] >= 0) & (doc_ids[lag:] == doc_ids[:-lag])).float()[:, None]
acc[lag:] = acc[lag:] + xf[:-lag] * w_eff[lag:] * same
return (acc * _INV_SQRT9).to(x.dtype)
x_c = x if x.stride(1) == 1 else x.contiguous()
sw_c = static_w.contiguous()
dy_c = dyn if dyn.stride(1) == 1 else dyn.contiguous()
d_c = doc_ids.contiguous()
BL, BC = 32, 128
grid = (triton.cdiv(T, BL), triton.cdiv(C, BC))
_doc_sconv_dynamic_kernel[grid](
x_c, sw_c, dy_c, d_c, out,
T, C,
x_c.stride(0), x_c.stride(1),
sw_c.stride(0), sw_c.stride(1),
dy_c.stride(0), dy_c.stride(1),
out.stride(0), out.stride(1),
HEAD_DIM=head_dim,
SCALE=_INV_SQRT9,
BL=BL, BC=BC, num_warps=4,
)
return out
# ---------------- Compiled PyTorch ops (Blackwell TorchInductor) ----------------
def _rms_norm_w_impl(x2d: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
xf = x2d.float()
y = xf * torch.rsqrt(xf.square().mean(dim=-1, keepdim=True) + eps) * weight.float()
return y.to(x2d.dtype)
def _rms_norm_now_impl(x2d: torch.Tensor, eps: float) -> torch.Tensor:
xf = x2d.float()
y = xf * torch.rsqrt(xf.square().mean(dim=-1, keepdim=True) + eps)
return y.to(x2d.dtype)
compiled_rms_norm_w = torch.compile(_rms_norm_w_impl, dynamic=True)
compiled_rms_norm_now = torch.compile(_rms_norm_now_impl, dynamic=True)
def i2m_rms_norm(
x: torch.Tensor,
weight: Optional[torch.Tensor],
eps: float = 1e-6,
out_dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
if x.is_cuda and (out_dtype is None or out_dtype == x.dtype):
orig_shape = x.shape
x2d = x.reshape(-1, orig_shape[-1]).contiguous()
if weight is not None:
return compiled_rms_norm_w(x2d, weight, eps).view(orig_shape)
return compiled_rms_norm_now(x2d, eps).view(orig_shape)
xf = x.float()
y = xf * torch.rsqrt(xf.square().mean(dim=-1, keepdim=True) + eps)
if weight is not None:
y = y * weight.float()
return y.to(out_dtype or x.dtype)
def _l2_clip_raw_impl(x3d: torch.Tensor, thresh: float, eps: float) -> torch.Tensor:
xf = x3d.float()
n = torch.linalg.vector_norm(xf, dim=-1, keepdim=True)
return (xf * (thresh / (n + eps)).clamp(max=1.0)).to(x3d.dtype)
def _l2_clip_sc_impl(x3d: torch.Tensor, scale2d: torch.Tensor, thresh: float, eps: float) -> torch.Tensor:
xf = x3d.float() * scale2d.float().unsqueeze(0)
n = torch.linalg.vector_norm(xf, dim=-1, keepdim=True)
return (xf * (thresh / (n + eps)).clamp(max=1.0)).to(x3d.dtype)
def _l2_clip_sc_tau_impl(
x3d: torch.Tensor, scale2d: torch.Tensor, thresh: float, eps: float, tau1d: torch.Tensor
) -> torch.Tensor:
xf = x3d.float() * scale2d.float().unsqueeze(0)
n = torch.linalg.vector_norm(xf, dim=-1, keepdim=True)
y = xf * (thresh / (n + eps)).clamp(max=1.0) * tau1d.float().view(-1, 1, 1)
return y.to(x3d.dtype)
compiled_l2_clip_raw = torch.compile(_l2_clip_raw_impl, dynamic=True)
compiled_l2_clip_sc = torch.compile(_l2_clip_sc_impl, dynamic=True)
compiled_l2_clip_sc_tau = torch.compile(_l2_clip_sc_tau_impl, dynamic=True)
def i2m_l2_clip(
x: torch.Tensor,
scale: Optional[torch.Tensor],
thresh: float,
eps: float = 1e-6,
tau: Optional[torch.Tensor] = None,
) -> torch.Tensor:
if x.is_cuda:
orig_shape = x.shape
x3d = x.reshape(-1, orig_shape[-2], orig_shape[-1])
if scale is None and tau is None:
return compiled_l2_clip_raw(x3d, thresh, eps).view(orig_shape)
if scale is not None and tau is None:
return compiled_l2_clip_sc(x3d, scale.reshape(orig_shape[-2], orig_shape[-1]), thresh, eps).view(orig_shape)
if scale is not None and tau is not None:
return compiled_l2_clip_sc_tau(
x3d, scale.reshape(orig_shape[-2], orig_shape[-1]), thresh, eps, tau.reshape(-1)
).view(orig_shape)
xf = x.float()
if scale is not None:
xf = xf * scale.float()
n = torch.linalg.vector_norm(xf, dim=-1, keepdim=True)
y = xf * (thresh / (n + eps)).clamp(max=1.0)
if tau is not None:
y = y * tau.float()
return y.to(x.dtype)
def _compute_log_scaling_tau(pos: torch.Tensor, n_floor: int = 8192, alpha: float = 0.1) -> torch.Tensor:
ratio = ((pos.float() + 1.0) / float(n_floor)).clamp(min=1.0)
return 1.0 + float(alpha) * torch.log(ratio)
compiled_log_scaling_tau = torch.compile(_compute_log_scaling_tau, dynamic=True)
def compute_log_scaling_tau(pos: torch.Tensor, n_floor: int = 8192, alpha: float = 0.1) -> torch.Tensor:
if pos.is_cuda:
return compiled_log_scaling_tau(pos, n_floor, alpha)
return _compute_log_scaling_tau(pos, n_floor, alpha)
def _gate_sink_impl(
attn_out: torch.Tensor, # [N, H, D]
gate: torch.Tensor, # [N, H, D]
lse: torch.Tensor, # [N, H]
sink: torch.Tensor, # [N, H]
) -> torch.Tensor:
o = attn_out.float()
o = o * torch.sigmoid(gate.float())
o = o * torch.sigmoid(lse.float() - sink.float()).unsqueeze(-1)
return o.to(attn_out.dtype)
compiled_gate_sink = torch.compile(_gate_sink_impl, dynamic=True)
def i2m_gate_sink(
attn_out: torch.Tensor,
gate: torch.Tensor,
lse: torch.Tensor,
sink: torch.Tensor,
) -> torch.Tensor:
if attn_out.is_cuda:
orig_shape = attn_out.shape
H, D = orig_shape[-2], orig_shape[-1]
return compiled_gate_sink(
attn_out.reshape(-1, H, D),
gate.reshape(-1, H, D),
lse.reshape(-1, H),
sink.reshape(-1, H),
).view(orig_shape)
return _gate_sink_impl(attn_out, gate, lse, sink)
@_maybe_triton_jit
def _triton_tanh(x):
ax = tl.abs(x)
e = tl.exp(-2.0 * ax)
t = (1.0 - e) / (1.0 + e)
return tl.where(x >= 0.0, t, -t)
@_maybe_triton_jit
def _situ_interleaved_kernel(
Y13_ptr, W_ptr, OUT_ptr,
N, I,
stride_yn, stride_on,
GATE_CAP: tl.constexpr,
UP_CAP: tl.constexpr,
BN: tl.constexpr,
BI: tl.constexpr,
):
pid_n = tl.program_id(0).to(tl.int64)
pid_i = tl.program_id(1).to(tl.int64)
offs_n = pid_n * BN + tl.arange(0, BN).to(tl.int64)
offs_i = pid_i * BI + tl.arange(0, BI).to(tl.int64)
n_m = offs_n < N
i_m = offs_i < I
m = n_m[:, None] & i_m[None, :]
base = offs_n[:, None] * stride_yn + (offs_i * 2)[None, :]
g = tl.load(Y13_ptr + base, mask=m, other=0.0).to(tl.float32)
u = tl.load(Y13_ptr + base + 1, mask=m, other=0.0).to(tl.float32)
w = tl.load(W_ptr + offs_n, mask=n_m, other=0.0).to(tl.float32)[:, None]
sig = tl.sigmoid(g)
g_c = GATE_CAP * _triton_tanh(g * (1.0 / GATE_CAP))
u_c = UP_CAP * _triton_tanh(u * (1.0 / UP_CAP))
out = (g_c * sig) * u_c * w
tl.store(OUT_ptr + offs_n[:, None] * stride_on + offs_i[None, :], out.to(OUT_ptr.dtype.element_ty), mask=m)
def i2m_situ_interleaved(
y13: torch.Tensor,
weights: torch.Tensor,
gate_cap: float = 4.0,
up_cap: float = 25.0,
) -> torch.Tensor:
if y13.is_cuda and triton is not None:
N, two_I = y13.shape
I = two_I // 2
y_c = y13.contiguous()
w_c = weights.contiguous()
out = torch.empty((N, I), dtype=y13.dtype, device=y13.device)
BN, BI = 32, 128
grid = (triton.cdiv(N, BN), triton.cdiv(I, BI))
_situ_interleaved_kernel[grid](
y_c, w_c, out, N, I, y_c.stride(0), out.stride(0),
GATE_CAP=float(gate_cap), UP_CAP=float(up_cap),
BN=BN, BI=BI, num_warps=4,
)
return out
yf = y13.float()
g = yf[:, 0::2]
u = yf[:, 1::2]
sig = torch.sigmoid(g)
g = gate_cap * torch.tanh(g / gate_cap)
u = up_cap * torch.tanh(u / up_cap)
return ((g * sig) * u * weights.float().unsqueeze(-1)).to(y13.dtype)
@_maybe_triton_jit
def _moe_unpermute_sum_kernel(
Y2_ptr, INV_ptr, OUT_ptr,
T, H,
stride_yn, stride_ot,
TOPK: tl.constexpr,
BH: tl.constexpr,
):
t = tl.program_id(0).to(tl.int64)
pid_h = tl.program_id(1)
cols = pid_h * BH + tl.arange(0, BH)
mask = cols < H
acc = tl.zeros((BH,), dtype=tl.float32)
inv_base = INV_ptr + t * TOPK
for k in tl.static_range(TOPK):
idx = tl.load(inv_base + k).to(tl.int64)
row = tl.load(Y2_ptr + idx * stride_yn + cols, mask=mask, other=0.0).to(tl.float32)
acc += row
tl.store(OUT_ptr + t * stride_ot + cols, acc.to(OUT_ptr.dtype.element_ty), mask=mask)
def triton_moe_unpermute_sum(
y2: torch.Tensor, # [T*topk, H] bf16
inv_2d: torch.Tensor, # [T, topk] int32/int64
out_dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
T, topk = inv_2d.shape
H = y2.shape[1]
out = torch.empty((T, H), dtype=out_dtype or y2.dtype, device=y2.device)
if y2.is_cuda and triton is not None:
y_c = y2.contiguous()
inv_c = inv_2d.contiguous()
BH = 256
grid = (T, triton.cdiv(H, BH))
_moe_unpermute_sum_kernel[grid](
y_c, inv_c, out, T, H, y_c.stride(0), out.stride(0),
TOPK=topk, BH=BH, num_warps=4,
)
return out
out.copy_(y2[inv_2d.long()].float().sum(dim=1).to(out.dtype))
return out
@_maybe_triton_jit
def _attn_res_kernel(
STACK_ptr, LAST_ptr, ADD_ptr, Q_ptr, NW_ptr, OUT_ptr,
T, D,
stride_sn, stride_st,
stride_lt, stride_at,
stride_qq, stride_nq,
stride_oq, stride_ot,
N_SRC: tl.constexpr,
HAS_ADD: tl.constexpr,
HAS_NORM: tl.constexpr,
EPS: tl.constexpr,
BD: tl.constexpr,
):
t = tl.program_id(0).to(tl.int64)
q = tl.program_id(1).to(tl.int64)
cols = tl.arange(0, BD)
mask = cols < D
inv_D = 1.0 / D
q_vec = tl.load(Q_ptr + q * stride_qq + cols, mask=mask, other=0.0).to(tl.float32)
# Pass 1: compute inv_rms & logits for each source n in 0..N_SRC-1 (N_SRC <= 5)
# Keep s0..s4 norms and logits in scalar registers; reloads hit L1/L2 cache!
inv0 = 0.0; l0 = -1e30
inv1 = 0.0; l1 = -1e30
inv2 = 0.0; l2 = -1e30
inv3 = 0.0; l3 = -1e30
inv4 = 0.0; l4 = -1e30
# Source 0..N_SRC-2 from STACK, last source (N_SRC-1) from LAST (+ ADD)
if N_SRC == 1:
s = tl.load(LAST_ptr + t * stride_lt + cols, mask=mask, other=0.0).to(tl.float32)
if HAS_ADD:
s = s + tl.load(ADD_ptr + t * stride_at + cols, mask=mask, other=0.0).to(tl.float32)
inv0 = tl.rsqrt(tl.sum(s * s, axis=0) * inv_D + EPS)
mixed = s * inv0
else:
if N_SRC >= 2:
s0 = tl.load(STACK_ptr + 0 * stride_sn + t * stride_st + cols, mask=mask, other=0.0).to(tl.float32)
inv0 = tl.rsqrt(tl.sum(s0 * s0, axis=0) * inv_D + EPS)
l0 = tl.sum((s0 * inv0) * q_vec, axis=0)
if N_SRC >= 3:
s1 = tl.load(STACK_ptr + 1 * stride_sn + t * stride_st + cols, mask=mask, other=0.0).to(tl.float32)
inv1 = tl.rsqrt(tl.sum(s1 * s1, axis=0) * inv_D + EPS)
l1 = tl.sum((s1 * inv1) * q_vec, axis=0)
if N_SRC >= 4:
s2 = tl.load(STACK_ptr + 2 * stride_sn + t * stride_st + cols, mask=mask, other=0.0).to(tl.float32)
inv2 = tl.rsqrt(tl.sum(s2 * s2, axis=0) * inv_D + EPS)
l2 = tl.sum((s2 * inv2) * q_vec, axis=0)
if N_SRC >= 5:
s3 = tl.load(STACK_ptr + 3 * stride_sn + t * stride_st + cols, mask=mask, other=0.0).to(tl.float32)
inv3 = tl.rsqrt(tl.sum(s3 * s3, axis=0) * inv_D + EPS)
l3 = tl.sum((s3 * inv3) * q_vec, axis=0)
sl = tl.load(LAST_ptr + t * stride_lt + cols, mask=mask, other=0.0).to(tl.float32)
if HAS_ADD:
sl = sl + tl.load(ADD_ptr + t * stride_at + cols, mask=mask, other=0.0).to(tl.float32)
inv_l = tl.rsqrt(tl.sum(sl * sl, axis=0) * inv_D + EPS)
ll = tl.sum((sl * inv_l) * q_vec, axis=0)
if N_SRC == 2:
inv1 = inv_l; l1 = ll
elif N_SRC == 3:
inv2 = inv_l; l2 = ll
elif N_SRC == 4:
inv3 = inv_l; l3 = ll
else:
inv4 = inv_l; l4 = ll
m = tl.maximum(l0, l1)
if N_SRC >= 3:
m = tl.maximum(m, l2)
if N_SRC >= 4:
m = tl.maximum(m, l3)
if N_SRC >= 5:
m = tl.maximum(m, l4)
e0 = tl.exp(l0 - m)
e1 = tl.exp(l1 - m)
e2 = tl.exp(l2 - m) if N_SRC >= 3 else 0.0
e3 = tl.exp(l3 - m) if N_SRC >= 4 else 0.0
e4 = tl.exp(l4 - m) if N_SRC >= 5 else 0.0
inv_sum = 1.0 / (e0 + e1 + e2 + e3 + e4)
p0 = e0 * inv_sum
p1 = e1 * inv_sum
p2 = e2 * inv_sum
p3 = e3 * inv_sum
p4 = e4 * inv_sum
# Pass 2: weighted sum (hits L1/L2 cache!)
if N_SRC == 2:
mixed = (s0 * inv0) * p0 + (sl * inv_l) * p1
elif N_SRC == 3:
mixed = (s0 * inv0) * p0 + (s1 * inv1) * p1 + (sl * inv_l) * p2
elif N_SRC == 4:
mixed = (s0 * inv0) * p0 + (s1 * inv1) * p1 + (s2 * inv2) * p2 + (sl * inv_l) * p3
else:
mixed = (s0 * inv0) * p0 + (s1 * inv1) * p1 + (s2 * inv2) * p2 + (s3 * inv3) * p3 + (sl * inv_l) * p4
if HAS_NORM:
inv_m = tl.rsqrt(tl.sum(mixed * mixed, axis=0) * inv_D + EPS)
nw = tl.load(NW_ptr + q * stride_nq + cols, mask=mask, other=0.0).to(tl.float32)
out_v = mixed * inv_m * nw
tl.store(OUT_ptr + q * stride_oq + t * stride_ot + cols, out_v.to(OUT_ptr.dtype.element_ty), mask=mask)
else:
tl.store(OUT_ptr + q * stride_oq + t * stride_ot + cols, mixed.to(OUT_ptr.dtype.element_ty), mask=mask)
def i2m_attn_res(
stack_slice: torch.Tensor, # [N_stack, T, D] fp32
last: torch.Tensor, # [T, D] fp32
addend: Optional[torch.Tensor], # [T, D] fp32 or None
queries: torch.Tensor, # [Q, D] fp32
norm_w: Optional[torch.Tensor], # [Q, D] bf16 or None
eps: float = 1e-6,
) -> torch.Tensor:
N_stack = stack_slice.shape[0]
N_src = N_stack + 1
T, D = last.shape
Q = queries.shape[0]
if last.is_cuda and triton is not None and N_src <= 5:
out_dtype = norm_w.dtype if norm_w is not None else torch.float32
out = torch.empty((Q, T, D), dtype=out_dtype, device=last.device)
st_c = stack_slice if N_stack > 0 else last.unsqueeze(0)
add_c = addend if addend is not None else last
nw_c = norm_w if norm_w is not None else queries
BD = triton.next_power_of_2(D)
_attn_res_kernel[(T, Q)](
st_c, last, add_c, queries, nw_c, out,
T, D,
st_c.stride(0), st_c.stride(1),
last.stride(0), add_c.stride(0),
queries.stride(0), nw_c.stride(0),
out.stride(0), out.stride(1),
N_SRC=N_src,
HAS_ADD=(addend is not None),
HAS_NORM=(norm_w is not None),
EPS=eps,
BD=BD,
num_warps=16,
)
return out
# CPU / fallback reference
last_eff = last if addend is None else (last + addend)
sources = last_eff.unsqueeze(0) if N_stack == 0 else torch.cat([stack_slice, last_eff.unsqueeze(0)], dim=0)
sn = sources * torch.rsqrt(sources.square().mean(dim=-1, keepdim=True) + eps)
logits = torch.einsum("ntd,qd->qnt", sn, queries)
probs = torch.softmax(logits, dim=1)
mixed = torch.einsum("qnt,ntd->qtd", probs, sn)
if norm_w is None:
return mixed
mixed_n = mixed * torch.rsqrt(mixed.square().mean(dim=-1, keepdim=True) + eps)
return (mixed_n * norm_w.float().unsqueeze(1)).to(norm_w.dtype)
@_maybe_triton_jit
def _loop_blend_pair_kernel(
DEST_ptr, MSG_ptr, PAIR_ptr,
T, D,
stride_ds, stride_dt,
stride_ms, stride_mt,
stride_ps, stride_pt,
EPS: tl.constexpr,
BD: tl.constexpr,
):
t = tl.program_id(0).to(tl.int64)
s = tl.program_id(1).to(tl.int64)
cols = tl.arange(0, BD)
mask = cols < D
inv_D = 1.0 / D
d = tl.load(DEST_ptr + s * stride_ds + t * stride_dt + cols, mask=mask, other=0.0).to(tl.float32)
m = tl.load(MSG_ptr + s * stride_ms + t * stride_mt + cols, mask=mask, other=0.0).to(tl.float32)
dn = d * tl.rsqrt(tl.sum(d * d, axis=0) * inv_D + EPS)
mn = m * tl.rsqrt(tl.sum(m * m, axis=0) * inv_D + EPS)
p_base = PAIR_ptr + s * stride_ps + t * stride_pt
tl.store(p_base + cols, dn.to(PAIR_ptr.dtype.element_ty), mask=mask)
tl.store(p_base + D + cols, mn.to(PAIR_ptr.dtype.element_ty), mask=mask)
@_maybe_triton_jit
def _loop_blend_out_kernel(
DEST_ptr, MSG_ptr, GF_ptr, NW_ptr, OUT_ptr,
T, D,
stride_ds, stride_dt,
stride_ms, stride_mt,
stride_gs, stride_gt,
stride_ns,
stride_os, stride_ot,
EPS: tl.constexpr,
BD: tl.constexpr,
):
t = tl.program_id(0).to(tl.int64)
s = tl.program_id(1).to(tl.int64)
cols = tl.arange(0, BD)
mask = cols < D
inv_D = 1.0 / D
d = tl.load(DEST_ptr + s * stride_ds + t * stride_dt + cols, mask=mask, other=0.0).to(tl.float32)
m = tl.load(MSG_ptr + s * stride_ms + t * stride_mt + cols, mask=mask, other=0.0).to(tl.float32)
g_base = GF_ptr + s * stride_gs + t * stride_gt
gg = tl.load(g_base + cols, mask=mask, other=0.0).to(tl.float32)
gf = tl.load(g_base + D + cols, mask=mask, other=0.0).to(tl.float32)
gain = _triton_tanh(gg)
forget = _triton_tanh(gf)
bl = (1.0 - forget) * d + gain * m
inv_b = tl.rsqrt(tl.sum(bl * bl, axis=0) * inv_D + EPS)
nw = tl.load(NW_ptr + s * stride_ns + cols, mask=mask, other=0.0).to(tl.float32)
out = bl * inv_b * nw
tl.store(OUT_ptr + s * stride_os + t * stride_ot + cols, out.to(OUT_ptr.dtype.element_ty), mask=mask)
def i2m_loop_blend(
dest: torch.Tensor, # [S, T, D] fp32 (may be expanded view!)
msg: torch.Tensor, # [S, T, D] fp32
down_w: torch.Tensor, # [S, R, 2D] bf16
up_w: torch.Tensor, # [S, 2D, R] bf16
norm_w: torch.Tensor, # [S, D] bf16 (may be expanded view!)
eps: float = 1e-6,
) -> torch.Tensor:
S, T, D = dest.shape
if dest.is_cuda and triton is not None:
BD = triton.next_power_of_2(D)
pair = torch.empty((S, T, 2 * D), dtype=down_w.dtype, device=dest.device)
_loop_blend_pair_kernel[(T, S)](
dest, msg, pair, T, D,
dest.stride(0), dest.stride(1),
msg.stride(0), msg.stride(1),
pair.stride(0), pair.stride(1),
EPS=eps, BD=BD, num_warps=16,
)
hid = torch.bmm(pair, down_w.transpose(1, 2))
del pair
gf = torch.bmm(hid, up_w.transpose(1, 2)) # [S, T, 2D] bf16!
del hid
out = torch.empty((S, T, D), dtype=norm_w.dtype, device=dest.device)
_loop_blend_out_kernel[(T, S)](
dest, msg, gf, norm_w, out, T, D,
dest.stride(0), dest.stride(1),
msg.stride(0), msg.stride(1),
gf.stride(0), gf.stride(1),
norm_w.stride(0),
out.stride(0), out.stride(1),
EPS=eps, BD=BD, num_warps=16,
)
return out
dn = dest * torch.rsqrt(dest.square().mean(dim=-1, keepdim=True) + eps)
mn = msg * torch.rsqrt(msg.square().mean(dim=-1, keepdim=True) + eps)
pair = torch.cat([dn, mn], dim=-1).to(down_w.dtype)
hid = torch.bmm(pair, down_w.transpose(1, 2))
gf = torch.bmm(hid, up_w.transpose(1, 2)).float()
gain = torch.tanh(gf[..., :D])
forget = torch.tanh(gf[..., D:])
bl = (1.0 - forget) * dest + gain * msg
bl_n = bl * torch.rsqrt(bl.square().mean(dim=-1, keepdim=True) + eps)
return (bl_n * norm_w.float().unsqueeze(1)).to(norm_w.dtype)
def _router_impl(
x: torch.Tensor, # [T, H] bf16
gate_w: torch.Tensor, # [E, H] bf16
gate_b: torch.Tensor, # [E] fp32
topk: int = 8,
route_scale: float = 8.0,
) -> Tuple[torch.Tensor, torch.Tensor]:
logits = F.linear(x, gate_w).float()
sel = torch.sigmoid(logits) + gate_b.unsqueeze(0)
top_idx = torch.topk(sel, topk, dim=-1).indices
top_log = logits.gather(1, top_idx)
weights = torch.softmax(F.logsigmoid(top_log), dim=-1) * route_scale
return top_idx, weights
compiled_router = torch.compile(_router_impl, dynamic=True)
@_maybe_triton_jit
def _l2_clip_to_bhld_kernel(
X_ptr, SC_ptr, TAU_ptr, OUT_ptr,
B, L,
stride_xt,
stride_sch,
stride_ob, stride_oh, stride_ol,
H: tl.constexpr,
D: tl.constexpr,
HAS_SCALE: tl.constexpr,
HAS_TAU: tl.constexpr,
THRESH: tl.constexpr,
EPS: tl.constexpr,
BL: tl.constexpr,
):
pid_l = tl.program_id(0).to(tl.int64)
pid_bh = tl.program_id(1).to(tl.int64)
b = pid_bh // H
h = pid_bh - b * H
offs_l = pid_l * BL + tl.arange(0, BL).to(tl.int64)
offs_d = tl.arange(0, D).to(tl.int64)
l_m = offs_l < L
t = b * L + offs_l
x = tl.load(X_ptr + t[:, None] * stride_xt + (h * D + offs_d)[None, :], mask=l_m[:, None], other=0.0).to(tl.float32)
if HAS_SCALE:
sc = tl.load(SC_ptr + h * stride_sch + offs_d).to(tl.float32)
x = x * sc[None, :]
n = tl.sqrt(tl.sum(x * x, axis=1, keep_dims=True))
fac = tl.minimum(THRESH / (n + EPS), 1.0)
y = x * fac
if HAS_TAU:
tau = tl.load(TAU_ptr + t, mask=l_m, other=1.0).to(tl.float32)[:, None]
y = y * tau
tl.store(
OUT_ptr + b * stride_ob + h * stride_oh + offs_l[:, None] * stride_ol + offs_d[None, :],
y.to(OUT_ptr.dtype.element_ty),
mask=l_m[:, None],
)
def triton_l2_clip_to_bhld(
x_2d: torch.Tensor, # [B*L, H*D] (may be strided along dim 0!)
scale: Optional[torch.Tensor], # [H, D] or None
thresh: float,
eps: float,
tau_flat: Optional[torch.Tensor], # [B*L] fp32 or None
B: int, L: int, H: int, D: int,
) -> torch.Tensor:
out = torch.empty((B, H, L, D), dtype=x_2d.dtype, device=x_2d.device)
if x_2d.is_cuda and triton is not None and x_2d.stride(1) == 1:
sc_c = scale.contiguous() if scale is not None else x_2d
tau_c = tau_flat.contiguous() if tau_flat is not None else x_2d
BL = 32 if D >= 64 else 64
grid = (triton.cdiv(L, BL), B * H)
_l2_clip_to_bhld_kernel[grid](
x_2d, sc_c, tau_c, out,
B, L, x_2d.stride(0),
sc_c.stride(0) if scale is not None else 0,
out.stride(0), out.stride(1), out.stride(2),
H=H, D=D,
HAS_SCALE=(scale is not None),
HAS_TAU=(tau_flat is not None),
THRESH=float(thresh), EPS=float(eps),
BL=BL, num_warps=4,
)
return out
tau_v = None if tau_flat is None else tau_flat.view(B * L, 1, 1)
y = i2m_l2_clip(x_2d.reshape(B * L, H, D), None if scale is None else scale.unsqueeze(0), thresh, eps, tau_v)
return y.view(B, L, H, D).transpose(1, 2).contiguous()
@_maybe_triton_jit
def _rms_norm_to_bhld_kernel(
X_ptr, OUT_ptr,
B, L,
stride_xt,
stride_ob, stride_oh, stride_ol,
H: tl.constexpr,
D: tl.constexpr,
EPS: tl.constexpr,
BL: tl.constexpr,
):
pid_l = tl.program_id(0).to(tl.int64)
pid_bh = tl.program_id(1).to(tl.int64)
b = pid_bh // H
h = pid_bh - b * H
offs_l = pid_l * BL + tl.arange(0, BL).to(tl.int64)
offs_d = tl.arange(0, D).to(tl.int64)
l_m = offs_l < L
t = b * L + offs_l
x = tl.load(X_ptr + t[:, None] * stride_xt + (h * D + offs_d)[None, :], mask=l_m[:, None], other=0.0).to(tl.float32)
inv = tl.rsqrt(tl.sum(x * x, axis=1, keep_dims=True) * (1.0 / D) + EPS)
y = x * inv
tl.store(
OUT_ptr + b * stride_ob + h * stride_oh + offs_l[:, None] * stride_ol + offs_d[None, :],
y.to(OUT_ptr.dtype.element_ty),
mask=l_m[:, None],
)
def triton_rms_norm_to_bhld(
x_2d: torch.Tensor, # [B*L, H*D]
eps: float,
B: int, L: int, H: int, D: int,
) -> torch.Tensor:
out = torch.empty((B, H, L, D), dtype=x_2d.dtype, device=x_2d.device)
if x_2d.is_cuda and triton is not None and x_2d.stride(1) == 1:
BL = 32
grid = (triton.cdiv(L, BL), B * H)
_rms_norm_to_bhld_kernel[grid](
x_2d, out,
B, L, x_2d.stride(0),
out.stride(0), out.stride(1), out.stride(2),
H=H, D=D, EPS=float(eps), BL=BL, num_warps=4,
)
return out
return i2m_rms_norm(x_2d.reshape(B * L, H, D), None, eps).view(B, L, H, D).transpose(1, 2).contiguous()
@_maybe_triton_jit
def _gate_sink_from_bhld_kernel(
AO_ptr, GATE_ptr, LSE_ptr, SINK_ptr, OUT_ptr,
B, L,
stride_ab, stride_ah, stride_al,
stride_gt,
stride_lb, stride_lh,
stride_st,
stride_ot,
H: tl.constexpr,
D: tl.constexpr,
BL: tl.constexpr,
):
pid_l = tl.program_id(0).to(tl.int64)
pid_bh = tl.program_id(1).to(tl.int64)
b = pid_bh // H
h = pid_bh - b * H
offs_l = pid_l * BL + tl.arange(0, BL).to(tl.int64)
offs_d = tl.arange(0, D).to(tl.int64)
l_m = offs_l < L
t = b * L + offs_l
ao = tl.load(AO_ptr + b * stride_ab + h * stride_ah + offs_l[:, None] * stride_al + offs_d[None, :], mask=l_m[:, None], other=0.0).to(tl.float32)
g = tl.load(GATE_ptr + t[:, None] * stride_gt + (h * D + offs_d)[None, :], mask=l_m[:, None], other=0.0).to(tl.float32)
lse = tl.load(LSE_ptr + b * stride_lb + h * stride_lh + offs_l, mask=l_m, other=0.0).to(tl.float32)
sk = tl.load(SINK_ptr + t * stride_st + h, mask=l_m, other=0.0).to(tl.float32)
y = ao * tl.sigmoid(g) * tl.sigmoid(lse - sk)[:, None]
tl.store(
OUT_ptr + t[:, None] * stride_ot + (h * D + offs_d)[None, :],
y.to(OUT_ptr.dtype.element_ty),
mask=l_m[:, None],
)
def triton_gate_sink_from_bhld(
ao_b: torch.Tensor, # [B, H, L, D]
gate_2d: torch.Tensor,# [B*L, H*D] (may be strided along dim 0!)
lse_b: torch.Tensor, # [B, H, L] fp32
sink_2d: torch.Tensor,# [B*L, H] (may be strided along dim 0!)
) -> torch.Tensor:
B, H, L, D = ao_b.shape
out = torch.empty((B * L, H * D), dtype=ao_b.dtype, device=ao_b.device)
if ao_b.is_cuda and triton is not None and gate_2d.stride(1) == 1 and sink_2d.stride(1) == 1:
BL = 32
grid = (triton.cdiv(L, BL), B * H)
_gate_sink_from_bhld_kernel[grid](
ao_b, gate_2d, lse_b, sink_2d, out,
B, L,
ao_b.stride(0), ao_b.stride(1), ao_b.stride(2),
gate_2d.stride(0),
lse_b.stride(0), lse_b.stride(1),
sink_2d.stride(0),
out.stride(0),
H=H, D=D, BL=BL, num_warps=4,
)
return out
ao = ao_b.transpose(1, 2).contiguous().view(B * L, H, D)
lse = lse_b.transpose(1, 2).contiguous().view(B * L, H)
return i2m_gate_sink(ao, gate_2d.reshape(B * L, H, D), lse, sink_2d).view(B * L, H * D)
def i2m_router(
x: torch.Tensor,
gate_w: torch.Tensor,
gate_b: torch.Tensor,
topk: int = 8,
route_scale: float = 8.0,
) -> Tuple[torch.Tensor, torch.Tensor]:
if x.is_cuda:
return compiled_router(x, gate_w, gate_b, topk, route_scale)
return _router_impl(x, gate_w, gate_b, topk, route_scale)