newfla4 / phi_kkt_approx_trace /decoding_one_step.py
msj19's picture
Add files using upload-large-folder tool
901795c verified
Raw History Blame Contribute Delete
16.5 kB
"""Fused Triton kernel for Sigma GKA token-by-token decoding.
Replaces the PyTorch reference recurrence + a separate Simple-GLA launch:
H_kk_t = exp(gk_t) H_kk_{t-1} + k_t k_t^T
q_t_out = a q + b (q H)/F + c (q H^2)/F^2 [+ d (q H^3)/F^3]
q_mix = q + alpha (q_t_out - q)
H_kv_t = exp(g_t) H_kv_{t-1} + k_t v_t^T
o_t = scale * q_mix @ H_kv_t
"""
from typing import Optional, Sequence, Tuple, Union
import torch
import triton
import triton.language as tl
from torch import Tensor
from fla.ops.simple_gla import fused_recurrent_simple_gla
from fla.ops.utils.op import exp
from fla.utils import input_guard
def test_q_kkt_solve_approx_abc(
q,
k,
gk,
# a=1.0,
# b=-0.5,
# c=0.375,
h0=None,
learnable_abc=None,
):
"""
PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2).
We follow the GLA recurrence to build the per-step key-key state
H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action
on q_t by a low-order polynomial in H_t / ||H_t||_F:
q_t_out = a * q_t
+ b * (q_t @ H_t) / ||H_t||_F
+ c * (q_t @ H_t @ H_t) / ||H_t||_F^2
Args:
q: Query tensor with shape [B, T, H, D].
k: Key tensor with shape [B, T, H, D].
gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use.
If None, the gate is treated as 1 (no decay).
a, b, c: Polynomial coefficients. Each may be a scalar or a length-H tensor.
h0: Optional previous key-key state with shape [B, H, D, D] or [H, D, D].
learnable_abc: Optional coefficients as [3] or [H, 3]. Overrides a, b, c.
Returns:
o: Output tensor with shape [B, T, H, D].
states: List of length T, each [B, H, D, D] (the per-step H_t).
fros: List of length T, each [B, H] (per-step Frobenius norm).
"""
B, T, H, D = q.shape
if learnable_abc is not None:
t = learnable_abc
if not torch.is_tensor(t):
t = torch.tensor(list(t), device=q.device, dtype=torch.float32)
else:
t = t.detach().to(device=q.device)
if t.numel() == 3:
a, b, c = t.reshape(3).unbind(0)
elif t.reshape(-1).numel() == H * 3:
t = t.reshape(H, 3)
a, b, c = t[:, 0], t[:, 1], t[:, 2]
else:
raise ValueError(
f"learnable_abc must be [3] or [H, 3] with H={H}, got {tuple(t.shape)}"
)
else:
raise ValueError("learnable_abc must be provided")
def _coeff(x):
if torch.is_tensor(x):
t = x.reshape(-1)
if t.numel() == 1:
t = t.expand(H)
elif t.numel() != H:
raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}")
# [1, H, 1] so it broadcasts with qi / q_state of shape [B, H, D]
return t.to(device=q.device, dtype=torch.float32).view(1, H, 1)
return x
a = _coeff(a)
b = _coeff(b)
c = _coeff(c)
if h0 is None:
state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device)
else:
state = h0.to(device=q.device, dtype=torch.float32)
if state.dim() == 3:
state = state.unsqueeze(0)
if state.shape[0] == 1 and B > 1:
state = state.expand(B, -1, -1, -1).contiguous()
if gk is None:
gkk = torch.ones(B, T, H, dtype=torch.float32, device=q.device)
else:
gkk = torch.exp(gk.float()).float()
outs = []
eps = 1e-12
for i in range(T):
ki = k[:, i, :, :] # [B, H, D]
# GLA-style state update: H_t = exp(g_t) * H_{t-1} + k_t k_t^T
state = gkk[:, i, :].view(B, H, 1, 1) * state + ki.unsqueeze(-1) * ki.unsqueeze(-2)
# Frobenius norm of the current state H_t
F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float() # [B, H, 1]
F_safe = F + eps
qi = q[:, i, :, :].float() # [B, H, D]
q_state = ((qi.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
q_state2 = ((q_state.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
out = (a * qi + b * q_state + c * q_state2).to(q.dtype)
outs.append(out)
fro = F.squeeze(-1)
o = torch.stack(outs, dim=1).to(q.dtype)
return o, state, fro
#############
def test_q_kkt_solve_approx_abcd(q, k, gk, a=1.0, b=-0.5, c=0.375, d=-0.3125,h0=None,learnable_abc=None):
"""
PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2).
We follow the GLA recurrence to build the per-step key-key state
H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action
on q_t by a cubic polynomial in H_t / ||H_t||_F:
q_t_out = a * q_t
+ b * (q_t @ H_t) / ||H_t||_F
+ c * (q_t @ H_t @ H_t) / ||H_t||_F^2
+ d * (q_t @ H_t @ H_t @ H_t) / ||H_t||_F^3
Args:
q: Query tensor with shape [B, T, H, D].
k: Key tensor with shape [B, T, H, D].
gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use.
a, b, c, d: Polynomial coefficients. Each may be a scalar or a length-H tensor.
Returns:
o: Output tensor with shape [B, T, H, D].
states: List of length T, each [B, H, D, D] (the per-step H_t).
fros: List of length T, each [B, H] (per-step Frobenius norm).
"""
B, T, H, D = q.shape
if learnable_abc is not None:
t = learnable_abc
if not torch.is_tensor(t):
t = torch.tensor(list(t), device=q.device, dtype=torch.float32)
else:
t = t.detach().to(device=q.device)
if t.numel() == 4:
a, b, c, d = t.reshape(4).unbind(0)
elif t.reshape(-1).numel() == H * 4:
t = t.reshape(H, 4)
a, b, c, d = t[:, 0], t[:, 1], t[:, 2], t[:, 3]
else:
raise ValueError(
f"learnable_abc must be [4] or [H, 4] with H={H}, got {tuple(t.shape)}"
)
def _coeff(x):
if torch.is_tensor(x):
t = x.reshape(-1)
if t.numel() == 1:
t = t.expand(H)
elif t.numel() != H:
raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}")
return t.to(device=q.device, dtype=torch.float32).view(1, H, 1)
return x
a = _coeff(a)
b = _coeff(b)
c = _coeff(c)
d = _coeff(d)
if h0 is None:
state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device)
else:
state = h0.to(device=q.device, dtype=torch.float32)
if state.dim() == 3:
state = state.unsqueeze(0)
if state.shape[0] == 1 and B > 1:
state = state.expand(B, -1, -1, -1).contiguous()
if gk is None:
gkk = torch.ones(B, T, H, dtype=torch.float32, device=q.device)
else:
gkk = torch.exp(gk.float()).float()
outs = []
eps = 1e-12
for i in range(T):
ki = k[:, i, :, :]
state = gkk[:, i, :].view(B, H, 1, 1) * state + ki.unsqueeze(-1) * ki.unsqueeze(-2)
F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float()
F_safe = F + eps
qi = q[:, i, :, :].float()
q_state = ((qi.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
q_state2 = ((q_state.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
q_state3 = ((q_state2.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
out = (
a * qi
+ b * q_state
+ c * q_state2
+ d * q_state3
).to(q.dtype)
outs.append(out)
fro = F.squeeze(-1)
o = torch.stack(outs, dim=1).to(q.dtype)
return o, state, fro
def _coeff_last_dim(learnable_abc: Union[Tensor, Sequence[float]]) -> int:
if torch.is_tensor(learnable_abc):
if learnable_abc.ndim == 0:
raise ValueError("learnable_abc must be a vector or [H, n] tensor, got a scalar")
return int(learnable_abc.shape[-1])
return len(learnable_abc)
def _normalize_abc(
learnable_abc: Union[Tensor, Sequence[float]],
H: int,
n_coeff: int,
device: torch.device,
) -> Tensor:
if torch.is_tensor(learnable_abc):
t = learnable_abc.detach().to(device=device, dtype=torch.float32)
else:
t = torch.tensor(list(learnable_abc), device=device, dtype=torch.float32)
if t.numel() == n_coeff:
t = t.reshape(1, n_coeff).expand(H, n_coeff).contiguous()
elif t.reshape(-1).numel() == H * n_coeff:
t = t.reshape(H, n_coeff).contiguous()
else:
raise ValueError(
f"learnable_abc must be [{n_coeff}] or [H, {n_coeff}] with H={H}, got {tuple(t.shape)}"
)
return t
def _as_bthd(x: Optional[Tensor], name: str) -> Optional[Tensor]:
if x is None:
return None
if x.dim() == 2:
return x[None, ...]
if x.dim() == 3:
return x
raise ValueError(f"{name} must have 2/3 dims, got {tuple(x.shape)}")
@triton.jit(do_not_specialize=["T"])
def phi_kkt_decoding_kernel(
q_ptr,
k_ptr,
v_ptr,
alpha_ptr,
g_ptr,
gk_ptr,
abc_ptr,
o_ptr,
prev_h_kk_ptr,
prev_h_kv_ptr,
curr_h_kk_ptr,
curr_h_kv_ptr,
T,
scale,
H: tl.constexpr,
D: tl.constexpr,
BD: tl.constexpr,
N_COEFF: tl.constexpr,
USE_G: tl.constexpr,
USE_GK: tl.constexpr,
):
b_id = tl.program_id(0)
h_id = tl.program_id(1)
o_d = tl.arange(0, BD)
mask_d = o_d < D
mask_dd = mask_d[:, None] & mask_d[None, :]
state_off = (b_id * H + h_id).to(tl.int64) * D * D
p_hkk = prev_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :]
p_hkv = prev_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :]
b_h_kk = tl.load(p_hkk, mask=mask_dd, other=0).to(tl.float32)
b_h_kv = tl.load(p_hkv, mask=mask_dd, other=0).to(tl.float32)
coeff_a = tl.load(abc_ptr + h_id * N_COEFF + 0).to(tl.float32)
coeff_b = tl.load(abc_ptr + h_id * N_COEFF + 1).to(tl.float32)
coeff_c = tl.load(abc_ptr + h_id * N_COEFF + 2).to(tl.float32)
coeff_d = 0.0
if N_COEFF == 4:
coeff_d = tl.load(abc_ptr + h_id * N_COEFF + 3).to(tl.float32)
for t in range(0, T):
vec_off = ((b_id * T + t) * H + h_id) * D
scalar_off = (b_id * T + t) * H + h_id
b_q = tl.load(q_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
b_k = tl.load(k_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
b_v = tl.load(v_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
b_alpha = tl.load(alpha_ptr + scalar_off).to(tl.float32)
if USE_GK:
b_gkk = exp(tl.load(gk_ptr + scalar_off).to(tl.float32))
else:
b_gkk = 1.0
if USE_G:
b_g = exp(tl.load(g_ptr + scalar_off).to(tl.float32))
else:
b_g = 1.0
b_h_kk = b_h_kk * b_gkk + b_k[:, None] * b_k[None, :]
fro = tl.sqrt(tl.sum(b_h_kk * b_h_kk)) + 1e-12
o1 = tl.sum(b_h_kk * b_q[:, None], axis=0) / fro
o2 = tl.sum(b_h_kk * o1[:, None], axis=0) / fro
q_poly = coeff_a * b_q + coeff_b * o1 + coeff_c * o2
if N_COEFF == 4:
o3 = tl.sum(b_h_kk * o2[:, None], axis=0) / fro
q_poly = q_poly + coeff_d * o3
q_mix = b_q + b_alpha * (q_poly - b_q)
b_h_kv = b_h_kv * b_g + b_k[:, None] * b_v[None, :]
b_o = scale * tl.sum(b_h_kv * q_mix[:, None], axis=0)
tl.store(o_ptr + vec_off + o_d, b_o.to(o_ptr.dtype.element_ty), mask=mask_d)
p_hkk_out = curr_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :]
p_hkv_out = curr_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :]
tl.store(p_hkk_out, b_h_kk.to(p_hkk_out.dtype.element_ty), mask=mask_dd)
tl.store(p_hkv_out, b_h_kv.to(p_hkv_out.dtype.element_ty), mask=mask_dd)
def _prepare_decode_inputs(
q: Tensor,
k: Tensor,
v: Tensor,
alpha: Tensor,
g: Optional[Tensor],
gk: Optional[Tensor],
prev_h_kk: Optional[Tensor],
prev_h_kv: Optional[Tensor],
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Optional[Tensor], Optional[Tensor], Tensor, Tensor]:
if q.dim() < 4:
q = q[None, ...]
k = k[None, ...]
v = v[None, ...]
alpha = _as_bthd(alpha, "alpha")
g = _as_bthd(g, "g")
gk = _as_bthd(gk, "gk")
B, T, H, D = q.shape
if prev_h_kk is None:
prev_h_kk = q.new_zeros(B, H, D, D, dtype=torch.float32)
else:
if prev_h_kk.dim() == 3:
prev_h_kk = prev_h_kk.unsqueeze(0)
prev_h_kk = prev_h_kk.contiguous()
if prev_h_kk.shape[0] == 1 and B > 1:
prev_h_kk = prev_h_kk.expand(B, -1, -1, -1).contiguous()
if prev_h_kv is None:
prev_h_kv = q.new_zeros(B, H, D, D, dtype=torch.float32)
else:
if prev_h_kv.dim() == 3:
prev_h_kv = prev_h_kv.unsqueeze(0)
prev_h_kv = prev_h_kv.contiguous()
if prev_h_kv.shape[0] == 1 and B > 1:
prev_h_kv = prev_h_kv.expand(B, -1, -1, -1).contiguous()
return q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
@input_guard
def phi_kkt_decoding_one_step(
q: Tensor,
k: Tensor,
v: Tensor,
alpha: Tensor,
g: Tensor,
gk: Tensor,
gla_scale,
learnable_abc: Tensor,
prev_h_kk: Tensor,
prev_h_kv: Tensor,
) -> Tuple[Tensor, Tensor, Tensor]:
"""
Fused single-step (or short-T) Sigma GKA inference with cached H_kk / H_kv.
H_t = exp(g_t) H_{t-1} + k_t k_t^T
q_t_out = a q_t + b (q_t H_t)/F + c (q_t H_t^2)/F^2 [+ d (q_t H_t^3)/F^3]
Args:
q, k, v: [B, T, H, D] or [T, H, D]
alpha: [B, T, H] or [T, H]
g, gk: [B, T, H] or [T, H]
prev_h_kk: previous key-key state [B, H, D, D] or [H, D, D]
prev_h_kv: previous key-value state [B, H, D, D] or [H, D, D]
"""
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv = _prepare_decode_inputs(
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
)
B, T, H, D = q.shape
n_coeff = _coeff_last_dim(learnable_abc)
if n_coeff not in (3, 4):
raise ValueError(
f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}"
)
abc = _normalize_abc(learnable_abc, H, n_coeff, q.device)
if gla_scale is None:
gla_scale = D ** -0.5
dummy = q.new_empty(1)
g_ptr = g if g is not None else dummy
gk_ptr = gk if gk is not None else dummy
o = torch.empty_like(q)
curr_h_kk = torch.empty_like(prev_h_kk)
curr_h_kv = torch.empty_like(prev_h_kv)
BD = max(triton.next_power_of_2(D), 16)
if BD > 256:
raise ValueError(f"fused decoding supports head dim <= 256, got D={D}")
phi_kkt_decoding_kernel[(B, H)](
q,
k,
v,
alpha,
g_ptr,
gk_ptr,
abc,
o,
prev_h_kk,
prev_h_kv,
curr_h_kk,
curr_h_kv,
T,
float(gla_scale),
H=H,
D=D,
BD=BD,
N_COEFF=n_coeff,
USE_G=g is not None,
USE_GK=gk is not None,
num_warps=4 if BD <= 64 else 8,
num_stages=2,
)
return o, curr_h_kk, curr_h_kv
def phi_kkt_decoding_one_step_ref(
q: Tensor,
k: Tensor,
v: Tensor,
alpha: Tensor,
g: Tensor,
gk: Tensor,
gla_scale,
learnable_abc: Tensor,
prev_h_kk: Tensor,
prev_h_kv: Tensor,
) -> Tuple[Tensor, Tensor, Tensor]:
"""PyTorch + fused-recurrent Simple-GLA reference used for correctness checks."""
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv = _prepare_decode_inputs(
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
)
n_coeff = _coeff_last_dim(learnable_abc)
if n_coeff == 3:
solver = test_q_kkt_solve_approx_abc
elif n_coeff == 4:
solver = test_q_kkt_solve_approx_abcd
else:
raise ValueError(
f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}"
)
q_, h_kk, _ = solver(
q,
k,
gk,
h0=prev_h_kk,
learnable_abc=learnable_abc,
)
q_mix = q + alpha[..., None] * (q_ - q)
o, h_kv = fused_recurrent_simple_gla(
q=q_mix,
k=k,
v=v,
scale=gla_scale,
g=g,
initial_state=prev_h_kv,
output_final_state=True,
)
return o, h_kk, h_kv