Download phi_kkt_approx_gla_trace_c16/decoding_trace.py from msj19/newfla4: direct link, hf CLI and curl.
- Browser
- Download file 9.07 kB
-
https://huggingface.co/msj19/newfla4/resolve/main/phi_kkt_approx_gla_trace_c16/decoding_trace.py
- Command line
-
hf download hf://msj19/newfla4/phi_kkt_approx_gla_trace_c16/decoding_trace.py
-
curl -L -o decoding_trace.py https://huggingface.co/msj19/newfla4/resolve/main/phi_kkt_approx_gla_trace_c16/decoding_trace.py
9.07 kB
| """One-step (or short-T) decoding for trace-phi + vector-gate GLA. | |
| Same recurrence as training in ``q_kkt_solve_trace_gla``: | |
| Hkk_t = Diag(exp(gk_t / 2)) Hkk_{t-1} Diag(exp(gk_t / 2)) + k_t k_t^T | |
| x_t = sum_m coeff[m] * q_t (Hkk_t / tr Hkk_t)^m | |
| qmix = q_t + alpha_t (x_t - q_t) | |
| Hkv_t = Hkv_{t-1} * exp(g_t) + k_t v_t^T (decay on the key axis) | |
| o_t = scale * qmix @ Hkv_t | |
| Per-step gates stay inside fp32 ``exp``; there is no chunk-long ``exp(-cumsum)``. | |
| """ | |
| from typing import Optional, Sequence, Tuple, Union | |
| import torch | |
| import triton | |
| import triton.language as tl | |
| from torch import Tensor | |
| def _coeff_last_dim(coeff: Union[Tensor, Sequence[float]]) -> int: | |
| if torch.is_tensor(coeff): | |
| if coeff.ndim == 0: | |
| raise ValueError("learnable_abc must be a vector or [H, n], got a scalar") | |
| return int(coeff.shape[-1]) | |
| return len(coeff) | |
| def _normalize_coeff(coeff: Union[Tensor, Sequence[float]], H: int, n: int, device) -> Tensor: | |
| if torch.is_tensor(coeff): | |
| t = coeff.detach().to(device=device, dtype=torch.float32) | |
| else: | |
| t = torch.tensor(list(coeff), device=device, dtype=torch.float32) | |
| if t.numel() == n: | |
| t = t.reshape(1, n).expand(H, n).contiguous() | |
| elif t.reshape(-1).numel() == H * n: | |
| t = t.reshape(H, n).contiguous() | |
| else: | |
| raise ValueError(f"learnable_abc must be [{n}] or [H, {n}], got {tuple(t.shape)}") | |
| return t | |
| def _as_bthd(x: Optional[Tensor]) -> Optional[Tensor]: | |
| if x is None: | |
| return None | |
| if x.dim() == 2: | |
| return x[None, ...] | |
| if x.dim() == 3: | |
| return x | |
| raise ValueError(f"expected 2 or 3 dims, got {tuple(x.shape)}") | |
| def _gate_bthd(gate: Optional[Tensor], like: Tensor) -> Optional[Tensor]: | |
| if gate is None: | |
| return None | |
| if gate.shape == like.shape: | |
| return gate.contiguous() | |
| if gate.ndim == 3 and gate.shape == like.shape[:3]: | |
| return gate.unsqueeze(-1).expand_as(like).contiguous() | |
| if gate.ndim == 2 and gate.shape == like.shape[1:3]: | |
| return gate[None, ..., None].expand_as(like).contiguous() | |
| raise ValueError(f"gate {tuple(gate.shape)} does not match {tuple(like.shape)}") | |
| def trace_gla_decoding_kernel( | |
| q_ptr, k_ptr, v_ptr, alpha_ptr, g_ptr, gk_ptr, coeff_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: 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 | |
| h_kk = tl.load(prev_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :], mask=mask_dd, other=0).to(tl.float32) | |
| h_kv = tl.load(prev_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :], mask=mask_dd, other=0).to(tl.float32) | |
| c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32) | |
| c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32) | |
| c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32) | |
| c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32) if N > 3 else 0.0 | |
| eye = o_d[:, None] == o_d[None, :] | |
| 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_gk = tl.load(gk_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32) | |
| mu = tl.exp(0.5 * b_gk) | |
| else: | |
| mu = tl.full([BD], 1.0, dtype=tl.float32) | |
| h_kk = h_kk * mu[:, None] * mu[None, :] + b_k[:, None] * b_k[None, :] | |
| h_kk = tl.where(mask_dd, h_kk, 0.0) | |
| tr = tl.sum(tl.where(eye & mask_dd, h_kk, 0.0)) | |
| f = tr + 1e-12 | |
| cur = b_q | |
| acc = c0 * cur | |
| cur = tl.sum(h_kk * cur[:, None], axis=0) / f | |
| acc += c1 * cur | |
| cur = tl.sum(h_kk * cur[:, None], axis=0) / f | |
| acc += c2 * cur | |
| if N > 3: | |
| cur = tl.sum(h_kk * cur[:, None], axis=0) / f | |
| acc += c3 * cur | |
| q_mix = b_q + b_alpha * (acc - b_q) | |
| if USE_G: | |
| decay = tl.exp(tl.load(g_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)) | |
| else: | |
| decay = tl.full([BD], 1.0, dtype=tl.float32) | |
| h_kv = h_kv * decay[:, None] + b_k[:, None] * b_v[None, :] | |
| h_kv = tl.where(mask_dd, h_kv, 0.0) | |
| b_o = scale * tl.sum(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) | |
| tl.store(curr_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :], h_kk.to(curr_h_kk_ptr.dtype.element_ty), mask=mask_dd) | |
| tl.store(curr_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :], h_kv.to(curr_h_kv_ptr.dtype.element_ty), mask=mask_dd) | |
| def _prepare(q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv): | |
| if q.dim() < 4: | |
| q, k, v = q[None], k[None], v[None] | |
| alpha = _as_bthd(alpha) | |
| B, T, H, D = q.shape | |
| g = _gate_bthd(g, q) | |
| gk = _gate_bthd(gk, q) | |
| def _state(h, name): | |
| if h is None: | |
| return q.new_zeros(B, H, D, D, dtype=torch.float32) | |
| if h.dim() == 3: | |
| h = h.unsqueeze(0) | |
| h = h.contiguous() | |
| if h.shape[0] == 1 and B > 1: | |
| h = h.expand(B, -1, -1, -1).contiguous() | |
| if h.shape != (B, H, D, D): | |
| raise ValueError(f"{name} must be [B, H, D, D], got {tuple(h.shape)}") | |
| return h | |
| return q.contiguous(), k.contiguous(), v.contiguous(), alpha.contiguous(), g, gk, _state(prev_h_kk, "prev_h_kk"), _state(prev_h_kv, "prev_h_kv") | |
| def phi_kkt_decoding_trace( | |
| q: Tensor, | |
| k: Tensor, | |
| v: Tensor, | |
| alpha: Tensor, | |
| g: Optional[Tensor], | |
| gk: Optional[Tensor], | |
| gla_scale: float, | |
| learnable_abc: Union[Tensor, Sequence[float]], | |
| prev_h_kk: Optional[Tensor] = None, | |
| prev_h_kv: Optional[Tensor] = None, | |
| ) -> Tuple[Tensor, Tensor, Tensor]: | |
| """Decode T tokens. ``q, k, v`` are ``[B, T, H, D]`` or ``[T, H, D]``.""" | |
| q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv = _prepare( | |
| q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv | |
| ) | |
| B, T, H, D = q.shape | |
| n = _coeff_last_dim(learnable_abc) | |
| if n not in (3, 4): | |
| raise ValueError(f"learnable_abc last dim must be 3 or 4, got {n}") | |
| if D > 128: | |
| raise ValueError(f"decoding kernel supports D <= 128, got {D}") | |
| coeff = _normalize_coeff(learnable_abc, H, n, q.device) | |
| o = torch.empty_like(q) | |
| curr_kk = torch.empty_like(prev_h_kk) | |
| curr_kv = torch.empty_like(prev_h_kv) | |
| dummy = q.new_empty(1) | |
| bd = max(triton.next_power_of_2(D), 16) | |
| trace_gla_decoding_kernel[(B, H)]( | |
| q, k, v, alpha, | |
| g if g is not None else dummy, | |
| gk if gk is not None else dummy, | |
| coeff, o, prev_h_kk, prev_h_kv, curr_kk, curr_kv, | |
| T, float(gla_scale), | |
| H=H, D=D, BD=bd, N=n, | |
| USE_G=g is not None, USE_GK=gk is not None, | |
| num_warps=4 if bd <= 64 else 8, num_stages=1, | |
| ) | |
| return o, curr_kk, curr_kv | |
| def phi_kkt_decoding_trace_ref( | |
| q: Tensor, | |
| k: Tensor, | |
| v: Tensor, | |
| alpha: Tensor, | |
| g: Optional[Tensor], | |
| gk: Optional[Tensor], | |
| gla_scale: float, | |
| learnable_abc: Union[Tensor, Sequence[float]], | |
| prev_h_kk: Optional[Tensor] = None, | |
| prev_h_kv: Optional[Tensor] = None, | |
| ) -> Tuple[Tensor, Tensor, Tensor]: | |
| """PyTorch reference of the decoding recurrence, fp32 accumulation.""" | |
| q, k, v, alpha, g, gk, h_kk, h_kv = _prepare( | |
| q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv | |
| ) | |
| B, T, H, D = q.shape | |
| n = _coeff_last_dim(learnable_abc) | |
| coeff = _normalize_coeff(learnable_abc, H, n, q.device) | |
| h_kk = h_kk.float() | |
| h_kv = h_kv.float() | |
| outs = [] | |
| for t in range(T): | |
| kt = k[:, t].float() | |
| qt = q[:, t].float() | |
| vt = v[:, t].float() | |
| if gk is not None: | |
| mu = torch.exp(0.5 * gk[:, t].float()) | |
| h_kk = mu[..., :, None] * h_kk * mu[..., None, :] | |
| h_kk = h_kk + kt[..., :, None] * kt[..., None, :] | |
| fv = torch.diagonal(h_kk, dim1=-2, dim2=-1).sum(-1, keepdim=True) + 1e-12 | |
| cur = qt | |
| acc = coeff[:, 0].view(1, H, 1) * cur | |
| for m in range(1, n): | |
| cur = (cur.unsqueeze(-2) @ h_kk).squeeze(-2) / fv | |
| acc = acc + coeff[:, m].view(1, H, 1) * cur | |
| q_mix = qt + alpha[:, t].unsqueeze(-1).float() * (acc - qt) | |
| if g is not None: | |
| h_kv = h_kv * torch.exp(g[:, t].float())[..., None] | |
| h_kv = h_kv + kt[..., :, None] * vt[..., None, :] | |
| outs.append((float(gla_scale) * (q_mix.unsqueeze(-2) @ h_kv).squeeze(-2)).to(q.dtype)) | |
| return torch.stack(outs, dim=1), h_kk, h_kv | |