Add files using upload-large-folder tool
Browse files- __init__.py +55 -0
- phi_kkt_approx/__pycache__/q_kkt_solve_abcd_fast.cpython-312.pyc +0 -0
- phi_kkt_approx_gla_trace/__pycache__/illegal_input_dump.cpython-312.pyc +0 -0
- phi_kkt_approx_gla_trace/__pycache__/phi_kkt_solve.cpython-312.pyc +0 -0
- phi_kkt_approx_gla_trace/__pycache__/phi_kkt_solve_trace.cpython-312.pyc +0 -0
- phi_kkt_approx_gla_trace_c16/__pycache__/q_kkt_solve_trace_gla.cpython-312.pyc +0 -0
- phi_kkt_approx_gla_trace_c16/q_kkt_solve_abc.py +255 -0
- phi_kkt_approx_gla_trace_c16/q_kkt_solve_trace_gla.py +77 -0
- phi_kkt_approx_trace/__pycache__/decoding_one_step.cpython-312.pyc +0 -0
- phi_kkt_approx_trace/__pycache__/phi_kkt_solve.cpython-312.pyc +0 -0
- phi_kkt_approx_trace/__pycache__/q_kkt_solve_abc_fast_2.cpython-312.pyc +0 -0
- phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace.cpython-312.pyc +0 -0
- phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace_triton_safe.cpython-312.pyc +0 -0
- phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace_triton_seg.cpython-310.pyc +0 -0
- phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace_triton_seg.cpython-312.pyc +0 -0
- phi_kkt_approx_trace/decoding_one_step.py +497 -0
- phi_kkt_approx_trace/q_kkt_solve_abcd_fast_2.py +1531 -0
- phi_kkt_approx_trace/q_kkt_solve_trace_triton.py +731 -0
- phi_kkt_approx_trace/q_kkt_solve_trace_triton_safe.py +1600 -0
- phi_kkt_approx_trace/q_kkt_solve_trace_triton_seg.py +1524 -0
- rebased/naive.py +27 -0
- rebased/parallel.py +464 -0
- retention/chunk.py +77 -0
- retention/fused_chunk.py +78 -0
- retention/naive.py +15 -0
- retention/parallel.py +71 -0
- rwkv4/__init__.py +7 -0
- rwkv4/fused_recurrent.py +472 -0
- rwkv6/__init__.py +9 -0
- rwkv6/chunk_naive.py +43 -0
- rwkv7/RWKV7(Goose).md +603 -0
- rwkv7/fused_k_update.py +350 -0
- rwkv7/fused_recurrent.py +335 -0
- simple_gla/__init__.py +13 -0
- simple_gla/fused_chunk.py +108 -0
- state_org/fused_recurrent.py +111 -0
- state_org/naive.py +41 -0
- titans/__init__.py +7 -0
- ttt/__init__.py +9 -0
- ttt/chunk.py +1447 -0
- utils/__init__.py +58 -0
- utils/__pycache__/cumsum.cpython-312.pyc +0 -0
- utils/__pycache__/matmul.cpython-312.pyc +0 -0
- utils/__pycache__/softmax.cpython-312.pyc +0 -0
- utils/__pycache__/solve_tril.cpython-312.pyc +0 -0
- utils/constant.py +6 -0
- utils/index.py +134 -0
- utils/pack.py +209 -0
- utils/softmax.py +108 -0
- utils/solve_tril.py +384 -0
__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
# from .abc import chunk_abc
|
| 4 |
+
# from .attn import parallel_attn
|
| 5 |
+
# from .based import fused_chunk_based, parallel_based
|
| 6 |
+
# from .comba import chunk_comba, fused_recurrent_comba
|
| 7 |
+
# from .delta_rule import chunk_delta_rule, fused_chunk_delta_rule, fused_recurrent_delta_rule
|
| 8 |
+
# from .forgetting_attn import parallel_forgetting_attn
|
| 9 |
+
# from .gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
|
| 10 |
+
# from .generalized_delta_rule import (
|
| 11 |
+
# chunk_dplr_delta_rule,
|
| 12 |
+
# chunk_iplr_delta_rule,
|
| 13 |
+
# fused_recurrent_dplr_delta_rule,
|
| 14 |
+
# fused_recurrent_iplr_delta_rule
|
| 15 |
+
# )
|
| 16 |
+
# from .gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
|
| 17 |
+
# from .gsa import chunk_gsa, fused_recurrent_gsa
|
| 18 |
+
# from .hgrn import fused_recurrent_hgrn
|
| 19 |
+
# from .lightning_attn import chunk_lightning_attn, fused_recurrent_lightning_attn
|
| 20 |
+
# from .linear_attn import chunk_linear_attn, fused_chunk_linear_attn, fused_recurrent_linear_attn
|
| 21 |
+
# from .log_linear_attn import chunk_log_linear_attn
|
| 22 |
+
# from .mesa_net import chunk_mesa_net
|
| 23 |
+
# from .nsa import parallel_nsa
|
| 24 |
+
# from .path_attn import parallel_path_attn
|
| 25 |
+
# from .retention import chunk_retention, fused_chunk_retention, fused_recurrent_retention, parallel_retention
|
| 26 |
+
# from .rwkv6 import chunk_rwkv6, fused_recurrent_rwkv6
|
| 27 |
+
# from .rwkv7 import chunk_rwkv7, fused_recurrent_rwkv7
|
| 28 |
+
# from .simple_gla import chunk_simple_gla, fused_chunk_simple_gla, fused_recurrent_simple_gla, parallel_simple_gla
|
| 29 |
+
from .mask_gated_delta_rule_t import mask_gated_chunk_delta_rule,mask_fused_recurrent_gated_delta_rule
|
| 30 |
+
|
| 31 |
+
# __all__ = [
|
| 32 |
+
# 'chunk_abc',
|
| 33 |
+
# 'parallel_attn',
|
| 34 |
+
# 'fused_chunk_based', 'parallel_based',
|
| 35 |
+
# 'chunk_delta_rule', 'fused_chunk_delta_rule', 'fused_recurrent_delta_rule',
|
| 36 |
+
# 'parallel_forgetting_attn',
|
| 37 |
+
# 'chunk_gated_delta_rule', 'fused_recurrent_gated_delta_rule',
|
| 38 |
+
# 'chunk_comba', 'fused_recurrent_comba',
|
| 39 |
+
# 'chunk_dplr_delta_rule', 'chunk_iplr_delta_rule',
|
| 40 |
+
# 'fused_recurrent_dplr_delta_rule', 'fused_recurrent_iplr_delta_rule',
|
| 41 |
+
# 'chunk_gla', 'fused_chunk_gla', 'fused_recurrent_gla',
|
| 42 |
+
# 'chunk_gsa', 'fused_recurrent_gsa',
|
| 43 |
+
# 'fused_recurrent_hgrn',
|
| 44 |
+
# 'chunk_lightning_attn', 'fused_recurrent_lightning_attn',
|
| 45 |
+
# 'chunk_linear_attn', 'fused_chunk_linear_attn', 'fused_recurrent_linear_attn',
|
| 46 |
+
# 'chunk_log_linear_attn',
|
| 47 |
+
# 'chunk_mesa_net',
|
| 48 |
+
# 'parallel_nsa',
|
| 49 |
+
# 'parallel_path_attn',
|
| 50 |
+
# 'chunk_retention', 'fused_chunk_retention', 'fused_recurrent_retention', 'parallel_retention',
|
| 51 |
+
# 'chunk_rwkv6', 'fused_recurrent_rwkv6',
|
| 52 |
+
# 'chunk_rwkv7', 'fused_recurrent_rwkv7',
|
| 53 |
+
# 'chunk_simple_gla', 'fused_chunk_simple_gla', 'fused_recurrent_simple_gla', 'parallel_simple_gla',
|
| 54 |
+
# 'mask_gated_chunk_delta_rule','mask_fused_recurrent_delta_rule',
|
| 55 |
+
# ]
|
phi_kkt_approx/__pycache__/q_kkt_solve_abcd_fast.cpython-312.pyc
ADDED
|
Binary file (62.3 kB). View file
|
|
|
phi_kkt_approx_gla_trace/__pycache__/illegal_input_dump.cpython-312.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
phi_kkt_approx_gla_trace/__pycache__/phi_kkt_solve.cpython-312.pyc
ADDED
|
Binary file (5.72 kB). View file
|
|
|
phi_kkt_approx_gla_trace/__pycache__/phi_kkt_solve_trace.cpython-312.pyc
ADDED
|
Binary file (2.04 kB). View file
|
|
|
phi_kkt_approx_gla_trace_c16/__pycache__/q_kkt_solve_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fused Phi-KKT (abc) + Simple-GLA autograd.
|
| 2 |
+
|
| 3 |
+
One ``torch.autograd.Function`` owns both the polynomial apply
|
| 4 |
+
|
| 5 |
+
x = a q + b (q @ H)/F + c (q @ H^2)/F^2
|
| 6 |
+
|
| 7 |
+
and the subsequent GLA recurrence. Matches GDN's checkpoint style:
|
| 8 |
+
|
| 9 |
+
- ``k`` is saved once (not once per op).
|
| 10 |
+
- Mixed query ``q_gla = (1-α) q + α x`` is reconstructed in backward.
|
| 11 |
+
- GLA chunk state ``h_kv`` is recomputed, not stored.
|
| 12 |
+
- Chunk-level ``h_kk`` is dropped after forward and rebuilt in backward.
|
| 13 |
+
- Triton kernels are reused from ``phi_kkt_approx.q_kkt_solve_abc_fast_2``.
|
| 14 |
+
"""
|
| 15 |
+
from typing import Optional, Sequence, Tuple, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
|
| 20 |
+
from fla.ops.simple_gla.chunk import chunk_simple_gla_bwd, chunk_simple_gla_fwd
|
| 21 |
+
from fla.ops.utils import chunk_local_cumsum
|
| 22 |
+
|
| 23 |
+
from ..phi_kkt_approx.q_kkt_solve_abc_fast_2 import (
|
| 24 |
+
_bwd_dH_to_dk_dgk,
|
| 25 |
+
_bwd_prep_du_dv_alpha,
|
| 26 |
+
_normalize_abc,
|
| 27 |
+
q_kkt_solve_approx_backward_triton,
|
| 28 |
+
q_kkt_solve_approx_forward_triton,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _poly_x_out(
|
| 33 |
+
q: Tensor,
|
| 34 |
+
o1: Tensor,
|
| 35 |
+
o2: Tensor,
|
| 36 |
+
abc_heads: Tensor,
|
| 37 |
+
) -> Tensor:
|
| 38 |
+
"""Reconstruct x = a q + b o1 + c o2 in fp32, store as ``q.dtype``."""
|
| 39 |
+
a = abc_heads[:, 0].view(1, 1, -1, 1)
|
| 40 |
+
b = abc_heads[:, 1].view(1, 1, -1, 1)
|
| 41 |
+
c = abc_heads[:, 2].view(1, 1, -1, 1)
|
| 42 |
+
return (a * q.float() + b * o1.float() + c * o2.float()).to(q.dtype)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _mix_q(q: Tensor, x_out: Tensor, alpha: Tensor) -> Tensor:
|
| 46 |
+
return q + alpha[..., None] * (x_out - q)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _cumsum_gates(
|
| 50 |
+
g: Optional[Tensor],
|
| 51 |
+
gk: Optional[Tensor],
|
| 52 |
+
chunk_size: int,
|
| 53 |
+
) -> Tuple[Optional[Tensor], Optional[Tensor]]:
|
| 54 |
+
"""Cumsum GLA gate ``g`` and KKT gate ``gk``. Reuse storage when they alias."""
|
| 55 |
+
gkk = chunk_local_cumsum(gk, chunk_size=chunk_size) if gk is not None else None
|
| 56 |
+
if g is None:
|
| 57 |
+
g_cum = None
|
| 58 |
+
elif gk is g:
|
| 59 |
+
g_cum = gkk
|
| 60 |
+
else:
|
| 61 |
+
g_cum = chunk_local_cumsum(g, chunk_size=chunk_size)
|
| 62 |
+
return g_cum, gkk
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _pack_abc_grad(
|
| 66 |
+
d_abc_h: Tensor,
|
| 67 |
+
abc_shape: Tuple[int, ...],
|
| 68 |
+
abc_dtype: torch.dtype,
|
| 69 |
+
abc_device: torch.device,
|
| 70 |
+
) -> Tensor:
|
| 71 |
+
if abc_shape == (3,) or (len(abc_shape) == 1 and abc_shape[0] == 3):
|
| 72 |
+
d_abc = d_abc_h.sum(dim=0)
|
| 73 |
+
else:
|
| 74 |
+
d_abc = d_abc_h
|
| 75 |
+
return d_abc.to(dtype=abc_dtype, device=abc_device).reshape(abc_shape)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class q_kkt_solve_approx(torch.autograd.Function):
|
| 79 |
+
"""Fused abc polynomial apply + alpha mix + chunk Simple-GLA."""
|
| 80 |
+
|
| 81 |
+
@staticmethod
|
| 82 |
+
def forward(
|
| 83 |
+
ctx,
|
| 84 |
+
k: Tensor,
|
| 85 |
+
q: Tensor,
|
| 86 |
+
v: Tensor,
|
| 87 |
+
alpha: Tensor,
|
| 88 |
+
g: Optional[Tensor],
|
| 89 |
+
gk: Optional[Tensor],
|
| 90 |
+
chunk_size: int,
|
| 91 |
+
learnable_abc: Union[Tensor, Sequence[float]],
|
| 92 |
+
gla_scale: float,
|
| 93 |
+
h0_kk=None,
|
| 94 |
+
h0_kv=None,
|
| 95 |
+
output_final_state: bool = False,
|
| 96 |
+
) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
|
| 97 |
+
B, T, H, _D = q.shape
|
| 98 |
+
assert torch.is_tensor(learnable_abc), "learnable_abc must be a tensor"
|
| 99 |
+
assert learnable_abc.dtype == torch.float32, (
|
| 100 |
+
f"learnable_abc.dtype must be float32, got {learnable_abc.dtype}"
|
| 101 |
+
)
|
| 102 |
+
ctx.abc_dtype = learnable_abc.dtype
|
| 103 |
+
ctx.abc_device = learnable_abc.device
|
| 104 |
+
ctx.abc_shape = tuple(learnable_abc.shape)
|
| 105 |
+
|
| 106 |
+
abc_heads = _normalize_abc(learnable_abc, H, q.device, torch.float32)
|
| 107 |
+
g_cum, gkk = _cumsum_gates(g, gk, chunk_size)
|
| 108 |
+
|
| 109 |
+
fro = torch.empty((B, T, H), dtype=torch.float32, device=q.device)
|
| 110 |
+
x_out, o1, o2, fro, h_kk, h_kk_final = q_kkt_solve_approx_forward_triton(
|
| 111 |
+
k,
|
| 112 |
+
q,
|
| 113 |
+
gkk,
|
| 114 |
+
fro,
|
| 115 |
+
learnable_abc=abc_heads,
|
| 116 |
+
chunk_size=chunk_size,
|
| 117 |
+
load_fro=0,
|
| 118 |
+
output_final_state=output_final_state,
|
| 119 |
+
h0=h0_kk,
|
| 120 |
+
)
|
| 121 |
+
del h_kk
|
| 122 |
+
q_gla = _mix_q(q, x_out, alpha)
|
| 123 |
+
o, kv_final = chunk_simple_gla_fwd(
|
| 124 |
+
q=q_gla,
|
| 125 |
+
k=k,
|
| 126 |
+
v=v,
|
| 127 |
+
g=g_cum,
|
| 128 |
+
g_gamma=None,
|
| 129 |
+
scale=gla_scale,
|
| 130 |
+
initial_state=h0_kv,
|
| 131 |
+
output_final_state=output_final_state,
|
| 132 |
+
cu_seqlens=None,
|
| 133 |
+
chunk_size=chunk_size,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
to_save = [k, q, v, alpha, o1, o2, fro, abc_heads]
|
| 137 |
+
if g_cum is not None:
|
| 138 |
+
to_save.append(g_cum)
|
| 139 |
+
if gk is not None:
|
| 140 |
+
to_save.append(gk)
|
| 141 |
+
if gkk is not None:
|
| 142 |
+
to_save.append(gkk)
|
| 143 |
+
if h0_kk is not None:
|
| 144 |
+
to_save.append(h0_kk)
|
| 145 |
+
if h0_kv is not None:
|
| 146 |
+
to_save.append(h0_kv)
|
| 147 |
+
ctx.save_for_backward(*to_save)
|
| 148 |
+
ctx.chunk_size = chunk_size
|
| 149 |
+
ctx.gla_scale = gla_scale
|
| 150 |
+
ctx.has_g_cum = g_cum is not None
|
| 151 |
+
ctx.has_gk = gk is not None
|
| 152 |
+
ctx.has_gkk = gkk is not None
|
| 153 |
+
ctx.has_h0_kk = h0_kk is not None
|
| 154 |
+
ctx.has_h0_kv = h0_kv is not None
|
| 155 |
+
return o.to(q.dtype), h_kk_final, kv_final
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def backward(
|
| 159 |
+
ctx,
|
| 160 |
+
do: Tensor,
|
| 161 |
+
d_kk_final: Optional[Tensor] = None,
|
| 162 |
+
d_kv_final: Optional[Tensor] = None,
|
| 163 |
+
):
|
| 164 |
+
saved = list(ctx.saved_tensors)
|
| 165 |
+
k, q, v, alpha, o1, o2, fro, abc_heads = saved[:8]
|
| 166 |
+
idx = 8
|
| 167 |
+
g_cum = saved[idx] if ctx.has_g_cum else None
|
| 168 |
+
idx += int(ctx.has_g_cum)
|
| 169 |
+
gk = saved[idx] if ctx.has_gk else None
|
| 170 |
+
idx += int(ctx.has_gk)
|
| 171 |
+
gkk = saved[idx] if ctx.has_gkk else None
|
| 172 |
+
idx += int(ctx.has_gkk)
|
| 173 |
+
h0_kk = saved[idx] if ctx.has_h0_kk else None
|
| 174 |
+
idx += int(ctx.has_h0_kk)
|
| 175 |
+
h0_kv = saved[idx] if ctx.has_h0_kv else None
|
| 176 |
+
chunk_size = ctx.chunk_size
|
| 177 |
+
gla_scale = ctx.gla_scale
|
| 178 |
+
|
| 179 |
+
x_out = _poly_x_out(q, o1, o2, abc_heads)
|
| 180 |
+
q_gla = _mix_q(q, x_out, alpha)
|
| 181 |
+
|
| 182 |
+
dq_gla, dk_gla, dv, dg_cum, dh0_kv = chunk_simple_gla_bwd(
|
| 183 |
+
q=q_gla,
|
| 184 |
+
k=k,
|
| 185 |
+
v=v,
|
| 186 |
+
g=g_cum,
|
| 187 |
+
g_gamma=None,
|
| 188 |
+
initial_state=h0_kv,
|
| 189 |
+
do=do,
|
| 190 |
+
dht=d_kv_final,
|
| 191 |
+
scale=gla_scale,
|
| 192 |
+
cu_seqlens=None,
|
| 193 |
+
chunk_size=chunk_size,
|
| 194 |
+
)
|
| 195 |
+
dg = None
|
| 196 |
+
if g_cum is not None:
|
| 197 |
+
dg = chunk_local_cumsum(
|
| 198 |
+
dg_cum, chunk_size=chunk_size, reverse=True, cu_seqlens=None
|
| 199 |
+
).to(dtype=g_cum.dtype)
|
| 200 |
+
|
| 201 |
+
dx_out = dq_gla * alpha[..., None]
|
| 202 |
+
dq_mix = dq_gla * (1.0 - alpha[..., None])
|
| 203 |
+
d_alpha = (dq_gla * (x_out - q)).sum(dim=-1)
|
| 204 |
+
|
| 205 |
+
dq_kkt, dx1, fro, h_kk, _ = q_kkt_solve_approx_backward_triton(
|
| 206 |
+
k,
|
| 207 |
+
dx_out,
|
| 208 |
+
gkk,
|
| 209 |
+
fro,
|
| 210 |
+
learnable_abc=abc_heads,
|
| 211 |
+
chunk_size=chunk_size,
|
| 212 |
+
load_fro=1,
|
| 213 |
+
output_final_state=False,
|
| 214 |
+
h0=h0_kk,
|
| 215 |
+
h_kk=None,
|
| 216 |
+
)
|
| 217 |
+
need_dabc = bool(ctx.needs_input_grad[7])
|
| 218 |
+
du, dv_poly, alpha_h, d_abc_h = _bwd_prep_du_dv_alpha(
|
| 219 |
+
q, o1, o2, dx_out, dx1, fro, abc_heads, chunk_size, need_dabc
|
| 220 |
+
)
|
| 221 |
+
dk_kkt, dgk, dh0_kk = _bwd_dH_to_dk_dgk(
|
| 222 |
+
k,
|
| 223 |
+
q,
|
| 224 |
+
o1,
|
| 225 |
+
du,
|
| 226 |
+
dv_poly,
|
| 227 |
+
alpha_h,
|
| 228 |
+
gk,
|
| 229 |
+
gkk,
|
| 230 |
+
d_kk_final,
|
| 231 |
+
h_kk,
|
| 232 |
+
h0_kk,
|
| 233 |
+
chunk_size,
|
| 234 |
+
)
|
| 235 |
+
d_abc = (
|
| 236 |
+
_pack_abc_grad(d_abc_h, ctx.abc_shape, ctx.abc_dtype, ctx.abc_device)
|
| 237 |
+
if need_dabc
|
| 238 |
+
else None
|
| 239 |
+
)
|
| 240 |
+
dq = dq_mix + dq_kkt
|
| 241 |
+
dk = dk_gla + dk_kkt
|
| 242 |
+
return (
|
| 243 |
+
dk,
|
| 244 |
+
dq,
|
| 245 |
+
dv,
|
| 246 |
+
d_alpha,
|
| 247 |
+
dg,
|
| 248 |
+
dgk,
|
| 249 |
+
None,
|
| 250 |
+
d_abc,
|
| 251 |
+
None,
|
| 252 |
+
dh0_kk,
|
| 253 |
+
dh0_kv,
|
| 254 |
+
None,
|
| 255 |
+
)
|
phi_kkt_approx_gla_trace_c16/q_kkt_solve_trace_gla.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trace-phi + vector-gate GLA, composed so both train in one call.
|
| 2 |
+
|
| 3 |
+
Phi uses ``q_kkt_solve_trace_triton`` (trace norm, per-dimension half-gate).
|
| 4 |
+
The value recurrence is ``chunk_gla``:
|
| 5 |
+
|
| 6 |
+
Hkv_t = Hkv_{t-1} * exp(g_t) + k_t v_t^T (decay on the key axis)
|
| 7 |
+
o_t = scale * q_mix_t @ Hkv_t
|
| 8 |
+
q_mix = q + alpha * (x - q)
|
| 9 |
+
|
| 10 |
+
``g`` / ``gk`` may be ``[B, T, H]`` (broadcast over D) or ``[B, T, H, D]``.
|
| 11 |
+
Coefficient count is the last dim of ``learnable_abc``: 3 or 4.
|
| 12 |
+
This path does not call ``simple_gla``.
|
| 13 |
+
"""
|
| 14 |
+
from typing import Optional, Sequence, Tuple, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from fla.ops.gla import chunk_gla
|
| 20 |
+
|
| 21 |
+
from ..phi_kkt_approx_trace.q_kkt_solve_trace_triton import q_kkt_solve_trace_triton
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _as_head_gate(gate: Optional[Tensor], like: Tensor) -> Optional[Tensor]:
|
| 25 |
+
"""Broadcast ``[B, T, H]`` or ``[B, T, H, D]`` onto ``like``'s last dim."""
|
| 26 |
+
if gate is None:
|
| 27 |
+
return None
|
| 28 |
+
if gate.shape == like.shape:
|
| 29 |
+
return gate
|
| 30 |
+
if gate.ndim == like.ndim - 1 and gate.shape == like.shape[:-1]:
|
| 31 |
+
return gate.unsqueeze(-1).expand_as(like)
|
| 32 |
+
raise ValueError(
|
| 33 |
+
f"gate must be {tuple(like.shape)} or {tuple(like.shape[:-1])}, got {tuple(gate.shape)}"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def phi_kkt_solve_trace_gla(
|
| 38 |
+
q: Tensor,
|
| 39 |
+
k: Tensor,
|
| 40 |
+
v: Tensor,
|
| 41 |
+
alpha: Tensor,
|
| 42 |
+
g: Optional[Tensor],
|
| 43 |
+
gk: Optional[Tensor],
|
| 44 |
+
gla_scale: float,
|
| 45 |
+
learnable_abc: Union[Tensor, Sequence[float]],
|
| 46 |
+
chunk_size: int = 16,
|
| 47 |
+
h0_kk: Optional[Tensor] = None,
|
| 48 |
+
h0_kv: Optional[Tensor] = None,
|
| 49 |
+
output_final_state: bool = True,
|
| 50 |
+
) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
|
| 51 |
+
"""x = phi_trace(q, k, gk), then vector-gate GLA on the alpha-mixed query.
|
| 52 |
+
|
| 53 |
+
Returns ``o [B, T, H, D]``, ``H_kk`` (or None), ``H_kv`` (or None).
|
| 54 |
+
"""
|
| 55 |
+
if q.ndim != 4:
|
| 56 |
+
raise ValueError(f"q must be [B, T, H, D], got {tuple(q.shape)}")
|
| 57 |
+
gk_vec = _as_head_gate(gk, k)
|
| 58 |
+
g_vec = _as_head_gate(g, k)
|
| 59 |
+
if g_vec is None:
|
| 60 |
+
g_vec = torch.zeros_like(k, dtype=torch.float32)
|
| 61 |
+
x, h_kk = q_kkt_solve_trace_triton.apply(
|
| 62 |
+
k, q, gk_vec, chunk_size, learnable_abc, h0_kk,
|
| 63 |
+
)
|
| 64 |
+
q_mix = q + alpha[..., None] * (x - q)
|
| 65 |
+
h0 = None if h0_kv is None else h0_kv.float().contiguous()
|
| 66 |
+
o, h_kv = chunk_gla(
|
| 67 |
+
q_mix,
|
| 68 |
+
k,
|
| 69 |
+
v,
|
| 70 |
+
g_vec,
|
| 71 |
+
scale=float(gla_scale),
|
| 72 |
+
initial_state=h0,
|
| 73 |
+
output_final_state=output_final_state,
|
| 74 |
+
)
|
| 75 |
+
if not output_final_state:
|
| 76 |
+
h_kk = None
|
| 77 |
+
return o, h_kk, h_kv
|
phi_kkt_approx_trace/__pycache__/decoding_one_step.cpython-312.pyc
ADDED
|
Binary file (24.7 kB). View file
|
|
|
phi_kkt_approx_trace/__pycache__/phi_kkt_solve.cpython-312.pyc
ADDED
|
Binary file (4.02 kB). View file
|
|
|
phi_kkt_approx_trace/__pycache__/q_kkt_solve_abc_fast_2.cpython-312.pyc
ADDED
|
Binary file (55.9 kB). View file
|
|
|
phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace.cpython-312.pyc
ADDED
|
Binary file (30.8 kB). View file
|
|
|
phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace_triton_safe.cpython-312.pyc
ADDED
|
Binary file (95.8 kB). View file
|
|
|
phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace_triton_seg.cpython-310.pyc
ADDED
|
Binary file (40.1 kB). View file
|
|
|
phi_kkt_approx_trace/__pycache__/q_kkt_solve_trace_triton_seg.cpython-312.pyc
ADDED
|
Binary file (92.1 kB). View file
|
|
|
phi_kkt_approx_trace/decoding_one_step.py
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fused Triton kernel for Sigma GKA token-by-token decoding.
|
| 2 |
+
|
| 3 |
+
Replaces the PyTorch reference recurrence + a separate Simple-GLA launch:
|
| 4 |
+
|
| 5 |
+
H_kk_t = exp(gk_t) H_kk_{t-1} + k_t k_t^T
|
| 6 |
+
q_t_out = a q + b (q H)/F + c (q H^2)/F^2 [+ d (q H^3)/F^3]
|
| 7 |
+
q_mix = q + alpha (q_t_out - q)
|
| 8 |
+
H_kv_t = exp(g_t) H_kv_{t-1} + k_t v_t^T
|
| 9 |
+
o_t = scale * q_mix @ H_kv_t
|
| 10 |
+
"""
|
| 11 |
+
from typing import Optional, Sequence, Tuple, Union
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import triton
|
| 15 |
+
import triton.language as tl
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
|
| 18 |
+
from fla.ops.simple_gla import fused_recurrent_simple_gla
|
| 19 |
+
from fla.ops.utils.op import exp
|
| 20 |
+
from fla.utils import input_guard
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_q_kkt_solve_approx_abc(
|
| 24 |
+
q,
|
| 25 |
+
k,
|
| 26 |
+
gk,
|
| 27 |
+
# a=1.0,
|
| 28 |
+
# b=-0.5,
|
| 29 |
+
# c=0.375,
|
| 30 |
+
h0=None,
|
| 31 |
+
learnable_abc=None,
|
| 32 |
+
):
|
| 33 |
+
"""
|
| 34 |
+
PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2).
|
| 35 |
+
|
| 36 |
+
We follow the GLA recurrence to build the per-step key-key state
|
| 37 |
+
H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action
|
| 38 |
+
on q_t by a low-order polynomial in H_t / ||H_t||_F:
|
| 39 |
+
|
| 40 |
+
q_t_out = a * q_t
|
| 41 |
+
+ b * (q_t @ H_t) / ||H_t||_F
|
| 42 |
+
+ c * (q_t @ H_t @ H_t) / ||H_t||_F^2
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
q: Query tensor with shape [B, T, H, D].
|
| 46 |
+
k: Key tensor with shape [B, T, H, D].
|
| 47 |
+
gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use.
|
| 48 |
+
If None, the gate is treated as 1 (no decay).
|
| 49 |
+
a, b, c: Polynomial coefficients. Each may be a scalar or a length-H tensor.
|
| 50 |
+
h0: Optional previous key-key state with shape [B, H, D, D] or [H, D, D].
|
| 51 |
+
learnable_abc: Optional coefficients as [3] or [H, 3]. Overrides a, b, c.
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
o: Output tensor with shape [B, T, H, D].
|
| 55 |
+
states: List of length T, each [B, H, D, D] (the per-step H_t).
|
| 56 |
+
fros: List of length T, each [B, H] (per-step Frobenius norm).
|
| 57 |
+
"""
|
| 58 |
+
B, T, H, D = q.shape
|
| 59 |
+
|
| 60 |
+
if learnable_abc is not None:
|
| 61 |
+
t = learnable_abc
|
| 62 |
+
if not torch.is_tensor(t):
|
| 63 |
+
t = torch.tensor(list(t), device=q.device, dtype=torch.float32)
|
| 64 |
+
else:
|
| 65 |
+
t = t.detach().to(device=q.device)
|
| 66 |
+
if t.numel() == 3:
|
| 67 |
+
a, b, c = t.reshape(3).unbind(0)
|
| 68 |
+
elif t.reshape(-1).numel() == H * 3:
|
| 69 |
+
t = t.reshape(H, 3)
|
| 70 |
+
a, b, c = t[:, 0], t[:, 1], t[:, 2]
|
| 71 |
+
else:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
f"learnable_abc must be [3] or [H, 3] with H={H}, got {tuple(t.shape)}"
|
| 74 |
+
)
|
| 75 |
+
else:
|
| 76 |
+
raise ValueError("learnable_abc must be provided")
|
| 77 |
+
|
| 78 |
+
def _coeff(x):
|
| 79 |
+
if torch.is_tensor(x):
|
| 80 |
+
t = x.reshape(-1)
|
| 81 |
+
if t.numel() == 1:
|
| 82 |
+
t = t.expand(H)
|
| 83 |
+
elif t.numel() != H:
|
| 84 |
+
raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}")
|
| 85 |
+
# [1, H, 1] so it broadcasts with qi / q_state of shape [B, H, D]
|
| 86 |
+
return t.to(device=q.device, dtype=torch.float32).view(1, H, 1)
|
| 87 |
+
return x
|
| 88 |
+
|
| 89 |
+
a = _coeff(a)
|
| 90 |
+
b = _coeff(b)
|
| 91 |
+
c = _coeff(c)
|
| 92 |
+
if h0 is None:
|
| 93 |
+
state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device)
|
| 94 |
+
else:
|
| 95 |
+
state = h0.to(device=q.device, dtype=torch.float32)
|
| 96 |
+
if state.dim() == 3:
|
| 97 |
+
state = state.unsqueeze(0)
|
| 98 |
+
if state.shape[0] == 1 and B > 1:
|
| 99 |
+
state = state.expand(B, -1, -1, -1).contiguous()
|
| 100 |
+
if gk is None:
|
| 101 |
+
gkk = torch.ones(B, T, H, dtype=torch.float32, device=q.device)
|
| 102 |
+
else:
|
| 103 |
+
gkk = torch.exp(gk.float()).float()
|
| 104 |
+
|
| 105 |
+
outs = []
|
| 106 |
+
eps = 1e-12
|
| 107 |
+
|
| 108 |
+
for i in range(T):
|
| 109 |
+
ki = k[:, i, :, :] # [B, H, D]
|
| 110 |
+
# GLA-style state update: H_t = exp(g_t) * H_{t-1} + k_t k_t^T
|
| 111 |
+
state = gkk[:, i, :].view(B, H, 1, 1) * state + ki.unsqueeze(-1) * ki.unsqueeze(-2)
|
| 112 |
+
# Frobenius norm of the current state H_t
|
| 113 |
+
F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float() # [B, H, 1]
|
| 114 |
+
F_safe = F + eps
|
| 115 |
+
qi = q[:, i, :, :].float() # [B, H, D]
|
| 116 |
+
q_state = ((qi.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
|
| 117 |
+
q_state2 = ((q_state.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
|
| 118 |
+
out = (a * qi + b * q_state + c * q_state2).to(q.dtype)
|
| 119 |
+
outs.append(out)
|
| 120 |
+
fro = F.squeeze(-1)
|
| 121 |
+
|
| 122 |
+
o = torch.stack(outs, dim=1).to(q.dtype)
|
| 123 |
+
return o, state, fro
|
| 124 |
+
|
| 125 |
+
#############
|
| 126 |
+
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):
|
| 127 |
+
"""
|
| 128 |
+
PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2).
|
| 129 |
+
|
| 130 |
+
We follow the GLA recurrence to build the per-step key-key state
|
| 131 |
+
H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action
|
| 132 |
+
on q_t by a cubic polynomial in H_t / ||H_t||_F:
|
| 133 |
+
|
| 134 |
+
q_t_out = a * q_t
|
| 135 |
+
+ b * (q_t @ H_t) / ||H_t||_F
|
| 136 |
+
+ c * (q_t @ H_t @ H_t) / ||H_t||_F^2
|
| 137 |
+
+ d * (q_t @ H_t @ H_t @ H_t) / ||H_t||_F^3
|
| 138 |
+
|
| 139 |
+
Args:
|
| 140 |
+
q: Query tensor with shape [B, T, H, D].
|
| 141 |
+
k: Key tensor with shape [B, T, H, D].
|
| 142 |
+
gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use.
|
| 143 |
+
a, b, c, d: Polynomial coefficients. Each may be a scalar or a length-H tensor.
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
o: Output tensor with shape [B, T, H, D].
|
| 147 |
+
states: List of length T, each [B, H, D, D] (the per-step H_t).
|
| 148 |
+
fros: List of length T, each [B, H] (per-step Frobenius norm).
|
| 149 |
+
"""
|
| 150 |
+
B, T, H, D = q.shape
|
| 151 |
+
if learnable_abc is not None:
|
| 152 |
+
t = learnable_abc
|
| 153 |
+
if not torch.is_tensor(t):
|
| 154 |
+
t = torch.tensor(list(t), device=q.device, dtype=torch.float32)
|
| 155 |
+
else:
|
| 156 |
+
t = t.detach().to(device=q.device)
|
| 157 |
+
if t.numel() == 4:
|
| 158 |
+
a, b, c, d = t.reshape(4).unbind(0)
|
| 159 |
+
elif t.reshape(-1).numel() == H * 4:
|
| 160 |
+
t = t.reshape(H, 4)
|
| 161 |
+
a, b, c, d = t[:, 0], t[:, 1], t[:, 2], t[:, 3]
|
| 162 |
+
else:
|
| 163 |
+
raise ValueError(
|
| 164 |
+
f"learnable_abc must be [4] or [H, 4] with H={H}, got {tuple(t.shape)}"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def _coeff(x):
|
| 168 |
+
if torch.is_tensor(x):
|
| 169 |
+
t = x.reshape(-1)
|
| 170 |
+
if t.numel() == 1:
|
| 171 |
+
t = t.expand(H)
|
| 172 |
+
elif t.numel() != H:
|
| 173 |
+
raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}")
|
| 174 |
+
return t.to(device=q.device, dtype=torch.float32).view(1, H, 1)
|
| 175 |
+
return x
|
| 176 |
+
|
| 177 |
+
a = _coeff(a)
|
| 178 |
+
b = _coeff(b)
|
| 179 |
+
c = _coeff(c)
|
| 180 |
+
d = _coeff(d)
|
| 181 |
+
if h0 is None:
|
| 182 |
+
state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device)
|
| 183 |
+
else:
|
| 184 |
+
state = h0.to(device=q.device, dtype=torch.float32)
|
| 185 |
+
if state.dim() == 3:
|
| 186 |
+
state = state.unsqueeze(0)
|
| 187 |
+
if state.shape[0] == 1 and B > 1:
|
| 188 |
+
state = state.expand(B, -1, -1, -1).contiguous()
|
| 189 |
+
if gk is None:
|
| 190 |
+
gkk = torch.ones(B, T, H, dtype=torch.float32, device=q.device)
|
| 191 |
+
else:
|
| 192 |
+
gkk = torch.exp(gk.float()).float()
|
| 193 |
+
|
| 194 |
+
outs = []
|
| 195 |
+
eps = 1e-12
|
| 196 |
+
|
| 197 |
+
for i in range(T):
|
| 198 |
+
ki = k[:, i, :, :]
|
| 199 |
+
state = gkk[:, i, :].view(B, H, 1, 1) * state + ki.unsqueeze(-1) * ki.unsqueeze(-2)
|
| 200 |
+
F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float()
|
| 201 |
+
F_safe = F + eps
|
| 202 |
+
qi = q[:, i, :, :].float()
|
| 203 |
+
q_state = ((qi.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
|
| 204 |
+
q_state2 = ((q_state.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
|
| 205 |
+
q_state3 = ((q_state2.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float() # [B, H, D]
|
| 206 |
+
out = (
|
| 207 |
+
a * qi
|
| 208 |
+
+ b * q_state
|
| 209 |
+
+ c * q_state2
|
| 210 |
+
+ d * q_state3
|
| 211 |
+
).to(q.dtype)
|
| 212 |
+
outs.append(out)
|
| 213 |
+
fro = F.squeeze(-1)
|
| 214 |
+
o = torch.stack(outs, dim=1).to(q.dtype)
|
| 215 |
+
return o, state, fro
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _coeff_last_dim(learnable_abc: Union[Tensor, Sequence[float]]) -> int:
|
| 220 |
+
if torch.is_tensor(learnable_abc):
|
| 221 |
+
if learnable_abc.ndim == 0:
|
| 222 |
+
raise ValueError("learnable_abc must be a vector or [H, n] tensor, got a scalar")
|
| 223 |
+
return int(learnable_abc.shape[-1])
|
| 224 |
+
return len(learnable_abc)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _normalize_abc(
|
| 228 |
+
learnable_abc: Union[Tensor, Sequence[float]],
|
| 229 |
+
H: int,
|
| 230 |
+
n_coeff: int,
|
| 231 |
+
device: torch.device,
|
| 232 |
+
) -> Tensor:
|
| 233 |
+
if torch.is_tensor(learnable_abc):
|
| 234 |
+
t = learnable_abc.detach().to(device=device, dtype=torch.float32)
|
| 235 |
+
else:
|
| 236 |
+
t = torch.tensor(list(learnable_abc), device=device, dtype=torch.float32)
|
| 237 |
+
if t.numel() == n_coeff:
|
| 238 |
+
t = t.reshape(1, n_coeff).expand(H, n_coeff).contiguous()
|
| 239 |
+
elif t.reshape(-1).numel() == H * n_coeff:
|
| 240 |
+
t = t.reshape(H, n_coeff).contiguous()
|
| 241 |
+
else:
|
| 242 |
+
raise ValueError(
|
| 243 |
+
f"learnable_abc must be [{n_coeff}] or [H, {n_coeff}] with H={H}, got {tuple(t.shape)}"
|
| 244 |
+
)
|
| 245 |
+
return t
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _as_bthd(x: Optional[Tensor], name: str) -> Optional[Tensor]:
|
| 249 |
+
if x is None:
|
| 250 |
+
return None
|
| 251 |
+
if x.dim() == 2:
|
| 252 |
+
return x[None, ...]
|
| 253 |
+
if x.dim() == 3:
|
| 254 |
+
return x
|
| 255 |
+
raise ValueError(f"{name} must have 2/3 dims, got {tuple(x.shape)}")
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@triton.jit(do_not_specialize=["T"])
|
| 259 |
+
def phi_kkt_decoding_kernel(
|
| 260 |
+
q_ptr,
|
| 261 |
+
k_ptr,
|
| 262 |
+
v_ptr,
|
| 263 |
+
alpha_ptr,
|
| 264 |
+
g_ptr,
|
| 265 |
+
gk_ptr,
|
| 266 |
+
abc_ptr,
|
| 267 |
+
o_ptr,
|
| 268 |
+
prev_h_kk_ptr,
|
| 269 |
+
prev_h_kv_ptr,
|
| 270 |
+
curr_h_kk_ptr,
|
| 271 |
+
curr_h_kv_ptr,
|
| 272 |
+
T,
|
| 273 |
+
scale,
|
| 274 |
+
H: tl.constexpr,
|
| 275 |
+
D: tl.constexpr,
|
| 276 |
+
BD: tl.constexpr,
|
| 277 |
+
N_COEFF: tl.constexpr,
|
| 278 |
+
USE_G: tl.constexpr,
|
| 279 |
+
USE_GK: tl.constexpr,
|
| 280 |
+
):
|
| 281 |
+
b_id = tl.program_id(0)
|
| 282 |
+
h_id = tl.program_id(1)
|
| 283 |
+
|
| 284 |
+
o_d = tl.arange(0, BD)
|
| 285 |
+
mask_d = o_d < D
|
| 286 |
+
mask_dd = mask_d[:, None] & mask_d[None, :]
|
| 287 |
+
|
| 288 |
+
state_off = (b_id * H + h_id).to(tl.int64) * D * D
|
| 289 |
+
p_hkk = prev_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :]
|
| 290 |
+
p_hkv = prev_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :]
|
| 291 |
+
b_h_kk = tl.load(p_hkk, mask=mask_dd, other=0).to(tl.float32)
|
| 292 |
+
b_h_kv = tl.load(p_hkv, mask=mask_dd, other=0).to(tl.float32)
|
| 293 |
+
|
| 294 |
+
coeff_a = tl.load(abc_ptr + h_id * N_COEFF + 0).to(tl.float32)
|
| 295 |
+
coeff_b = tl.load(abc_ptr + h_id * N_COEFF + 1).to(tl.float32)
|
| 296 |
+
coeff_c = tl.load(abc_ptr + h_id * N_COEFF + 2).to(tl.float32)
|
| 297 |
+
coeff_d = 0.0
|
| 298 |
+
if N_COEFF == 4:
|
| 299 |
+
coeff_d = tl.load(abc_ptr + h_id * N_COEFF + 3).to(tl.float32)
|
| 300 |
+
|
| 301 |
+
for t in range(0, T):
|
| 302 |
+
vec_off = ((b_id * T + t) * H + h_id) * D
|
| 303 |
+
scalar_off = (b_id * T + t) * H + h_id
|
| 304 |
+
|
| 305 |
+
b_q = tl.load(q_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
|
| 306 |
+
b_k = tl.load(k_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
|
| 307 |
+
b_v = tl.load(v_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
|
| 308 |
+
b_alpha = tl.load(alpha_ptr + scalar_off).to(tl.float32)
|
| 309 |
+
|
| 310 |
+
if USE_GK:
|
| 311 |
+
b_gkk = exp(tl.load(gk_ptr + scalar_off).to(tl.float32))
|
| 312 |
+
else:
|
| 313 |
+
b_gkk = 1.0
|
| 314 |
+
if USE_G:
|
| 315 |
+
b_g = exp(tl.load(g_ptr + scalar_off).to(tl.float32))
|
| 316 |
+
else:
|
| 317 |
+
b_g = 1.0
|
| 318 |
+
|
| 319 |
+
b_h_kk = b_h_kk * b_gkk + b_k[:, None] * b_k[None, :]
|
| 320 |
+
fro = tl.sqrt(tl.sum(b_h_kk * b_h_kk)) + 1e-12
|
| 321 |
+
|
| 322 |
+
o1 = tl.sum(b_h_kk * b_q[:, None], axis=0) / fro
|
| 323 |
+
o2 = tl.sum(b_h_kk * o1[:, None], axis=0) / fro
|
| 324 |
+
q_poly = coeff_a * b_q + coeff_b * o1 + coeff_c * o2
|
| 325 |
+
if N_COEFF == 4:
|
| 326 |
+
o3 = tl.sum(b_h_kk * o2[:, None], axis=0) / fro
|
| 327 |
+
q_poly = q_poly + coeff_d * o3
|
| 328 |
+
|
| 329 |
+
q_mix = b_q + b_alpha * (q_poly - b_q)
|
| 330 |
+
b_h_kv = b_h_kv * b_g + b_k[:, None] * b_v[None, :]
|
| 331 |
+
b_o = scale * tl.sum(b_h_kv * q_mix[:, None], axis=0)
|
| 332 |
+
tl.store(o_ptr + vec_off + o_d, b_o.to(o_ptr.dtype.element_ty), mask=mask_d)
|
| 333 |
+
|
| 334 |
+
p_hkk_out = curr_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :]
|
| 335 |
+
p_hkv_out = curr_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :]
|
| 336 |
+
tl.store(p_hkk_out, b_h_kk.to(p_hkk_out.dtype.element_ty), mask=mask_dd)
|
| 337 |
+
tl.store(p_hkv_out, b_h_kv.to(p_hkv_out.dtype.element_ty), mask=mask_dd)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def _prepare_decode_inputs(
|
| 341 |
+
q: Tensor,
|
| 342 |
+
k: Tensor,
|
| 343 |
+
v: Tensor,
|
| 344 |
+
alpha: Tensor,
|
| 345 |
+
g: Optional[Tensor],
|
| 346 |
+
gk: Optional[Tensor],
|
| 347 |
+
prev_h_kk: Optional[Tensor],
|
| 348 |
+
prev_h_kv: Optional[Tensor],
|
| 349 |
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Optional[Tensor], Optional[Tensor], Tensor, Tensor]:
|
| 350 |
+
if q.dim() < 4:
|
| 351 |
+
q = q[None, ...]
|
| 352 |
+
k = k[None, ...]
|
| 353 |
+
v = v[None, ...]
|
| 354 |
+
alpha = _as_bthd(alpha, "alpha")
|
| 355 |
+
g = _as_bthd(g, "g")
|
| 356 |
+
gk = _as_bthd(gk, "gk")
|
| 357 |
+
|
| 358 |
+
B, T, H, D = q.shape
|
| 359 |
+
if prev_h_kk is None:
|
| 360 |
+
prev_h_kk = q.new_zeros(B, H, D, D, dtype=torch.float32)
|
| 361 |
+
else:
|
| 362 |
+
if prev_h_kk.dim() == 3:
|
| 363 |
+
prev_h_kk = prev_h_kk.unsqueeze(0)
|
| 364 |
+
prev_h_kk = prev_h_kk.contiguous()
|
| 365 |
+
if prev_h_kk.shape[0] == 1 and B > 1:
|
| 366 |
+
prev_h_kk = prev_h_kk.expand(B, -1, -1, -1).contiguous()
|
| 367 |
+
if prev_h_kv is None:
|
| 368 |
+
prev_h_kv = q.new_zeros(B, H, D, D, dtype=torch.float32)
|
| 369 |
+
else:
|
| 370 |
+
if prev_h_kv.dim() == 3:
|
| 371 |
+
prev_h_kv = prev_h_kv.unsqueeze(0)
|
| 372 |
+
prev_h_kv = prev_h_kv.contiguous()
|
| 373 |
+
if prev_h_kv.shape[0] == 1 and B > 1:
|
| 374 |
+
prev_h_kv = prev_h_kv.expand(B, -1, -1, -1).contiguous()
|
| 375 |
+
return q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
@input_guard
|
| 379 |
+
def phi_kkt_decoding_one_step(
|
| 380 |
+
q: Tensor,
|
| 381 |
+
k: Tensor,
|
| 382 |
+
v: Tensor,
|
| 383 |
+
alpha: Tensor,
|
| 384 |
+
g: Tensor,
|
| 385 |
+
gk: Tensor,
|
| 386 |
+
gla_scale,
|
| 387 |
+
learnable_abc: Tensor,
|
| 388 |
+
prev_h_kk: Tensor,
|
| 389 |
+
prev_h_kv: Tensor,
|
| 390 |
+
) -> Tuple[Tensor, Tensor, Tensor]:
|
| 391 |
+
"""
|
| 392 |
+
Fused single-step (or short-T) Sigma GKA inference with cached H_kk / H_kv.
|
| 393 |
+
|
| 394 |
+
H_t = exp(g_t) H_{t-1} + k_t k_t^T
|
| 395 |
+
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]
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
q, k, v: [B, T, H, D] or [T, H, D]
|
| 399 |
+
alpha: [B, T, H] or [T, H]
|
| 400 |
+
g, gk: [B, T, H] or [T, H]
|
| 401 |
+
prev_h_kk: previous key-key state [B, H, D, D] or [H, D, D]
|
| 402 |
+
prev_h_kv: previous key-value state [B, H, D, D] or [H, D, D]
|
| 403 |
+
"""
|
| 404 |
+
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv = _prepare_decode_inputs(
|
| 405 |
+
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
|
| 406 |
+
)
|
| 407 |
+
B, T, H, D = q.shape
|
| 408 |
+
n_coeff = _coeff_last_dim(learnable_abc)
|
| 409 |
+
if n_coeff not in (3, 4):
|
| 410 |
+
raise ValueError(
|
| 411 |
+
f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}"
|
| 412 |
+
)
|
| 413 |
+
abc = _normalize_abc(learnable_abc, H, n_coeff, q.device)
|
| 414 |
+
if gla_scale is None:
|
| 415 |
+
gla_scale = D ** -0.5
|
| 416 |
+
|
| 417 |
+
dummy = q.new_empty(1)
|
| 418 |
+
g_ptr = g if g is not None else dummy
|
| 419 |
+
gk_ptr = gk if gk is not None else dummy
|
| 420 |
+
|
| 421 |
+
o = torch.empty_like(q)
|
| 422 |
+
curr_h_kk = torch.empty_like(prev_h_kk)
|
| 423 |
+
curr_h_kv = torch.empty_like(prev_h_kv)
|
| 424 |
+
BD = max(triton.next_power_of_2(D), 16)
|
| 425 |
+
if BD > 256:
|
| 426 |
+
raise ValueError(f"fused decoding supports head dim <= 256, got D={D}")
|
| 427 |
+
|
| 428 |
+
phi_kkt_decoding_kernel[(B, H)](
|
| 429 |
+
q,
|
| 430 |
+
k,
|
| 431 |
+
v,
|
| 432 |
+
alpha,
|
| 433 |
+
g_ptr,
|
| 434 |
+
gk_ptr,
|
| 435 |
+
abc,
|
| 436 |
+
o,
|
| 437 |
+
prev_h_kk,
|
| 438 |
+
prev_h_kv,
|
| 439 |
+
curr_h_kk,
|
| 440 |
+
curr_h_kv,
|
| 441 |
+
T,
|
| 442 |
+
float(gla_scale),
|
| 443 |
+
H=H,
|
| 444 |
+
D=D,
|
| 445 |
+
BD=BD,
|
| 446 |
+
N_COEFF=n_coeff,
|
| 447 |
+
USE_G=g is not None,
|
| 448 |
+
USE_GK=gk is not None,
|
| 449 |
+
num_warps=4 if BD <= 64 else 8,
|
| 450 |
+
num_stages=2,
|
| 451 |
+
)
|
| 452 |
+
return o, curr_h_kk, curr_h_kv
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def phi_kkt_decoding_one_step_ref(
|
| 456 |
+
q: Tensor,
|
| 457 |
+
k: Tensor,
|
| 458 |
+
v: Tensor,
|
| 459 |
+
alpha: Tensor,
|
| 460 |
+
g: Tensor,
|
| 461 |
+
gk: Tensor,
|
| 462 |
+
gla_scale,
|
| 463 |
+
learnable_abc: Tensor,
|
| 464 |
+
prev_h_kk: Tensor,
|
| 465 |
+
prev_h_kv: Tensor,
|
| 466 |
+
) -> Tuple[Tensor, Tensor, Tensor]:
|
| 467 |
+
"""PyTorch + fused-recurrent Simple-GLA reference used for correctness checks."""
|
| 468 |
+
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv = _prepare_decode_inputs(
|
| 469 |
+
q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
|
| 470 |
+
)
|
| 471 |
+
n_coeff = _coeff_last_dim(learnable_abc)
|
| 472 |
+
if n_coeff == 3:
|
| 473 |
+
solver = test_q_kkt_solve_approx_abc
|
| 474 |
+
elif n_coeff == 4:
|
| 475 |
+
solver = test_q_kkt_solve_approx_abcd
|
| 476 |
+
else:
|
| 477 |
+
raise ValueError(
|
| 478 |
+
f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}"
|
| 479 |
+
)
|
| 480 |
+
q_, h_kk, _ = solver(
|
| 481 |
+
q,
|
| 482 |
+
k,
|
| 483 |
+
gk,
|
| 484 |
+
h0=prev_h_kk,
|
| 485 |
+
learnable_abc=learnable_abc,
|
| 486 |
+
)
|
| 487 |
+
q_mix = q + alpha[..., None] * (q_ - q)
|
| 488 |
+
o, h_kv = fused_recurrent_simple_gla(
|
| 489 |
+
q=q_mix,
|
| 490 |
+
k=k,
|
| 491 |
+
v=v,
|
| 492 |
+
scale=gla_scale,
|
| 493 |
+
g=g,
|
| 494 |
+
initial_state=prev_h_kv,
|
| 495 |
+
output_final_state=True,
|
| 496 |
+
)
|
| 497 |
+
return o, h_kk, h_kv
|
phi_kkt_approx_trace/q_kkt_solve_abcd_fast_2.py
ADDED
|
@@ -0,0 +1,1531 @@
|
|
|
|
|
|
|
|
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
|
| 2 |
+
|
| 3 |
+
Do not edit ``q_kkt_solve_abcd_fast.py``. Change vs that file:
|
| 4 |
+
|
| 5 |
+
Forward already stored o1 / o2; this fork also writes
|
| 6 |
+
``o3 = (o2 @ H) / F`` to a [B, L, H, D] buffer. Backward loads it for
|
| 7 |
+
``alpha`` / ``dabcd`` instead of reconstructing
|
| 8 |
+
``o3 = (x - a q - b o1 - c o2) / d``, which overflows when ``d`` is near 0.
|
| 9 |
+
"""
|
| 10 |
+
from typing import Optional, Sequence, Tuple, Union
|
| 11 |
+
import time
|
| 12 |
+
import torch
|
| 13 |
+
import triton
|
| 14 |
+
import triton.language as tl
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from fla.ops.common.chunk_h import chunk_fwd_h
|
| 18 |
+
from fla.ops.utils import chunk_local_cumsum
|
| 19 |
+
from fla.ops.utils.op import exp
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _choose_block_d(D: int) -> int:
|
| 23 |
+
"""Tile width along D. D=64 stays one 64x64 tile; larger D uses 32."""
|
| 24 |
+
if D == 64:
|
| 25 |
+
return 64
|
| 26 |
+
if D % 32 == 0:
|
| 27 |
+
return 32
|
| 28 |
+
if D % 16 == 0:
|
| 29 |
+
return 16
|
| 30 |
+
raise ValueError(f"head dim D={D} must be 64, or divisible by 16 or 32")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _normalize_abcd(
|
| 34 |
+
learnable_abcd: Union[torch.Tensor, Sequence[float]],
|
| 35 |
+
H: int,
|
| 36 |
+
device: torch.device,
|
| 37 |
+
dtype: torch.dtype = torch.float32,
|
| 38 |
+
) -> torch.Tensor:
|
| 39 |
+
"""Broadcast learnable_abcd to a contiguous [H, 4] tensor.
|
| 40 |
+
|
| 41 |
+
Accepts a length-4 sequence / [4] tensor (shared by all heads) or [H, 4].
|
| 42 |
+
"""
|
| 43 |
+
if torch.is_tensor(learnable_abcd):
|
| 44 |
+
t = learnable_abcd.detach().to(device=device, dtype=dtype)
|
| 45 |
+
else:
|
| 46 |
+
t = torch.tensor(list(learnable_abcd), device=device, dtype=dtype)
|
| 47 |
+
if t.numel() == 4:
|
| 48 |
+
t = t.reshape(1, 4).expand(H, 4).contiguous()
|
| 49 |
+
elif t.shape == (H, 4):
|
| 50 |
+
t = t.contiguous()
|
| 51 |
+
else:
|
| 52 |
+
raise ValueError(
|
| 53 |
+
f"learnable_abcd must be [4] or [H, 4] with H={H}, got {tuple(t.shape)}"
|
| 54 |
+
)
|
| 55 |
+
return t
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@triton.autotune(
|
| 59 |
+
configs=[
|
| 60 |
+
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
| 61 |
+
for num_warps in [2, 4, 8]
|
| 62 |
+
for num_stages in [1, 2, 3]
|
| 63 |
+
],
|
| 64 |
+
key=["D", "BLOCK_D", "load_fro"],
|
| 65 |
+
)
|
| 66 |
+
@triton.jit(do_not_specialize=["T"])
|
| 67 |
+
def q_kkt_solve_approx_gating_forward_kernel(
|
| 68 |
+
h_kk_ptr,
|
| 69 |
+
k_ptr,
|
| 70 |
+
q_ptr,
|
| 71 |
+
gkk_ptr,
|
| 72 |
+
abcd_ptr,
|
| 73 |
+
x_out_ptr,
|
| 74 |
+
o1_ptr,
|
| 75 |
+
o2_ptr,
|
| 76 |
+
o3_ptr,
|
| 77 |
+
fro_ptr,
|
| 78 |
+
T,
|
| 79 |
+
H: tl.constexpr,
|
| 80 |
+
D: tl.constexpr,
|
| 81 |
+
chunk_size: tl.constexpr,
|
| 82 |
+
BLOCK_D: tl.constexpr,
|
| 83 |
+
load_fro: tl.constexpr,
|
| 84 |
+
):
|
| 85 |
+
"""Tiled GLA apply of phi(H) ~ a I + b H/F + c H^2/F^2 + d H^3/F^3.
|
| 86 |
+
|
| 87 |
+
Grid: (num_chunks, B*H). D is walked in BLOCK_D tiles so D=128 stays
|
| 88 |
+
[C, BD] / [BD, BD] instead of a live [D, D] plus fro intermediates.
|
| 89 |
+
Stores o3 so backward does not reconstruct it via /d.
|
| 90 |
+
"""
|
| 91 |
+
chunk_id, bh_id = tl.program_id(0), tl.program_id(1)
|
| 92 |
+
b_id, h_id = bh_id // H, bh_id % H
|
| 93 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 94 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 95 |
+
|
| 96 |
+
scalar_off = b_id * T * H + h_id
|
| 97 |
+
gkk_ptr += scalar_off
|
| 98 |
+
vec_off = scalar_off * D
|
| 99 |
+
q_ptr += vec_off
|
| 100 |
+
x_out_ptr += vec_off
|
| 101 |
+
o1_ptr += vec_off
|
| 102 |
+
o2_ptr += vec_off
|
| 103 |
+
o3_ptr += vec_off
|
| 104 |
+
k_ptr += vec_off
|
| 105 |
+
h_kk_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 106 |
+
|
| 107 |
+
p_gkk = tl.make_block_ptr(
|
| 108 |
+
gkk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 109 |
+
)
|
| 110 |
+
gkk = tl.load(p_gkk, boundary_check=(0,)).to(tl.float32)
|
| 111 |
+
o_t = chunk_id * chunk_size + tl.arange(0, chunk_size)
|
| 112 |
+
m_t = o_t < T
|
| 113 |
+
mask = tl.where(
|
| 114 |
+
(o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :]),
|
| 115 |
+
exp(gkk[:, None] - gkk[None, :]),
|
| 116 |
+
0.0,
|
| 117 |
+
)
|
| 118 |
+
exp_gkk = exp(gkk[:, None])
|
| 119 |
+
|
| 120 |
+
if load_fro == 1:
|
| 121 |
+
fro_ptr += scalar_off
|
| 122 |
+
p_fro = tl.make_block_ptr(
|
| 123 |
+
fro_ptr, (T, 1), (H, 1), (chunk_id * chunk_size, 0), (chunk_size, 1), (1, 0)
|
| 124 |
+
)
|
| 125 |
+
fro = tl.load(p_fro, boundary_check=(0, 1)).to(tl.float32)
|
| 126 |
+
else:
|
| 127 |
+
S_kk = _bwd_dot_xyT(
|
| 128 |
+
k_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 129 |
+
)
|
| 130 |
+
n0 = tl.zeros((1,), dtype=tl.float32)
|
| 131 |
+
vec = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 132 |
+
for i in tl.static_range(0, NUM_D):
|
| 133 |
+
d0 = i * BLOCK_D
|
| 134 |
+
kh = _fwd_vh(
|
| 135 |
+
k_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D
|
| 136 |
+
)
|
| 137 |
+
ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 138 |
+
vec += tl.sum(kh * ki, axis=1)
|
| 139 |
+
for j in tl.static_range(0, NUM_D):
|
| 140 |
+
d1 = j * BLOCK_D
|
| 141 |
+
h_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D)
|
| 142 |
+
n0 += tl.sum(tl.sum(h_tile * h_tile, axis=0), axis=0)
|
| 143 |
+
intra = tl.sum(tl.dot(mask, S_kk * S_kk) * mask, axis=1, keep_dims=True)
|
| 144 |
+
mixed = tl.sum(mask * vec[None, :], axis=1, keep_dims=True)
|
| 145 |
+
n0_s = tl.sum(n0)
|
| 146 |
+
fro = tl.sqrt(intra + exp_gkk * (exp_gkk * n0_s) + 2.0 * exp_gkk * mixed)
|
| 147 |
+
fro_ptr += scalar_off
|
| 148 |
+
p_fro = tl.make_block_ptr(
|
| 149 |
+
fro_ptr, (T, 1), (H, 1), (chunk_id * chunk_size, 0), (chunk_size, 1), (1, 0)
|
| 150 |
+
)
|
| 151 |
+
tl.store(
|
| 152 |
+
p_fro,
|
| 153 |
+
fro.to(p_fro.dtype.element_ty, fp_downcast_rounding="rtne"),
|
| 154 |
+
boundary_check=(0, 1),
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
fro_safe = fro + 1e-12
|
| 158 |
+
S_qk = _bwd_dot_xyT(
|
| 159 |
+
q_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 160 |
+
)
|
| 161 |
+
W = S_qk * mask
|
| 162 |
+
for i in tl.static_range(0, NUM_D):
|
| 163 |
+
d0 = i * BLOCK_D
|
| 164 |
+
qh = _fwd_vh(
|
| 165 |
+
q_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D
|
| 166 |
+
)
|
| 167 |
+
ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 168 |
+
o1 = (exp_gkk * qh + tl.dot(W, ki)) / fro_safe
|
| 169 |
+
_bwd_store_vec(o1_ptr, o1, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 170 |
+
|
| 171 |
+
S_o1k = _bwd_dot_xyT(
|
| 172 |
+
o1_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 173 |
+
)
|
| 174 |
+
W2 = S_o1k * mask
|
| 175 |
+
for i in tl.static_range(0, NUM_D):
|
| 176 |
+
d0 = i * BLOCK_D
|
| 177 |
+
o1h = _fwd_vh(
|
| 178 |
+
o1_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D
|
| 179 |
+
)
|
| 180 |
+
ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 181 |
+
o2 = (exp_gkk * o1h + tl.dot(W2, ki)) / fro_safe
|
| 182 |
+
_bwd_store_vec(o2_ptr, o2, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 183 |
+
|
| 184 |
+
S_o2k = _bwd_dot_xyT(
|
| 185 |
+
o2_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 186 |
+
)
|
| 187 |
+
W3 = S_o2k * mask
|
| 188 |
+
a = tl.load(abcd_ptr + h_id * 4 + 0).to(tl.float32)
|
| 189 |
+
b = tl.load(abcd_ptr + h_id * 4 + 1).to(tl.float32)
|
| 190 |
+
c = tl.load(abcd_ptr + h_id * 4 + 2).to(tl.float32)
|
| 191 |
+
d = tl.load(abcd_ptr + h_id * 4 + 3).to(tl.float32)
|
| 192 |
+
for i in tl.static_range(0, NUM_D):
|
| 193 |
+
d0 = i * BLOCK_D
|
| 194 |
+
o2h = _fwd_vh(
|
| 195 |
+
o2_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D
|
| 196 |
+
)
|
| 197 |
+
ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 198 |
+
o2i = _bwd_load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 199 |
+
o1i = _bwd_load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 200 |
+
qi = _bwd_load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 201 |
+
o3 = (exp_gkk * o2h + tl.dot(W3, ki)) / fro_safe
|
| 202 |
+
_bwd_store_vec(o3_ptr, o3, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 203 |
+
_bwd_store_vec(
|
| 204 |
+
x_out_ptr,
|
| 205 |
+
a * qi + b * o1i + c * o2i + d * o3,
|
| 206 |
+
T,
|
| 207 |
+
H,
|
| 208 |
+
D,
|
| 209 |
+
chunk_id,
|
| 210 |
+
chunk_size,
|
| 211 |
+
d0,
|
| 212 |
+
BLOCK_D,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def q_kkt_solve_approx_forward_triton(
|
| 217 |
+
k: torch.Tensor,
|
| 218 |
+
q: torch.Tensor,
|
| 219 |
+
gkk: torch.Tensor,
|
| 220 |
+
fro: torch.Tensor,
|
| 221 |
+
learnable_abcd: list = [1.0, -0.5, 0.375, -0.3125],
|
| 222 |
+
chunk_size: int = 64,
|
| 223 |
+
load_fro: int = 0,
|
| 224 |
+
output_final_state: bool = False,
|
| 225 |
+
h0=None,
|
| 226 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 227 |
+
"""
|
| 228 |
+
Solves q phi(k^T k) where phi(x) = x^(-1/2) using chunked processing.
|
| 229 |
+
|
| 230 |
+
Cubic polynomial: x = a q + b (q @ H)/F + c (q @ H^2)/F^2 + d (q @ H^3)/F^3.
|
| 231 |
+
Also stores o3 so backward does not reconstruct it via /d.
|
| 232 |
+
"""
|
| 233 |
+
h_kk, h_kk_final = chunk_fwd_h(
|
| 234 |
+
k=k,
|
| 235 |
+
v=k,
|
| 236 |
+
g=gkk,
|
| 237 |
+
gk=None,
|
| 238 |
+
gv=None,
|
| 239 |
+
h0=h0,
|
| 240 |
+
output_final_state=output_final_state,
|
| 241 |
+
states_in_fp32=False,
|
| 242 |
+
cu_seqlens=None,
|
| 243 |
+
chunk_size=chunk_size,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
B, T, H, D = q.shape
|
| 247 |
+
|
| 248 |
+
num_chunks = triton.cdiv(T, chunk_size)
|
| 249 |
+
grid = (num_chunks, H * B)
|
| 250 |
+
|
| 251 |
+
x_out = torch.empty_like(q)
|
| 252 |
+
o1 = torch.empty_like(q)
|
| 253 |
+
o2 = torch.empty_like(q)
|
| 254 |
+
o3 = torch.empty_like(q)
|
| 255 |
+
|
| 256 |
+
abcd_heads = _normalize_abcd(learnable_abcd, H, q.device, torch.float32)
|
| 257 |
+
block_d = _choose_block_d(D)
|
| 258 |
+
q_kkt_solve_approx_gating_forward_kernel[grid](
|
| 259 |
+
h_kk,
|
| 260 |
+
k,
|
| 261 |
+
q,
|
| 262 |
+
gkk,
|
| 263 |
+
abcd_heads,
|
| 264 |
+
x_out,
|
| 265 |
+
o1,
|
| 266 |
+
o2,
|
| 267 |
+
o3,
|
| 268 |
+
fro,
|
| 269 |
+
T,
|
| 270 |
+
H,
|
| 271 |
+
D,
|
| 272 |
+
chunk_size,
|
| 273 |
+
block_d,
|
| 274 |
+
load_fro,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
return x_out, o1, o2, o3, fro, h_kk, h_kk_final
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def q_kkt_solve_approx_backward_triton(
|
| 281 |
+
k: torch.Tensor,
|
| 282 |
+
dx: torch.Tensor,
|
| 283 |
+
gkk: torch.Tensor,
|
| 284 |
+
fro: torch.Tensor,
|
| 285 |
+
learnable_abcd: list = [1.0, -0.5, 0.375, -0.3125],
|
| 286 |
+
chunk_size: int = 64,
|
| 287 |
+
load_fro: int = 1,
|
| 288 |
+
output_final_state: bool = False,
|
| 289 |
+
h0=None,
|
| 290 |
+
h_kk: Optional[torch.Tensor] = None,
|
| 291 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 292 |
+
"""
|
| 293 |
+
Fused backward apply of self-adjoint phi(H).
|
| 294 |
+
|
| 295 |
+
dq = phi(H) dx = a dx + b (dx @ H)/F + c (dx @ H^2)/F^2 + d (dx @ H^3)/F^3
|
| 296 |
+
dx1 = (dx @ H) / F
|
| 297 |
+
dx2 = (dx @ H^2) / F^2
|
| 298 |
+
|
| 299 |
+
Pass ``h_kk`` from the forward to skip recomputing ``chunk_fwd_h``.
|
| 300 |
+
"""
|
| 301 |
+
if h_kk is None:
|
| 302 |
+
h_kk, h_kk_final = chunk_fwd_h(
|
| 303 |
+
k=k,
|
| 304 |
+
v=k,
|
| 305 |
+
g=gkk,
|
| 306 |
+
gk=None,
|
| 307 |
+
gv=None,
|
| 308 |
+
h0=h0,
|
| 309 |
+
output_final_state=output_final_state,
|
| 310 |
+
states_in_fp32=False,
|
| 311 |
+
cu_seqlens=None,
|
| 312 |
+
chunk_size=chunk_size,
|
| 313 |
+
)
|
| 314 |
+
else:
|
| 315 |
+
h_kk_final = None
|
| 316 |
+
|
| 317 |
+
B, T, H, D = dx.shape
|
| 318 |
+
num_chunks = triton.cdiv(T, chunk_size)
|
| 319 |
+
grid = (num_chunks, H * B)
|
| 320 |
+
|
| 321 |
+
dq = torch.empty_like(dx)
|
| 322 |
+
dx1 = torch.empty_like(dx)
|
| 323 |
+
dx2 = torch.empty_like(dx)
|
| 324 |
+
# Forward kernel now also stores o3; backward only needs dq / dx1 / dx2.
|
| 325 |
+
dx3 = torch.empty_like(dx)
|
| 326 |
+
|
| 327 |
+
abcd_heads = _normalize_abcd(learnable_abcd, H, dx.device, torch.float32)
|
| 328 |
+
block_d = _choose_block_d(D)
|
| 329 |
+
q_kkt_solve_approx_gating_forward_kernel[grid](
|
| 330 |
+
h_kk,
|
| 331 |
+
k,
|
| 332 |
+
dx,
|
| 333 |
+
gkk,
|
| 334 |
+
abcd_heads,
|
| 335 |
+
dq,
|
| 336 |
+
dx1,
|
| 337 |
+
dx2,
|
| 338 |
+
dx3,
|
| 339 |
+
fro,
|
| 340 |
+
T,
|
| 341 |
+
H,
|
| 342 |
+
D,
|
| 343 |
+
chunk_size,
|
| 344 |
+
block_d,
|
| 345 |
+
load_fro,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
return dq, dx1, dx2, fro, h_kk, h_kk_final
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@triton.jit
|
| 352 |
+
def _bwd_load_vec(
|
| 353 |
+
ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D: tl.constexpr
|
| 354 |
+
):
|
| 355 |
+
"""Load a [chunk_size, BLOCK_D] tile as fp32.
|
| 356 |
+
|
| 357 |
+
Storage may be bf16; promote to fp32 so G_partial / dgk accumulate
|
| 358 |
+
in TF32 MMA instead of truncating operands to bf16.
|
| 359 |
+
"""
|
| 360 |
+
p = tl.make_block_ptr(
|
| 361 |
+
ptr,
|
| 362 |
+
(T, D),
|
| 363 |
+
(H * D, 1),
|
| 364 |
+
(chunk_id * chunk_size, d0),
|
| 365 |
+
(chunk_size, BLOCK_D),
|
| 366 |
+
(1, 0),
|
| 367 |
+
)
|
| 368 |
+
x = tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 369 |
+
return tl.where(m_t[:, None], x, 0.0)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@triton.jit
|
| 373 |
+
def _bwd_store_vec(ptr, val, T, H, D, chunk_id, chunk_size, d0, BLOCK_D: tl.constexpr):
|
| 374 |
+
p = tl.make_block_ptr(
|
| 375 |
+
ptr,
|
| 376 |
+
(T, D),
|
| 377 |
+
(H * D, 1),
|
| 378 |
+
(chunk_id * chunk_size, d0),
|
| 379 |
+
(chunk_size, BLOCK_D),
|
| 380 |
+
(1, 0),
|
| 381 |
+
)
|
| 382 |
+
tl.store(
|
| 383 |
+
p,
|
| 384 |
+
val.to(p.dtype.element_ty, fp_downcast_rounding="rtne"),
|
| 385 |
+
boundary_check=(0, 1),
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@triton.jit
|
| 390 |
+
def _bwd_load_mat(ptr, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 391 |
+
p = tl.make_block_ptr(
|
| 392 |
+
ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0)
|
| 393 |
+
)
|
| 394 |
+
return tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
@triton.jit
|
| 398 |
+
def _bwd_store_mat(ptr, val, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 399 |
+
p = tl.make_block_ptr(
|
| 400 |
+
ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0)
|
| 401 |
+
)
|
| 402 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
@triton.jit
|
| 406 |
+
def _bwd_dot_xyT(
|
| 407 |
+
x_ptr,
|
| 408 |
+
y_ptr,
|
| 409 |
+
T,
|
| 410 |
+
H,
|
| 411 |
+
D,
|
| 412 |
+
chunk_id,
|
| 413 |
+
chunk_size,
|
| 414 |
+
m_t,
|
| 415 |
+
BLOCK_D: tl.constexpr,
|
| 416 |
+
NUM_D: tl.constexpr,
|
| 417 |
+
):
|
| 418 |
+
S = tl.zeros((chunk_size, chunk_size), dtype=tl.float32)
|
| 419 |
+
for i in tl.static_range(0, NUM_D):
|
| 420 |
+
d0 = i * BLOCK_D
|
| 421 |
+
x = _bwd_load_vec(x_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 422 |
+
y = _bwd_load_vec(y_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 423 |
+
S += tl.dot(x, tl.trans(y))
|
| 424 |
+
return S
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
@triton.jit
|
| 428 |
+
def _bwd_acc_weighted(
|
| 429 |
+
dk_ptr,
|
| 430 |
+
v_ptr,
|
| 431 |
+
A,
|
| 432 |
+
S,
|
| 433 |
+
T,
|
| 434 |
+
H,
|
| 435 |
+
D,
|
| 436 |
+
chunk_id,
|
| 437 |
+
chunk_size,
|
| 438 |
+
m_t,
|
| 439 |
+
BLOCK_D: tl.constexpr,
|
| 440 |
+
NUM_D: tl.constexpr,
|
| 441 |
+
):
|
| 442 |
+
for i in tl.static_range(0, NUM_D):
|
| 443 |
+
d0 = i * BLOCK_D
|
| 444 |
+
v = _bwd_load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 445 |
+
dk = _bwd_load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 446 |
+
_bwd_store_vec(
|
| 447 |
+
dk_ptr,
|
| 448 |
+
dk + tl.dot(tl.trans(A * S), v),
|
| 449 |
+
T,
|
| 450 |
+
H,
|
| 451 |
+
D,
|
| 452 |
+
chunk_id,
|
| 453 |
+
chunk_size,
|
| 454 |
+
d0,
|
| 455 |
+
BLOCK_D,
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
@triton.jit
|
| 460 |
+
def _bwd_h0v(
|
| 461 |
+
v_ptr,
|
| 462 |
+
h0_ptr,
|
| 463 |
+
T,
|
| 464 |
+
H,
|
| 465 |
+
D,
|
| 466 |
+
chunk_id,
|
| 467 |
+
chunk_size,
|
| 468 |
+
d0,
|
| 469 |
+
m_t,
|
| 470 |
+
BLOCK_D: tl.constexpr,
|
| 471 |
+
NUM_D: tl.constexpr,
|
| 472 |
+
):
|
| 473 |
+
"""(v @ h0^T)[:, d0:d0+BD] = sum_d1 v[:, d1] @ h0[d0, d1].T"""
|
| 474 |
+
acc = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 475 |
+
for j in tl.static_range(0, NUM_D):
|
| 476 |
+
d1 = j * BLOCK_D
|
| 477 |
+
v1 = _bwd_load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 478 |
+
h01 = _bwd_load_mat(h0_ptr, D, d0, d1, BLOCK_D)
|
| 479 |
+
acc += tl.dot(v1, tl.trans(h01))
|
| 480 |
+
return acc
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
@triton.jit
|
| 484 |
+
def _fwd_vh(
|
| 485 |
+
v_ptr,
|
| 486 |
+
h_ptr,
|
| 487 |
+
T,
|
| 488 |
+
H,
|
| 489 |
+
D,
|
| 490 |
+
chunk_id,
|
| 491 |
+
chunk_size,
|
| 492 |
+
d0,
|
| 493 |
+
m_t,
|
| 494 |
+
BLOCK_D: tl.constexpr,
|
| 495 |
+
NUM_D: tl.constexpr,
|
| 496 |
+
):
|
| 497 |
+
"""(v @ h)[:, d0:d0+BD] = sum_d1 v[:, d1] @ h[d1, d0]."""
|
| 498 |
+
acc = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 499 |
+
for j in tl.static_range(0, NUM_D):
|
| 500 |
+
d1 = j * BLOCK_D
|
| 501 |
+
v1 = _bwd_load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 502 |
+
h01 = _bwd_load_mat(h_ptr, D, d1, d0, BLOCK_D)
|
| 503 |
+
acc += tl.dot(v1, h01)
|
| 504 |
+
return acc
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
@triton.jit
|
| 508 |
+
def _bwd_gin_reverse_scan_kernel(
|
| 509 |
+
g_partial_ptr,
|
| 510 |
+
scale_last_ptr,
|
| 511 |
+
gin_ptr,
|
| 512 |
+
dht_ptr,
|
| 513 |
+
NC: tl.constexpr,
|
| 514 |
+
H: tl.constexpr,
|
| 515 |
+
D: tl.constexpr,
|
| 516 |
+
BLOCK_D: tl.constexpr,
|
| 517 |
+
HAS_DHT: tl.constexpr,
|
| 518 |
+
):
|
| 519 |
+
"""gin[c] = g_partial[c+1] + scale_last[c+1] * gin[c+1], gin[-1] = dht.
|
| 520 |
+
|
| 521 |
+
Grid: (B*H, NUM_D*NUM_D). Each program carries one [BLOCK_D, BLOCK_D]
|
| 522 |
+
tile; tiles are independent (scalar * matrix). D=64 uses one tile.
|
| 523 |
+
A full [128, 128] fp32 carry would exceed A100 SMEM.
|
| 524 |
+
"""
|
| 525 |
+
i_bh = tl.program_id(0)
|
| 526 |
+
i_tile = tl.program_id(1)
|
| 527 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 528 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 529 |
+
r0 = (i_tile // NUM_D) * BLOCK_D
|
| 530 |
+
c0 = (i_tile % NUM_D) * BLOCK_D
|
| 531 |
+
G = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32)
|
| 532 |
+
if HAS_DHT:
|
| 533 |
+
p_dht = tl.make_block_ptr(
|
| 534 |
+
dht_ptr + (i_b * H + i_h).to(tl.int64) * D * D,
|
| 535 |
+
(D, D),
|
| 536 |
+
(D, 1),
|
| 537 |
+
(r0, c0),
|
| 538 |
+
(BLOCK_D, BLOCK_D),
|
| 539 |
+
(1, 0),
|
| 540 |
+
)
|
| 541 |
+
G = tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32)
|
| 542 |
+
last = NC - 1
|
| 543 |
+
p_gin = tl.make_block_ptr(
|
| 544 |
+
gin_ptr + ((i_b * NC + last) * H + i_h).to(tl.int64) * D * D,
|
| 545 |
+
(D, D),
|
| 546 |
+
(D, 1),
|
| 547 |
+
(r0, c0),
|
| 548 |
+
(BLOCK_D, BLOCK_D),
|
| 549 |
+
(1, 0),
|
| 550 |
+
)
|
| 551 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 552 |
+
# Triton range() does not reliably support a negative step; walk it=0..NC-2.
|
| 553 |
+
for it in tl.range(0, NC - 1):
|
| 554 |
+
cid = NC - 2 - it
|
| 555 |
+
src = cid + 1
|
| 556 |
+
p_gp = tl.make_block_ptr(
|
| 557 |
+
g_partial_ptr + ((i_b * NC + src) * H + i_h).to(tl.int64) * D * D,
|
| 558 |
+
(D, D),
|
| 559 |
+
(D, 1),
|
| 560 |
+
(r0, c0),
|
| 561 |
+
(BLOCK_D, BLOCK_D),
|
| 562 |
+
(1, 0),
|
| 563 |
+
)
|
| 564 |
+
gp = tl.load(p_gp, boundary_check=(0, 1)).to(tl.float32)
|
| 565 |
+
s = tl.load(scale_last_ptr + (i_b * NC + src) * H + i_h).to(tl.float32)
|
| 566 |
+
G = gp + s * G
|
| 567 |
+
p_gin = tl.make_block_ptr(
|
| 568 |
+
gin_ptr + ((i_b * NC + cid) * H + i_h).to(tl.int64) * D * D,
|
| 569 |
+
(D, D),
|
| 570 |
+
(D, 1),
|
| 571 |
+
(r0, c0),
|
| 572 |
+
(BLOCK_D, BLOCK_D),
|
| 573 |
+
(1, 0),
|
| 574 |
+
)
|
| 575 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
@triton.jit(do_not_specialize=["T"])
|
| 580 |
+
def q_kkt_bwd_chunk_kernel(
|
| 581 |
+
h_kk_ptr,
|
| 582 |
+
k_ptr,
|
| 583 |
+
q_ptr,
|
| 584 |
+
o1_ptr,
|
| 585 |
+
du_ptr,
|
| 586 |
+
dv_ptr,
|
| 587 |
+
alpha_ptr,
|
| 588 |
+
gkk_ptr,
|
| 589 |
+
gin_ptr,
|
| 590 |
+
g_partial_ptr,
|
| 591 |
+
scale_last_ptr,
|
| 592 |
+
dk_ptr,
|
| 593 |
+
dgk_ptr,
|
| 594 |
+
T,
|
| 595 |
+
H: tl.constexpr,
|
| 596 |
+
D: tl.constexpr,
|
| 597 |
+
chunk_size: tl.constexpr,
|
| 598 |
+
BLOCK_D: tl.constexpr,
|
| 599 |
+
STAGE: tl.constexpr,
|
| 600 |
+
HAS_GK: tl.constexpr,
|
| 601 |
+
):
|
| 602 |
+
"""Intra-chunk dk/dgk for the (q, o1, du, dv) terms. D is tiled by BLOCK_D.
|
| 603 |
+
|
| 604 |
+
D=64 uses BLOCK_D=64 (one tile). D=128 uses BLOCK_D=32.
|
| 605 |
+
Cubic (o2, dw) terms stay in ``q_kkt_bwd_chunk_o2_kernel`` to keep SMEM
|
| 606 |
+
under A100's 163 KiB when BLOCK_D=64.
|
| 607 |
+
|
| 608 |
+
STAGE 0: no G_in. Writes intra dk/dgk, G_partial, scale_last.
|
| 609 |
+
STAGE 1: loads per-chunk G_in (after reverse scan) and adds boundary terms.
|
| 610 |
+
|
| 611 |
+
dgk_t = <dH_t, H_t - k_t k_t^T> is formed with strictly-lower-triangular A
|
| 612 |
+
(previous tokens only), avoiding the unstable <dH, H> - 0.5 <k, dk> split.
|
| 613 |
+
"""
|
| 614 |
+
chunk_id, bh_id = tl.program_id(0), tl.program_id(1)
|
| 615 |
+
b_id, h_id = bh_id // H, bh_id % H
|
| 616 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 617 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 618 |
+
|
| 619 |
+
scalar_off = b_id * T * H + h_id
|
| 620 |
+
gkk_ptr += scalar_off
|
| 621 |
+
alpha_ptr += scalar_off
|
| 622 |
+
dgk_ptr += scalar_off
|
| 623 |
+
vec_off = scalar_off * D
|
| 624 |
+
k_ptr += vec_off
|
| 625 |
+
q_ptr += vec_off
|
| 626 |
+
o1_ptr += vec_off
|
| 627 |
+
du_ptr += vec_off
|
| 628 |
+
dv_ptr += vec_off
|
| 629 |
+
dk_ptr += vec_off
|
| 630 |
+
mat_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 631 |
+
h_kk_ptr += mat_off
|
| 632 |
+
gin_ptr += mat_off
|
| 633 |
+
g_partial_ptr += mat_off
|
| 634 |
+
|
| 635 |
+
p_gkk = tl.make_block_ptr(
|
| 636 |
+
gkk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 637 |
+
)
|
| 638 |
+
p_dgk = tl.make_block_ptr(
|
| 639 |
+
dgk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 640 |
+
)
|
| 641 |
+
gkk = tl.load(p_gkk, boundary_check=(0,)).to(tl.float32)
|
| 642 |
+
o_t = chunk_id * chunk_size + tl.arange(0, chunk_size)
|
| 643 |
+
m_t = o_t < T
|
| 644 |
+
A = tl.where(
|
| 645 |
+
(o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :]),
|
| 646 |
+
exp(gkk[:, None] - gkk[None, :]),
|
| 647 |
+
0.0,
|
| 648 |
+
)
|
| 649 |
+
# Strict causal: H_t - k_t k_t^T, so dgk_t = <dH_t, exp(gk_t) H_{t-1}>
|
| 650 |
+
# without subtracting <dH, kk^T> (that cancellation is the dgk error source).
|
| 651 |
+
A_strict = tl.where(o_t[:, None] > o_t[None, :], A, 0.0)
|
| 652 |
+
scale = tl.where(m_t, exp(gkk), 0.0)
|
| 653 |
+
chunk_range = tl.arange(0, chunk_size)
|
| 654 |
+
last = tl.minimum(chunk_size, T - chunk_id * chunk_size) - 1
|
| 655 |
+
is_last = chunk_range == last
|
| 656 |
+
w_last = tl.sum(tl.where(is_last[:, None], A, 0.0), axis=0)
|
| 657 |
+
scale_last = tl.sum(tl.where(is_last, scale, 0.0))
|
| 658 |
+
|
| 659 |
+
if STAGE == 0:
|
| 660 |
+
p_alpha = tl.make_block_ptr(
|
| 661 |
+
alpha_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 662 |
+
)
|
| 663 |
+
alpha = tl.where(m_t, tl.load(p_alpha, boundary_check=(0,)).to(tl.float32), 0.0)
|
| 664 |
+
|
| 665 |
+
S_duk = _bwd_dot_xyT(
|
| 666 |
+
du_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 667 |
+
)
|
| 668 |
+
S_qk = _bwd_dot_xyT(
|
| 669 |
+
q_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 670 |
+
)
|
| 671 |
+
_bwd_acc_weighted(
|
| 672 |
+
dk_ptr, q_ptr, A, S_duk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 673 |
+
)
|
| 674 |
+
_bwd_acc_weighted(
|
| 675 |
+
dk_ptr, du_ptr, A, S_qk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 676 |
+
)
|
| 677 |
+
M = tl.dot(tl.trans(S_duk) * tl.trans(S_qk), A)
|
| 678 |
+
|
| 679 |
+
S_dvk = _bwd_dot_xyT(
|
| 680 |
+
dv_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 681 |
+
)
|
| 682 |
+
S_o1k = _bwd_dot_xyT(
|
| 683 |
+
o1_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 684 |
+
)
|
| 685 |
+
_bwd_acc_weighted(
|
| 686 |
+
dk_ptr, o1_ptr, A, S_dvk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 687 |
+
)
|
| 688 |
+
_bwd_acc_weighted(
|
| 689 |
+
dk_ptr, dv_ptr, A, S_o1k, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 690 |
+
)
|
| 691 |
+
M += tl.dot(tl.trans(S_dvk) * tl.trans(S_o1k), A)
|
| 692 |
+
|
| 693 |
+
beta = tl.sum(A * (alpha * scale)[:, None], axis=0)
|
| 694 |
+
z = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 695 |
+
n0 = tl.zeros((1,), dtype=tl.float32)
|
| 696 |
+
vec_h0 = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 697 |
+
for i in tl.static_range(0, NUM_D):
|
| 698 |
+
d0 = i * BLOCK_D
|
| 699 |
+
h0k = _bwd_h0v(
|
| 700 |
+
k_ptr,
|
| 701 |
+
h_kk_ptr,
|
| 702 |
+
T,
|
| 703 |
+
H,
|
| 704 |
+
D,
|
| 705 |
+
chunk_id,
|
| 706 |
+
chunk_size,
|
| 707 |
+
d0,
|
| 708 |
+
m_t,
|
| 709 |
+
BLOCK_D,
|
| 710 |
+
NUM_D,
|
| 711 |
+
)
|
| 712 |
+
k0 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 713 |
+
dk = _bwd_load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 714 |
+
_bwd_store_vec(
|
| 715 |
+
dk_ptr,
|
| 716 |
+
dk + 2.0 * beta[:, None] * h0k,
|
| 717 |
+
T,
|
| 718 |
+
H,
|
| 719 |
+
D,
|
| 720 |
+
chunk_id,
|
| 721 |
+
chunk_size,
|
| 722 |
+
d0,
|
| 723 |
+
BLOCK_D,
|
| 724 |
+
)
|
| 725 |
+
z += tl.sum(h0k * k0, axis=1)
|
| 726 |
+
h0q = _bwd_h0v(
|
| 727 |
+
q_ptr,
|
| 728 |
+
h_kk_ptr,
|
| 729 |
+
T,
|
| 730 |
+
H,
|
| 731 |
+
D,
|
| 732 |
+
chunk_id,
|
| 733 |
+
chunk_size,
|
| 734 |
+
d0,
|
| 735 |
+
m_t,
|
| 736 |
+
BLOCK_D,
|
| 737 |
+
NUM_D,
|
| 738 |
+
)
|
| 739 |
+
h0o1 = _bwd_h0v(
|
| 740 |
+
o1_ptr,
|
| 741 |
+
h_kk_ptr,
|
| 742 |
+
T,
|
| 743 |
+
H,
|
| 744 |
+
D,
|
| 745 |
+
chunk_id,
|
| 746 |
+
chunk_size,
|
| 747 |
+
d0,
|
| 748 |
+
m_t,
|
| 749 |
+
BLOCK_D,
|
| 750 |
+
NUM_D,
|
| 751 |
+
)
|
| 752 |
+
du0 = _bwd_load_vec(du_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 753 |
+
dv0 = _bwd_load_vec(dv_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 754 |
+
vec_h0 += tl.sum(h0q * du0, axis=1) + tl.sum(h0o1 * dv0, axis=1)
|
| 755 |
+
for j in tl.static_range(0, NUM_D):
|
| 756 |
+
d1 = j * BLOCK_D
|
| 757 |
+
h0_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D)
|
| 758 |
+
n0 += tl.sum(tl.sum(h0_tile * h0_tile, axis=0), axis=0)
|
| 759 |
+
|
| 760 |
+
P = tl.dot(tl.trans(A), alpha[:, None] * A)
|
| 761 |
+
S_kk = _bwd_dot_xyT(
|
| 762 |
+
k_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 763 |
+
)
|
| 764 |
+
ones = tl.zeros((chunk_size, chunk_size), dtype=tl.float32) + 1.0
|
| 765 |
+
_bwd_acc_weighted(
|
| 766 |
+
dk_ptr,
|
| 767 |
+
k_ptr,
|
| 768 |
+
2.0 * (S_kk * P),
|
| 769 |
+
ones,
|
| 770 |
+
T,
|
| 771 |
+
H,
|
| 772 |
+
D,
|
| 773 |
+
chunk_id,
|
| 774 |
+
chunk_size,
|
| 775 |
+
m_t,
|
| 776 |
+
BLOCK_D,
|
| 777 |
+
NUM_D,
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
c0 = tl.sum(alpha * scale * scale)
|
| 781 |
+
for i in tl.static_range(0, NUM_D):
|
| 782 |
+
d0 = i * BLOCK_D
|
| 783 |
+
q0 = _bwd_load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 784 |
+
o10 = _bwd_load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 785 |
+
k0 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 786 |
+
for j in tl.static_range(0, NUM_D):
|
| 787 |
+
d1 = j * BLOCK_D
|
| 788 |
+
du1 = _bwd_load_vec(
|
| 789 |
+
du_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D
|
| 790 |
+
)
|
| 791 |
+
dv1 = _bwd_load_vec(
|
| 792 |
+
dv_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D
|
| 793 |
+
)
|
| 794 |
+
k1 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 795 |
+
h0_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D)
|
| 796 |
+
Rout = tl.dot(tl.trans(scale[:, None] * q0), du1) + tl.dot(
|
| 797 |
+
tl.trans(scale[:, None] * o10), dv1
|
| 798 |
+
)
|
| 799 |
+
G_partial = (
|
| 800 |
+
Rout
|
| 801 |
+
+ c0 * h0_tile
|
| 802 |
+
+ tl.dot(tl.trans(beta[:, None] * k0), k1)
|
| 803 |
+
)
|
| 804 |
+
_bwd_store_mat(g_partial_ptr, G_partial, D, d0, d1, BLOCK_D)
|
| 805 |
+
tl.store(scale_last_ptr + (b_id * num_chunks + chunk_id) * H + h_id, scale_last)
|
| 806 |
+
|
| 807 |
+
RH = scale * tl.sum(A * vec_h0[:, None], axis=0) + tl.sum(
|
| 808 |
+
A_strict * tl.trans(M), axis=1
|
| 809 |
+
)
|
| 810 |
+
Az = tl.sum(A * z[None, :], axis=1)
|
| 811 |
+
Az_prev = tl.sum(A_strict * z[None, :], axis=1)
|
| 812 |
+
N = tl.dot(A, tl.dot(S_kk * S_kk, tl.trans(A_strict)))
|
| 813 |
+
n0_s = tl.sum(n0)
|
| 814 |
+
HH = (
|
| 815 |
+
n0_s * scale * beta
|
| 816 |
+
+ Az_prev * beta
|
| 817 |
+
+ scale * tl.sum(A * (alpha * Az)[:, None], axis=0)
|
| 818 |
+
+ tl.sum(alpha[:, None] * A * N, axis=0)
|
| 819 |
+
)
|
| 820 |
+
dgk = RH + HH
|
| 821 |
+
tl.store(
|
| 822 |
+
p_dgk,
|
| 823 |
+
tl.where(m_t, dgk, 0.0).to(p_dgk.dtype.element_ty, fp_downcast_rounding="rtne"),
|
| 824 |
+
boundary_check=(0,),
|
| 825 |
+
)
|
| 826 |
+
else:
|
| 827 |
+
dgk0 = tl.load(p_dgk, boundary_check=(0,)).to(tl.float32)
|
| 828 |
+
u = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 829 |
+
n_gh = tl.zeros((1,), dtype=tl.float32)
|
| 830 |
+
for i in tl.static_range(0, NUM_D):
|
| 831 |
+
d0 = i * BLOCK_D
|
| 832 |
+
acc = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 833 |
+
gink = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 834 |
+
k0 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 835 |
+
for j in tl.static_range(0, NUM_D):
|
| 836 |
+
d1 = j * BLOCK_D
|
| 837 |
+
k1 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 838 |
+
G_d0d1 = _bwd_load_mat(gin_ptr, D, d0, d1, BLOCK_D)
|
| 839 |
+
G_d1d0 = _bwd_load_mat(gin_ptr, D, d1, d0, BLOCK_D)
|
| 840 |
+
h0_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D)
|
| 841 |
+
acc += tl.dot(k1, G_d1d0) + tl.dot(k1, tl.trans(G_d0d1))
|
| 842 |
+
gink += tl.dot(k1, tl.trans(G_d0d1))
|
| 843 |
+
n_gh += tl.sum(tl.sum(G_d0d1 * h0_tile, axis=0), axis=0)
|
| 844 |
+
dk0 = _bwd_load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 845 |
+
dk = dk0 + w_last[:, None] * acc
|
| 846 |
+
_bwd_store_vec(dk_ptr, dk, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 847 |
+
u += tl.sum(gink * k0, axis=1)
|
| 848 |
+
Gin_H = scale * tl.sum(n_gh) + tl.sum(A_strict * u[None, :], axis=1)
|
| 849 |
+
dgk = dgk0 + w_last * Gin_H
|
| 850 |
+
tl.store(
|
| 851 |
+
p_dgk,
|
| 852 |
+
tl.where(m_t, dgk, 0.0).to(p_dgk.dtype.element_ty, fp_downcast_rounding="rtne"),
|
| 853 |
+
boundary_check=(0,),
|
| 854 |
+
)
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
@triton.jit(do_not_specialize=["T"])
|
| 858 |
+
def q_kkt_bwd_chunk_o2_kernel(
|
| 859 |
+
h_kk_ptr,
|
| 860 |
+
k_ptr,
|
| 861 |
+
o2_ptr,
|
| 862 |
+
dw_ptr,
|
| 863 |
+
gkk_ptr,
|
| 864 |
+
g_partial_ptr,
|
| 865 |
+
dk_ptr,
|
| 866 |
+
dgk_ptr,
|
| 867 |
+
T,
|
| 868 |
+
H: tl.constexpr,
|
| 869 |
+
D: tl.constexpr,
|
| 870 |
+
chunk_size: tl.constexpr,
|
| 871 |
+
BLOCK_D: tl.constexpr,
|
| 872 |
+
):
|
| 873 |
+
"""Add cubic (o2, dw) contributions onto STAGE-0 dk / G_partial / dgk.
|
| 874 |
+
|
| 875 |
+
Same BLOCK_D tiling as ``q_kkt_bwd_chunk_kernel``. Kept separate so
|
| 876 |
+
A100 SMEM stays under 163 KiB when D=64 / BLOCK_D=64.
|
| 877 |
+
"""
|
| 878 |
+
chunk_id, bh_id = tl.program_id(0), tl.program_id(1)
|
| 879 |
+
b_id, h_id = bh_id // H, bh_id % H
|
| 880 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 881 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 882 |
+
|
| 883 |
+
scalar_off = b_id * T * H + h_id
|
| 884 |
+
gkk_ptr += scalar_off
|
| 885 |
+
dgk_ptr += scalar_off
|
| 886 |
+
vec_off = scalar_off * D
|
| 887 |
+
k_ptr += vec_off
|
| 888 |
+
o2_ptr += vec_off
|
| 889 |
+
dw_ptr += vec_off
|
| 890 |
+
dk_ptr += vec_off
|
| 891 |
+
mat_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 892 |
+
h_kk_ptr += mat_off
|
| 893 |
+
g_partial_ptr += mat_off
|
| 894 |
+
|
| 895 |
+
p_gkk = tl.make_block_ptr(
|
| 896 |
+
gkk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 897 |
+
)
|
| 898 |
+
p_dgk = tl.make_block_ptr(
|
| 899 |
+
dgk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 900 |
+
)
|
| 901 |
+
gkk = tl.load(p_gkk, boundary_check=(0,)).to(tl.float32)
|
| 902 |
+
o_t = chunk_id * chunk_size + tl.arange(0, chunk_size)
|
| 903 |
+
m_t = o_t < T
|
| 904 |
+
A = tl.where(
|
| 905 |
+
(o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :]),
|
| 906 |
+
exp(gkk[:, None] - gkk[None, :]),
|
| 907 |
+
0.0,
|
| 908 |
+
)
|
| 909 |
+
A_strict = tl.where(o_t[:, None] > o_t[None, :], A, 0.0)
|
| 910 |
+
scale = tl.where(m_t, exp(gkk), 0.0)
|
| 911 |
+
|
| 912 |
+
S_dwk = _bwd_dot_xyT(
|
| 913 |
+
dw_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 914 |
+
)
|
| 915 |
+
S_o2k = _bwd_dot_xyT(
|
| 916 |
+
o2_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 917 |
+
)
|
| 918 |
+
_bwd_acc_weighted(
|
| 919 |
+
dk_ptr, o2_ptr, A, S_dwk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 920 |
+
)
|
| 921 |
+
_bwd_acc_weighted(
|
| 922 |
+
dk_ptr, dw_ptr, A, S_o2k, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D
|
| 923 |
+
)
|
| 924 |
+
|
| 925 |
+
vec_h0 = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 926 |
+
for i in tl.static_range(0, NUM_D):
|
| 927 |
+
d0 = i * BLOCK_D
|
| 928 |
+
h0o2 = _bwd_h0v(
|
| 929 |
+
o2_ptr,
|
| 930 |
+
h_kk_ptr,
|
| 931 |
+
T,
|
| 932 |
+
H,
|
| 933 |
+
D,
|
| 934 |
+
chunk_id,
|
| 935 |
+
chunk_size,
|
| 936 |
+
d0,
|
| 937 |
+
m_t,
|
| 938 |
+
BLOCK_D,
|
| 939 |
+
NUM_D,
|
| 940 |
+
)
|
| 941 |
+
dw0 = _bwd_load_vec(dw_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 942 |
+
vec_h0 += tl.sum(h0o2 * dw0, axis=1)
|
| 943 |
+
|
| 944 |
+
for i in tl.static_range(0, NUM_D):
|
| 945 |
+
d0 = i * BLOCK_D
|
| 946 |
+
o20 = _bwd_load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 947 |
+
for j in tl.static_range(0, NUM_D):
|
| 948 |
+
d1 = j * BLOCK_D
|
| 949 |
+
dw1 = _bwd_load_vec(
|
| 950 |
+
dw_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D
|
| 951 |
+
)
|
| 952 |
+
Rout = tl.dot(tl.trans(scale[:, None] * o20), dw1)
|
| 953 |
+
G = _bwd_load_mat(g_partial_ptr, D, d0, d1, BLOCK_D) + Rout
|
| 954 |
+
_bwd_store_mat(g_partial_ptr, G, D, d0, d1, BLOCK_D)
|
| 955 |
+
|
| 956 |
+
M = tl.dot(tl.trans(S_dwk) * tl.trans(S_o2k), A)
|
| 957 |
+
RH = scale * tl.sum(A * vec_h0[:, None], axis=0) + tl.sum(
|
| 958 |
+
A_strict * tl.trans(M), axis=1
|
| 959 |
+
)
|
| 960 |
+
dgk0 = tl.load(p_dgk, boundary_check=(0,)).to(tl.float32)
|
| 961 |
+
dgk = dgk0 + RH
|
| 962 |
+
tl.store(
|
| 963 |
+
p_dgk,
|
| 964 |
+
tl.where(m_t, dgk, 0.0).to(p_dgk.dtype.element_ty, fp_downcast_rounding="rtne"),
|
| 965 |
+
boundary_check=(0,),
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def _bwd_dH_to_dk_dgk(
|
| 970 |
+
k: torch.Tensor,
|
| 971 |
+
q: torch.Tensor,
|
| 972 |
+
o1: torch.Tensor,
|
| 973 |
+
o2: torch.Tensor,
|
| 974 |
+
du: torch.Tensor,
|
| 975 |
+
dv: torch.Tensor,
|
| 976 |
+
dw: torch.Tensor,
|
| 977 |
+
alpha: torch.Tensor,
|
| 978 |
+
gk: Optional[torch.Tensor],
|
| 979 |
+
gkk: Optional[torch.Tensor],
|
| 980 |
+
dht: Optional[torch.Tensor],
|
| 981 |
+
h_kk: torch.Tensor,
|
| 982 |
+
h0,
|
| 983 |
+
chunk_size: int,
|
| 984 |
+
scan_mode: str = "gpu_scan",
|
| 985 |
+
block_d: Optional[int] = None,
|
| 986 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
|
| 987 |
+
"""
|
| 988 |
+
Reverse-mode through H_t = exp(gk_t) H_{t-1} + k_t k_t^T.
|
| 989 |
+
|
| 990 |
+
Intra-chunk work is a Triton kernel with grid (num_chunks, B*H).
|
| 991 |
+
D is tiled by BLOCK_D (64 for D=64, 32 for D=128). Cubic (o2, dw) terms
|
| 992 |
+
are a second kernel after STAGE 0. Inter-chunk G_in is a tiled reverse
|
| 993 |
+
scan (grid (B*H, NUM_D^2)).
|
| 994 |
+
|
| 995 |
+
scan_mode:
|
| 996 |
+
python – STAGE 0 || o2 extra || host loop over chunks || STAGE 1
|
| 997 |
+
gpu_scan – STAGE 0 || o2 extra || one Triton reverse-scan kernel || STAGE 1
|
| 998 |
+
"""
|
| 999 |
+
B, T, nH, D = k.shape
|
| 1000 |
+
block_d = int(block_d) if block_d is not None else _choose_block_d(D)
|
| 1001 |
+
if D % block_d != 0:
|
| 1002 |
+
raise ValueError(f"D={D} must be divisible by BLOCK_D={block_d}")
|
| 1003 |
+
if scan_mode not in ("python", "gpu_scan"):
|
| 1004 |
+
raise ValueError(f"unknown scan_mode={scan_mode!r}")
|
| 1005 |
+
num_chunks = (T + chunk_size - 1) // chunk_size
|
| 1006 |
+
k = k.contiguous()
|
| 1007 |
+
q = q.contiguous()
|
| 1008 |
+
o1 = o1.contiguous()
|
| 1009 |
+
o2 = o2.contiguous()
|
| 1010 |
+
du = du.contiguous()
|
| 1011 |
+
dv = dv.contiguous()
|
| 1012 |
+
dw = dw.contiguous()
|
| 1013 |
+
alpha = alpha.contiguous()
|
| 1014 |
+
h_kk = h_kk.contiguous()
|
| 1015 |
+
if gkk is None:
|
| 1016 |
+
gkk = torch.zeros(B, T, nH, device=k.device, dtype=torch.float32)
|
| 1017 |
+
has_gk = gk is not None
|
| 1018 |
+
dk = torch.zeros_like(k, dtype=torch.float32)
|
| 1019 |
+
dgk = torch.zeros(B, T, nH, device=k.device, dtype=torch.float32)
|
| 1020 |
+
# STAGE 0/1 have no autotune (would re-run and double-add into dk).
|
| 1021 |
+
# Sweep on A100: (4 warps, 1–3 stages) all ~0.39 ms; 8 warps is slower.
|
| 1022 |
+
launch = dict(num_warps=4, num_stages=1)
|
| 1023 |
+
|
| 1024 |
+
g_partial = torch.empty(B, num_chunks, nH, D, D, device=k.device, dtype=torch.float32)
|
| 1025 |
+
scale_last = torch.empty(B, num_chunks, nH, device=k.device, dtype=torch.float32)
|
| 1026 |
+
gin = torch.empty(B, num_chunks, nH, D, D, device=k.device, dtype=torch.float32)
|
| 1027 |
+
grid = (num_chunks, nH * B)
|
| 1028 |
+
|
| 1029 |
+
q_kkt_bwd_chunk_kernel[grid](
|
| 1030 |
+
h_kk,
|
| 1031 |
+
k,
|
| 1032 |
+
q,
|
| 1033 |
+
o1,
|
| 1034 |
+
du,
|
| 1035 |
+
dv,
|
| 1036 |
+
alpha,
|
| 1037 |
+
gkk,
|
| 1038 |
+
gin,
|
| 1039 |
+
g_partial,
|
| 1040 |
+
scale_last,
|
| 1041 |
+
dk,
|
| 1042 |
+
dgk,
|
| 1043 |
+
T,
|
| 1044 |
+
nH,
|
| 1045 |
+
D,
|
| 1046 |
+
chunk_size,
|
| 1047 |
+
block_d,
|
| 1048 |
+
0,
|
| 1049 |
+
int(has_gk),
|
| 1050 |
+
**launch,
|
| 1051 |
+
)
|
| 1052 |
+
q_kkt_bwd_chunk_o2_kernel[grid](
|
| 1053 |
+
h_kk,
|
| 1054 |
+
k,
|
| 1055 |
+
o2,
|
| 1056 |
+
dw,
|
| 1057 |
+
gkk,
|
| 1058 |
+
g_partial,
|
| 1059 |
+
dk,
|
| 1060 |
+
dgk,
|
| 1061 |
+
T,
|
| 1062 |
+
nH,
|
| 1063 |
+
D,
|
| 1064 |
+
chunk_size,
|
| 1065 |
+
block_d,
|
| 1066 |
+
**launch,
|
| 1067 |
+
)
|
| 1068 |
+
if scan_mode == "python":
|
| 1069 |
+
if dht is not None:
|
| 1070 |
+
gin[:, -1] = dht.float()
|
| 1071 |
+
else:
|
| 1072 |
+
gin[:, -1] = 0
|
| 1073 |
+
for cid in range(num_chunks - 2, -1, -1):
|
| 1074 |
+
gin[:, cid] = g_partial[:, cid + 1] + scale_last[
|
| 1075 |
+
:, cid + 1, :, None, None
|
| 1076 |
+
] * gin[:, cid + 1]
|
| 1077 |
+
else:
|
| 1078 |
+
dummy = h_kk.new_empty(B, nH, D, D)
|
| 1079 |
+
dht_buf = dht.float().contiguous() if dht is not None else dummy
|
| 1080 |
+
num_d = D // block_d
|
| 1081 |
+
_bwd_gin_reverse_scan_kernel[(nH * B, num_d * num_d)](
|
| 1082 |
+
g_partial,
|
| 1083 |
+
scale_last,
|
| 1084 |
+
gin,
|
| 1085 |
+
dht_buf,
|
| 1086 |
+
num_chunks,
|
| 1087 |
+
nH,
|
| 1088 |
+
D,
|
| 1089 |
+
block_d,
|
| 1090 |
+
int(dht is not None),
|
| 1091 |
+
num_warps=4,
|
| 1092 |
+
num_stages=1,
|
| 1093 |
+
)
|
| 1094 |
+
q_kkt_bwd_chunk_kernel[grid](
|
| 1095 |
+
h_kk,
|
| 1096 |
+
k,
|
| 1097 |
+
q,
|
| 1098 |
+
o1,
|
| 1099 |
+
du,
|
| 1100 |
+
dv,
|
| 1101 |
+
alpha,
|
| 1102 |
+
gkk,
|
| 1103 |
+
gin,
|
| 1104 |
+
g_partial,
|
| 1105 |
+
scale_last,
|
| 1106 |
+
dk,
|
| 1107 |
+
dgk,
|
| 1108 |
+
T,
|
| 1109 |
+
nH,
|
| 1110 |
+
D,
|
| 1111 |
+
chunk_size,
|
| 1112 |
+
block_d,
|
| 1113 |
+
1,
|
| 1114 |
+
int(has_gk),
|
| 1115 |
+
**launch,
|
| 1116 |
+
)
|
| 1117 |
+
dh0 = None
|
| 1118 |
+
if h0 is not None:
|
| 1119 |
+
dh0 = (
|
| 1120 |
+
g_partial[:, 0] + scale_last[:, 0, :, None, None] * gin[:, 0]
|
| 1121 |
+
).to(h0.dtype)
|
| 1122 |
+
return (
|
| 1123 |
+
dk.to(k.dtype),
|
| 1124 |
+
dgk.to(gk.dtype) if has_gk else None,
|
| 1125 |
+
dh0,
|
| 1126 |
+
)
|
| 1127 |
+
|
| 1128 |
+
|
| 1129 |
+
@triton.jit(do_not_specialize=["T"])
|
| 1130 |
+
def q_kkt_bwd_prep_kernel(
|
| 1131 |
+
q_ptr,
|
| 1132 |
+
o1_ptr,
|
| 1133 |
+
o2_ptr,
|
| 1134 |
+
o3_ptr,
|
| 1135 |
+
dx_ptr,
|
| 1136 |
+
dx1_ptr,
|
| 1137 |
+
dx2_ptr,
|
| 1138 |
+
fro_ptr,
|
| 1139 |
+
abcd_ptr,
|
| 1140 |
+
du_ptr,
|
| 1141 |
+
dv_ptr,
|
| 1142 |
+
dw_ptr,
|
| 1143 |
+
alpha_ptr,
|
| 1144 |
+
dabcd_ptr,
|
| 1145 |
+
T,
|
| 1146 |
+
H: tl.constexpr,
|
| 1147 |
+
D: tl.constexpr,
|
| 1148 |
+
chunk_size: tl.constexpr,
|
| 1149 |
+
BLOCK_D: tl.constexpr,
|
| 1150 |
+
NEED_DABCD: tl.constexpr,
|
| 1151 |
+
EPS: tl.constexpr,
|
| 1152 |
+
):
|
| 1153 |
+
"""Fuse stored o3 / du / dv / dw / alpha / partial dabcd for one (chunk, B*H)."""
|
| 1154 |
+
chunk_id, bh_id = tl.program_id(0), tl.program_id(1)
|
| 1155 |
+
b_id, h_id = bh_id // H, bh_id % H
|
| 1156 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1157 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 1158 |
+
|
| 1159 |
+
scalar_off = b_id * T * H + h_id
|
| 1160 |
+
fro_ptr += scalar_off
|
| 1161 |
+
alpha_ptr += scalar_off
|
| 1162 |
+
vec_off = scalar_off * D
|
| 1163 |
+
q_ptr += vec_off
|
| 1164 |
+
o1_ptr += vec_off
|
| 1165 |
+
o2_ptr += vec_off
|
| 1166 |
+
o3_ptr += vec_off
|
| 1167 |
+
dx_ptr += vec_off
|
| 1168 |
+
dx1_ptr += vec_off
|
| 1169 |
+
dx2_ptr += vec_off
|
| 1170 |
+
du_ptr += vec_off
|
| 1171 |
+
dv_ptr += vec_off
|
| 1172 |
+
dw_ptr += vec_off
|
| 1173 |
+
|
| 1174 |
+
o_t = chunk_id * chunk_size + tl.arange(0, chunk_size)
|
| 1175 |
+
m_t = o_t < T
|
| 1176 |
+
p_fro = tl.make_block_ptr(
|
| 1177 |
+
fro_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 1178 |
+
)
|
| 1179 |
+
fro = tl.where(m_t, tl.load(p_fro, boundary_check=(0,)).to(tl.float32), 0.0)
|
| 1180 |
+
F = fro + EPS
|
| 1181 |
+
b = tl.load(abcd_ptr + h_id * 4 + 1).to(tl.float32)
|
| 1182 |
+
c = tl.load(abcd_ptr + h_id * 4 + 2).to(tl.float32)
|
| 1183 |
+
d = tl.load(abcd_ptr + h_id * 4 + 3).to(tl.float32)
|
| 1184 |
+
|
| 1185 |
+
s_o1dx = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 1186 |
+
s_o2dx = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 1187 |
+
s_o3dx = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 1188 |
+
da = tl.zeros((1,), dtype=tl.float32)
|
| 1189 |
+
db = tl.zeros((1,), dtype=tl.float32)
|
| 1190 |
+
dc = tl.zeros((1,), dtype=tl.float32)
|
| 1191 |
+
dd = tl.zeros((1,), dtype=tl.float32)
|
| 1192 |
+
for i in tl.static_range(0, NUM_D):
|
| 1193 |
+
d0 = i * BLOCK_D
|
| 1194 |
+
q = _bwd_load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1195 |
+
o1 = _bwd_load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1196 |
+
o2 = _bwd_load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1197 |
+
o3 = _bwd_load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1198 |
+
dx = _bwd_load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1199 |
+
dx1 = _bwd_load_vec(dx1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1200 |
+
dx2 = _bwd_load_vec(dx2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1201 |
+
_bwd_store_vec(
|
| 1202 |
+
du_ptr,
|
| 1203 |
+
(b * dx + c * dx1 + d * dx2) / F[:, None],
|
| 1204 |
+
T,
|
| 1205 |
+
H,
|
| 1206 |
+
D,
|
| 1207 |
+
chunk_id,
|
| 1208 |
+
chunk_size,
|
| 1209 |
+
d0,
|
| 1210 |
+
BLOCK_D,
|
| 1211 |
+
)
|
| 1212 |
+
_bwd_store_vec(
|
| 1213 |
+
dv_ptr,
|
| 1214 |
+
(c * dx + d * dx1) / F[:, None],
|
| 1215 |
+
T,
|
| 1216 |
+
H,
|
| 1217 |
+
D,
|
| 1218 |
+
chunk_id,
|
| 1219 |
+
chunk_size,
|
| 1220 |
+
d0,
|
| 1221 |
+
BLOCK_D,
|
| 1222 |
+
)
|
| 1223 |
+
_bwd_store_vec(
|
| 1224 |
+
dw_ptr, (d * dx) / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D
|
| 1225 |
+
)
|
| 1226 |
+
s_o1dx += tl.sum(o1 * dx, axis=1)
|
| 1227 |
+
s_o2dx += tl.sum(o2 * dx, axis=1)
|
| 1228 |
+
s_o3dx += tl.sum(o3 * dx, axis=1)
|
| 1229 |
+
if NEED_DABCD:
|
| 1230 |
+
da += tl.sum(tl.sum(dx * q, axis=0), axis=0)
|
| 1231 |
+
db += tl.sum(tl.sum(dx * o1, axis=0), axis=0)
|
| 1232 |
+
dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0)
|
| 1233 |
+
dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0)
|
| 1234 |
+
|
| 1235 |
+
alpha = -(b * s_o1dx + 2.0 * c * s_o2dx + 3.0 * d * s_o3dx) / (F * F)
|
| 1236 |
+
p_alpha = tl.make_block_ptr(
|
| 1237 |
+
alpha_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)
|
| 1238 |
+
)
|
| 1239 |
+
tl.store(
|
| 1240 |
+
p_alpha,
|
| 1241 |
+
tl.where(m_t, alpha, 0.0).to(p_alpha.dtype.element_ty, fp_downcast_rounding="rtne"),
|
| 1242 |
+
boundary_check=(0,),
|
| 1243 |
+
)
|
| 1244 |
+
if NEED_DABCD:
|
| 1245 |
+
off = ((b_id * num_chunks + chunk_id) * H + h_id) * 4
|
| 1246 |
+
tl.store(dabcd_ptr + off + 0, tl.sum(da))
|
| 1247 |
+
tl.store(dabcd_ptr + off + 1, tl.sum(db))
|
| 1248 |
+
tl.store(dabcd_ptr + off + 2, tl.sum(dc))
|
| 1249 |
+
tl.store(dabcd_ptr + off + 3, tl.sum(dd))
|
| 1250 |
+
|
| 1251 |
+
|
| 1252 |
+
def _bwd_prep_du_dv_dw_alpha(
|
| 1253 |
+
q: torch.Tensor,
|
| 1254 |
+
o1: torch.Tensor,
|
| 1255 |
+
o2: torch.Tensor,
|
| 1256 |
+
o3: torch.Tensor,
|
| 1257 |
+
dx: torch.Tensor,
|
| 1258 |
+
dx1: torch.Tensor,
|
| 1259 |
+
dx2: torch.Tensor,
|
| 1260 |
+
fro: torch.Tensor,
|
| 1261 |
+
abcd_heads: torch.Tensor,
|
| 1262 |
+
chunk_size: int,
|
| 1263 |
+
need_dabcd: bool,
|
| 1264 |
+
) -> Tuple[
|
| 1265 |
+
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]
|
| 1266 |
+
]:
|
| 1267 |
+
B, T, H, D = q.shape
|
| 1268 |
+
block_d = _choose_block_d(D)
|
| 1269 |
+
num_chunks = (T + chunk_size - 1) // chunk_size
|
| 1270 |
+
du = torch.empty_like(q)
|
| 1271 |
+
dv = torch.empty_like(q)
|
| 1272 |
+
dw = torch.empty_like(q)
|
| 1273 |
+
alpha = torch.empty(B, T, H, device=q.device, dtype=torch.float32)
|
| 1274 |
+
dabcd = (
|
| 1275 |
+
torch.empty(B, num_chunks, H, 4, device=q.device, dtype=torch.float32)
|
| 1276 |
+
if need_dabcd
|
| 1277 |
+
else q.new_empty(1)
|
| 1278 |
+
)
|
| 1279 |
+
q_kkt_bwd_prep_kernel[(num_chunks, H * B)](
|
| 1280 |
+
q,
|
| 1281 |
+
o1,
|
| 1282 |
+
o2,
|
| 1283 |
+
o3,
|
| 1284 |
+
dx,
|
| 1285 |
+
dx1,
|
| 1286 |
+
dx2,
|
| 1287 |
+
fro,
|
| 1288 |
+
abcd_heads,
|
| 1289 |
+
du,
|
| 1290 |
+
dv,
|
| 1291 |
+
dw,
|
| 1292 |
+
alpha,
|
| 1293 |
+
dabcd,
|
| 1294 |
+
T,
|
| 1295 |
+
H,
|
| 1296 |
+
D,
|
| 1297 |
+
chunk_size,
|
| 1298 |
+
block_d,
|
| 1299 |
+
int(need_dabcd),
|
| 1300 |
+
1e-12,
|
| 1301 |
+
num_warps=4,
|
| 1302 |
+
num_stages=1,
|
| 1303 |
+
)
|
| 1304 |
+
d_abcd_h = dabcd.sum(dim=(0, 1)) if need_dabcd else None
|
| 1305 |
+
return du, dv, dw, alpha, d_abcd_h
|
| 1306 |
+
|
| 1307 |
+
|
| 1308 |
+
class q_kkt_solve_approx(torch.autograd.Function):
|
| 1309 |
+
"""
|
| 1310 |
+
Autograd for x_t = q_t @ phi(H_t), phi(H) ~ a I + b H/F + c H^2/F^2 + d H^3/F^3.
|
| 1311 |
+
|
| 1312 |
+
a, b, c, d are per-head learnable scalars packed as a tensor of shape [H, 4].
|
| 1313 |
+
A length-4 / [4] input is broadcast to all heads; its gradient is summed over heads.
|
| 1314 |
+
"""
|
| 1315 |
+
|
| 1316 |
+
@staticmethod
|
| 1317 |
+
def forward(
|
| 1318 |
+
ctx,
|
| 1319 |
+
k: torch.Tensor,
|
| 1320 |
+
q: torch.Tensor,
|
| 1321 |
+
gk: Optional[torch.Tensor] = None,
|
| 1322 |
+
chunk_size: int = 64,
|
| 1323 |
+
learnable_abcd: Union[torch.Tensor, Sequence[float]] = (
|
| 1324 |
+
1.0,
|
| 1325 |
+
-0.5,
|
| 1326 |
+
0.375,
|
| 1327 |
+
-0.3125,
|
| 1328 |
+
),
|
| 1329 |
+
h0=None,
|
| 1330 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 1331 |
+
B, T, H, D = q.shape
|
| 1332 |
+
fro = torch.empty((B, T, H), dtype=torch.float32, device=q.device)
|
| 1333 |
+
abc_is_tensor = torch.is_tensor(learnable_abcd)
|
| 1334 |
+
if abc_is_tensor:
|
| 1335 |
+
ctx.abc_dtype = learnable_abcd.dtype
|
| 1336 |
+
assert learnable_abcd.dtype == torch.float32, f"learnable_abcd.dtype must be float32, got {learnable_abcd.dtype}"
|
| 1337 |
+
ctx.abc_device = learnable_abcd.device
|
| 1338 |
+
ctx.abc_shape = tuple(learnable_abcd.shape)
|
| 1339 |
+
else:
|
| 1340 |
+
assert abc_is_tensor, "learnable_abcd must be a tensor"
|
| 1341 |
+
|
| 1342 |
+
abcd_heads = _normalize_abcd(learnable_abcd, H, q.device, torch.float32)
|
| 1343 |
+
gkk = chunk_local_cumsum(gk, chunk_size=chunk_size) if gk is not None else None
|
| 1344 |
+
x_out, o1, o2, o3, fro, h_kk, h_kk_final = q_kkt_solve_approx_forward_triton(
|
| 1345 |
+
k,
|
| 1346 |
+
q,
|
| 1347 |
+
gkk,
|
| 1348 |
+
fro,
|
| 1349 |
+
learnable_abcd=abcd_heads,
|
| 1350 |
+
chunk_size=chunk_size,
|
| 1351 |
+
load_fro=0,
|
| 1352 |
+
output_final_state=True,
|
| 1353 |
+
h0=h0,
|
| 1354 |
+
)
|
| 1355 |
+
to_save = [k, q, o1, o2, o3, fro, abcd_heads, h_kk]
|
| 1356 |
+
if gk is not None:
|
| 1357 |
+
to_save.append(gk)
|
| 1358 |
+
if gkk is not None:
|
| 1359 |
+
to_save.append(gkk)
|
| 1360 |
+
if h0 is not None:
|
| 1361 |
+
to_save.append(h0)
|
| 1362 |
+
ctx.save_for_backward(*to_save)
|
| 1363 |
+
ctx.chunk_size = chunk_size
|
| 1364 |
+
ctx.has_gk = gk is not None
|
| 1365 |
+
ctx.has_gkk = gkk is not None
|
| 1366 |
+
ctx.has_h0 = h0 is not None
|
| 1367 |
+
return x_out, h_kk_final
|
| 1368 |
+
|
| 1369 |
+
@staticmethod
|
| 1370 |
+
def backward(
|
| 1371 |
+
ctx, dx_out: torch.Tensor, d_kk_final: Optional[torch.Tensor] = None
|
| 1372 |
+
) -> Tuple[
|
| 1373 |
+
Optional[torch.Tensor],
|
| 1374 |
+
Optional[torch.Tensor],
|
| 1375 |
+
Optional[torch.Tensor],
|
| 1376 |
+
None,
|
| 1377 |
+
Optional[torch.Tensor],
|
| 1378 |
+
Optional[torch.Tensor],
|
| 1379 |
+
]:
|
| 1380 |
+
saved = list(ctx.saved_tensors)
|
| 1381 |
+
k, q, o1, o2, o3, fro, abcd_heads, h_kk = saved[:8]
|
| 1382 |
+
idx = 8
|
| 1383 |
+
gk = saved[idx] if ctx.has_gk else None
|
| 1384 |
+
idx += int(ctx.has_gk)
|
| 1385 |
+
gkk = saved[idx] if ctx.has_gkk else None
|
| 1386 |
+
idx += int(ctx.has_gkk)
|
| 1387 |
+
h0 = saved[idx] if ctx.has_h0 else None
|
| 1388 |
+
chunk_size = ctx.chunk_size
|
| 1389 |
+
|
| 1390 |
+
dq, dx1, dx2, fro, h_kk, _ = q_kkt_solve_approx_backward_triton(
|
| 1391 |
+
k,
|
| 1392 |
+
dx_out,
|
| 1393 |
+
gkk,
|
| 1394 |
+
fro,
|
| 1395 |
+
learnable_abcd=abcd_heads,
|
| 1396 |
+
chunk_size=chunk_size,
|
| 1397 |
+
load_fro=1,
|
| 1398 |
+
output_final_state=False,
|
| 1399 |
+
h0=h0,
|
| 1400 |
+
h_kk=h_kk,
|
| 1401 |
+
)
|
| 1402 |
+
need_dabcd = bool(ctx.needs_input_grad[4])
|
| 1403 |
+
du, dv, dw, alpha, d_abcd_h = _bwd_prep_du_dv_dw_alpha(
|
| 1404 |
+
q,
|
| 1405 |
+
o1,
|
| 1406 |
+
o2,
|
| 1407 |
+
o3,
|
| 1408 |
+
dx_out,
|
| 1409 |
+
dx1,
|
| 1410 |
+
dx2,
|
| 1411 |
+
fro,
|
| 1412 |
+
abcd_heads,
|
| 1413 |
+
chunk_size,
|
| 1414 |
+
need_dabcd,
|
| 1415 |
+
)
|
| 1416 |
+
dk, dgk, dh0 = _bwd_dH_to_dk_dgk(
|
| 1417 |
+
k,
|
| 1418 |
+
q,
|
| 1419 |
+
o1,
|
| 1420 |
+
o2,
|
| 1421 |
+
du,
|
| 1422 |
+
dv,
|
| 1423 |
+
dw,
|
| 1424 |
+
alpha,
|
| 1425 |
+
gk,
|
| 1426 |
+
gkk,
|
| 1427 |
+
d_kk_final,
|
| 1428 |
+
h_kk,
|
| 1429 |
+
h0,
|
| 1430 |
+
chunk_size,
|
| 1431 |
+
)
|
| 1432 |
+
d_abcd = None
|
| 1433 |
+
if need_dabcd:
|
| 1434 |
+
if ctx.abc_shape == (4,) or (
|
| 1435 |
+
len(ctx.abc_shape) == 1 and ctx.abc_shape[0] == 4
|
| 1436 |
+
):
|
| 1437 |
+
d_abcd = d_abcd_h.sum(dim=0)
|
| 1438 |
+
else:
|
| 1439 |
+
d_abcd = d_abcd_h
|
| 1440 |
+
d_abcd = d_abcd.to(dtype=ctx.abc_dtype, device=ctx.abc_device).reshape(
|
| 1441 |
+
ctx.abc_shape
|
| 1442 |
+
)
|
| 1443 |
+
return dk, dq, dgk, None, d_abcd, dh0
|
| 1444 |
+
|
| 1445 |
+
|
| 1446 |
+
#############
|
| 1447 |
+
def test_q_kkt_solve_approx(q, k, gk, a=1.0, b=-0.5, c=0.375, d=-0.3125):
|
| 1448 |
+
"""
|
| 1449 |
+
PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2).
|
| 1450 |
+
|
| 1451 |
+
We follow the GLA recurrence to build the per-step key-key state
|
| 1452 |
+
H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action
|
| 1453 |
+
on q_t by a cubic polynomial in H_t / ||H_t||_F:
|
| 1454 |
+
|
| 1455 |
+
q_t_out = a * q_t
|
| 1456 |
+
+ b * (q_t @ H_t) / ||H_t||_F
|
| 1457 |
+
+ c * (q_t @ H_t @ H_t) / ||H_t||_F^2
|
| 1458 |
+
+ d * (q_t @ H_t @ H_t @ H_t) / ||H_t||_F^3
|
| 1459 |
+
|
| 1460 |
+
Args:
|
| 1461 |
+
q: Query tensor with shape [B, T, H, D].
|
| 1462 |
+
k: Key tensor with shape [B, T, H, D].
|
| 1463 |
+
gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use.
|
| 1464 |
+
a, b, c, d: Polynomial coefficients. Each may be a scalar or a length-H tensor.
|
| 1465 |
+
|
| 1466 |
+
Returns:
|
| 1467 |
+
o: Output tensor with shape [B, T, H, D].
|
| 1468 |
+
states: List of length T, each [B, H, D, D] (the per-step H_t).
|
| 1469 |
+
fros: List of length T, each [B, H] (per-step Frobenius norm).
|
| 1470 |
+
"""
|
| 1471 |
+
B, T, H, D = q.shape
|
| 1472 |
+
|
| 1473 |
+
def _coeff(x):
|
| 1474 |
+
if torch.is_tensor(x):
|
| 1475 |
+
t = x.reshape(-1)
|
| 1476 |
+
if t.numel() == 1:
|
| 1477 |
+
t = t.expand(H)
|
| 1478 |
+
elif t.numel() != H:
|
| 1479 |
+
raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}")
|
| 1480 |
+
return t.to(device=q.device).view(1, H, 1)
|
| 1481 |
+
return x
|
| 1482 |
+
|
| 1483 |
+
a = _coeff(a)
|
| 1484 |
+
b = _coeff(b)
|
| 1485 |
+
c = _coeff(c)
|
| 1486 |
+
d = _coeff(d)
|
| 1487 |
+
state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device)
|
| 1488 |
+
gkk = torch.exp(gk.float()).float()
|
| 1489 |
+
|
| 1490 |
+
outs = []
|
| 1491 |
+
states = []
|
| 1492 |
+
fros = []
|
| 1493 |
+
|
| 1494 |
+
for i in range(T):
|
| 1495 |
+
ki = k[:, i, :, :].float() # [B, H, D]
|
| 1496 |
+
# GLA-style state update: H_t = exp(g_t) * H_{t-1} + k_t k_t^T
|
| 1497 |
+
state = gkk[:, i, :].view(B, H, 1, 1).float() * state + ki.unsqueeze(-1).float() * ki.unsqueeze(-2).float()
|
| 1498 |
+
F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float()
|
| 1499 |
+
F_safe = F + 1e-12
|
| 1500 |
+
qi = q[:, i, :, :].float() # [B, H, D]
|
| 1501 |
+
q_state = (qi.unsqueeze(-2) @ state).squeeze(-2).float()
|
| 1502 |
+
q_state2 = (q_state.unsqueeze(-2) @ state).squeeze(-2).float()
|
| 1503 |
+
q_state3 = (q_state2.unsqueeze(-2) @ state).squeeze(-2).float()
|
| 1504 |
+
out = (
|
| 1505 |
+
a * qi
|
| 1506 |
+
+ b * q_state / F_safe
|
| 1507 |
+
+ c * q_state2 / (F_safe * F_safe)
|
| 1508 |
+
+ d * q_state3 / (F_safe * F_safe * F_safe)
|
| 1509 |
+
).to(q.dtype)
|
| 1510 |
+
outs.append(out)
|
| 1511 |
+
states.append(state.clone())
|
| 1512 |
+
fros.append(F.squeeze(-1).clone())
|
| 1513 |
+
o = torch.stack(outs, dim=1)
|
| 1514 |
+
return o, states, fros
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
##############
|
| 1518 |
+
if __name__ == "__main__":
|
| 1519 |
+
k = torch.randn(1, 10, 1, 64)
|
| 1520 |
+
q = torch.randn(1, 10, 1, 64)
|
| 1521 |
+
gk = torch.randn(1, 10, 1)
|
| 1522 |
+
a, b, c, d = 1.0, -0.5, 0.375, -0.3125 # Taylor (1+x)^(-1/2) through x^3
|
| 1523 |
+
|
| 1524 |
+
o_ref, states, fros = test_q_kkt_solve_approx(q, k, gk, a, b, c, d)
|
| 1525 |
+
print("Reference output shape:", o_ref.shape)
|
| 1526 |
+
print("Reference output:", o_ref)
|
| 1527 |
+
print("Number of states:", len(states), "last state shape:", states[-1].shape)
|
| 1528 |
+
print("Last Frobenius norm:", fros[-1])
|
| 1529 |
+
|
| 1530 |
+
|
| 1531 |
+
|
phi_kkt_approx_trace/q_kkt_solve_trace_triton.py
ADDED
|
@@ -0,0 +1,731 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
x_t = sum_m coeff[m] * q_t (H_t / tr H_t)^m
|
| 7 |
+
|
| 8 |
+
Kernels:
|
| 9 |
+
|
| 10 |
+
chunk_fwd_h states before each chunk (gk = gv = half-cumsum)
|
| 11 |
+
trace_fwd_kernel tr(H) and o_1 .. o_{N-1}, x
|
| 12 |
+
trace_bwd_chunk_kernel p_j = dx H^j / F^j, dq, alpha, dcoeff, intra-chunk dk / dgk, g_partial
|
| 13 |
+
trace_bwd_scan_kernel gin[c-1] = g_partial[c] + Diag(E_C) gin[c] Diag(E_C)
|
| 14 |
+
trace_bwd_gin_kernel S_in contribution from later chunks
|
| 15 |
+
|
| 16 |
+
Backward identities used by ``trace_bwd_chunk_kernel`` (X_m = o_{m-1} E,
|
| 17 |
+
Y_m = u_m E, u_m = do_m / F, B_j = tril((p_j E) k'^T)):
|
| 18 |
+
|
| 19 |
+
X_m H_in + tril(X_m k'^T) k' = o_m F / E
|
| 20 |
+
Y_m H_in + tril(Y_m k'^T) k' = w_m / E, w_m = sum_j coeff[m+j] p_{j+1}
|
| 21 |
+
|
| 22 |
+
so the low-rank dgk terms (H_in part plus in-chunk corner sums) collapse to
|
| 23 |
+
|
| 24 |
+
suffix( sum_m (o_{m-1} * w_m + do_m * o_m) - k' * Z ),
|
| 25 |
+
Z = sum_m tril(Y_m k'^T)^T X_m + tril(X_m k'^T)^T Y_m,
|
| 26 |
+
|
| 27 |
+
and Z is the low-rank part of dk. tril(Y_m k'^T) is a combination of the B_j
|
| 28 |
+
already formed while applying H to dx:
|
| 29 |
+
|
| 30 |
+
sum_m tril(Y_m k'^T)^T X_m = sum_j B_j^T Xt_j,
|
| 31 |
+
Xt_j = (E / F) sum_{m=1}^{N-1-j} coeff[m+j] o_{m-1}.
|
| 32 |
+
"""
|
| 33 |
+
import os
|
| 34 |
+
from typing import Optional, Sequence, Tuple, Union
|
| 35 |
+
|
| 36 |
+
import torch
|
| 37 |
+
import triton
|
| 38 |
+
import triton.language as tl
|
| 39 |
+
|
| 40 |
+
from fla.ops.common.chunk_h import chunk_fwd_h
|
| 41 |
+
from fla.ops.utils import chunk_local_cumsum
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
EPS = 1e-12
|
| 45 |
+
# Matmul operand precision; gate math (exp, cumsums) is always fp32.
|
| 46 |
+
# bf16 operands cast to bf16, fp32 accumulate (fastest; dk ~3e-3, dgk ~9e-3 rel. error)
|
| 47 |
+
# tf32 fp32 operands on TF32 tensor cores (dk / dgk ~1.5e-3)
|
| 48 |
+
# tf32x3 hand-written 3xTF32 (dk / dgk ~1e-4, bounded by chunk_fwd_h), ~2x slower than tf32
|
| 49 |
+
# The tf32 / tf32x3 values are bit masks over the ``_dot`` call sites (set bit = 3xTF32).
|
| 50 |
+
_PREC_MASKS = {"tf32": 0, "tf32x3": 0x7F, "bf16": 0x100}
|
| 51 |
+
DOT_PRECISION = _PREC_MASKS[os.environ.get("TRACE_KKT_DOT_PRECISION", "bf16")]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _choose_block_d(D: int) -> int:
|
| 55 |
+
if D % 64 == 0:
|
| 56 |
+
return 64
|
| 57 |
+
if D % 32 == 0:
|
| 58 |
+
return 32
|
| 59 |
+
if D % 16 == 0:
|
| 60 |
+
return 16
|
| 61 |
+
raise ValueError(f"head dim D={D} must be divisible by 16, 32, or 64")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _choose_scan_block(D: int) -> int:
|
| 65 |
+
return 8 if D >= 16 else D
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _normalize_coeff(coeff, H: int, device, dtype=torch.float32) -> torch.Tensor:
|
| 69 |
+
if torch.is_tensor(coeff):
|
| 70 |
+
t = coeff.detach().to(device=device, dtype=dtype)
|
| 71 |
+
else:
|
| 72 |
+
t = torch.tensor(list(coeff), device=device, dtype=dtype)
|
| 73 |
+
if t.dim() == 1:
|
| 74 |
+
t = t.reshape(1, -1).expand(H, -1).contiguous()
|
| 75 |
+
elif t.shape[0] != H:
|
| 76 |
+
raise ValueError(f"coeff must be [N] or [H, N] with H={H}, got {tuple(t.shape)}")
|
| 77 |
+
else:
|
| 78 |
+
t = t.contiguous()
|
| 79 |
+
if t.shape[-1] not in (3, 4):
|
| 80 |
+
raise ValueError(f"coeff last dim must be 3 or 4, got {t.shape[-1]}")
|
| 81 |
+
return t
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ---------------------------------------------------------------------------
|
| 85 |
+
# Loads / stores. Layout [B, T, H, D], pointer already at one (b, h).
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
@triton.jit
|
| 88 |
+
def _load_vec(ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D: tl.constexpr):
|
| 89 |
+
p = tl.make_block_ptr(
|
| 90 |
+
ptr, (T, D), (H * D, 1),
|
| 91 |
+
(chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0),
|
| 92 |
+
)
|
| 93 |
+
x = tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 94 |
+
return tl.where(m_t[:, None], x, 0.0)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@triton.jit
|
| 98 |
+
def _store_vec(ptr, val, T, H, D, chunk_id, chunk_size, d0, BLOCK_D: tl.constexpr):
|
| 99 |
+
p = tl.make_block_ptr(
|
| 100 |
+
ptr, (T, D), (H * D, 1),
|
| 101 |
+
(chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0),
|
| 102 |
+
)
|
| 103 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@triton.jit
|
| 107 |
+
def _load_mat(ptr, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 108 |
+
p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0))
|
| 109 |
+
return tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@triton.jit
|
| 113 |
+
def _store_mat(ptr, val, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 114 |
+
p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0))
|
| 115 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@triton.jit
|
| 119 |
+
def _load_row(ptr, T, H, chunk_id, chunk_size, m_t, other):
|
| 120 |
+
p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,))
|
| 121 |
+
return tl.where(m_t, tl.load(p, boundary_check=(0,)).to(tl.float32), other)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@triton.jit
|
| 125 |
+
def _store_row(ptr, val, T, H, chunk_id, chunk_size):
|
| 126 |
+
p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,))
|
| 127 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0,))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@triton.jit
|
| 131 |
+
def _masks(chunk_id, chunk_size, T):
|
| 132 |
+
o_t = chunk_id * chunk_size + tl.arange(0, chunk_size)
|
| 133 |
+
m_t = o_t < T
|
| 134 |
+
tril = (o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :])
|
| 135 |
+
return m_t, tril
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@triton.jit
|
| 139 |
+
def _suffix(x):
|
| 140 |
+
"""Inclusive suffix sum over the chunk axis. x: [C, BD].
|
| 141 |
+
|
| 142 |
+
Not total - cumsum + x: the tail entries are tiny next to the head (alpha E^2
|
| 143 |
+
decays) and that difference leaves O(eps * head) behind, later scaled by E^{-2}.
|
| 144 |
+
"""
|
| 145 |
+
return tl.cumsum(x, axis=0, reverse=True)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@triton.jit
|
| 149 |
+
def _excl(x):
|
| 150 |
+
"""Exclusive prefix sum over the chunk axis."""
|
| 151 |
+
return tl.cumsum(x, axis=0) - x
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@triton.jit
|
| 155 |
+
def _diag_of(tile, BLOCK_D: tl.constexpr):
|
| 156 |
+
ar = tl.arange(0, BLOCK_D)
|
| 157 |
+
return tl.sum(tl.where(ar[:, None] == ar[None, :], tile, 0.0), axis=1)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@triton.jit
|
| 161 |
+
def _split_tf32(x):
|
| 162 |
+
hi = (x.to(tl.uint32, bitcast=True) & 0xFFFFE000).to(tl.float32, bitcast=True)
|
| 163 |
+
return hi, x - hi
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@triton.jit
|
| 167 |
+
def _dot(a, b, PREC: tl.constexpr, SITE: tl.constexpr):
|
| 168 |
+
"""a @ b with fp32 accumulation. PREC == 0x100 is bf16 operands; otherwise bit
|
| 169 |
+
SITE of PREC selects 3xTF32 (spelled out by hand: Triton's built-in "tf32x3"
|
| 170 |
+
lowering spills heavily) over plain TF32."""
|
| 171 |
+
if PREC == 0x100:
|
| 172 |
+
return tl.dot(a.to(tl.bfloat16), b.to(tl.bfloat16))
|
| 173 |
+
elif (PREC >> SITE) & 1:
|
| 174 |
+
a_hi, a_lo = _split_tf32(a)
|
| 175 |
+
b_hi, b_lo = _split_tf32(b)
|
| 176 |
+
acc = tl.dot(a_lo, b_hi, input_precision="tf32")
|
| 177 |
+
acc = tl.dot(a_hi, b_lo, acc, input_precision="tf32")
|
| 178 |
+
return tl.dot(a_hi, b_hi, acc, input_precision="tf32")
|
| 179 |
+
else:
|
| 180 |
+
return tl.dot(a, b, input_precision="tf32")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@triton.jit
|
| 184 |
+
def _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D: tl.constexpr):
|
| 185 |
+
"""E = exp(Gam), E^{-1} = exp(-Gam) on one [C, BD] tile."""
|
| 186 |
+
gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 187 |
+
return tl.exp(gam), tl.exp(-gam)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@triton.jit
|
| 191 |
+
def _scores(
|
| 192 |
+
v_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, m_t,
|
| 193 |
+
BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, PREC: tl.constexpr,
|
| 194 |
+
):
|
| 195 |
+
"""(v * E) @ k'^T, [C, C], not masked."""
|
| 196 |
+
S = tl.zeros((chunk_size, chunk_size), dtype=tl.float32)
|
| 197 |
+
for i in tl.static_range(NUM_D):
|
| 198 |
+
d0 = i * BLOCK_D
|
| 199 |
+
e, e_inv = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 200 |
+
v = _load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e
|
| 201 |
+
kp = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e_inv
|
| 202 |
+
S += _dot(v, tl.trans(kp), PREC, 0)
|
| 203 |
+
return S
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@triton.jit
|
| 207 |
+
def _vh(
|
| 208 |
+
v_ptr, h_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t,
|
| 209 |
+
BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, PREC: tl.constexpr,
|
| 210 |
+
):
|
| 211 |
+
"""((v * E) @ H_in)[:, d0:d0+BD]."""
|
| 212 |
+
acc = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 213 |
+
for j in tl.static_range(NUM_D):
|
| 214 |
+
d1 = j * BLOCK_D
|
| 215 |
+
gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 216 |
+
v = _load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * tl.exp(gam)
|
| 217 |
+
h = _load_mat(h_ptr, D, d1, d0, BLOCK_D)
|
| 218 |
+
acc += _dot(v, h, PREC, 1)
|
| 219 |
+
return acc
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ---------------------------------------------------------------------------
|
| 223 |
+
# Forward
|
| 224 |
+
# ---------------------------------------------------------------------------
|
| 225 |
+
@triton.jit(do_not_specialize=["T"])
|
| 226 |
+
def trace_fwd_kernel(
|
| 227 |
+
h_ptr, k_ptr, q_ptr, gam_ptr, coeff_ptr,
|
| 228 |
+
x_ptr, o1_ptr, o2_ptr, o3_ptr, f_ptr,
|
| 229 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 230 |
+
BLOCK_D: tl.constexpr, N: tl.constexpr, EPS: tl.constexpr, PREC: tl.constexpr,
|
| 231 |
+
):
|
| 232 |
+
chunk_id = tl.program_id(0)
|
| 233 |
+
bh = tl.program_id(1)
|
| 234 |
+
b_id, h_id = bh // H, bh % H
|
| 235 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 236 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 237 |
+
m_t, tril = _masks(chunk_id, chunk_size, T)
|
| 238 |
+
|
| 239 |
+
vec_off = (b_id * T * H + h_id) * D
|
| 240 |
+
q_ptr += vec_off
|
| 241 |
+
k_ptr += vec_off
|
| 242 |
+
gam_ptr += vec_off
|
| 243 |
+
x_ptr += vec_off
|
| 244 |
+
o1_ptr += vec_off
|
| 245 |
+
o2_ptr += vec_off
|
| 246 |
+
o3_ptr += vec_off
|
| 247 |
+
f_ptr += b_id * T * H + h_id
|
| 248 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 249 |
+
|
| 250 |
+
F = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 251 |
+
for i in tl.static_range(NUM_D):
|
| 252 |
+
d0 = i * BLOCK_D
|
| 253 |
+
e, e_inv = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 254 |
+
kp = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e_inv
|
| 255 |
+
diag = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D)
|
| 256 |
+
F += tl.sum(e * e * (diag[None, :] + tl.cumsum(kp * kp, axis=0)), axis=1)
|
| 257 |
+
F = tl.where(m_t, F + EPS, 0.0)
|
| 258 |
+
_store_row(f_ptr, F, T, H, chunk_id, chunk_size)
|
| 259 |
+
F = tl.where(m_t, F, 1.0)
|
| 260 |
+
|
| 261 |
+
for m in tl.static_range(1, N):
|
| 262 |
+
if m == 1:
|
| 263 |
+
src = q_ptr
|
| 264 |
+
dst = o1_ptr
|
| 265 |
+
elif m == 2:
|
| 266 |
+
src = o1_ptr
|
| 267 |
+
dst = o2_ptr
|
| 268 |
+
else:
|
| 269 |
+
src = o2_ptr
|
| 270 |
+
dst = o3_ptr
|
| 271 |
+
S = tl.where(tril, _scores(src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, m_t,
|
| 272 |
+
BLOCK_D, NUM_D, PREC), 0.0)
|
| 273 |
+
for i in tl.static_range(NUM_D):
|
| 274 |
+
d0 = i * BLOCK_D
|
| 275 |
+
e, e_inv = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 276 |
+
kp = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e_inv
|
| 277 |
+
inter = _vh(src, h_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t,
|
| 278 |
+
BLOCK_D, NUM_D, PREC)
|
| 279 |
+
out = (inter + _dot(S, kp, PREC, 2)) * e / F[:, None]
|
| 280 |
+
_store_vec(dst, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 281 |
+
tl.debug_barrier()
|
| 282 |
+
|
| 283 |
+
c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32)
|
| 284 |
+
c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32)
|
| 285 |
+
c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32)
|
| 286 |
+
for i in tl.static_range(NUM_D):
|
| 287 |
+
d0 = i * BLOCK_D
|
| 288 |
+
acc = c0 * _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 289 |
+
acc += c1 * _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 290 |
+
acc += c2 * _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 291 |
+
if N > 3:
|
| 292 |
+
c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32)
|
| 293 |
+
acc += c3 * _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 294 |
+
_store_vec(x_ptr, acc, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# ---------------------------------------------------------------------------
|
| 298 |
+
# Backward
|
| 299 |
+
# ---------------------------------------------------------------------------
|
| 300 |
+
@triton.jit(do_not_specialize=["T"])
|
| 301 |
+
def trace_bwd_chunk_kernel(
|
| 302 |
+
h_ptr, k_ptr, gam_ptr, q_ptr, o1_ptr, o2_ptr, o3_ptr, dx_ptr, f_ptr, coeff_ptr,
|
| 303 |
+
p1_ptr, p2_ptr, p3_ptr, u1_ptr, u2_ptr, u3_ptr,
|
| 304 |
+
dq_ptr, dk_ptr, dgk_ptr, g_partial_ptr, dcoeff_ptr,
|
| 305 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 306 |
+
BLOCK_D: tl.constexpr, N: tl.constexpr, PREC: tl.constexpr,
|
| 307 |
+
):
|
| 308 |
+
"""Everything inside one chunk except the S_in term from later chunks.
|
| 309 |
+
|
| 310 |
+
dk holds Z (low-rank part, before E^{-1}) and dgk holds the per-token
|
| 311 |
+
linear term until the final pass.
|
| 312 |
+
"""
|
| 313 |
+
chunk_id = tl.program_id(0)
|
| 314 |
+
bh = tl.program_id(1)
|
| 315 |
+
b_id, h_id = bh // H, bh % H
|
| 316 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 317 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 318 |
+
m_t, tril = _masks(chunk_id, chunk_size, T)
|
| 319 |
+
|
| 320 |
+
scalar = b_id * T * H + h_id
|
| 321 |
+
vec = scalar * D
|
| 322 |
+
k_ptr += vec
|
| 323 |
+
gam_ptr += vec
|
| 324 |
+
q_ptr += vec
|
| 325 |
+
o1_ptr += vec
|
| 326 |
+
o2_ptr += vec
|
| 327 |
+
o3_ptr += vec
|
| 328 |
+
dx_ptr += vec
|
| 329 |
+
p1_ptr += vec
|
| 330 |
+
p2_ptr += vec
|
| 331 |
+
p3_ptr += vec
|
| 332 |
+
u1_ptr += vec
|
| 333 |
+
u2_ptr += vec
|
| 334 |
+
u3_ptr += vec
|
| 335 |
+
dq_ptr += vec
|
| 336 |
+
dk_ptr += vec
|
| 337 |
+
dgk_ptr += vec
|
| 338 |
+
f_ptr += scalar
|
| 339 |
+
mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 340 |
+
h_ptr += mat
|
| 341 |
+
g_partial_ptr += mat
|
| 342 |
+
|
| 343 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 344 |
+
c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32)
|
| 345 |
+
c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32)
|
| 346 |
+
c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32)
|
| 347 |
+
c3 = 0.0
|
| 348 |
+
if N > 3:
|
| 349 |
+
c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32)
|
| 350 |
+
|
| 351 |
+
# (1) p_{j+1} = p_j H / F, and Z += B_j^T Xt_j with B_j = tril((p_j E) k'^T).
|
| 352 |
+
for j in tl.static_range(N - 1):
|
| 353 |
+
if j == 0:
|
| 354 |
+
src = dx_ptr
|
| 355 |
+
dst = p1_ptr
|
| 356 |
+
elif j == 1:
|
| 357 |
+
src = p1_ptr
|
| 358 |
+
dst = p2_ptr
|
| 359 |
+
else:
|
| 360 |
+
src = p2_ptr
|
| 361 |
+
dst = p3_ptr
|
| 362 |
+
ca = tl.load(coeff_ptr + h_id * N + j + 1).to(tl.float32)
|
| 363 |
+
Bj = tl.where(tril, _scores(src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, m_t,
|
| 364 |
+
BLOCK_D, NUM_D, PREC), 0.0)
|
| 365 |
+
for i in tl.static_range(NUM_D):
|
| 366 |
+
d0 = i * BLOCK_D
|
| 367 |
+
e, e_inv = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 368 |
+
kp = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e_inv
|
| 369 |
+
inter = _vh(src, h_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t,
|
| 370 |
+
BLOCK_D, NUM_D, PREC)
|
| 371 |
+
out = (inter + _dot(Bj, kp, PREC, 2)) * e / F[:, None]
|
| 372 |
+
_store_vec(dst, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 373 |
+
xt = ca * _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 374 |
+
if j + 2 < N:
|
| 375 |
+
cb = tl.load(coeff_ptr + h_id * N + j + 2).to(tl.float32)
|
| 376 |
+
xt += cb * _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 377 |
+
if j + 3 < N:
|
| 378 |
+
cc = tl.load(coeff_ptr + h_id * N + j + 3).to(tl.float32)
|
| 379 |
+
xt += cc * _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 380 |
+
z = _dot(tl.trans(Bj), xt * e / F[:, None], PREC, 3)
|
| 381 |
+
if j > 0:
|
| 382 |
+
z += _load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 383 |
+
_store_vec(dk_ptr, z, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 384 |
+
tl.debug_barrier()
|
| 385 |
+
|
| 386 |
+
# (2) dq, u_m, alpha, dcoeff and lin = sum_m o_{m-1} w_m + do_m o_m.
|
| 387 |
+
s = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 388 |
+
da = tl.zeros((1,), dtype=tl.float32)
|
| 389 |
+
db = tl.zeros((1,), dtype=tl.float32)
|
| 390 |
+
dc = tl.zeros((1,), dtype=tl.float32)
|
| 391 |
+
dd = tl.zeros((1,), dtype=tl.float32)
|
| 392 |
+
for i in tl.static_range(NUM_D):
|
| 393 |
+
d0 = i * BLOCK_D
|
| 394 |
+
q = _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 395 |
+
o1 = _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 396 |
+
o2 = _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 397 |
+
dx = _load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 398 |
+
p1 = _load_vec(p1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 399 |
+
p2 = _load_vec(p2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 400 |
+
dq = c0 * dx + c1 * p1 + c2 * p2
|
| 401 |
+
do1 = c1 * dx + c2 * p1
|
| 402 |
+
do2 = c2 * dx
|
| 403 |
+
w1 = c1 * p1 + c2 * p2
|
| 404 |
+
w2 = c2 * p1
|
| 405 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2
|
| 406 |
+
if N > 3:
|
| 407 |
+
o3 = _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 408 |
+
p3 = _load_vec(p3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 409 |
+
dq += c3 * p3
|
| 410 |
+
do1 += c3 * p2
|
| 411 |
+
do2 += c3 * p1
|
| 412 |
+
do3 = c3 * dx
|
| 413 |
+
w1 += c3 * p3
|
| 414 |
+
w2 += c3 * p2
|
| 415 |
+
w3 = c3 * p1
|
| 416 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + o2 * w3 + do3 * o3
|
| 417 |
+
_store_vec(u3_ptr, do3 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 418 |
+
s += tl.sum(o3 * do3, axis=1)
|
| 419 |
+
dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0)
|
| 420 |
+
_store_vec(dq_ptr, dq, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 421 |
+
_store_vec(u1_ptr, do1 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 422 |
+
_store_vec(u2_ptr, do2 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 423 |
+
_store_vec(dgk_ptr, lin, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 424 |
+
s += tl.sum(o1 * do1, axis=1) + tl.sum(o2 * do2, axis=1)
|
| 425 |
+
da += tl.sum(tl.sum(dx * q, axis=0), axis=0)
|
| 426 |
+
db += tl.sum(tl.sum(dx * o1, axis=0), axis=0)
|
| 427 |
+
dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0)
|
| 428 |
+
alpha = tl.where(m_t, -s / F, 0.0)
|
| 429 |
+
base = ((b_id * num_chunks + chunk_id) * H + h_id) * N
|
| 430 |
+
tl.store(dcoeff_ptr + base + 0, tl.sum(da))
|
| 431 |
+
tl.store(dcoeff_ptr + base + 1, tl.sum(db))
|
| 432 |
+
tl.store(dcoeff_ptr + base + 2, tl.sum(dc))
|
| 433 |
+
if N > 3:
|
| 434 |
+
tl.store(dcoeff_ptr + base + 3, tl.sum(dd))
|
| 435 |
+
tl.debug_barrier()
|
| 436 |
+
|
| 437 |
+
# (3) Z += tril(X_m k'^T)^T Y_m.
|
| 438 |
+
for m in tl.static_range(1, N):
|
| 439 |
+
if m == 1:
|
| 440 |
+
xs = q_ptr
|
| 441 |
+
us = u1_ptr
|
| 442 |
+
elif m == 2:
|
| 443 |
+
xs = o1_ptr
|
| 444 |
+
us = u2_ptr
|
| 445 |
+
else:
|
| 446 |
+
xs = o2_ptr
|
| 447 |
+
us = u3_ptr
|
| 448 |
+
A = tl.where(tril, _scores(xs, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, m_t,
|
| 449 |
+
BLOCK_D, NUM_D, PREC), 0.0)
|
| 450 |
+
for i in tl.static_range(NUM_D):
|
| 451 |
+
d0 = i * BLOCK_D
|
| 452 |
+
e, e_inv = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 453 |
+
y = _load_vec(us, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e
|
| 454 |
+
z = _load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 455 |
+
z += _dot(tl.trans(A), y, PREC, 4)
|
| 456 |
+
_store_vec(dk_ptr, z, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 457 |
+
tl.debug_barrier()
|
| 458 |
+
|
| 459 |
+
# (4) trace term, E^{-1} on dk, suffix sums for dgk, g_partial = sum_m X_m^T Y_m + Diag(R_0).
|
| 460 |
+
eye = tl.arange(0, BLOCK_D)
|
| 461 |
+
for i in tl.static_range(NUM_D):
|
| 462 |
+
d0 = i * BLOCK_D
|
| 463 |
+
e, e_inv = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 464 |
+
kp = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e_inv
|
| 465 |
+
ae2 = alpha[:, None] * e * e
|
| 466 |
+
R = _suffix(ae2)
|
| 467 |
+
diag = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D)
|
| 468 |
+
z = _load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 469 |
+
lin = _load_vec(dgk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 470 |
+
dgk = 0.5 * _suffix(lin - kp * z) + R * (diag[None, :] + _excl(kp * kp))
|
| 471 |
+
_store_vec(dgk_ptr, dgk, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 472 |
+
_store_vec(dk_ptr, (z + 2.0 * R * kp) * e_inv, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 473 |
+
r0 = tl.sum(ae2, axis=0)
|
| 474 |
+
for jd in tl.static_range(NUM_D):
|
| 475 |
+
d1 = jd * BLOCK_D
|
| 476 |
+
e1, _ = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 477 |
+
g = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32)
|
| 478 |
+
for m in tl.static_range(1, N):
|
| 479 |
+
if m == 1:
|
| 480 |
+
xs = q_ptr
|
| 481 |
+
us = u1_ptr
|
| 482 |
+
elif m == 2:
|
| 483 |
+
xs = o1_ptr
|
| 484 |
+
us = u2_ptr
|
| 485 |
+
else:
|
| 486 |
+
xs = o2_ptr
|
| 487 |
+
us = u3_ptr
|
| 488 |
+
x = _load_vec(xs, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e
|
| 489 |
+
y = _load_vec(us, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * e1
|
| 490 |
+
g += _dot(tl.trans(x), y, PREC, 5)
|
| 491 |
+
if i == jd:
|
| 492 |
+
g += tl.where(eye[:, None] == eye[None, :], r0[:, None], 0.0)
|
| 493 |
+
_store_mat(g_partial_ptr, g, D, d0, d1, BLOCK_D)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
@triton.jit
|
| 497 |
+
def _e_last_of(gam_ptr, b_id, h_id, cid, T, H: tl.constexpr, D: tl.constexpr,
|
| 498 |
+
chunk_size: tl.constexpr, d0, BLOCK: tl.constexpr):
|
| 499 |
+
"""exp(Gam) at the last valid token of chunk ``cid``, dims d0:d0+BLOCK."""
|
| 500 |
+
t_last = cid * chunk_size + tl.minimum(chunk_size, T - cid * chunk_size) - 1
|
| 501 |
+
off = ((b_id * T + t_last) * H + h_id).to(tl.int64) * D + d0
|
| 502 |
+
return tl.exp(tl.load(gam_ptr + off + tl.arange(0, BLOCK)).to(tl.float32))
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@triton.jit(do_not_specialize=["T"])
|
| 506 |
+
def trace_bwd_scan_kernel(
|
| 507 |
+
g_partial_ptr, gam_ptr, gin_ptr, dht_ptr,
|
| 508 |
+
T, NC, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 509 |
+
BLOCK_S: tl.constexpr, HAS_DHT: tl.constexpr,
|
| 510 |
+
):
|
| 511 |
+
"""gin[c] = g_partial[c+1] + Diag(E_last[c+1]) gin[c+1] Diag(E_last[c+1])."""
|
| 512 |
+
i_bh = tl.program_id(0)
|
| 513 |
+
i_tile = tl.program_id(1)
|
| 514 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 515 |
+
NUM_S: tl.constexpr = D // BLOCK_S
|
| 516 |
+
r0 = (i_tile // NUM_S) * BLOCK_S
|
| 517 |
+
c0 = (i_tile % NUM_S) * BLOCK_S
|
| 518 |
+
G = tl.zeros((BLOCK_S, BLOCK_S), dtype=tl.float32)
|
| 519 |
+
if HAS_DHT:
|
| 520 |
+
p_dht = tl.make_block_ptr(
|
| 521 |
+
dht_ptr + (i_b * H + i_h).to(tl.int64) * D * D,
|
| 522 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 523 |
+
)
|
| 524 |
+
G = tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32)
|
| 525 |
+
last = NC - 1
|
| 526 |
+
p_gin = tl.make_block_ptr(
|
| 527 |
+
gin_ptr + ((i_b * NC + last) * H + i_h).to(tl.int64) * D * D,
|
| 528 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 529 |
+
)
|
| 530 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 531 |
+
for it in tl.range(0, NC - 1):
|
| 532 |
+
cid = NC - 2 - it
|
| 533 |
+
src = cid + 1
|
| 534 |
+
p_gp = tl.make_block_ptr(
|
| 535 |
+
g_partial_ptr + ((i_b * NC + src) * H + i_h).to(tl.int64) * D * D,
|
| 536 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 537 |
+
)
|
| 538 |
+
gp = tl.load(p_gp, boundary_check=(0, 1)).to(tl.float32)
|
| 539 |
+
er = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, r0, BLOCK_S)
|
| 540 |
+
ec = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, c0, BLOCK_S)
|
| 541 |
+
G = gp + er[:, None] * G * ec[None, :]
|
| 542 |
+
p_gin = tl.make_block_ptr(
|
| 543 |
+
gin_ptr + ((i_b * NC + cid) * H + i_h).to(tl.int64) * D * D,
|
| 544 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 545 |
+
)
|
| 546 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
@triton.jit(do_not_specialize=["T"])
|
| 550 |
+
def trace_bwd_gin_kernel(
|
| 551 |
+
h_ptr, k_ptr, gam_ptr, gin_ptr, dk_ptr, dgk_ptr,
|
| 552 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 553 |
+
BLOCK_D: tl.constexpr, PREC: tl.constexpr,
|
| 554 |
+
):
|
| 555 |
+
"""Add S_in = Diag(E_C) (gin + gin^T) Diag(E_C) into dk and dgk."""
|
| 556 |
+
chunk_id = tl.program_id(0)
|
| 557 |
+
bh = tl.program_id(1)
|
| 558 |
+
b_id, h_id = bh // H, bh % H
|
| 559 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 560 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 561 |
+
m_t, _ = _masks(chunk_id, chunk_size, T)
|
| 562 |
+
|
| 563 |
+
gam_base = gam_ptr
|
| 564 |
+
vec = (b_id * T * H + h_id) * D
|
| 565 |
+
k_ptr += vec
|
| 566 |
+
gam_ptr += vec
|
| 567 |
+
dk_ptr += vec
|
| 568 |
+
dgk_ptr += vec
|
| 569 |
+
mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 570 |
+
h_ptr += mat
|
| 571 |
+
gin_ptr += mat
|
| 572 |
+
|
| 573 |
+
for i in tl.static_range(NUM_D):
|
| 574 |
+
d0 = i * BLOCK_D
|
| 575 |
+
_, e_inv0 = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 576 |
+
el0 = _e_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d0, BLOCK_D)
|
| 577 |
+
Za = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 578 |
+
v1 = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 579 |
+
for j in tl.static_range(NUM_D):
|
| 580 |
+
d1 = j * BLOCK_D
|
| 581 |
+
_, e_inv1 = _gate(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 582 |
+
kp1 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * e_inv1
|
| 583 |
+
el1 = _e_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d1, BLOCK_D)
|
| 584 |
+
sym = _load_mat(gin_ptr, D, d1, d0, BLOCK_D) + tl.trans(_load_mat(gin_ptr, D, d0, d1, BLOCK_D))
|
| 585 |
+
Za += _dot(kp1 * el1[None, :], sym, PREC, 6)
|
| 586 |
+
h_ij = _load_mat(h_ptr, D, d0, d1, BLOCK_D)
|
| 587 |
+
v1 += tl.sum(tl.trans(sym) * el1[None, :] * h_ij, axis=1)
|
| 588 |
+
Za = Za * el0[None, :]
|
| 589 |
+
dk = _load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 590 |
+
_store_vec(dk_ptr, dk + e_inv0 * Za, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 591 |
+
kp0 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e_inv0
|
| 592 |
+
dgk = _load_vec(dgk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 593 |
+
dgk += 0.5 * (v1[None, :] * el0[None, :] + _excl(kp0 * Za))
|
| 594 |
+
_store_vec(dgk_ptr, dgk, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def _bwd(k, q, os, dx, F, coeff_h, gam, h, dht, h0, chunk_size, n_coeff):
|
| 598 |
+
"""os = (o1, o2[, o3]) in fp32."""
|
| 599 |
+
B, T, H, D = q.shape
|
| 600 |
+
C = chunk_size
|
| 601 |
+
N = n_coeff
|
| 602 |
+
nc = triton.cdiv(T, C)
|
| 603 |
+
block_d = _choose_block_d(D)
|
| 604 |
+
f32 = dict(device=q.device, dtype=torch.float32)
|
| 605 |
+
o1, o2 = os[0], os[1]
|
| 606 |
+
o3 = os[2] if N == 4 else o2
|
| 607 |
+
p1 = torch.empty(B, T, H, D, **f32)
|
| 608 |
+
p2 = torch.empty(B, T, H, D, **f32)
|
| 609 |
+
p3 = torch.empty(B, T, H, D, **f32) if N == 4 else p2
|
| 610 |
+
u1 = torch.empty(B, T, H, D, **f32)
|
| 611 |
+
u2 = torch.empty(B, T, H, D, **f32)
|
| 612 |
+
u3 = torch.empty(B, T, H, D, **f32) if N == 4 else u2
|
| 613 |
+
dq = torch.empty_like(q)
|
| 614 |
+
dk = torch.empty(B, T, H, D, **f32)
|
| 615 |
+
dgk = torch.empty(B, T, H, D, **f32)
|
| 616 |
+
g_partial = torch.empty(B, nc, H, D, D, **f32)
|
| 617 |
+
gin = torch.empty(B, nc, H, D, D, **f32)
|
| 618 |
+
dcoeff_part = torch.empty(B, nc, H, N, **f32)
|
| 619 |
+
grid = (nc, B * H)
|
| 620 |
+
trace_bwd_chunk_kernel[grid](
|
| 621 |
+
h, k, gam, q, o1, o2, o3, dx, F, coeff_h,
|
| 622 |
+
p1, p2, p3, u1, u2, u3,
|
| 623 |
+
dq, dk, dgk, g_partial, dcoeff_part,
|
| 624 |
+
T, H, D, C, block_d, N, DOT_PRECISION,
|
| 625 |
+
num_warps=8, num_stages=1,
|
| 626 |
+
)
|
| 627 |
+
block_s = _choose_scan_block(D)
|
| 628 |
+
num_s = D // block_s
|
| 629 |
+
dht_buf = dht.float().contiguous() if dht is not None else gin.new_empty(1)
|
| 630 |
+
trace_bwd_scan_kernel[(B * H, num_s * num_s)](
|
| 631 |
+
g_partial, gam, gin, dht_buf,
|
| 632 |
+
T, nc, H, D, C, block_s, int(dht is not None),
|
| 633 |
+
num_warps=1, num_stages=1,
|
| 634 |
+
)
|
| 635 |
+
trace_bwd_gin_kernel[grid](
|
| 636 |
+
h, k, gam, gin, dk, dgk,
|
| 637 |
+
T, H, D, C, block_d, DOT_PRECISION, num_warps=8, num_stages=1,
|
| 638 |
+
)
|
| 639 |
+
dh0 = None
|
| 640 |
+
if h0 is not None:
|
| 641 |
+
e0 = gam[:, min(C, T) - 1].exp()
|
| 642 |
+
dh0 = g_partial[:, 0] + e0[..., :, None] * gin[:, 0] * e0[..., None, :]
|
| 643 |
+
dh0 = dh0.to(h0.dtype)
|
| 644 |
+
return dq, dk, dgk, dcoeff_part, dh0
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
class q_kkt_solve_trace_triton(torch.autograd.Function):
|
| 648 |
+
"""x, H_T = phi(q, k, gk) with F = tr(H) and per-dimension decay.
|
| 649 |
+
|
| 650 |
+
apply(k, q, gk, chunk_size, coeff, h0) -> (x [B, T, H, D], H_T [B, H, D, D])
|
| 651 |
+
coeff is [N] or [H, N], N = 3 or 4. chunk_size must be a power of two.
|
| 652 |
+
"""
|
| 653 |
+
|
| 654 |
+
@staticmethod
|
| 655 |
+
def forward(ctx, k, q, gk=None, chunk_size: int = 64, coeff=(1.0, -0.5, 0.375), h0=None):
|
| 656 |
+
if q.ndim != 4:
|
| 657 |
+
raise ValueError(f"q must be [B, T, H, D], got {tuple(q.shape)}")
|
| 658 |
+
if chunk_size != 2 ** (chunk_size.bit_length() - 1):
|
| 659 |
+
raise ValueError(f"chunk_size must be a power of 2, got {chunk_size}")
|
| 660 |
+
k = k.contiguous()
|
| 661 |
+
q = q.contiguous()
|
| 662 |
+
B, T, H, D = q.shape
|
| 663 |
+
coeff_is_tensor = torch.is_tensor(coeff)
|
| 664 |
+
coeff_shape = tuple(coeff.shape) if coeff_is_tensor else None
|
| 665 |
+
coeff_dtype = coeff.dtype if coeff_is_tensor else None
|
| 666 |
+
coeff_h = _normalize_coeff(coeff, H, q.device)
|
| 667 |
+
n_coeff = coeff_h.shape[-1]
|
| 668 |
+
|
| 669 |
+
if gk is None:
|
| 670 |
+
gam = torch.zeros(B, T, H, D, device=q.device, dtype=torch.float32)
|
| 671 |
+
gk_arg = gv_arg = None
|
| 672 |
+
else:
|
| 673 |
+
gk = gk.contiguous()
|
| 674 |
+
gam = chunk_local_cumsum(gk, chunk_size=chunk_size, scale=0.5, output_dtype=torch.float32)
|
| 675 |
+
gk_arg = gv_arg = gam
|
| 676 |
+
h, ht = chunk_fwd_h(
|
| 677 |
+
k=k, v=k, gk=gk_arg, gv=gv_arg, h0=h0,
|
| 678 |
+
output_final_state=True, chunk_size=chunk_size, states_in_fp32=True,
|
| 679 |
+
)
|
| 680 |
+
f32 = dict(device=q.device, dtype=torch.float32)
|
| 681 |
+
x = torch.empty_like(q)
|
| 682 |
+
o1 = torch.empty(B, T, H, D, **f32)
|
| 683 |
+
o2 = torch.empty(B, T, H, D, **f32)
|
| 684 |
+
o3 = torch.empty(B, T, H, D, **f32) if n_coeff == 4 else o2
|
| 685 |
+
F = torch.empty(B, T, H, **f32)
|
| 686 |
+
trace_fwd_kernel[(triton.cdiv(T, chunk_size), B * H)](
|
| 687 |
+
h, k, q, gam, coeff_h, x, o1, o2, o3, F,
|
| 688 |
+
T, H, D, chunk_size, _choose_block_d(D), n_coeff, EPS, DOT_PRECISION,
|
| 689 |
+
num_warps=8 if DOT_PRECISION & 0x7F else 4, num_stages=1,
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
saved = [k, q, o1, o2, F, coeff_h, h, gam]
|
| 693 |
+
if n_coeff == 4:
|
| 694 |
+
saved.append(o3)
|
| 695 |
+
if gk is not None:
|
| 696 |
+
saved.append(gk)
|
| 697 |
+
if h0 is not None:
|
| 698 |
+
saved.append(h0)
|
| 699 |
+
ctx.save_for_backward(*saved)
|
| 700 |
+
ctx.chunk_size = chunk_size
|
| 701 |
+
ctx.n_coeff = n_coeff
|
| 702 |
+
ctx.has_gk = gk is not None
|
| 703 |
+
ctx.has_h0 = h0 is not None
|
| 704 |
+
ctx.coeff_is_tensor = coeff_is_tensor
|
| 705 |
+
ctx.coeff_shape = coeff_shape
|
| 706 |
+
ctx.coeff_dtype = coeff_dtype
|
| 707 |
+
return x, ht
|
| 708 |
+
|
| 709 |
+
@staticmethod
|
| 710 |
+
def backward(ctx, dx, dht=None):
|
| 711 |
+
saved = list(ctx.saved_tensors)
|
| 712 |
+
k, q, o1, o2, F, coeff_h, h, gam = saved[:8]
|
| 713 |
+
idx = 8
|
| 714 |
+
o3 = saved[idx] if ctx.n_coeff == 4 else None
|
| 715 |
+
idx += int(ctx.n_coeff == 4)
|
| 716 |
+
gk = saved[idx] if ctx.has_gk else None
|
| 717 |
+
idx += int(ctx.has_gk)
|
| 718 |
+
h0 = saved[idx] if ctx.has_h0 else None
|
| 719 |
+
os_ = [o1, o2] + ([o3] if o3 is not None else [])
|
| 720 |
+
dq, dk, dgk, dcoeff_part, dh0 = _bwd(
|
| 721 |
+
k, q, os_, dx.contiguous(), F, coeff_h, gam, h,
|
| 722 |
+
None if dht is None else dht.contiguous(), h0, ctx.chunk_size, ctx.n_coeff,
|
| 723 |
+
)
|
| 724 |
+
dcoeff = None
|
| 725 |
+
if ctx.coeff_is_tensor and ctx.needs_input_grad[4]:
|
| 726 |
+
dcoeff_h = dcoeff_part.sum(dim=(0, 1))
|
| 727 |
+
if len(ctx.coeff_shape) == 1:
|
| 728 |
+
dcoeff_h = dcoeff_h.sum(0)
|
| 729 |
+
dcoeff = dcoeff_h.to(ctx.coeff_dtype).reshape(ctx.coeff_shape)
|
| 730 |
+
dgk_out = dgk.to(gk.dtype) if gk is not None else None
|
| 731 |
+
return dk.to(k.dtype), dq, dgk_out, None, dcoeff, dh0
|
phi_kkt_approx_trace/q_kkt_solve_trace_triton_safe.py
ADDED
|
@@ -0,0 +1,1600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Triton chunk implementation of trace-normalized phi-KKT, with KDA-style gates.
|
| 2 |
+
|
| 3 |
+
Same recurrence as ``q_kkt_solve_trace_triton.py``. A chunk of 64 is four blocks
|
| 4 |
+
of 16. Scores use one reference per block so the two factors of
|
| 5 |
+
``exp(Gam_t - Gam_i)`` stay inside the fp32 range:
|
| 6 |
+
|
| 7 |
+
off-diagonal: reference = first token of the query block (both factors <= 1
|
| 8 |
+
when gk is non-positive)
|
| 9 |
+
diagonal: reference = that token minus (BC - 1), the same shift KDA uses
|
| 10 |
+
for s = 2. The diagonal dot is tf32 when the matmul preset is
|
| 11 |
+
bf16, because a factor can exceed the bf16 range.
|
| 12 |
+
|
| 13 |
+
The trace is the one-step recurrence ``d_t = exp(gk_t) d_{t-1} + k_t^2``.
|
| 14 |
+
``exp(-Gam)`` is never materialized.
|
| 15 |
+
"""
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import triton
|
| 20 |
+
import triton.language as tl
|
| 21 |
+
|
| 22 |
+
from fla.ops.common.chunk_h import chunk_fwd_h
|
| 23 |
+
from fla.ops.utils import chunk_local_cumsum
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
EPS = 1e-12
|
| 27 |
+
# Matmul operand precision; gate math (exp, cumsums) is always fp32.
|
| 28 |
+
# bf16 operands cast to bf16, fp32 accumulate. Diagonal-block dots stay tf32.
|
| 29 |
+
# tf32 fp32 operands on TF32 tensor cores
|
| 30 |
+
# tf32x3 hand-written 3xTF32
|
| 31 |
+
# The tf32 / tf32x3 values are bit masks over the ``_dot`` call sites (set bit = 3xTF32).
|
| 32 |
+
_PREC_MASKS = {"tf32": 0, "tf32x3": 0x7F, "bf16": 0x100}
|
| 33 |
+
DOT_PRECISION = _PREC_MASKS[os.environ.get("TRACE_KKT_DOT_PRECISION", "bf16")]
|
| 34 |
+
BLOCK_C = 16
|
| 35 |
+
# (BC - 1) * s / 2 with s = 2, in natural log of Gam. Same centering as KDA.
|
| 36 |
+
SHIFT = float(BLOCK_C - 1)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _choose_block_d(D: int) -> int:
|
| 40 |
+
if D % 64 == 0:
|
| 41 |
+
return 64
|
| 42 |
+
if D % 32 == 0:
|
| 43 |
+
return 32
|
| 44 |
+
if D % 16 == 0:
|
| 45 |
+
return 16
|
| 46 |
+
raise ValueError(f"head dim D={D} must be divisible by 16, 32, or 64")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _choose_intra_d(D: int) -> int:
|
| 50 |
+
"""64-wide state tiles, same tensor-core tile as the original kernel.
|
| 51 |
+
|
| 52 |
+
A 16-row score still reduces over the whole head inside ``_scores_block``.
|
| 53 |
+
"""
|
| 54 |
+
return _choose_block_d(D)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _choose_scan_block(D: int) -> int:
|
| 58 |
+
return 8 if D >= 16 else D
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _normalize_coeff(coeff, H: int, device, dtype=torch.float32) -> torch.Tensor:
|
| 62 |
+
if torch.is_tensor(coeff):
|
| 63 |
+
t = coeff.detach().to(device=device, dtype=dtype)
|
| 64 |
+
else:
|
| 65 |
+
t = torch.tensor(list(coeff), device=device, dtype=dtype)
|
| 66 |
+
if t.dim() == 1:
|
| 67 |
+
t = t.reshape(1, -1).expand(H, -1).contiguous()
|
| 68 |
+
elif t.shape[0] != H:
|
| 69 |
+
raise ValueError(f"coeff must be [N] or [H, N] with H={H}, got {tuple(t.shape)}")
|
| 70 |
+
else:
|
| 71 |
+
t = t.contiguous()
|
| 72 |
+
if t.shape[-1] not in (3, 4):
|
| 73 |
+
raise ValueError(f"coeff last dim must be 3 or 4, got {t.shape[-1]}")
|
| 74 |
+
return t
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ---------------------------------------------------------------------------
|
| 78 |
+
# Loads / stores. Layout [B, T, H, D], pointer already at one (b, h).
|
| 79 |
+
# ---------------------------------------------------------------------------
|
| 80 |
+
@triton.jit
|
| 81 |
+
def _load_vec(ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D: tl.constexpr):
|
| 82 |
+
p = tl.make_block_ptr(
|
| 83 |
+
ptr, (T, D), (H * D, 1),
|
| 84 |
+
(chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0),
|
| 85 |
+
)
|
| 86 |
+
x = tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 87 |
+
return tl.where(m_t[:, None], x, 0.0)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@triton.jit
|
| 91 |
+
def _store_vec(ptr, val, T, H, D, chunk_id, chunk_size, d0, BLOCK_D: tl.constexpr):
|
| 92 |
+
p = tl.make_block_ptr(
|
| 93 |
+
ptr, (T, D), (H * D, 1),
|
| 94 |
+
(chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0),
|
| 95 |
+
)
|
| 96 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@triton.jit
|
| 100 |
+
def _load_bc(ptr, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr):
|
| 101 |
+
p = tl.make_block_ptr(
|
| 102 |
+
ptr, (T, D), (H * D, 1),
|
| 103 |
+
(chunk_id * chunk_size + s0, d0), (BLOCK_C, BLOCK_D), (1, 0),
|
| 104 |
+
)
|
| 105 |
+
return tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@triton.jit
|
| 109 |
+
def _store_bc(ptr, val, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr):
|
| 110 |
+
p = tl.make_block_ptr(
|
| 111 |
+
ptr, (T, D), (H * D, 1),
|
| 112 |
+
(chunk_id * chunk_size + s0, d0), (BLOCK_C, BLOCK_D), (1, 0),
|
| 113 |
+
)
|
| 114 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@triton.jit
|
| 118 |
+
def _load_mat(ptr, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 119 |
+
p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0))
|
| 120 |
+
return tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@triton.jit
|
| 124 |
+
def _store_mat(ptr, val, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 125 |
+
p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0))
|
| 126 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@triton.jit
|
| 130 |
+
def _load_row(ptr, T, H, chunk_id, chunk_size, m_t, other):
|
| 131 |
+
p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,))
|
| 132 |
+
return tl.where(m_t, tl.load(p, boundary_check=(0,)).to(tl.float32), other)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@triton.jit
|
| 136 |
+
def _store_row(ptr, val, T, H, chunk_id, chunk_size):
|
| 137 |
+
p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,))
|
| 138 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0,))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@triton.jit
|
| 142 |
+
def _masks(chunk_id, chunk_size, T):
|
| 143 |
+
o_t = chunk_id * chunk_size + tl.arange(0, chunk_size)
|
| 144 |
+
m_t = o_t < T
|
| 145 |
+
return m_t
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@triton.jit
|
| 149 |
+
def _suffix(x):
|
| 150 |
+
"""Inclusive suffix sum over the chunk axis. x: [C, BD]."""
|
| 151 |
+
return tl.cumsum(x, axis=0, reverse=True)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@triton.jit
|
| 155 |
+
def _excl(x):
|
| 156 |
+
"""Exclusive prefix sum over the chunk axis."""
|
| 157 |
+
return tl.cumsum(x, axis=0) - x
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@triton.jit
|
| 161 |
+
def _diag_of(tile, BLOCK_D: tl.constexpr):
|
| 162 |
+
ar = tl.arange(0, BLOCK_D)
|
| 163 |
+
return tl.sum(tl.where(ar[:, None] == ar[None, :], tile, 0.0), axis=1)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@triton.jit
|
| 167 |
+
def _split_tf32(x):
|
| 168 |
+
hi = (x.to(tl.uint32, bitcast=True) & 0xFFFFE000).to(tl.float32, bitcast=True)
|
| 169 |
+
return hi, x - hi
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@triton.jit
|
| 173 |
+
def _dot(a, b, PREC: tl.constexpr, SITE: tl.constexpr):
|
| 174 |
+
"""a @ b with fp32 accumulation. PREC == 0x100 is bf16 operands; otherwise bit
|
| 175 |
+
SITE of PREC selects 3xTF32 over plain TF32."""
|
| 176 |
+
if PREC == 0x100:
|
| 177 |
+
return tl.dot(a.to(tl.bfloat16), b.to(tl.bfloat16))
|
| 178 |
+
elif (PREC >> SITE) & 1:
|
| 179 |
+
a_hi, a_lo = _split_tf32(a)
|
| 180 |
+
b_hi, b_lo = _split_tf32(b)
|
| 181 |
+
acc = tl.dot(a_lo, b_hi, input_precision="tf32")
|
| 182 |
+
acc = tl.dot(a_hi, b_lo, acc, input_precision="tf32")
|
| 183 |
+
return tl.dot(a_hi, b_hi, acc, input_precision="tf32")
|
| 184 |
+
else:
|
| 185 |
+
return tl.dot(a, b, input_precision="tf32")
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@triton.jit
|
| 189 |
+
def _dot_block(a, b, DIAG: tl.constexpr, PREC: tl.constexpr, SITE: tl.constexpr):
|
| 190 |
+
"""Diagonal blocks can hold exp(SHIFT); bf16 operands would overflow."""
|
| 191 |
+
if DIAG and PREC == 0x100:
|
| 192 |
+
return tl.dot(a, b, input_precision="tf32")
|
| 193 |
+
else:
|
| 194 |
+
return _dot(a, b, PREC, SITE)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@triton.jit
|
| 198 |
+
def _load_tok(ptr, H, D, tok, d0, alive, BLOCK_D: tl.constexpr):
|
| 199 |
+
ar = tl.arange(0, BLOCK_D)
|
| 200 |
+
return tl.load(ptr + tok.to(tl.int64) * H * D + d0 + ar, mask=alive, other=0.0).to(tl.float32)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@triton.jit
|
| 204 |
+
def _load_f_bc(ptr, H, chunk_id, chunk_size, s0, BLOCK_C: tl.constexpr):
|
| 205 |
+
offs = chunk_id * chunk_size + s0 + tl.arange(0, BLOCK_C)
|
| 206 |
+
return tl.load(ptr + offs * H, mask=offs < (chunk_id * chunk_size + chunk_size), other=1.0).to(tl.float32)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@triton.jit
|
| 210 |
+
def _s_offs(BLOCK_C: tl.constexpr):
|
| 211 |
+
return tl.arange(0, BLOCK_C)[:, None] * BLOCK_C + tl.arange(0, BLOCK_C)[None, :]
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@triton.jit
|
| 215 |
+
def _store_S(s_ptr, S, qb, kb, NUM_C: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 216 |
+
base = (qb * NUM_C + kb) * BLOCK_C * BLOCK_C
|
| 217 |
+
tl.store(s_ptr + base + _s_offs(BLOCK_C), S)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@triton.jit
|
| 221 |
+
def _load_S(s_ptr, qb, kb, NUM_C: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 222 |
+
base = (qb * NUM_C + kb) * BLOCK_C * BLOCK_C
|
| 223 |
+
return tl.load(s_ptr + base + _s_offs(BLOCK_C))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@triton.jit
|
| 227 |
+
def _ref_of(g, DIAG: tl.constexpr, SHIFT: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 228 |
+
ref = tl.sum(tl.where(tl.arange(0, BLOCK_C)[:, None] == 0, g, 0.0), axis=0)
|
| 229 |
+
if DIAG:
|
| 230 |
+
ref = ref - SHIFT
|
| 231 |
+
return ref
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
@triton.jit
|
| 235 |
+
def _one_score(
|
| 236 |
+
v, gv, k, gk, s0_q, s0_k, n_valid,
|
| 237 |
+
DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, BLOCK_C: tl.constexpr,
|
| 238 |
+
):
|
| 239 |
+
"""One D-tile of exp(Gam_t - Gam_i) = exp(Gam_t - C) exp(C - Gam_i)."""
|
| 240 |
+
ref = _ref_of(gv, DIAG, SHIFT, BLOCK_C)
|
| 241 |
+
valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid
|
| 242 |
+
valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid
|
| 243 |
+
gv_s = tl.where(valid_q[:, None], gv, ref[None, :])
|
| 244 |
+
gk_s = tl.where(valid_k[:, None], gk, ref[None, :])
|
| 245 |
+
vs = tl.where(valid_q[:, None], v * tl.exp(gv_s - ref[None, :]), 0.0)
|
| 246 |
+
ks = tl.where(valid_k[:, None], k * tl.exp(ref[None, :] - gk_s), 0.0)
|
| 247 |
+
S = _dot_block(vs, tl.trans(ks), DIAG, PREC, 0)
|
| 248 |
+
if DIAG:
|
| 249 |
+
tri = tl.arange(0, BLOCK_C)[:, None] >= tl.arange(0, BLOCK_C)[None, :]
|
| 250 |
+
S = tl.where(tri, S, 0.0)
|
| 251 |
+
return tl.where(valid_q[:, None] & valid_k[None, :], S, 0.0)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
@triton.jit
|
| 255 |
+
def _scores_block(
|
| 256 |
+
v_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, s0_q, s0_k, n_valid,
|
| 257 |
+
BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, BLOCK_C: tl.constexpr,
|
| 258 |
+
DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr,
|
| 259 |
+
):
|
| 260 |
+
S = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 261 |
+
for i in tl.static_range(NUM_D):
|
| 262 |
+
d0 = i * BLOCK_D
|
| 263 |
+
v = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, s0_q, d0, BLOCK_C, BLOCK_D)
|
| 264 |
+
gv = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0_q, d0, BLOCK_C, BLOCK_D)
|
| 265 |
+
k = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, s0_k, d0, BLOCK_C, BLOCK_D)
|
| 266 |
+
gk = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0_k, d0, BLOCK_C, BLOCK_D)
|
| 267 |
+
S += _one_score(v, gv, k, gk, s0_q, s0_k, n_valid, DIAG, SHIFT, PREC, BLOCK_C)
|
| 268 |
+
return S
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@triton.jit
|
| 272 |
+
def _apply_block(
|
| 273 |
+
S, k, gk, gq, s0_q, s0_k, n_valid,
|
| 274 |
+
DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, BLOCK_C: tl.constexpr,
|
| 275 |
+
):
|
| 276 |
+
"""sum_i S_ti * k_i * exp(Gam_t - Gam_i), with the same C used to build S."""
|
| 277 |
+
ref = _ref_of(gq, DIAG, SHIFT, BLOCK_C)
|
| 278 |
+
valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid
|
| 279 |
+
valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid
|
| 280 |
+
gq_s = tl.where(valid_q[:, None], gq, ref[None, :])
|
| 281 |
+
gk_s = tl.where(valid_k[:, None], gk, ref[None, :])
|
| 282 |
+
ks = tl.where(valid_k[:, None], k * tl.exp(ref[None, :] - gk_s), 0.0)
|
| 283 |
+
acc = _dot_block(S, ks, DIAG, PREC, 2)
|
| 284 |
+
return tl.where(valid_q[:, None], tl.exp(gq_s - ref[None, :]) * acc, 0.0)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@triton.jit
|
| 288 |
+
def _z_pair(
|
| 289 |
+
S, y, gq, gk, s0_q, s0_k, n_valid,
|
| 290 |
+
DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, BLOCK_C: tl.constexpr,
|
| 291 |
+
):
|
| 292 |
+
"""Key-block rows of sum_t S_ti * y_t * exp(Gam_t - Gam_i)."""
|
| 293 |
+
ref = _ref_of(gq, DIAG, SHIFT, BLOCK_C)
|
| 294 |
+
valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid
|
| 295 |
+
valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid
|
| 296 |
+
gq_s = tl.where(valid_q[:, None], gq, ref[None, :])
|
| 297 |
+
gk_s = tl.where(valid_k[:, None], gk, ref[None, :])
|
| 298 |
+
ys = tl.where(valid_q[:, None], y * tl.exp(gq_s - ref[None, :]), 0.0)
|
| 299 |
+
acc = _dot_block(tl.trans(S), ys, DIAG, PREC, 3)
|
| 300 |
+
return tl.where(valid_k[:, None], tl.exp(ref[None, :] - gk_s) * acc, 0.0)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@triton.jit
|
| 304 |
+
def _vh_rows(
|
| 305 |
+
v_ptr, h_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid,
|
| 306 |
+
BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, BLOCK_C: tl.constexpr, PREC: tl.constexpr,
|
| 307 |
+
):
|
| 308 |
+
"""((v * E) @ H_in) for BLOCK_C query rows. E = exp(Gam) <= 1."""
|
| 309 |
+
acc = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 310 |
+
valid = (s0 + tl.arange(0, BLOCK_C)) < n_valid
|
| 311 |
+
for j in tl.static_range(NUM_D):
|
| 312 |
+
d1 = j * BLOCK_D
|
| 313 |
+
g = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0, d1, BLOCK_C, BLOCK_D)
|
| 314 |
+
v = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, s0, d1, BLOCK_C, BLOCK_D) * tl.exp(g)
|
| 315 |
+
h = _load_mat(h_ptr, D, d1, d0, BLOCK_D)
|
| 316 |
+
acc += _dot(v, h, PREC, 1)
|
| 317 |
+
return tl.where(valid[:, None], acc, 0.0)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
# ---------------------------------------------------------------------------
|
| 321 |
+
# Forward
|
| 322 |
+
# ---------------------------------------------------------------------------
|
| 323 |
+
@triton.jit(do_not_specialize=["T"])
|
| 324 |
+
def trace_fwd_kernel(
|
| 325 |
+
h_ptr, k_ptr, q_ptr, gam_ptr, coeff_ptr,
|
| 326 |
+
x_ptr, o1_ptr, o2_ptr, o3_ptr, f_ptr,
|
| 327 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 328 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr,
|
| 329 |
+
N: tl.constexpr, EPS: tl.constexpr, PREC: tl.constexpr,
|
| 330 |
+
):
|
| 331 |
+
chunk_id = tl.program_id(0)
|
| 332 |
+
bh = tl.program_id(1)
|
| 333 |
+
b_id, h_id = bh // H, bh % H
|
| 334 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 335 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 336 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 337 |
+
m_t = _masks(chunk_id, chunk_size, T)
|
| 338 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 339 |
+
|
| 340 |
+
vec_off = (b_id * T * H + h_id) * D
|
| 341 |
+
q_ptr += vec_off
|
| 342 |
+
k_ptr += vec_off
|
| 343 |
+
gam_ptr += vec_off
|
| 344 |
+
x_ptr += vec_off
|
| 345 |
+
o1_ptr += vec_off
|
| 346 |
+
o2_ptr += vec_off
|
| 347 |
+
o3_ptr += vec_off
|
| 348 |
+
f_ptr += b_id * T * H + h_id
|
| 349 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 350 |
+
|
| 351 |
+
F = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 352 |
+
base_tok = chunk_id * chunk_size
|
| 353 |
+
ar_t = tl.arange(0, chunk_size)
|
| 354 |
+
for i in tl.static_range(NUM_D):
|
| 355 |
+
d0 = i * BLOCK_D
|
| 356 |
+
dstate = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D)
|
| 357 |
+
gprev = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 358 |
+
Ft = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 359 |
+
for t in tl.range(0, chunk_size):
|
| 360 |
+
alive = t < n_valid
|
| 361 |
+
kt = _load_tok(k_ptr, H, D, base_tok + t, d0, alive, BLOCK_D)
|
| 362 |
+
gt = _load_tok(gam_ptr, H, D, base_tok + t, d0, alive, BLOCK_D)
|
| 363 |
+
gt_s = tl.where(alive, gt, gprev)
|
| 364 |
+
d_new = tl.exp(2.0 * (gt_s - gprev)) * dstate + tl.where(alive, kt * kt, 0.0)
|
| 365 |
+
dstate = tl.where(alive, d_new, dstate)
|
| 366 |
+
gprev = gt_s
|
| 367 |
+
Ft += tl.where(ar_t == t, tl.sum(tl.where(alive, d_new, 0.0)), 0.0)
|
| 368 |
+
F += Ft
|
| 369 |
+
F = tl.where(m_t, F + EPS, 0.0)
|
| 370 |
+
_store_row(f_ptr, F, T, H, chunk_id, chunk_size)
|
| 371 |
+
F = tl.where(m_t, F, 1.0)
|
| 372 |
+
|
| 373 |
+
for m in tl.static_range(1, N):
|
| 374 |
+
if m == 1:
|
| 375 |
+
src = q_ptr
|
| 376 |
+
dst = o1_ptr
|
| 377 |
+
elif m == 2:
|
| 378 |
+
src = o1_ptr
|
| 379 |
+
dst = o2_ptr
|
| 380 |
+
else:
|
| 381 |
+
src = o2_ptr
|
| 382 |
+
dst = o3_ptr
|
| 383 |
+
# Intra term only. Each causal 16x16 score is formed once, then applied.
|
| 384 |
+
if NUM_D == 1:
|
| 385 |
+
for qb in tl.static_range(NUM_C):
|
| 386 |
+
sq = qb * BLOCK_C
|
| 387 |
+
rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 388 |
+
if sq < n_valid:
|
| 389 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 390 |
+
for kb in tl.static_range(NUM_C):
|
| 391 |
+
sk = kb * BLOCK_C
|
| 392 |
+
if kb < qb:
|
| 393 |
+
S = _scores_block(
|
| 394 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 395 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 396 |
+
)
|
| 397 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 398 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 399 |
+
rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 400 |
+
if kb == qb:
|
| 401 |
+
S = _scores_block(
|
| 402 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 403 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 404 |
+
)
|
| 405 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 406 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 407 |
+
rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 408 |
+
_store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 409 |
+
else:
|
| 410 |
+
for qb in tl.static_range(NUM_C):
|
| 411 |
+
sq = qb * BLOCK_C
|
| 412 |
+
for di in tl.static_range(NUM_D):
|
| 413 |
+
d0 = di * BLOCK_D
|
| 414 |
+
rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 415 |
+
if sq < n_valid:
|
| 416 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 417 |
+
for kb in tl.static_range(NUM_C):
|
| 418 |
+
sk = kb * BLOCK_C
|
| 419 |
+
if kb < qb:
|
| 420 |
+
S = _scores_block(
|
| 421 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 422 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 423 |
+
)
|
| 424 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 425 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 426 |
+
rows += _apply_block(
|
| 427 |
+
S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C,
|
| 428 |
+
)
|
| 429 |
+
if kb == qb:
|
| 430 |
+
S = _scores_block(
|
| 431 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 432 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 433 |
+
)
|
| 434 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 435 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 436 |
+
rows += _apply_block(
|
| 437 |
+
S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C,
|
| 438 |
+
)
|
| 439 |
+
_store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 440 |
+
tl.debug_barrier()
|
| 441 |
+
for i in tl.static_range(NUM_D):
|
| 442 |
+
d0 = i * BLOCK_D
|
| 443 |
+
g = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 444 |
+
e = tl.exp(g)
|
| 445 |
+
inter = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 446 |
+
for j in tl.static_range(NUM_D):
|
| 447 |
+
d1 = j * BLOCK_D
|
| 448 |
+
v = _load_vec(src, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 449 |
+
v *= tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D))
|
| 450 |
+
inter += _dot(v, _load_mat(h_ptr, D, d1, d0, BLOCK_D), PREC, 1)
|
| 451 |
+
intra = _load_vec(dst, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 452 |
+
out = tl.where(m_t[:, None], (inter * e + intra) / F[:, None], 0.0)
|
| 453 |
+
_store_vec(dst, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 454 |
+
tl.debug_barrier()
|
| 455 |
+
|
| 456 |
+
c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32)
|
| 457 |
+
c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32)
|
| 458 |
+
c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32)
|
| 459 |
+
for i in tl.static_range(NUM_D):
|
| 460 |
+
d0 = i * BLOCK_D
|
| 461 |
+
acc = c0 * _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 462 |
+
acc += c1 * _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 463 |
+
acc += c2 * _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 464 |
+
if N > 3:
|
| 465 |
+
c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32)
|
| 466 |
+
acc += c3 * _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 467 |
+
_store_vec(x_ptr, acc, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
# ---------------------------------------------------------------------------
|
| 471 |
+
# Backward
|
| 472 |
+
# ---------------------------------------------------------------------------
|
| 473 |
+
@triton.jit(do_not_specialize=["T"])
|
| 474 |
+
def trace_bwd_chunk_kernel(
|
| 475 |
+
h_ptr, k_ptr, gam_ptr, q_ptr, o1_ptr, o2_ptr, o3_ptr, dx_ptr, f_ptr, coeff_ptr,
|
| 476 |
+
p1_ptr, p2_ptr, p3_ptr, u1_ptr, u2_ptr, u3_ptr,
|
| 477 |
+
dq_ptr, dk_ptr, dgk_ptr, g_partial_ptr, dcoeff_ptr, alpha_ptr, s_ptr,
|
| 478 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 479 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr,
|
| 480 |
+
N: tl.constexpr, PREC: tl.constexpr,
|
| 481 |
+
):
|
| 482 |
+
"""Same splits as the forward. dk stores the E^{-1}-scaled low-rank term."""
|
| 483 |
+
chunk_id = tl.program_id(0)
|
| 484 |
+
bh = tl.program_id(1)
|
| 485 |
+
b_id, h_id = bh // H, bh % H
|
| 486 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 487 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 488 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 489 |
+
m_t = _masks(chunk_id, chunk_size, T)
|
| 490 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 491 |
+
|
| 492 |
+
scalar = b_id * T * H + h_id
|
| 493 |
+
vec = scalar * D
|
| 494 |
+
k_ptr += vec
|
| 495 |
+
gam_ptr += vec
|
| 496 |
+
q_ptr += vec
|
| 497 |
+
o1_ptr += vec
|
| 498 |
+
o2_ptr += vec
|
| 499 |
+
o3_ptr += vec
|
| 500 |
+
dx_ptr += vec
|
| 501 |
+
p1_ptr += vec
|
| 502 |
+
p2_ptr += vec
|
| 503 |
+
p3_ptr += vec
|
| 504 |
+
u1_ptr += vec
|
| 505 |
+
u2_ptr += vec
|
| 506 |
+
u3_ptr += vec
|
| 507 |
+
dq_ptr += vec
|
| 508 |
+
dk_ptr += vec
|
| 509 |
+
dgk_ptr += vec
|
| 510 |
+
f_ptr += scalar
|
| 511 |
+
alpha_ptr += scalar
|
| 512 |
+
s_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C)
|
| 513 |
+
mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 514 |
+
h_ptr += mat
|
| 515 |
+
g_partial_ptr += mat
|
| 516 |
+
|
| 517 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 518 |
+
c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32)
|
| 519 |
+
c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32)
|
| 520 |
+
c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32)
|
| 521 |
+
c3 = 0.0
|
| 522 |
+
if N > 3:
|
| 523 |
+
c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32)
|
| 524 |
+
|
| 525 |
+
# (1) p_{j+1} = p_j H / F, and Z += B_j^T Xt_j in the E^{-1} frame.
|
| 526 |
+
# Scores are written once and reused for both p and Z.
|
| 527 |
+
for j in tl.static_range(N - 1):
|
| 528 |
+
if j == 0:
|
| 529 |
+
src = dx_ptr
|
| 530 |
+
dst = p1_ptr
|
| 531 |
+
elif j == 1:
|
| 532 |
+
src = p1_ptr
|
| 533 |
+
dst = p2_ptr
|
| 534 |
+
else:
|
| 535 |
+
src = p2_ptr
|
| 536 |
+
dst = p3_ptr
|
| 537 |
+
ca = tl.load(coeff_ptr + h_id * N + j + 1).to(tl.float32)
|
| 538 |
+
cb = 0.0
|
| 539 |
+
cc = 0.0
|
| 540 |
+
if j + 2 < N:
|
| 541 |
+
cb = tl.load(coeff_ptr + h_id * N + j + 2).to(tl.float32)
|
| 542 |
+
if j + 3 < N:
|
| 543 |
+
cc = tl.load(coeff_ptr + h_id * N + j + 3).to(tl.float32)
|
| 544 |
+
if NUM_D == 1:
|
| 545 |
+
for qb in tl.static_range(NUM_C):
|
| 546 |
+
sq = qb * BLOCK_C
|
| 547 |
+
rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 548 |
+
if sq < n_valid:
|
| 549 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 550 |
+
for kb in tl.static_range(NUM_C):
|
| 551 |
+
sk = kb * BLOCK_C
|
| 552 |
+
if kb < qb:
|
| 553 |
+
S = _scores_block(
|
| 554 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 555 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 556 |
+
)
|
| 557 |
+
_store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C)
|
| 558 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 559 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 560 |
+
rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 561 |
+
if kb == qb:
|
| 562 |
+
S = _scores_block(
|
| 563 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 564 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 565 |
+
)
|
| 566 |
+
_store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C)
|
| 567 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 568 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 569 |
+
rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 570 |
+
_store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 571 |
+
else:
|
| 572 |
+
for qb in tl.static_range(NUM_C):
|
| 573 |
+
sq = qb * BLOCK_C
|
| 574 |
+
for di in tl.static_range(NUM_D):
|
| 575 |
+
d0 = di * BLOCK_D
|
| 576 |
+
rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 577 |
+
if sq < n_valid:
|
| 578 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 579 |
+
for kb in tl.static_range(NUM_C):
|
| 580 |
+
sk = kb * BLOCK_C
|
| 581 |
+
if kb < qb:
|
| 582 |
+
S = _scores_block(
|
| 583 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 584 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 585 |
+
)
|
| 586 |
+
if di == 0:
|
| 587 |
+
_store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C)
|
| 588 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 589 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 590 |
+
rows += _apply_block(
|
| 591 |
+
S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C,
|
| 592 |
+
)
|
| 593 |
+
if kb == qb:
|
| 594 |
+
S = _scores_block(
|
| 595 |
+
src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 596 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 597 |
+
)
|
| 598 |
+
if di == 0:
|
| 599 |
+
_store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C)
|
| 600 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 601 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 602 |
+
rows += _apply_block(
|
| 603 |
+
S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C,
|
| 604 |
+
)
|
| 605 |
+
_store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 606 |
+
tl.debug_barrier()
|
| 607 |
+
for i in tl.static_range(NUM_D):
|
| 608 |
+
d0 = i * BLOCK_D
|
| 609 |
+
g = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 610 |
+
e = tl.exp(g)
|
| 611 |
+
inter = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 612 |
+
for jj in tl.static_range(NUM_D):
|
| 613 |
+
d1 = jj * BLOCK_D
|
| 614 |
+
v = _load_vec(src, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 615 |
+
v *= tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D))
|
| 616 |
+
inter += _dot(v, _load_mat(h_ptr, D, d1, d0, BLOCK_D), PREC, 1)
|
| 617 |
+
intra = _load_vec(dst, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 618 |
+
out = tl.where(m_t[:, None], (inter * e + intra) / F[:, None], 0.0)
|
| 619 |
+
_store_vec(dst, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 620 |
+
tl.debug_barrier()
|
| 621 |
+
for kb in tl.static_range(NUM_C):
|
| 622 |
+
sk = kb * BLOCK_C
|
| 623 |
+
for di in tl.static_range(NUM_D):
|
| 624 |
+
d0 = di * BLOCK_D
|
| 625 |
+
zrows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 626 |
+
if sk < n_valid:
|
| 627 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 628 |
+
for qb in tl.static_range(NUM_C):
|
| 629 |
+
sq = qb * BLOCK_C
|
| 630 |
+
if qb >= kb and sq < n_valid:
|
| 631 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 632 |
+
Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C)
|
| 633 |
+
xt = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 634 |
+
if j + 2 < N:
|
| 635 |
+
xt += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 636 |
+
if j + 3 < N:
|
| 637 |
+
xt += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 638 |
+
yb = xt / Fb[:, None]
|
| 639 |
+
if qb == kb:
|
| 640 |
+
S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C)
|
| 641 |
+
zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 642 |
+
else:
|
| 643 |
+
S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C)
|
| 644 |
+
zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 645 |
+
if j > 0:
|
| 646 |
+
zrows += _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 647 |
+
_store_bc(dk_ptr, zrows, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 648 |
+
tl.debug_barrier()
|
| 649 |
+
|
| 650 |
+
# (2) dq, u_m, alpha, dcoeff and lin = sum_m o_{m-1} w_m + do_m o_m.
|
| 651 |
+
s = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 652 |
+
da = tl.zeros((1,), dtype=tl.float32)
|
| 653 |
+
db = tl.zeros((1,), dtype=tl.float32)
|
| 654 |
+
dc = tl.zeros((1,), dtype=tl.float32)
|
| 655 |
+
dd = tl.zeros((1,), dtype=tl.float32)
|
| 656 |
+
for i in tl.static_range(NUM_D):
|
| 657 |
+
d0 = i * BLOCK_D
|
| 658 |
+
q = _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 659 |
+
o1 = _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 660 |
+
o2 = _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 661 |
+
dx = _load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 662 |
+
p1 = _load_vec(p1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 663 |
+
p2 = _load_vec(p2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 664 |
+
dq = c0 * dx + c1 * p1 + c2 * p2
|
| 665 |
+
do1 = c1 * dx + c2 * p1
|
| 666 |
+
do2 = c2 * dx
|
| 667 |
+
w1 = c1 * p1 + c2 * p2
|
| 668 |
+
w2 = c2 * p1
|
| 669 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2
|
| 670 |
+
if N > 3:
|
| 671 |
+
o3 = _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 672 |
+
p3 = _load_vec(p3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 673 |
+
dq += c3 * p3
|
| 674 |
+
do1 += c3 * p2
|
| 675 |
+
do2 += c3 * p1
|
| 676 |
+
do3 = c3 * dx
|
| 677 |
+
w1 += c3 * p3
|
| 678 |
+
w2 += c3 * p2
|
| 679 |
+
w3 = c3 * p1
|
| 680 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + o2 * w3 + do3 * o3
|
| 681 |
+
_store_vec(u3_ptr, do3 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 682 |
+
s += tl.sum(o3 * do3, axis=1)
|
| 683 |
+
dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0)
|
| 684 |
+
_store_vec(dq_ptr, dq, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 685 |
+
_store_vec(u1_ptr, do1 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 686 |
+
_store_vec(u2_ptr, do2 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 687 |
+
_store_vec(dgk_ptr, lin, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 688 |
+
s += tl.sum(o1 * do1, axis=1) + tl.sum(o2 * do2, axis=1)
|
| 689 |
+
da += tl.sum(tl.sum(dx * q, axis=0), axis=0)
|
| 690 |
+
db += tl.sum(tl.sum(dx * o1, axis=0), axis=0)
|
| 691 |
+
dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0)
|
| 692 |
+
alpha = tl.where(m_t, -s / F, 0.0)
|
| 693 |
+
base = ((b_id * num_chunks + chunk_id) * H + h_id) * N
|
| 694 |
+
tl.store(dcoeff_ptr + base + 0, tl.sum(da))
|
| 695 |
+
tl.store(dcoeff_ptr + base + 1, tl.sum(db))
|
| 696 |
+
tl.store(dcoeff_ptr + base + 2, tl.sum(dc))
|
| 697 |
+
if N > 3:
|
| 698 |
+
tl.store(dcoeff_ptr + base + 3, tl.sum(dd))
|
| 699 |
+
tl.debug_barrier()
|
| 700 |
+
|
| 701 |
+
_store_row(alpha_ptr, alpha, T, H, chunk_id, chunk_size)
|
| 702 |
+
tl.debug_barrier()
|
| 703 |
+
|
| 704 |
+
# (3) Z += tril(X_m k'^T)^T Y_m, already multiplied by E^{-1}.
|
| 705 |
+
for m in tl.static_range(1, N):
|
| 706 |
+
if m == 1:
|
| 707 |
+
xs = q_ptr
|
| 708 |
+
us = u1_ptr
|
| 709 |
+
elif m == 2:
|
| 710 |
+
xs = o1_ptr
|
| 711 |
+
us = u2_ptr
|
| 712 |
+
else:
|
| 713 |
+
xs = o2_ptr
|
| 714 |
+
us = u3_ptr
|
| 715 |
+
for kb in tl.static_range(NUM_C):
|
| 716 |
+
sk = kb * BLOCK_C
|
| 717 |
+
for di in tl.static_range(NUM_D):
|
| 718 |
+
d0 = di * BLOCK_D
|
| 719 |
+
zrows = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 720 |
+
if sk < n_valid:
|
| 721 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 722 |
+
for qb in tl.static_range(NUM_C):
|
| 723 |
+
sq = qb * BLOCK_C
|
| 724 |
+
if qb >= kb and sq < n_valid:
|
| 725 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 726 |
+
yb = _load_bc(us, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D)
|
| 727 |
+
if qb == kb:
|
| 728 |
+
S = _scores_block(
|
| 729 |
+
xs, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 730 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 731 |
+
)
|
| 732 |
+
zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 733 |
+
else:
|
| 734 |
+
S = _scores_block(
|
| 735 |
+
xs, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 736 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 737 |
+
)
|
| 738 |
+
zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 739 |
+
_store_bc(dk_ptr, zrows, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D)
|
| 740 |
+
tl.debug_barrier()
|
| 741 |
+
|
| 742 |
+
# (4) g_partial. The trace term on dk / dgk is a separate epilogue.
|
| 743 |
+
eye = tl.arange(0, BLOCK_D)
|
| 744 |
+
for i in tl.static_range(NUM_D):
|
| 745 |
+
d0 = i * BLOCK_D
|
| 746 |
+
gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 747 |
+
e = tl.exp(gam)
|
| 748 |
+
r0 = tl.sum(alpha[:, None] * e * e, axis=0)
|
| 749 |
+
for jd in tl.static_range(NUM_D):
|
| 750 |
+
d1 = jd * BLOCK_D
|
| 751 |
+
e1 = tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D))
|
| 752 |
+
g = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32)
|
| 753 |
+
for mm in tl.static_range(1, N):
|
| 754 |
+
if mm == 1:
|
| 755 |
+
xs = q_ptr
|
| 756 |
+
us = u1_ptr
|
| 757 |
+
elif mm == 2:
|
| 758 |
+
xs = o1_ptr
|
| 759 |
+
us = u2_ptr
|
| 760 |
+
else:
|
| 761 |
+
xs = o2_ptr
|
| 762 |
+
us = u3_ptr
|
| 763 |
+
x = _load_vec(xs, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e
|
| 764 |
+
y = _load_vec(us, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * e1
|
| 765 |
+
g += _dot(tl.trans(x), y, PREC, 5)
|
| 766 |
+
if i == jd:
|
| 767 |
+
g += tl.where(eye[:, None] == eye[None, :], r0[:, None], 0.0)
|
| 768 |
+
_store_mat(g_partial_ptr, g, D, d0, d1, BLOCK_D)
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
@triton.jit
|
| 772 |
+
def _e_last_of(gam_ptr, b_id, h_id, cid, T, H: tl.constexpr, D: tl.constexpr,
|
| 773 |
+
chunk_size: tl.constexpr, d0, BLOCK: tl.constexpr):
|
| 774 |
+
"""exp(Gam) at the last valid token of chunk ``cid``, dims d0:d0+BLOCK."""
|
| 775 |
+
t_last = cid * chunk_size + tl.minimum(chunk_size, T - cid * chunk_size) - 1
|
| 776 |
+
off = ((b_id * T + t_last) * H + h_id).to(tl.int64) * D + d0
|
| 777 |
+
return tl.exp(tl.load(gam_ptr + off + tl.arange(0, BLOCK)).to(tl.float32))
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
@triton.jit
|
| 781 |
+
def _gam_last_of(gam_ptr, b_id, h_id, cid, T, H: tl.constexpr, D: tl.constexpr,
|
| 782 |
+
chunk_size: tl.constexpr, d0, BLOCK: tl.constexpr):
|
| 783 |
+
t_last = cid * chunk_size + tl.minimum(chunk_size, T - cid * chunk_size) - 1
|
| 784 |
+
off = ((b_id * T + t_last) * H + h_id).to(tl.int64) * D + d0
|
| 785 |
+
return tl.load(gam_ptr + off + tl.arange(0, BLOCK)).to(tl.float32)
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
@triton.jit(do_not_specialize=["T"])
|
| 789 |
+
def trace_bwd_scan_kernel(
|
| 790 |
+
g_partial_ptr, gam_ptr, gin_ptr, dht_ptr,
|
| 791 |
+
T, NC, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 792 |
+
BLOCK_S: tl.constexpr, HAS_DHT: tl.constexpr,
|
| 793 |
+
):
|
| 794 |
+
"""gin[c] = g_partial[c+1] + Diag(E_last[c+1]) gin[c+1] Diag(E_last[c+1])."""
|
| 795 |
+
i_bh = tl.program_id(0)
|
| 796 |
+
i_tile = tl.program_id(1)
|
| 797 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 798 |
+
NUM_S: tl.constexpr = D // BLOCK_S
|
| 799 |
+
r0 = (i_tile // NUM_S) * BLOCK_S
|
| 800 |
+
c0 = (i_tile % NUM_S) * BLOCK_S
|
| 801 |
+
G = tl.zeros((BLOCK_S, BLOCK_S), dtype=tl.float32)
|
| 802 |
+
if HAS_DHT:
|
| 803 |
+
p_dht = tl.make_block_ptr(
|
| 804 |
+
dht_ptr + (i_b * H + i_h).to(tl.int64) * D * D,
|
| 805 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 806 |
+
)
|
| 807 |
+
G = tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32)
|
| 808 |
+
last = NC - 1
|
| 809 |
+
p_gin = tl.make_block_ptr(
|
| 810 |
+
gin_ptr + ((i_b * NC + last) * H + i_h).to(tl.int64) * D * D,
|
| 811 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 812 |
+
)
|
| 813 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 814 |
+
for it in tl.range(0, NC - 1):
|
| 815 |
+
cid = NC - 2 - it
|
| 816 |
+
src = cid + 1
|
| 817 |
+
p_gp = tl.make_block_ptr(
|
| 818 |
+
g_partial_ptr + ((i_b * NC + src) * H + i_h).to(tl.int64) * D * D,
|
| 819 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 820 |
+
)
|
| 821 |
+
gp = tl.load(p_gp, boundary_check=(0, 1)).to(tl.float32)
|
| 822 |
+
er = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, r0, BLOCK_S)
|
| 823 |
+
ec = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, c0, BLOCK_S)
|
| 824 |
+
G = gp + er[:, None] * G * ec[None, :]
|
| 825 |
+
p_gin = tl.make_block_ptr(
|
| 826 |
+
gin_ptr + ((i_b * NC + cid) * H + i_h).to(tl.int64) * D * D,
|
| 827 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 828 |
+
)
|
| 829 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
@triton.jit(do_not_specialize=["T"])
|
| 833 |
+
def trace_bwd_gin_kernel(
|
| 834 |
+
h_ptr, k_ptr, gam_ptr, gin_ptr, dk_ptr, dgk_ptr,
|
| 835 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 836 |
+
BLOCK_D: tl.constexpr, PREC: tl.constexpr,
|
| 837 |
+
):
|
| 838 |
+
"""Add S_in = Diag(E_C) (gin + gin^T) Diag(E_C) into dk and dgk.
|
| 839 |
+
|
| 840 |
+
k is scaled by exp(Gam_last - Gam_t), which is <= 1 for non-positive gk.
|
| 841 |
+
"""
|
| 842 |
+
chunk_id = tl.program_id(0)
|
| 843 |
+
bh = tl.program_id(1)
|
| 844 |
+
b_id, h_id = bh // H, bh % H
|
| 845 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 846 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 847 |
+
m_t = _masks(chunk_id, chunk_size, T)
|
| 848 |
+
|
| 849 |
+
gam_base = gam_ptr
|
| 850 |
+
vec = (b_id * T * H + h_id) * D
|
| 851 |
+
k_ptr += vec
|
| 852 |
+
gam_ptr += vec
|
| 853 |
+
dk_ptr += vec
|
| 854 |
+
dgk_ptr += vec
|
| 855 |
+
mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 856 |
+
h_ptr += mat
|
| 857 |
+
gin_ptr += mat
|
| 858 |
+
|
| 859 |
+
for i in tl.static_range(NUM_D):
|
| 860 |
+
d0 = i * BLOCK_D
|
| 861 |
+
gam0 = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 862 |
+
el_log0 = _gam_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d0, BLOCK_D)
|
| 863 |
+
el0 = tl.exp(el_log0)
|
| 864 |
+
Za = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 865 |
+
v1 = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 866 |
+
for j in tl.static_range(NUM_D):
|
| 867 |
+
d1 = j * BLOCK_D
|
| 868 |
+
gam1 = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 869 |
+
k1 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 870 |
+
el_log1 = _gam_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d1, BLOCK_D)
|
| 871 |
+
el1 = tl.exp(el_log1)
|
| 872 |
+
w1 = k1 * tl.exp(el_log1[None, :] - gam1)
|
| 873 |
+
sym = _load_mat(gin_ptr, D, d1, d0, BLOCK_D) + tl.trans(_load_mat(gin_ptr, D, d0, d1, BLOCK_D))
|
| 874 |
+
Za += _dot(w1, sym, PREC, 6)
|
| 875 |
+
h_ij = _load_mat(h_ptr, D, d0, d1, BLOCK_D)
|
| 876 |
+
v1 += tl.sum(tl.trans(sym) * el1[None, :] * h_ij, axis=1)
|
| 877 |
+
scale0 = tl.exp(el_log0[None, :] - gam0)
|
| 878 |
+
dk = _load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 879 |
+
_store_vec(dk_ptr, dk + scale0 * Za, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 880 |
+
k0 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 881 |
+
dgk = _load_vec(dgk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 882 |
+
dgk += 0.5 * (v1[None, :] * el0[None, :] + _excl(k0 * scale0 * Za))
|
| 883 |
+
_store_vec(dgk_ptr, dgk, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
@triton.jit(do_not_specialize=["T"])
|
| 887 |
+
def trace_bwd_epilogue_kernel(
|
| 888 |
+
h_ptr, k_ptr, gam_ptr, alpha_ptr, diag_ptr, dk_ptr, dgk_ptr,
|
| 889 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 890 |
+
BLOCK_D: tl.constexpr,
|
| 891 |
+
):
|
| 892 |
+
"""dgk / dk trace term. One exp(gk) step at a time, same recurrence as the safe scans."""
|
| 893 |
+
chunk_id = tl.program_id(0)
|
| 894 |
+
tile = tl.program_id(1)
|
| 895 |
+
bh = tl.program_id(2)
|
| 896 |
+
b_id, h_id = bh // H, bh % H
|
| 897 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 898 |
+
m_t = _masks(chunk_id, chunk_size, T)
|
| 899 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 900 |
+
scalar = b_id * T * H + h_id
|
| 901 |
+
vec = scalar * D
|
| 902 |
+
k_ptr += vec
|
| 903 |
+
gam_ptr += vec
|
| 904 |
+
dk_ptr += vec
|
| 905 |
+
dgk_ptr += vec
|
| 906 |
+
diag_ptr += vec
|
| 907 |
+
alpha_ptr += scalar
|
| 908 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 909 |
+
alpha = _load_row(alpha_ptr, T, H, chunk_id, chunk_size, m_t, 0.0)
|
| 910 |
+
base_tok = chunk_id * chunk_size
|
| 911 |
+
d0 = tile * BLOCK_D
|
| 912 |
+
dstate = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D)
|
| 913 |
+
gprev = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 914 |
+
ar = tl.arange(0, BLOCK_D)
|
| 915 |
+
for t in tl.range(0, chunk_size):
|
| 916 |
+
alive = t < n_valid
|
| 917 |
+
tok = base_tok + t
|
| 918 |
+
kt = _load_tok(k_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 919 |
+
gt = _load_tok(gam_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 920 |
+
gt_s = tl.where(alive, gt, gprev)
|
| 921 |
+
d_new = tl.exp(2.0 * (gt_s - gprev)) * dstate + tl.where(alive, kt * kt, 0.0)
|
| 922 |
+
dstate = tl.where(alive, d_new, dstate)
|
| 923 |
+
gprev = gt_s
|
| 924 |
+
tl.store(diag_ptr + tok.to(tl.int64) * H * D + d0 + ar, tl.where(alive, d_new, 0.0), mask=alive)
|
| 925 |
+
tl.debug_barrier()
|
| 926 |
+
Rstate = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 927 |
+
g_carry = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 928 |
+
have = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 929 |
+
suf = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 930 |
+
for ti in tl.range(0, chunk_size):
|
| 931 |
+
t = chunk_size - 1 - ti
|
| 932 |
+
alive = t < n_valid
|
| 933 |
+
tok = base_tok + t
|
| 934 |
+
gt = _load_tok(gam_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 935 |
+
kt = _load_tok(k_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 936 |
+
zt = _load_tok(dk_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 937 |
+
lt = _load_tok(dgk_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 938 |
+
dh = _load_tok(diag_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 939 |
+
at = tl.load(alpha_ptr + tok.to(tl.int64) * H, mask=alive, other=0.0).to(tl.float32)
|
| 940 |
+
term = tl.where(alive, lt - kt * zt, 0.0)
|
| 941 |
+
suf_t = term + suf
|
| 942 |
+
suf = tl.where(alive, suf_t, suf)
|
| 943 |
+
g_n = have * g_carry + (1.0 - have) * gt
|
| 944 |
+
gt_s = tl.where(alive, gt, g_n)
|
| 945 |
+
step = tl.exp(2.0 * (g_n - gt_s))
|
| 946 |
+
Rt = at + step * (have * Rstate)
|
| 947 |
+
Rstate = tl.where(alive, Rt, Rstate)
|
| 948 |
+
g_carry = tl.where(alive, gt, g_carry)
|
| 949 |
+
have = tl.where(alive, 1.0, have)
|
| 950 |
+
dg = 0.5 * suf_t + Rt * (dh - kt * kt)
|
| 951 |
+
dk = zt + 2.0 * Rt * kt
|
| 952 |
+
tl.store(dgk_ptr + tok.to(tl.int64) * H * D + d0 + ar, tl.where(alive, dg, 0.0), mask=alive)
|
| 953 |
+
tl.store(dk_ptr + tok.to(tl.int64) * H * D + d0 + ar, tl.where(alive, dk, 0.0), mask=alive)
|
| 954 |
+
|
| 955 |
+
|
| 956 |
+
@triton.jit(do_not_specialize=["T"])
|
| 957 |
+
def trace_F_kernel(
|
| 958 |
+
h_ptr, k_ptr, gam_ptr, f_ptr,
|
| 959 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 960 |
+
BLOCK_D: tl.constexpr, EPS: tl.constexpr,
|
| 961 |
+
):
|
| 962 |
+
chunk_id = tl.program_id(0)
|
| 963 |
+
bh = tl.program_id(1)
|
| 964 |
+
b_id, h_id = bh // H, bh % H
|
| 965 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 966 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 967 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 968 |
+
vec = (b_id * T * H + h_id) * D
|
| 969 |
+
k_ptr += vec
|
| 970 |
+
gam_ptr += vec
|
| 971 |
+
f_ptr += b_id * T * H + h_id
|
| 972 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 973 |
+
base_tok = chunk_id * chunk_size
|
| 974 |
+
for i in tl.static_range(NUM_D):
|
| 975 |
+
d0 = i * BLOCK_D
|
| 976 |
+
dstate = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D)
|
| 977 |
+
gprev = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 978 |
+
for t in tl.range(0, chunk_size):
|
| 979 |
+
alive = t < n_valid
|
| 980 |
+
tok = base_tok + t
|
| 981 |
+
kt = _load_tok(k_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 982 |
+
gt = _load_tok(gam_ptr, H, D, tok, d0, alive, BLOCK_D)
|
| 983 |
+
gt_s = tl.where(alive, gt, gprev)
|
| 984 |
+
d_new = tl.exp(2.0 * (gt_s - gprev)) * dstate + tl.where(alive, kt * kt, 0.0)
|
| 985 |
+
dstate = tl.where(alive, d_new, dstate)
|
| 986 |
+
gprev = gt_s
|
| 987 |
+
# One scalar per token. A chunk-sized where-scatter here dominates the kernel.
|
| 988 |
+
slot = f_ptr + tok.to(tl.int64) * H
|
| 989 |
+
contrib = tl.sum(tl.where(alive, d_new, 0.0))
|
| 990 |
+
if i == 0:
|
| 991 |
+
tl.store(slot, contrib + EPS, mask=alive)
|
| 992 |
+
else:
|
| 993 |
+
prev = tl.load(slot, mask=alive, other=0.0).to(tl.float32)
|
| 994 |
+
tl.store(slot, prev + contrib, mask=alive)
|
| 995 |
+
tl.debug_barrier()
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
@triton.jit(do_not_specialize=["T"])
|
| 999 |
+
def trace_intra_qb_kernel(
|
| 1000 |
+
src_ptr, k_ptr, gam_ptr, dst_ptr, s_ptr,
|
| 1001 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 1002 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr,
|
| 1003 |
+
PREC: tl.constexpr, STORE_S: tl.constexpr,
|
| 1004 |
+
):
|
| 1005 |
+
"""One query block. Scores are formed once and applied to every D tile."""
|
| 1006 |
+
chunk_id = tl.program_id(0)
|
| 1007 |
+
qb = tl.program_id(1)
|
| 1008 |
+
bh = tl.program_id(2)
|
| 1009 |
+
b_id, h_id = bh // H, bh % H
|
| 1010 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 1011 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1012 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 1013 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 1014 |
+
vec = (b_id * T * H + h_id) * D
|
| 1015 |
+
src_ptr += vec
|
| 1016 |
+
k_ptr += vec
|
| 1017 |
+
gam_ptr += vec
|
| 1018 |
+
dst_ptr += vec
|
| 1019 |
+
s_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C)
|
| 1020 |
+
sq = qb * BLOCK_C
|
| 1021 |
+
if NUM_D == 1:
|
| 1022 |
+
rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1023 |
+
if sq < n_valid:
|
| 1024 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1025 |
+
for kb in tl.range(0, qb):
|
| 1026 |
+
sk = kb * BLOCK_C
|
| 1027 |
+
S = _scores_block(
|
| 1028 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1029 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 1030 |
+
)
|
| 1031 |
+
if STORE_S:
|
| 1032 |
+
_store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C)
|
| 1033 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1034 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1035 |
+
rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 1036 |
+
sk = sq
|
| 1037 |
+
S = _scores_block(
|
| 1038 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1039 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 1040 |
+
)
|
| 1041 |
+
if STORE_S:
|
| 1042 |
+
_store_S(s_ptr, S, qb, qb, NUM_C, BLOCK_C)
|
| 1043 |
+
kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1044 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1045 |
+
rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 1046 |
+
_store_bc(dst_ptr, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1047 |
+
else:
|
| 1048 |
+
rows0 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1049 |
+
rows1 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1050 |
+
if sq < n_valid:
|
| 1051 |
+
gq0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1052 |
+
gq1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1053 |
+
for kb in tl.range(0, qb):
|
| 1054 |
+
sk = kb * BLOCK_C
|
| 1055 |
+
S = _scores_block(
|
| 1056 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1057 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 1058 |
+
)
|
| 1059 |
+
if STORE_S:
|
| 1060 |
+
_store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C)
|
| 1061 |
+
k0 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1062 |
+
g0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1063 |
+
k1 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1064 |
+
g1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1065 |
+
rows0 += _apply_block(S, k0, g0, gq0, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 1066 |
+
rows1 += _apply_block(S, k1, g1, gq1, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 1067 |
+
sk = sq
|
| 1068 |
+
S = _scores_block(
|
| 1069 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1070 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 1071 |
+
)
|
| 1072 |
+
if STORE_S:
|
| 1073 |
+
_store_S(s_ptr, S, qb, qb, NUM_C, BLOCK_C)
|
| 1074 |
+
k0 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1075 |
+
g0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1076 |
+
k1 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1077 |
+
g1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1078 |
+
rows0 += _apply_block(S, k0, g0, gq0, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 1079 |
+
rows1 += _apply_block(S, k1, g1, gq1, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 1080 |
+
_store_bc(dst_ptr, rows0, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1081 |
+
_store_bc(dst_ptr, rows1, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
@triton.jit(do_not_specialize=["T"])
|
| 1085 |
+
def trace_combine_kernel(
|
| 1086 |
+
h_ptr, src_ptr, gam_ptr, dst_ptr, f_ptr,
|
| 1087 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 1088 |
+
BLOCK_D: tl.constexpr, PREC: tl.constexpr,
|
| 1089 |
+
):
|
| 1090 |
+
"""Add the carried state to the intra term already stored in dst, then divide by F.
|
| 1091 |
+
|
| 1092 |
+
One D tile per program. The inner reduction reuses one operand tile.
|
| 1093 |
+
"""
|
| 1094 |
+
chunk_id = tl.program_id(0)
|
| 1095 |
+
tile = tl.program_id(1)
|
| 1096 |
+
bh = tl.program_id(2)
|
| 1097 |
+
b_id, h_id = bh // H, bh % H
|
| 1098 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 1099 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1100 |
+
m_t = _masks(chunk_id, chunk_size, T)
|
| 1101 |
+
vec = (b_id * T * H + h_id) * D
|
| 1102 |
+
src_ptr += vec
|
| 1103 |
+
gam_ptr += vec
|
| 1104 |
+
dst_ptr += vec
|
| 1105 |
+
f_ptr += b_id * T * H + h_id
|
| 1106 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 1107 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 1108 |
+
d0 = tile * BLOCK_D
|
| 1109 |
+
g = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1110 |
+
e = tl.exp(g)
|
| 1111 |
+
inter = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 1112 |
+
for j in tl.range(0, NUM_D):
|
| 1113 |
+
d1 = j * BLOCK_D
|
| 1114 |
+
v = _load_vec(src_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 1115 |
+
v *= tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D))
|
| 1116 |
+
inter += _dot(v, _load_mat(h_ptr, D, d1, d0, BLOCK_D), PREC, 1)
|
| 1117 |
+
intra = _load_vec(dst_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1118 |
+
out = tl.where(m_t[:, None], (inter * e + intra) / F[:, None], 0.0)
|
| 1119 |
+
_store_vec(dst_ptr, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
@triton.jit(do_not_specialize=["T"])
|
| 1123 |
+
def trace_mix_kernel(
|
| 1124 |
+
q_ptr, o1_ptr, o2_ptr, o3_ptr, x_ptr, coeff_ptr,
|
| 1125 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 1126 |
+
BLOCK_D: tl.constexpr, N: tl.constexpr,
|
| 1127 |
+
):
|
| 1128 |
+
chunk_id = tl.program_id(0)
|
| 1129 |
+
bh = tl.program_id(1)
|
| 1130 |
+
b_id, h_id = bh // H, bh % H
|
| 1131 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1132 |
+
m_t = _masks(chunk_id, chunk_size, T)
|
| 1133 |
+
vec = (b_id * T * H + h_id) * D
|
| 1134 |
+
q_ptr += vec
|
| 1135 |
+
o1_ptr += vec
|
| 1136 |
+
o2_ptr += vec
|
| 1137 |
+
o3_ptr += vec
|
| 1138 |
+
x_ptr += vec
|
| 1139 |
+
c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32)
|
| 1140 |
+
c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32)
|
| 1141 |
+
c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32)
|
| 1142 |
+
for i in tl.static_range(NUM_D):
|
| 1143 |
+
d0 = i * BLOCK_D
|
| 1144 |
+
acc = c0 * _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1145 |
+
acc += c1 * _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1146 |
+
acc += c2 * _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1147 |
+
if N > 3:
|
| 1148 |
+
c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32)
|
| 1149 |
+
acc += c3 * _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1150 |
+
_store_vec(x_ptr, acc, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
+
@triton.jit(do_not_specialize=["T"])
|
| 1154 |
+
def trace_z_kb_kernel(
|
| 1155 |
+
src_ptr, k_ptr, gam_ptr, y_ptr, q_ptr, o1_ptr, o2_ptr, f_ptr, coeff_ptr,
|
| 1156 |
+
dk_ptr, s_ptr,
|
| 1157 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 1158 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr,
|
| 1159 |
+
N: tl.constexpr, J: tl.constexpr, PREC: tl.constexpr,
|
| 1160 |
+
LOAD_S: tl.constexpr, USE_COEFF: tl.constexpr, ACCUM: tl.constexpr,
|
| 1161 |
+
):
|
| 1162 |
+
"""One key block of Z. S is either reloaded or rebuilt for this pair."""
|
| 1163 |
+
chunk_id = tl.program_id(0)
|
| 1164 |
+
kb = tl.program_id(1)
|
| 1165 |
+
bh = tl.program_id(2)
|
| 1166 |
+
b_id, h_id = bh // H, bh % H
|
| 1167 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 1168 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1169 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 1170 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 1171 |
+
vec = (b_id * T * H + h_id) * D
|
| 1172 |
+
src_ptr += vec
|
| 1173 |
+
k_ptr += vec
|
| 1174 |
+
gam_ptr += vec
|
| 1175 |
+
y_ptr += vec
|
| 1176 |
+
q_ptr += vec
|
| 1177 |
+
o1_ptr += vec
|
| 1178 |
+
o2_ptr += vec
|
| 1179 |
+
dk_ptr += vec
|
| 1180 |
+
f_ptr += b_id * T * H + h_id
|
| 1181 |
+
s_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C)
|
| 1182 |
+
ca = 0.0
|
| 1183 |
+
cb = 0.0
|
| 1184 |
+
cc = 0.0
|
| 1185 |
+
if USE_COEFF:
|
| 1186 |
+
ca = tl.load(coeff_ptr + h_id * N + J + 1).to(tl.float32)
|
| 1187 |
+
if J + 2 < N:
|
| 1188 |
+
cb = tl.load(coeff_ptr + h_id * N + J + 2).to(tl.float32)
|
| 1189 |
+
if J + 3 < N:
|
| 1190 |
+
cc = tl.load(coeff_ptr + h_id * N + J + 3).to(tl.float32)
|
| 1191 |
+
sk = kb * BLOCK_C
|
| 1192 |
+
if NUM_D == 1:
|
| 1193 |
+
z = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1194 |
+
if ACCUM:
|
| 1195 |
+
z = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1196 |
+
if sk < n_valid:
|
| 1197 |
+
gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1198 |
+
for qb in tl.range(kb, NUM_C):
|
| 1199 |
+
sq = qb * BLOCK_C
|
| 1200 |
+
if sq < n_valid:
|
| 1201 |
+
gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1202 |
+
if USE_COEFF:
|
| 1203 |
+
Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C)
|
| 1204 |
+
yb = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1205 |
+
if J + 2 < N:
|
| 1206 |
+
yb += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1207 |
+
if J + 3 < N:
|
| 1208 |
+
yb += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1209 |
+
yb = yb / Fb[:, None]
|
| 1210 |
+
else:
|
| 1211 |
+
yb = _load_bc(y_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1212 |
+
if qb == kb:
|
| 1213 |
+
if LOAD_S:
|
| 1214 |
+
S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C)
|
| 1215 |
+
else:
|
| 1216 |
+
S = _scores_block(
|
| 1217 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1218 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 1219 |
+
)
|
| 1220 |
+
z += _z_pair(S, yb, gq, gg, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 1221 |
+
else:
|
| 1222 |
+
if LOAD_S:
|
| 1223 |
+
S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C)
|
| 1224 |
+
else:
|
| 1225 |
+
S = _scores_block(
|
| 1226 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1227 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 1228 |
+
)
|
| 1229 |
+
z += _z_pair(S, yb, gq, gg, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 1230 |
+
_store_bc(dk_ptr, z, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1231 |
+
else:
|
| 1232 |
+
z0 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1233 |
+
z1 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1234 |
+
if ACCUM:
|
| 1235 |
+
z0 = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1236 |
+
z1 = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1237 |
+
if sk < n_valid:
|
| 1238 |
+
gg0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1239 |
+
gg1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1240 |
+
for qb in tl.range(kb, NUM_C):
|
| 1241 |
+
sq = qb * BLOCK_C
|
| 1242 |
+
if sq < n_valid:
|
| 1243 |
+
gq0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1244 |
+
gq1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1245 |
+
if USE_COEFF:
|
| 1246 |
+
Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C)
|
| 1247 |
+
y0 = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1248 |
+
y1 = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1249 |
+
if J + 2 < N:
|
| 1250 |
+
y0 += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1251 |
+
y1 += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1252 |
+
if J + 3 < N:
|
| 1253 |
+
y0 += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1254 |
+
y1 += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1255 |
+
y0 = y0 / Fb[:, None]
|
| 1256 |
+
y1 = y1 / Fb[:, None]
|
| 1257 |
+
else:
|
| 1258 |
+
y0 = _load_bc(y_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D)
|
| 1259 |
+
y1 = _load_bc(y_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1260 |
+
if qb == kb:
|
| 1261 |
+
if LOAD_S:
|
| 1262 |
+
S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C)
|
| 1263 |
+
else:
|
| 1264 |
+
S = _scores_block(
|
| 1265 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1266 |
+
BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC,
|
| 1267 |
+
)
|
| 1268 |
+
z0 += _z_pair(S, y0, gq0, gg0, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 1269 |
+
z1 += _z_pair(S, y1, gq1, gg1, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C)
|
| 1270 |
+
else:
|
| 1271 |
+
if LOAD_S:
|
| 1272 |
+
S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C)
|
| 1273 |
+
else:
|
| 1274 |
+
S = _scores_block(
|
| 1275 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid,
|
| 1276 |
+
BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC,
|
| 1277 |
+
)
|
| 1278 |
+
z0 += _z_pair(S, y0, gq0, gg0, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 1279 |
+
z1 += _z_pair(S, y1, gq1, gg1, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C)
|
| 1280 |
+
_store_bc(dk_ptr, z0, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D)
|
| 1281 |
+
_store_bc(dk_ptr, z1, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D)
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
@triton.jit(do_not_specialize=["T"])
|
| 1285 |
+
def trace_bwd_grad_kernel(
|
| 1286 |
+
h_ptr, gam_ptr, q_ptr, o1_ptr, o2_ptr, o3_ptr, dx_ptr, f_ptr, coeff_ptr,
|
| 1287 |
+
p1_ptr, p2_ptr, p3_ptr, u1_ptr, u2_ptr, u3_ptr,
|
| 1288 |
+
dq_ptr, dgk_ptr, g_partial_ptr, dcoeff_ptr, alpha_ptr,
|
| 1289 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 1290 |
+
BLOCK_D: tl.constexpr, N: tl.constexpr, PREC: tl.constexpr,
|
| 1291 |
+
):
|
| 1292 |
+
chunk_id = tl.program_id(0)
|
| 1293 |
+
bh = tl.program_id(1)
|
| 1294 |
+
b_id, h_id = bh // H, bh % H
|
| 1295 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 1296 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1297 |
+
m_t = _masks(chunk_id, chunk_size, T)
|
| 1298 |
+
scalar = b_id * T * H + h_id
|
| 1299 |
+
vec = scalar * D
|
| 1300 |
+
gam_ptr += vec
|
| 1301 |
+
q_ptr += vec
|
| 1302 |
+
o1_ptr += vec
|
| 1303 |
+
o2_ptr += vec
|
| 1304 |
+
o3_ptr += vec
|
| 1305 |
+
dx_ptr += vec
|
| 1306 |
+
p1_ptr += vec
|
| 1307 |
+
p2_ptr += vec
|
| 1308 |
+
p3_ptr += vec
|
| 1309 |
+
u1_ptr += vec
|
| 1310 |
+
u2_ptr += vec
|
| 1311 |
+
u3_ptr += vec
|
| 1312 |
+
dq_ptr += vec
|
| 1313 |
+
dgk_ptr += vec
|
| 1314 |
+
f_ptr += scalar
|
| 1315 |
+
alpha_ptr += scalar
|
| 1316 |
+
mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 1317 |
+
h_ptr += mat
|
| 1318 |
+
g_partial_ptr += mat
|
| 1319 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 1320 |
+
c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32)
|
| 1321 |
+
c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32)
|
| 1322 |
+
c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32)
|
| 1323 |
+
c3 = 0.0
|
| 1324 |
+
if N > 3:
|
| 1325 |
+
c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32)
|
| 1326 |
+
s = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 1327 |
+
da = tl.zeros((1,), dtype=tl.float32)
|
| 1328 |
+
db = tl.zeros((1,), dtype=tl.float32)
|
| 1329 |
+
dc = tl.zeros((1,), dtype=tl.float32)
|
| 1330 |
+
dd = tl.zeros((1,), dtype=tl.float32)
|
| 1331 |
+
for i in tl.static_range(NUM_D):
|
| 1332 |
+
d0 = i * BLOCK_D
|
| 1333 |
+
q = _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1334 |
+
o1 = _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1335 |
+
o2 = _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1336 |
+
dx = _load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1337 |
+
p1 = _load_vec(p1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1338 |
+
p2 = _load_vec(p2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1339 |
+
dq = c0 * dx + c1 * p1 + c2 * p2
|
| 1340 |
+
do1 = c1 * dx + c2 * p1
|
| 1341 |
+
do2 = c2 * dx
|
| 1342 |
+
w1 = c1 * p1 + c2 * p2
|
| 1343 |
+
w2 = c2 * p1
|
| 1344 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2
|
| 1345 |
+
if N > 3:
|
| 1346 |
+
o3 = _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1347 |
+
p3 = _load_vec(p3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1348 |
+
dq += c3 * p3
|
| 1349 |
+
do1 += c3 * p2
|
| 1350 |
+
do2 += c3 * p1
|
| 1351 |
+
do3 = c3 * dx
|
| 1352 |
+
w1 += c3 * p3
|
| 1353 |
+
w2 += c3 * p2
|
| 1354 |
+
w3 = c3 * p1
|
| 1355 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + o2 * w3 + do3 * o3
|
| 1356 |
+
_store_vec(u3_ptr, do3 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 1357 |
+
s += tl.sum(o3 * do3, axis=1)
|
| 1358 |
+
dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0)
|
| 1359 |
+
_store_vec(dq_ptr, dq, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 1360 |
+
_store_vec(u1_ptr, do1 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 1361 |
+
_store_vec(u2_ptr, do2 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 1362 |
+
_store_vec(dgk_ptr, lin, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 1363 |
+
s += tl.sum(o1 * do1, axis=1) + tl.sum(o2 * do2, axis=1)
|
| 1364 |
+
da += tl.sum(tl.sum(dx * q, axis=0), axis=0)
|
| 1365 |
+
db += tl.sum(tl.sum(dx * o1, axis=0), axis=0)
|
| 1366 |
+
dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0)
|
| 1367 |
+
alpha = tl.where(m_t, -s / F, 0.0)
|
| 1368 |
+
base = ((b_id * num_chunks + chunk_id) * H + h_id) * N
|
| 1369 |
+
tl.store(dcoeff_ptr + base + 0, tl.sum(da))
|
| 1370 |
+
tl.store(dcoeff_ptr + base + 1, tl.sum(db))
|
| 1371 |
+
tl.store(dcoeff_ptr + base + 2, tl.sum(dc))
|
| 1372 |
+
if N > 3:
|
| 1373 |
+
tl.store(dcoeff_ptr + base + 3, tl.sum(dd))
|
| 1374 |
+
_store_row(alpha_ptr, alpha, T, H, chunk_id, chunk_size)
|
| 1375 |
+
tl.debug_barrier()
|
| 1376 |
+
eye = tl.arange(0, BLOCK_D)
|
| 1377 |
+
for i in tl.static_range(NUM_D):
|
| 1378 |
+
d0 = i * BLOCK_D
|
| 1379 |
+
gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 1380 |
+
e = tl.exp(gam)
|
| 1381 |
+
r0 = tl.sum(alpha[:, None] * e * e, axis=0)
|
| 1382 |
+
for jd in tl.static_range(NUM_D):
|
| 1383 |
+
d1 = jd * BLOCK_D
|
| 1384 |
+
e1 = tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D))
|
| 1385 |
+
g = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32)
|
| 1386 |
+
for mm in tl.static_range(1, N):
|
| 1387 |
+
if mm == 1:
|
| 1388 |
+
xs, us = q_ptr, u1_ptr
|
| 1389 |
+
elif mm == 2:
|
| 1390 |
+
xs, us = o1_ptr, u2_ptr
|
| 1391 |
+
else:
|
| 1392 |
+
xs, us = o2_ptr, u3_ptr
|
| 1393 |
+
x = _load_vec(xs, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e
|
| 1394 |
+
y = _load_vec(us, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * e1
|
| 1395 |
+
g += _dot(tl.trans(x), y, PREC, 5)
|
| 1396 |
+
if i == jd:
|
| 1397 |
+
g += tl.where(eye[:, None] == eye[None, :], r0[:, None], 0.0)
|
| 1398 |
+
_store_mat(g_partial_ptr, g, D, d0, d1, BLOCK_D)
|
| 1399 |
+
|
| 1400 |
+
|
| 1401 |
+
def _bwd(k, q, os, dx, F, coeff_h, gam, h, dht, h0, chunk_size, n_coeff, s_fwd):
|
| 1402 |
+
"""os = (o1, o2[, o3]) in fp32."""
|
| 1403 |
+
B, T, H, D = q.shape
|
| 1404 |
+
C = chunk_size
|
| 1405 |
+
N = n_coeff
|
| 1406 |
+
nc = triton.cdiv(T, C)
|
| 1407 |
+
block_d = _choose_intra_d(D)
|
| 1408 |
+
gin_d = _choose_block_d(D)
|
| 1409 |
+
num_c = C // BLOCK_C
|
| 1410 |
+
f32 = dict(device=q.device, dtype=torch.float32)
|
| 1411 |
+
o1, o2 = os[0], os[1]
|
| 1412 |
+
o3 = os[2] if N == 4 else o2
|
| 1413 |
+
p1 = torch.empty(B, T, H, D, **f32)
|
| 1414 |
+
p2 = torch.empty(B, T, H, D, **f32)
|
| 1415 |
+
p3 = torch.empty(B, T, H, D, **f32) if N == 4 else p2
|
| 1416 |
+
u1 = torch.empty(B, T, H, D, **f32)
|
| 1417 |
+
u2 = torch.empty(B, T, H, D, **f32)
|
| 1418 |
+
u3 = torch.empty(B, T, H, D, **f32) if N == 4 else u2
|
| 1419 |
+
dq = torch.empty_like(q)
|
| 1420 |
+
dk = torch.empty(B, T, H, D, **f32)
|
| 1421 |
+
dgk = torch.empty(B, T, H, D, **f32)
|
| 1422 |
+
g_partial = torch.empty(B, nc, H, D, D, **f32)
|
| 1423 |
+
gin = torch.empty(B, nc, H, D, D, **f32)
|
| 1424 |
+
dcoeff_part = torch.empty(B, nc, H, N, **f32)
|
| 1425 |
+
alpha = torch.empty(B, T, H, **f32)
|
| 1426 |
+
s_ws = torch.empty(B, nc, H, num_c, num_c, BLOCK_C, BLOCK_C, **f32)
|
| 1427 |
+
diag_ws = torch.empty(B, T, H, D, **f32)
|
| 1428 |
+
grid = (nc, B * H)
|
| 1429 |
+
grid_b = (nc, num_c, B * H)
|
| 1430 |
+
bwd_src = [dx, p1, p2]
|
| 1431 |
+
bwd_dst = [p1, p2, p3]
|
| 1432 |
+
for j in range(N - 1):
|
| 1433 |
+
trace_intra_qb_kernel[grid_b](
|
| 1434 |
+
bwd_src[j], k, gam, bwd_dst[j], s_ws,
|
| 1435 |
+
T, H, D, C, block_d, BLOCK_C, SHIFT, DOT_PRECISION, True,
|
| 1436 |
+
num_warps=4, num_stages=1,
|
| 1437 |
+
)
|
| 1438 |
+
trace_combine_kernel[(nc, D // block_d, B * H)](
|
| 1439 |
+
h, bwd_src[j], gam, bwd_dst[j], F,
|
| 1440 |
+
T, H, D, C, block_d, DOT_PRECISION,
|
| 1441 |
+
num_warps=8, num_stages=1,
|
| 1442 |
+
)
|
| 1443 |
+
trace_z_kb_kernel[grid_b](
|
| 1444 |
+
q, k, gam, q, q, o1, o2, F, coeff_h, dk, s_ws,
|
| 1445 |
+
T, H, D, C, block_d, BLOCK_C, SHIFT, N, j, DOT_PRECISION,
|
| 1446 |
+
True, True, j > 0,
|
| 1447 |
+
num_warps=4, num_stages=1,
|
| 1448 |
+
)
|
| 1449 |
+
trace_bwd_grad_kernel[grid](
|
| 1450 |
+
h, gam, q, o1, o2, o3, dx, F, coeff_h,
|
| 1451 |
+
p1, p2, p3, u1, u2, u3,
|
| 1452 |
+
dq, dgk, g_partial, dcoeff_part, alpha,
|
| 1453 |
+
T, H, D, C, block_d, N, DOT_PRECISION,
|
| 1454 |
+
num_warps=8, num_stages=1,
|
| 1455 |
+
)
|
| 1456 |
+
z_src = [q, o1, o2]
|
| 1457 |
+
z_y = [u1, u2, u3]
|
| 1458 |
+
for m in range(1, N):
|
| 1459 |
+
trace_z_kb_kernel[grid_b](
|
| 1460 |
+
z_src[m - 1], k, gam, z_y[m - 1], q, o1, o2, F, coeff_h, dk, s_fwd[m - 1],
|
| 1461 |
+
T, H, D, C, block_d, BLOCK_C, SHIFT, N, 0, DOT_PRECISION,
|
| 1462 |
+
True, False, True,
|
| 1463 |
+
num_warps=4, num_stages=1,
|
| 1464 |
+
)
|
| 1465 |
+
trace_bwd_epilogue_kernel[(nc, D // block_d, B * H)](
|
| 1466 |
+
h, k, gam, alpha, diag_ws, dk, dgk,
|
| 1467 |
+
T, H, D, C, block_d,
|
| 1468 |
+
num_warps=4, num_stages=1,
|
| 1469 |
+
)
|
| 1470 |
+
block_s = _choose_scan_block(D)
|
| 1471 |
+
num_s = D // block_s
|
| 1472 |
+
dht_buf = dht.float().contiguous() if dht is not None else gin.new_empty(1)
|
| 1473 |
+
trace_bwd_scan_kernel[(B * H, num_s * num_s)](
|
| 1474 |
+
g_partial, gam, gin, dht_buf,
|
| 1475 |
+
T, nc, H, D, C, block_s, int(dht is not None),
|
| 1476 |
+
num_warps=1, num_stages=1,
|
| 1477 |
+
)
|
| 1478 |
+
trace_bwd_gin_kernel[grid](
|
| 1479 |
+
h, k, gam, gin, dk, dgk,
|
| 1480 |
+
T, H, D, C, gin_d, DOT_PRECISION, num_warps=8, num_stages=1,
|
| 1481 |
+
)
|
| 1482 |
+
dh0 = None
|
| 1483 |
+
if h0 is not None:
|
| 1484 |
+
e0 = gam[:, min(C, T) - 1].exp()
|
| 1485 |
+
dh0 = g_partial[:, 0] + e0[..., :, None] * gin[:, 0] * e0[..., None, :]
|
| 1486 |
+
dh0 = dh0.to(h0.dtype)
|
| 1487 |
+
return dq, dk, dgk, dcoeff_part, dh0
|
| 1488 |
+
|
| 1489 |
+
|
| 1490 |
+
class q_kkt_solve_trace_triton_safe(torch.autograd.Function):
|
| 1491 |
+
"""x, H_T = phi(q, k, gk) with F = tr(H) and per-dimension decay.
|
| 1492 |
+
|
| 1493 |
+
apply(k, q, gk, chunk_size, coeff, h0) -> (x [B, T, H, D], H_T [B, H, D, D])
|
| 1494 |
+
coeff is [N] or [H, N], N = 3 or 4. chunk_size must be 16, 32, or 64.
|
| 1495 |
+
gk is non-positive; the block references rely on that.
|
| 1496 |
+
"""
|
| 1497 |
+
|
| 1498 |
+
@staticmethod
|
| 1499 |
+
def forward(ctx, k, q, gk=None, chunk_size: int = 64, coeff=(1.0, -0.5, 0.375), h0=None):
|
| 1500 |
+
if q.ndim != 4:
|
| 1501 |
+
raise ValueError(f"q must be [B, T, H, D], got {tuple(q.shape)}")
|
| 1502 |
+
if chunk_size not in (16, 32, 64):
|
| 1503 |
+
raise ValueError(f"chunk_size must be 16, 32, or 64, got {chunk_size}")
|
| 1504 |
+
k = k.contiguous()
|
| 1505 |
+
q = q.contiguous()
|
| 1506 |
+
B, T, H, D = q.shape
|
| 1507 |
+
coeff_is_tensor = torch.is_tensor(coeff)
|
| 1508 |
+
coeff_shape = tuple(coeff.shape) if coeff_is_tensor else None
|
| 1509 |
+
coeff_dtype = coeff.dtype if coeff_is_tensor else None
|
| 1510 |
+
coeff_h = _normalize_coeff(coeff, H, q.device)
|
| 1511 |
+
n_coeff = coeff_h.shape[-1]
|
| 1512 |
+
|
| 1513 |
+
if gk is None:
|
| 1514 |
+
gam = torch.zeros(B, T, H, D, device=q.device, dtype=torch.float32)
|
| 1515 |
+
gk_arg = gv_arg = None
|
| 1516 |
+
else:
|
| 1517 |
+
gk = gk.contiguous()
|
| 1518 |
+
gam = chunk_local_cumsum(gk, chunk_size=chunk_size, scale=0.5, output_dtype=torch.float32)
|
| 1519 |
+
gk_arg = gv_arg = gam
|
| 1520 |
+
h, ht = chunk_fwd_h(
|
| 1521 |
+
k=k, v=k, gk=gk_arg, gv=gv_arg, h0=h0,
|
| 1522 |
+
output_final_state=True, chunk_size=chunk_size, states_in_fp32=True,
|
| 1523 |
+
)
|
| 1524 |
+
f32 = dict(device=q.device, dtype=torch.float32)
|
| 1525 |
+
x = torch.empty_like(q)
|
| 1526 |
+
o1 = torch.empty(B, T, H, D, **f32)
|
| 1527 |
+
o2 = torch.empty(B, T, H, D, **f32)
|
| 1528 |
+
o3 = torch.empty(B, T, H, D, **f32) if n_coeff == 4 else o2
|
| 1529 |
+
F = torch.empty(B, T, H, **f32)
|
| 1530 |
+
bd = _choose_intra_d(D)
|
| 1531 |
+
nc = triton.cdiv(T, chunk_size)
|
| 1532 |
+
nC = chunk_size // BLOCK_C
|
| 1533 |
+
trace_F_kernel[(nc, B * H)](
|
| 1534 |
+
h, k, gam, F, T, H, D, chunk_size, bd, EPS, num_warps=4, num_stages=1,
|
| 1535 |
+
)
|
| 1536 |
+
srcs = [q, o1, o2]
|
| 1537 |
+
dsts = [o1, o2, o3]
|
| 1538 |
+
s_fwd = [
|
| 1539 |
+
torch.empty(B, nc, H, nC, nC, BLOCK_C, BLOCK_C, **f32)
|
| 1540 |
+
for _ in range(1, n_coeff)
|
| 1541 |
+
]
|
| 1542 |
+
for m in range(1, n_coeff):
|
| 1543 |
+
trace_intra_qb_kernel[(nc, nC, B * H)](
|
| 1544 |
+
srcs[m - 1], k, gam, dsts[m - 1], s_fwd[m - 1],
|
| 1545 |
+
T, H, D, chunk_size, bd, BLOCK_C, SHIFT, DOT_PRECISION, True,
|
| 1546 |
+
num_warps=4, num_stages=1,
|
| 1547 |
+
)
|
| 1548 |
+
trace_combine_kernel[(nc, D // bd, B * H)](
|
| 1549 |
+
h, srcs[m - 1], gam, dsts[m - 1], F,
|
| 1550 |
+
T, H, D, chunk_size, bd, DOT_PRECISION,
|
| 1551 |
+
num_warps=8, num_stages=1,
|
| 1552 |
+
)
|
| 1553 |
+
trace_mix_kernel[(nc, B * H)](
|
| 1554 |
+
q, o1, o2, o3, x, coeff_h, T, H, D, chunk_size, bd, n_coeff,
|
| 1555 |
+
num_warps=4, num_stages=1,
|
| 1556 |
+
)
|
| 1557 |
+
|
| 1558 |
+
saved = [k, q, o1, o2, F, coeff_h, h, gam, *s_fwd]
|
| 1559 |
+
if n_coeff == 4:
|
| 1560 |
+
saved.append(o3)
|
| 1561 |
+
if gk is not None:
|
| 1562 |
+
saved.append(gk)
|
| 1563 |
+
if h0 is not None:
|
| 1564 |
+
saved.append(h0)
|
| 1565 |
+
ctx.save_for_backward(*saved)
|
| 1566 |
+
ctx.chunk_size = chunk_size
|
| 1567 |
+
ctx.n_coeff = n_coeff
|
| 1568 |
+
ctx.n_s = n_coeff - 1
|
| 1569 |
+
ctx.has_gk = gk is not None
|
| 1570 |
+
ctx.has_h0 = h0 is not None
|
| 1571 |
+
ctx.coeff_is_tensor = coeff_is_tensor
|
| 1572 |
+
ctx.coeff_shape = coeff_shape
|
| 1573 |
+
ctx.coeff_dtype = coeff_dtype
|
| 1574 |
+
return x, ht
|
| 1575 |
+
|
| 1576 |
+
@staticmethod
|
| 1577 |
+
def backward(ctx, dx, dht=None):
|
| 1578 |
+
saved = list(ctx.saved_tensors)
|
| 1579 |
+
k, q, o1, o2, F, coeff_h, h, gam = saved[:8]
|
| 1580 |
+
idx = 8
|
| 1581 |
+
s_fwd = saved[idx:idx + ctx.n_s]
|
| 1582 |
+
idx += ctx.n_s
|
| 1583 |
+
o3 = saved[idx] if ctx.n_coeff == 4 else None
|
| 1584 |
+
idx += int(ctx.n_coeff == 4)
|
| 1585 |
+
gk = saved[idx] if ctx.has_gk else None
|
| 1586 |
+
idx += int(ctx.has_gk)
|
| 1587 |
+
h0 = saved[idx] if ctx.has_h0 else None
|
| 1588 |
+
os_ = [o1, o2] + ([o3] if o3 is not None else [])
|
| 1589 |
+
dq, dk, dgk, dcoeff_part, dh0 = _bwd(
|
| 1590 |
+
k, q, os_, dx.contiguous(), F, coeff_h, gam, h,
|
| 1591 |
+
None if dht is None else dht.contiguous(), h0, ctx.chunk_size, ctx.n_coeff, s_fwd,
|
| 1592 |
+
)
|
| 1593 |
+
dcoeff = None
|
| 1594 |
+
if ctx.coeff_is_tensor and ctx.needs_input_grad[4]:
|
| 1595 |
+
dcoeff_h = dcoeff_part.sum(dim=(0, 1))
|
| 1596 |
+
if len(ctx.coeff_shape) == 1:
|
| 1597 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Segmented (numerically stable) Triton chunk implementation of trace-normalized phi-KKT.
|
| 2 |
+
|
| 3 |
+
A 64-token chunk is four blocks of 16, the same split KDA uses. Off-diagonal
|
| 4 |
+
blocks are dense tensor-core dots. The reference gate is the first token of
|
| 5 |
+
the later block, so both ``exp(g_q - g_ref)`` and ``exp(g_ref - g_k)`` stay
|
| 6 |
+
<= 1 for non-positive gates. The diagonal 16x16 is one tril-masked dot; that
|
| 7 |
+
dot uses tf32 when the preset is bf16, because ``exp(g_ref - g_k)`` can exceed
|
| 8 |
+
1 inside the block. Relative exponents replace ``exp(Gam) * exp(-Gam)``.
|
| 9 |
+
The 1-D trace uses ``d_t = exp(gk_t) d_{t-1} + k_t^2``.
|
| 10 |
+
|
| 11 |
+
Same recurrence as ``q_kkt_solve_trace.py``:
|
| 12 |
+
|
| 13 |
+
H_t = Diag(exp(gk_t / 2)) H_{t-1} Diag(exp(gk_t / 2)) + k_t k_t^T
|
| 14 |
+
x_t = sum_m coeff[m] * q_t (H_t / tr H_t)^m
|
| 15 |
+
|
| 16 |
+
The 16x16 scores are written to a workspace. Apply then runs one program per
|
| 17 |
+
16-row block: off-diagonal tiles are bf16 K=16 dots, the diagonal 16 stays tf32.
|
| 18 |
+
|
| 19 |
+
Kernels:
|
| 20 |
+
|
| 21 |
+
chunk_fwd_h states before each chunk (gk = gv = half-cumsum)
|
| 22 |
+
trace_fwd_f_kernel tr(H)
|
| 23 |
+
trace_score_kernel 16x16 blocks of tril(v k^T) into workspace S
|
| 24 |
+
trace_apply_p_d_kernel chunk 64: one M=64 H gemm per D tile, then 16-row intra
|
| 25 |
+
trace_apply_p_block_kernel one query block of o = (v H + S k) / F, chunk 16 or 32
|
| 26 |
+
trace_apply_z_block_kernel one key block of Z = S^T y into dk
|
| 27 |
+
trace_bwd_mid_kernel dq, u, alpha, dcoeff, lin
|
| 28 |
+
trace_bwd_diagh_kernel in-chunk diag(H), 16 rows at a time
|
| 29 |
+
trace_bwd_rev_kernel reverse trace into dk / dgk
|
| 30 |
+
trace_bwd_gpartial_kernel g_partial from 16-row dots
|
| 31 |
+
trace_bwd_scan_kernel gin[c-1] = g_partial[c] + Diag(E_C) gin[c] Diag(E_C)
|
| 32 |
+
trace_bwd_gin_kernel S_in contribution from later chunks
|
| 33 |
+
|
| 34 |
+
Backward identities (X_m = o_{m-1} E,
|
| 35 |
+
Y_m = u_m E, u_m = do_m / F, B_j = tril((p_j E) k'^T)):
|
| 36 |
+
|
| 37 |
+
X_m H_in + tril(X_m k'^T) k' = o_m F / E
|
| 38 |
+
Y_m H_in + tril(Y_m k'^T) k' = w_m / E, w_m = sum_j coeff[m+j] p_{j+1}
|
| 39 |
+
|
| 40 |
+
so the low-rank dgk terms (H_in part plus in-chunk corner sums) collapse to
|
| 41 |
+
|
| 42 |
+
suffix( sum_m (o_{m-1} * w_m + do_m * o_m) - k' * Z ),
|
| 43 |
+
Z = sum_m tril(Y_m k'^T)^T X_m + tril(X_m k'^T)^T Y_m,
|
| 44 |
+
|
| 45 |
+
and Z is the low-rank part of dk. tril(Y_m k'^T) is a combination of the B_j
|
| 46 |
+
already formed while applying H to dx:
|
| 47 |
+
|
| 48 |
+
sum_m tril(Y_m k'^T)^T X_m = sum_j B_j^T Xt_j,
|
| 49 |
+
Xt_j = (E / F) sum_{m=1}^{N-1-j} coeff[m+j] o_{m-1}.
|
| 50 |
+
"""
|
| 51 |
+
import os
|
| 52 |
+
from typing import Optional, Sequence, Tuple, Union
|
| 53 |
+
|
| 54 |
+
import torch
|
| 55 |
+
import triton
|
| 56 |
+
import triton.language as tl
|
| 57 |
+
|
| 58 |
+
from fla.ops.common.chunk_h import chunk_fwd_h
|
| 59 |
+
from fla.ops.utils import chunk_local_cumsum
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
EPS = 1e-12
|
| 63 |
+
# Matmul operand precision; gate math (exp, cumsums) is always fp32.
|
| 64 |
+
# bf16 operands cast to bf16, fp32 accumulate (fastest; dk ~3e-3, dgk ~9e-3 rel. error)
|
| 65 |
+
# tf32 fp32 operands on TF32 tensor cores (dk / dgk ~1.5e-3)
|
| 66 |
+
# tf32x3 hand-written 3xTF32 (dk / dgk ~1e-4, bounded by chunk_fwd_h), ~2x slower than tf32
|
| 67 |
+
# The tf32 / tf32x3 values are bit masks over the ``_dot`` call sites (set bit = 3xTF32).
|
| 68 |
+
_PREC_MASKS = {"tf32": 0, "tf32x3": 0x7F, "bf16": 0x100}
|
| 69 |
+
DOT_PRECISION = _PREC_MASKS[os.environ.get("TRACE_KKT_DOT_PRECISION", "bf16")]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _choose_block_d(D: int) -> int:
|
| 73 |
+
if D % 64 == 0:
|
| 74 |
+
return 64
|
| 75 |
+
if D % 32 == 0:
|
| 76 |
+
return 32
|
| 77 |
+
if D % 16 == 0:
|
| 78 |
+
return 16
|
| 79 |
+
raise ValueError(f"head dim D={D} must be divisible by 16, 32, or 64")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _choose_scan_block(D: int) -> int:
|
| 83 |
+
"""Tile of the cross-chunk gin scan. 8x8 under-fills the memory path."""
|
| 84 |
+
if D % 32 == 0:
|
| 85 |
+
return 32
|
| 86 |
+
if D % 16 == 0:
|
| 87 |
+
return 16
|
| 88 |
+
return D
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _choose_block_c(chunk_size: int) -> int:
|
| 92 |
+
"""16-token sub-blocks. chunk 16/32/64 -> 1/2/4 blocks, matching KDA."""
|
| 93 |
+
if chunk_size not in (16, 32, 64):
|
| 94 |
+
raise ValueError(f"chunk_size must be 16, 32, or 64, got {chunk_size}")
|
| 95 |
+
return 16
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _normalize_coeff(coeff, H: int, device, dtype=torch.float32) -> torch.Tensor:
|
| 99 |
+
if torch.is_tensor(coeff):
|
| 100 |
+
t = coeff.detach().to(device=device, dtype=dtype)
|
| 101 |
+
else:
|
| 102 |
+
t = torch.tensor(list(coeff), device=device, dtype=dtype)
|
| 103 |
+
if t.dim() == 1:
|
| 104 |
+
t = t.reshape(1, -1).expand(H, -1).contiguous()
|
| 105 |
+
elif t.shape[0] != H:
|
| 106 |
+
raise ValueError(f"coeff must be [N] or [H, N] with H={H}, got {tuple(t.shape)}")
|
| 107 |
+
else:
|
| 108 |
+
t = t.contiguous()
|
| 109 |
+
if t.shape[-1] not in (3, 4):
|
| 110 |
+
raise ValueError(f"coeff last dim must be 3 or 4, got {t.shape[-1]}")
|
| 111 |
+
return t
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ---------------------------------------------------------------------------
|
| 115 |
+
# Loads / stores. Layout [B, T, H, D], pointer already at one (b, h).
|
| 116 |
+
# ---------------------------------------------------------------------------
|
| 117 |
+
@triton.jit
|
| 118 |
+
def _load_vec(ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D: tl.constexpr):
|
| 119 |
+
p = tl.make_block_ptr(
|
| 120 |
+
ptr, (T, D), (H * D, 1),
|
| 121 |
+
(chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0),
|
| 122 |
+
)
|
| 123 |
+
x = tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 124 |
+
return tl.where(m_t[:, None], x, 0.0)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@triton.jit
|
| 128 |
+
def _store_vec(ptr, val, T, H, D, chunk_id, chunk_size, d0, BLOCK_D: tl.constexpr):
|
| 129 |
+
p = tl.make_block_ptr(
|
| 130 |
+
ptr, (T, D), (H * D, 1),
|
| 131 |
+
(chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0),
|
| 132 |
+
)
|
| 133 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@triton.jit
|
| 137 |
+
def _load_mat(ptr, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 138 |
+
p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0))
|
| 139 |
+
return tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@triton.jit
|
| 143 |
+
def _store_mat(ptr, val, D, r0, c0, BLOCK_D: tl.constexpr):
|
| 144 |
+
p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0))
|
| 145 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@triton.jit
|
| 149 |
+
def _load_row(ptr, T, H, chunk_id, chunk_size, m_t, other):
|
| 150 |
+
p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,))
|
| 151 |
+
return tl.where(m_t, tl.load(p, boundary_check=(0,)).to(tl.float32), other)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@triton.jit
|
| 155 |
+
def _store_row(ptr, val, T, H, chunk_id, chunk_size):
|
| 156 |
+
p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,))
|
| 157 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0,))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@triton.jit
|
| 161 |
+
def _masks(chunk_id, chunk_size, T):
|
| 162 |
+
o_t = chunk_id * chunk_size + tl.arange(0, chunk_size)
|
| 163 |
+
m_t = o_t < T
|
| 164 |
+
tril = (o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :])
|
| 165 |
+
return m_t, tril
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@triton.jit
|
| 169 |
+
def _suffix(x):
|
| 170 |
+
"""Inclusive suffix sum over the chunk axis. x: [C, BD].
|
| 171 |
+
|
| 172 |
+
Not total - cumsum + x: the tail entries are tiny next to the head (alpha E^2
|
| 173 |
+
decays) and that difference leaves O(eps * head) behind, later scaled by E^{-2}.
|
| 174 |
+
"""
|
| 175 |
+
return tl.cumsum(x, axis=0, reverse=True)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@triton.jit
|
| 179 |
+
def _excl(x):
|
| 180 |
+
"""Exclusive prefix sum over the chunk axis."""
|
| 181 |
+
return tl.cumsum(x, axis=0) - x
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@triton.jit
|
| 185 |
+
def _diag_of(tile, BLOCK_D: tl.constexpr):
|
| 186 |
+
ar = tl.arange(0, BLOCK_D)
|
| 187 |
+
return tl.sum(tl.where(ar[:, None] == ar[None, :], tile, 0.0), axis=1)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@triton.jit
|
| 191 |
+
def _split_tf32(x):
|
| 192 |
+
hi = (x.to(tl.uint32, bitcast=True) & 0xFFFFE000).to(tl.float32, bitcast=True)
|
| 193 |
+
return hi, x - hi
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@triton.jit
|
| 197 |
+
def _dot(a, b, PREC: tl.constexpr, SITE: tl.constexpr):
|
| 198 |
+
"""a @ b with fp32 accumulation. PREC == 0x100 is bf16 operands; otherwise bit
|
| 199 |
+
SITE of PREC selects 3xTF32 (spelled out by hand: Triton's built-in "tf32x3"
|
| 200 |
+
lowering spills heavily) over plain TF32."""
|
| 201 |
+
if PREC == 0x100:
|
| 202 |
+
return tl.dot(a.to(tl.bfloat16), b.to(tl.bfloat16))
|
| 203 |
+
elif (PREC >> SITE) & 1:
|
| 204 |
+
a_hi, a_lo = _split_tf32(a)
|
| 205 |
+
b_hi, b_lo = _split_tf32(b)
|
| 206 |
+
acc = tl.dot(a_lo, b_hi, input_precision="tf32")
|
| 207 |
+
acc = tl.dot(a_hi, b_lo, acc, input_precision="tf32")
|
| 208 |
+
return tl.dot(a_hi, b_hi, acc, input_precision="tf32")
|
| 209 |
+
else:
|
| 210 |
+
return tl.dot(a, b, input_precision="tf32")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# ---------------------------------------------------------------------------
|
| 214 |
+
# 16-token sub-blocks. A 64-token chunk is 4 x 16, the same split KDA uses.
|
| 215 |
+
# Off-diagonal block (query block strictly after the key block), reference =
|
| 216 |
+
# first token of the query block:
|
| 217 |
+
# exp(g_t - g_i) = exp(g_t - g_ref) * exp(g_ref - g_i)
|
| 218 |
+
# both factors are <= 1 when gates are non-positive. The diagonal 16x16 block
|
| 219 |
+
# is one tril-masked dot; exp(g_ref - g_i) can exceed 1 there, so that dot is
|
| 220 |
+
# tf32 when the user preset is bf16.
|
| 221 |
+
# ---------------------------------------------------------------------------
|
| 222 |
+
@triton.jit
|
| 223 |
+
def _row0(x, BLOCK_C: tl.constexpr):
|
| 224 |
+
return tl.sum(tl.where(tl.arange(0, BLOCK_C)[:, None] == 0, x, 0.0), axis=0)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@triton.jit
|
| 228 |
+
def _load_bc(ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid,
|
| 229 |
+
BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr):
|
| 230 |
+
o = s0 + tl.arange(0, BLOCK_C)
|
| 231 |
+
p = tl.make_block_ptr(
|
| 232 |
+
ptr, (T, D), (H * D, 1),
|
| 233 |
+
(chunk_id * chunk_size + s0, d0), (BLOCK_C, BLOCK_D), (1, 0),
|
| 234 |
+
)
|
| 235 |
+
x = tl.load(p, boundary_check=(0, 1)).to(tl.float32)
|
| 236 |
+
return tl.where((o < n_valid)[:, None], x, 0.0)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@triton.jit
|
| 240 |
+
def _store_bc(ptr, val, T, H, D, chunk_id, chunk_size, s0, d0,
|
| 241 |
+
BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr):
|
| 242 |
+
p = tl.make_block_ptr(
|
| 243 |
+
ptr, (T, D), (H * D, 1),
|
| 244 |
+
(chunk_id * chunk_size + s0, d0), (BLOCK_C, BLOCK_D), (1, 0),
|
| 245 |
+
)
|
| 246 |
+
tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@triton.jit
|
| 250 |
+
def _f_bc(F, s0, chunk_size: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 251 |
+
idx = tl.arange(0, chunk_size)
|
| 252 |
+
loc = s0 + tl.arange(0, BLOCK_C)
|
| 253 |
+
return tl.sum(tl.where(idx[None, :] == loc[:, None], F[None, :], 0.0), axis=1)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@triton.jit
|
| 257 |
+
def _dot_diag(a, b, PREC: tl.constexpr, SITE: tl.constexpr):
|
| 258 |
+
"""Diagonal-block dot. One factor can exceed 1, so bf16 mode uses tf32."""
|
| 259 |
+
if PREC == 0x100:
|
| 260 |
+
return tl.dot(a, b, input_precision="tf32")
|
| 261 |
+
else:
|
| 262 |
+
return _dot(a, b, PREC, SITE)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@triton.jit
|
| 266 |
+
def _diag_scores(v, g, k, s0, n_valid, PREC: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 267 |
+
g_ref = _row0(g, BLOCK_C)
|
| 268 |
+
valid = (s0 + tl.arange(0, BLOCK_C)) < n_valid
|
| 269 |
+
g_s = tl.where(valid[:, None], g, g_ref[None, :])
|
| 270 |
+
v_s = tl.where(valid[:, None], v * tl.exp(g_s - g_ref[None, :]), 0.0)
|
| 271 |
+
k_s = tl.where(valid[:, None], k * tl.exp(g_ref[None, :] - g_s), 0.0)
|
| 272 |
+
score = _dot_diag(v_s, tl.trans(k_s), PREC, 0)
|
| 273 |
+
tri = tl.arange(0, BLOCK_C)[:, None] >= tl.arange(0, BLOCK_C)[None, :]
|
| 274 |
+
return tl.where(tri, score, 0.0)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@triton.jit
|
| 278 |
+
def _off_scores(v_q, g_q, k_k, g_k, s0_q, s0_k, n_valid,
|
| 279 |
+
PREC: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 280 |
+
g_ref = _row0(g_q, BLOCK_C)
|
| 281 |
+
valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid
|
| 282 |
+
valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid
|
| 283 |
+
g_q_s = tl.where(valid_q[:, None], g_q, g_ref[None, :])
|
| 284 |
+
g_k_s = tl.where(valid_k[:, None], g_k, g_ref[None, :])
|
| 285 |
+
v_s = tl.where(valid_q[:, None], v_q * tl.exp(g_q_s - g_ref[None, :]), 0.0)
|
| 286 |
+
k_s = tl.where(valid_k[:, None], k_k * tl.exp(g_ref[None, :] - g_k_s), 0.0)
|
| 287 |
+
return _dot(v_s, tl.trans(k_s), PREC, 0)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@triton.jit
|
| 291 |
+
def _scores_blocks(
|
| 292 |
+
v_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, n_valid,
|
| 293 |
+
BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, BLOCK_C: tl.constexpr,
|
| 294 |
+
NUM_C: tl.constexpr, PREC: tl.constexpr,
|
| 295 |
+
):
|
| 296 |
+
S00 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 297 |
+
S10 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 298 |
+
S11 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 299 |
+
S20 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 300 |
+
S21 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 301 |
+
S22 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 302 |
+
S30 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 303 |
+
S31 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 304 |
+
S32 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 305 |
+
S33 = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 306 |
+
for di in tl.static_range(NUM_D):
|
| 307 |
+
d0 = di * BLOCK_D
|
| 308 |
+
k0 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, 0, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 309 |
+
g0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, 0, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 310 |
+
v0 = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, 0, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 311 |
+
S00 += _diag_scores(v0, g0, k0, 0, n_valid, PREC, BLOCK_C)
|
| 312 |
+
if NUM_C > 1:
|
| 313 |
+
if BLOCK_C < n_valid:
|
| 314 |
+
k1 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 315 |
+
g1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 316 |
+
v1 = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 317 |
+
S11 += _diag_scores(v1, g1, k1, BLOCK_C, n_valid, PREC, BLOCK_C)
|
| 318 |
+
S10 += _off_scores(v1, g1, k0, g0, BLOCK_C, 0, n_valid, PREC, BLOCK_C)
|
| 319 |
+
if NUM_C > 2:
|
| 320 |
+
if 2 * BLOCK_C < n_valid:
|
| 321 |
+
k2 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, 2 * BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 322 |
+
g2 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, 2 * BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 323 |
+
v2 = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, 2 * BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 324 |
+
S22 += _diag_scores(v2, g2, k2, 2 * BLOCK_C, n_valid, PREC, BLOCK_C)
|
| 325 |
+
S20 += _off_scores(v2, g2, k0, g0, 2 * BLOCK_C, 0, n_valid, PREC, BLOCK_C)
|
| 326 |
+
S21 += _off_scores(v2, g2, k1, g1, 2 * BLOCK_C, BLOCK_C, n_valid, PREC, BLOCK_C)
|
| 327 |
+
if 3 * BLOCK_C < n_valid:
|
| 328 |
+
k3 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, 3 * BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 329 |
+
g3 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, 3 * BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 330 |
+
v3 = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, 3 * BLOCK_C, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 331 |
+
S33 += _diag_scores(v3, g3, k3, 3 * BLOCK_C, n_valid, PREC, BLOCK_C)
|
| 332 |
+
S30 += _off_scores(v3, g3, k0, g0, 3 * BLOCK_C, 0, n_valid, PREC, BLOCK_C)
|
| 333 |
+
S31 += _off_scores(v3, g3, k1, g1, 3 * BLOCK_C, BLOCK_C, n_valid, PREC, BLOCK_C)
|
| 334 |
+
S32 += _off_scores(v3, g3, k2, g2, 3 * BLOCK_C, 2 * BLOCK_C, n_valid, PREC, BLOCK_C)
|
| 335 |
+
return S00, S10, S11, S20, S21, S22, S30, S31, S32, S33
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
@triton.jit
|
| 339 |
+
def _store_tile(ptr, blk, r0, c0, chunk_size: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 340 |
+
p = tl.make_block_ptr(
|
| 341 |
+
ptr, (chunk_size, chunk_size), (chunk_size, 1),
|
| 342 |
+
(r0, c0), (BLOCK_C, BLOCK_C), (1, 0),
|
| 343 |
+
)
|
| 344 |
+
tl.store(p, blk.to(tl.float32), boundary_check=(0, 1))
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@triton.jit
|
| 348 |
+
def _dump_S(
|
| 349 |
+
ptr, S00, S10, S11, S20, S21, S22, S30, S31, S32, S33,
|
| 350 |
+
chunk_size: tl.constexpr, BLOCK_C: tl.constexpr, NUM_C: tl.constexpr,
|
| 351 |
+
):
|
| 352 |
+
z = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32)
|
| 353 |
+
_store_tile(ptr, S00, 0, 0, chunk_size, BLOCK_C)
|
| 354 |
+
if NUM_C > 1:
|
| 355 |
+
_store_tile(ptr, z, 0, BLOCK_C, chunk_size, BLOCK_C)
|
| 356 |
+
_store_tile(ptr, S10, BLOCK_C, 0, chunk_size, BLOCK_C)
|
| 357 |
+
_store_tile(ptr, S11, BLOCK_C, BLOCK_C, chunk_size, BLOCK_C)
|
| 358 |
+
if NUM_C > 2:
|
| 359 |
+
_store_tile(ptr, z, 0, 2 * BLOCK_C, chunk_size, BLOCK_C)
|
| 360 |
+
_store_tile(ptr, z, 0, 3 * BLOCK_C, chunk_size, BLOCK_C)
|
| 361 |
+
_store_tile(ptr, z, BLOCK_C, 2 * BLOCK_C, chunk_size, BLOCK_C)
|
| 362 |
+
_store_tile(ptr, z, BLOCK_C, 3 * BLOCK_C, chunk_size, BLOCK_C)
|
| 363 |
+
_store_tile(ptr, z, 2 * BLOCK_C, 3 * BLOCK_C, chunk_size, BLOCK_C)
|
| 364 |
+
_store_tile(ptr, S20, 2 * BLOCK_C, 0, chunk_size, BLOCK_C)
|
| 365 |
+
_store_tile(ptr, S21, 2 * BLOCK_C, BLOCK_C, chunk_size, BLOCK_C)
|
| 366 |
+
_store_tile(ptr, S22, 2 * BLOCK_C, 2 * BLOCK_C, chunk_size, BLOCK_C)
|
| 367 |
+
_store_tile(ptr, S30, 3 * BLOCK_C, 0, chunk_size, BLOCK_C)
|
| 368 |
+
_store_tile(ptr, S31, 3 * BLOCK_C, BLOCK_C, chunk_size, BLOCK_C)
|
| 369 |
+
_store_tile(ptr, S32, 3 * BLOCK_C, 2 * BLOCK_C, chunk_size, BLOCK_C)
|
| 370 |
+
_store_tile(ptr, S33, 3 * BLOCK_C, 3 * BLOCK_C, chunk_size, BLOCK_C)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
@triton.jit
|
| 374 |
+
def _load_gref(gam_ptr, chunk_id, chunk_size, s0, H, D, d0, BLOCK_D: tl.constexpr):
|
| 375 |
+
off = (chunk_id * chunk_size + s0) * (H * D) + d0
|
| 376 |
+
return tl.load(gam_ptr + off + tl.arange(0, BLOCK_D)).to(tl.float32)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
@triton.jit
|
| 380 |
+
def _row_at(x, t, chunk_size: tl.constexpr, BLOCK_D: tl.constexpr):
|
| 381 |
+
idx = tl.arange(0, chunk_size)
|
| 382 |
+
return tl.sum(tl.where(idx[:, None] == t, x, 0.0), axis=0)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
@triton.jit
|
| 386 |
+
def _fwd_block(
|
| 387 |
+
k, gam, s_carry, g_carry, s0, n_valid,
|
| 388 |
+
chunk_size: tl.constexpr, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr,
|
| 389 |
+
):
|
| 390 |
+
"""One 16-row trace block. Scales stay relative to the block's first gate."""
|
| 391 |
+
idx = tl.arange(0, chunk_size)
|
| 392 |
+
g_ref = _row_at(gam, s0, chunk_size, BLOCK_D)
|
| 393 |
+
in_block = (idx >= s0) & (idx < s0 + BLOCK_C) & (idx < n_valid)
|
| 394 |
+
g_s = tl.where(in_block[:, None], gam, g_ref[None, :])
|
| 395 |
+
rel = tl.exp(2.0 * (g_ref[None, :] - g_s))
|
| 396 |
+
term = tl.where(in_block[:, None], (k * k) * rel, 0.0)
|
| 397 |
+
u_start = tl.exp(2.0 * (g_ref - g_carry)) * s_carry
|
| 398 |
+
s_here = (tl.cumsum(term, axis=0) + u_start[None, :]) * tl.exp(2.0 * (g_s - g_ref[None, :]))
|
| 399 |
+
s_here = tl.where(in_block[:, None], s_here, 0.0)
|
| 400 |
+
last = tl.where(s0 + BLOCK_C <= n_valid, s0 + BLOCK_C - 1, n_valid - 1)
|
| 401 |
+
return s_here, _row_at(s_here, last, chunk_size, BLOCK_D), _row_at(gam, last, chunk_size, BLOCK_D)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
@triton.jit
|
| 405 |
+
def _diag_scan(k, gam, diag_in, n_valid, chunk_size: tl.constexpr, BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 406 |
+
"""diag(H_t) = exp(gk_t) diag(H_{t-1}) + k_t^2, one cumsum per 16-row block."""
|
| 407 |
+
s_carry = diag_in
|
| 408 |
+
g_carry = tl.zeros([BLOCK_D], dtype=tl.float32)
|
| 409 |
+
out = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 410 |
+
for bi in tl.static_range(4):
|
| 411 |
+
if bi < chunk_size // BLOCK_C:
|
| 412 |
+
if bi * BLOCK_C < n_valid:
|
| 413 |
+
blk, s_carry, g_carry = _fwd_block(
|
| 414 |
+
k, gam, s_carry, g_carry, bi * BLOCK_C, n_valid, chunk_size, BLOCK_C, BLOCK_D,
|
| 415 |
+
)
|
| 416 |
+
out += blk
|
| 417 |
+
return out
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
@triton.jit
|
| 421 |
+
def _rev_block(
|
| 422 |
+
alpha, gam, R_after, g_after, started, s0, n_valid,
|
| 423 |
+
chunk_size: tl.constexpr, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr,
|
| 424 |
+
):
|
| 425 |
+
"""Reverse trace block. started=0 means this is the last alive block."""
|
| 426 |
+
idx = tl.arange(0, chunk_size)
|
| 427 |
+
g_ref = _row_at(gam, s0, chunk_size, BLOCK_D)
|
| 428 |
+
in_block = (idx >= s0) & (idx < s0 + BLOCK_C) & (idx < n_valid)
|
| 429 |
+
g_s = tl.where(in_block[:, None], gam, g_ref[None, :])
|
| 430 |
+
use = tl.sum(started) > 0.5
|
| 431 |
+
g_after_s = tl.where(use, g_after, g_ref)
|
| 432 |
+
carry = tl.where(use, R_after * tl.exp(2.0 * (g_after_s - g_ref)), 0.0)
|
| 433 |
+
w = tl.where(in_block[:, None], alpha[:, None] * tl.exp(2.0 * (g_s - g_ref[None, :])), 0.0)
|
| 434 |
+
R = (tl.cumsum(w, axis=0, reverse=True) + carry[None, :]) * tl.exp(2.0 * (g_ref[None, :] - g_s))
|
| 435 |
+
R = tl.where(in_block[:, None], R, 0.0)
|
| 436 |
+
R0 = _row_at(R, s0, chunk_size, BLOCK_D)
|
| 437 |
+
return R, R0, g_ref, started * 0.0 + 1.0
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@triton.jit
|
| 441 |
+
def _rev_R(alpha, gam, n_valid, chunk_size: tl.constexpr, BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr):
|
| 442 |
+
"""R_t[d] = sum_{s>=t} alpha_s exp(2 (Gam_s[d] - Gam_t[d])). [C, BD]."""
|
| 443 |
+
R_after = tl.zeros([BLOCK_D], dtype=tl.float32)
|
| 444 |
+
g_after = tl.zeros([BLOCK_D], dtype=tl.float32)
|
| 445 |
+
started = tl.zeros([1], dtype=tl.float32)
|
| 446 |
+
out = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 447 |
+
for bi in tl.static_range(4):
|
| 448 |
+
bj = 3 - bi
|
| 449 |
+
if bj < chunk_size // BLOCK_C:
|
| 450 |
+
if bj * BLOCK_C < n_valid:
|
| 451 |
+
blk, R_after, g_after, started = _rev_block(
|
| 452 |
+
alpha, gam, R_after, g_after, started, bj * BLOCK_C, n_valid,
|
| 453 |
+
chunk_size, BLOCK_C, BLOCK_D,
|
| 454 |
+
)
|
| 455 |
+
out += blk
|
| 456 |
+
return out
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
@triton.jit
|
| 460 |
+
def _vh_rows(
|
| 461 |
+
v_ptr, h_ptr, gam_ptr, s0, n_valid, chunk_id, T, H, D, d0,
|
| 462 |
+
BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr, NUM_D: tl.constexpr,
|
| 463 |
+
chunk_size: tl.constexpr, PREC: tl.constexpr,
|
| 464 |
+
):
|
| 465 |
+
"""((v * E) @ H_in) for rows s0:s0+BLOCK_C only."""
|
| 466 |
+
acc = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 467 |
+
for j in tl.range(NUM_D):
|
| 468 |
+
d1 = j * BLOCK_D
|
| 469 |
+
gam = _load_bc(
|
| 470 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, s0, d1, n_valid, BLOCK_C, BLOCK_D,
|
| 471 |
+
)
|
| 472 |
+
v = _load_bc(
|
| 473 |
+
v_ptr, T, H, D, chunk_id, chunk_size, s0, d1, n_valid, BLOCK_C, BLOCK_D,
|
| 474 |
+
) * tl.exp(gam)
|
| 475 |
+
h = _load_mat(h_ptr, D, d1, d0, BLOCK_D)
|
| 476 |
+
acc += _dot(v, h, PREC, 1)
|
| 477 |
+
return acc
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
@triton.jit(do_not_specialize=["T"])
|
| 481 |
+
def trace_fwd_f_kernel(
|
| 482 |
+
h_ptr, k_ptr, gam_ptr, f_ptr,
|
| 483 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 484 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, EPS: tl.constexpr,
|
| 485 |
+
):
|
| 486 |
+
chunk_id = tl.program_id(0)
|
| 487 |
+
bh = tl.program_id(1)
|
| 488 |
+
b_id, h_id = bh // H, bh % H
|
| 489 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 490 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 491 |
+
m_t, _ = _masks(chunk_id, chunk_size, T)
|
| 492 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 493 |
+
vec_off = (b_id * T * H + h_id) * D
|
| 494 |
+
k_ptr += vec_off
|
| 495 |
+
gam_ptr += vec_off
|
| 496 |
+
f_ptr += b_id * T * H + h_id
|
| 497 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 498 |
+
|
| 499 |
+
F = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 500 |
+
for i in tl.static_range(NUM_D):
|
| 501 |
+
d0 = i * BLOCK_D
|
| 502 |
+
gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 503 |
+
k = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 504 |
+
diag_in = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D)
|
| 505 |
+
F += tl.sum(_diag_scan(k, gam, diag_in, n_valid, chunk_size, BLOCK_D, BLOCK_C), axis=1)
|
| 506 |
+
F = tl.where(m_t, F + EPS, 0.0)
|
| 507 |
+
_store_row(f_ptr, F, T, H, chunk_id, chunk_size)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
@triton.jit(do_not_specialize=["T"])
|
| 511 |
+
def trace_score_kernel(
|
| 512 |
+
src_ptr, k_ptr, gam_ptr, s_ptr,
|
| 513 |
+
T, BH, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 514 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, PREC: tl.constexpr,
|
| 515 |
+
):
|
| 516 |
+
chunk_id = tl.program_id(0)
|
| 517 |
+
bh = tl.program_id(1)
|
| 518 |
+
b_id, h_id = bh // H, bh % H
|
| 519 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 520 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 521 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 522 |
+
vec = (b_id * T * H + h_id) * D
|
| 523 |
+
src_ptr += vec
|
| 524 |
+
k_ptr += vec
|
| 525 |
+
gam_ptr += vec
|
| 526 |
+
s_ptr += (chunk_id * BH + bh).to(tl.int64) * chunk_size * chunk_size
|
| 527 |
+
S00, S10, S11, S20, S21, S22, S30, S31, S32, S33 = _scores_blocks(
|
| 528 |
+
src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, n_valid,
|
| 529 |
+
BLOCK_D, NUM_D, BLOCK_C, NUM_C, PREC,
|
| 530 |
+
)
|
| 531 |
+
_dump_S(
|
| 532 |
+
s_ptr, S00, S10, S11, S20, S21, S22, S30, S31, S32, S33,
|
| 533 |
+
chunk_size, BLOCK_C, NUM_C,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
@triton.jit(do_not_specialize=["T"])
|
| 538 |
+
def trace_bwd_mid_kernel(
|
| 539 |
+
q_ptr, o1_ptr, o2_ptr, o3_ptr, dx_ptr, f_ptr, coeff_ptr,
|
| 540 |
+
p1_ptr, p2_ptr, p3_ptr, u1_ptr, u2_ptr, u3_ptr,
|
| 541 |
+
dq_ptr, dgk_ptr, alpha_ptr, dcoeff_ptr,
|
| 542 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 543 |
+
BLOCK_D: tl.constexpr, N: tl.constexpr,
|
| 544 |
+
):
|
| 545 |
+
chunk_id = tl.program_id(0)
|
| 546 |
+
bh = tl.program_id(1)
|
| 547 |
+
b_id, h_id = bh // H, bh % H
|
| 548 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 549 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 550 |
+
m_t, _ = _masks(chunk_id, chunk_size, T)
|
| 551 |
+
scalar = b_id * T * H + h_id
|
| 552 |
+
vec = scalar * D
|
| 553 |
+
q_ptr += vec
|
| 554 |
+
o1_ptr += vec
|
| 555 |
+
o2_ptr += vec
|
| 556 |
+
o3_ptr += vec
|
| 557 |
+
dx_ptr += vec
|
| 558 |
+
p1_ptr += vec
|
| 559 |
+
p2_ptr += vec
|
| 560 |
+
p3_ptr += vec
|
| 561 |
+
u1_ptr += vec
|
| 562 |
+
u2_ptr += vec
|
| 563 |
+
u3_ptr += vec
|
| 564 |
+
dq_ptr += vec
|
| 565 |
+
dgk_ptr += vec
|
| 566 |
+
f_ptr += scalar
|
| 567 |
+
alpha_ptr += scalar
|
| 568 |
+
|
| 569 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 570 |
+
c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32)
|
| 571 |
+
c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32)
|
| 572 |
+
c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32)
|
| 573 |
+
c3 = 0.0
|
| 574 |
+
if N > 3:
|
| 575 |
+
c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32)
|
| 576 |
+
|
| 577 |
+
s = tl.zeros((chunk_size,), dtype=tl.float32)
|
| 578 |
+
da = tl.zeros((1,), dtype=tl.float32)
|
| 579 |
+
db = tl.zeros((1,), dtype=tl.float32)
|
| 580 |
+
dc = tl.zeros((1,), dtype=tl.float32)
|
| 581 |
+
dd = tl.zeros((1,), dtype=tl.float32)
|
| 582 |
+
for i in tl.static_range(NUM_D):
|
| 583 |
+
d0 = i * BLOCK_D
|
| 584 |
+
q = _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 585 |
+
o1 = _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 586 |
+
o2 = _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 587 |
+
dx = _load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 588 |
+
p1 = _load_vec(p1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 589 |
+
p2 = _load_vec(p2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 590 |
+
dq = c0 * dx + c1 * p1 + c2 * p2
|
| 591 |
+
do1 = c1 * dx + c2 * p1
|
| 592 |
+
do2 = c2 * dx
|
| 593 |
+
w1 = c1 * p1 + c2 * p2
|
| 594 |
+
w2 = c2 * p1
|
| 595 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2
|
| 596 |
+
if N > 3:
|
| 597 |
+
o3 = _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 598 |
+
p3 = _load_vec(p3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 599 |
+
dq += c3 * p3
|
| 600 |
+
do1 += c3 * p2
|
| 601 |
+
do2 += c3 * p1
|
| 602 |
+
do3 = c3 * dx
|
| 603 |
+
w1 += c3 * p3
|
| 604 |
+
w2 += c3 * p2
|
| 605 |
+
w3 = c3 * p1
|
| 606 |
+
lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + o2 * w3 + do3 * o3
|
| 607 |
+
_store_vec(u3_ptr, do3 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 608 |
+
s += tl.sum(o3 * do3, axis=1)
|
| 609 |
+
dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0)
|
| 610 |
+
_store_vec(dq_ptr, dq, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 611 |
+
_store_vec(u1_ptr, do1 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 612 |
+
_store_vec(u2_ptr, do2 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 613 |
+
_store_vec(dgk_ptr, lin, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 614 |
+
s += tl.sum(o1 * do1, axis=1) + tl.sum(o2 * do2, axis=1)
|
| 615 |
+
da += tl.sum(tl.sum(dx * q, axis=0), axis=0)
|
| 616 |
+
db += tl.sum(tl.sum(dx * o1, axis=0), axis=0)
|
| 617 |
+
dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0)
|
| 618 |
+
alpha = tl.where(m_t, -s / F, 0.0)
|
| 619 |
+
_store_row(alpha_ptr, alpha, T, H, chunk_id, chunk_size)
|
| 620 |
+
base = ((b_id * num_chunks + chunk_id) * H + h_id) * N
|
| 621 |
+
tl.store(dcoeff_ptr + base + 0, tl.sum(da))
|
| 622 |
+
tl.store(dcoeff_ptr + base + 1, tl.sum(db))
|
| 623 |
+
tl.store(dcoeff_ptr + base + 2, tl.sum(dc))
|
| 624 |
+
if N > 3:
|
| 625 |
+
tl.store(dcoeff_ptr + base + 3, tl.sum(dd))
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
@triton.jit
|
| 629 |
+
def _fwd_tile(k, gam, s_carry, g_carry, n_rows, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr):
|
| 630 |
+
"""diag(H) for one 16-row block. Same values as ``_fwd_block`` on those rows."""
|
| 631 |
+
valid = tl.arange(0, BLOCK_C) < n_rows
|
| 632 |
+
g_ref = _row0(gam, BLOCK_C)
|
| 633 |
+
g_s = tl.where(valid[:, None], gam, g_ref[None, :])
|
| 634 |
+
rel = tl.exp(2.0 * (g_ref[None, :] - g_s))
|
| 635 |
+
term = tl.where(valid[:, None], (k * k) * rel, 0.0)
|
| 636 |
+
u_start = tl.exp(2.0 * (g_ref - g_carry)) * s_carry
|
| 637 |
+
s_here = (tl.cumsum(term, axis=0) + u_start[None, :]) * tl.exp(2.0 * (g_s - g_ref[None, :]))
|
| 638 |
+
s_here = tl.where(valid[:, None], s_here, 0.0)
|
| 639 |
+
last = n_rows - 1
|
| 640 |
+
rows = tl.arange(0, BLOCK_C)[:, None]
|
| 641 |
+
s_last = tl.sum(tl.where(rows == last, s_here, 0.0), axis=0)
|
| 642 |
+
g_last = tl.sum(tl.where(rows == last, gam, 0.0), axis=0)
|
| 643 |
+
return s_here, s_last, g_last
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
@triton.jit(do_not_specialize=["T"])
|
| 647 |
+
def trace_bwd_diagh_kernel(
|
| 648 |
+
h_ptr, k_ptr, gam_ptr, diag_ptr,
|
| 649 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 650 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr,
|
| 651 |
+
):
|
| 652 |
+
"""Write diag(H_t) in 16-row tiles. A full [64, 64] scan spills."""
|
| 653 |
+
chunk_id = tl.program_id(0)
|
| 654 |
+
bh = tl.program_id(1)
|
| 655 |
+
b_id, h_id = bh // H, bh % H
|
| 656 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 657 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 658 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 659 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 660 |
+
vec = (b_id * T * H + h_id) * D
|
| 661 |
+
k_ptr += vec
|
| 662 |
+
gam_ptr += vec
|
| 663 |
+
diag_ptr += vec
|
| 664 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 665 |
+
for i in tl.range(NUM_D):
|
| 666 |
+
d0 = i * BLOCK_D
|
| 667 |
+
s_carry = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D)
|
| 668 |
+
g_carry = tl.zeros([BLOCK_D], dtype=tl.float32)
|
| 669 |
+
for bi in tl.range(NUM_C):
|
| 670 |
+
s0 = bi * BLOCK_C
|
| 671 |
+
if s0 < n_valid:
|
| 672 |
+
n_rows = tl.minimum(BLOCK_C, n_valid - s0)
|
| 673 |
+
k = _load_bc(
|
| 674 |
+
k_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 675 |
+
)
|
| 676 |
+
gam = _load_bc(
|
| 677 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 678 |
+
)
|
| 679 |
+
diag, s_carry, g_carry = _fwd_tile(
|
| 680 |
+
k, gam, s_carry, g_carry, n_rows, BLOCK_C, BLOCK_D,
|
| 681 |
+
)
|
| 682 |
+
_store_bc(
|
| 683 |
+
diag_ptr, diag, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D,
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
@triton.jit
|
| 688 |
+
def _rev_tile(alpha, gam, R_after, g_after, started, n_rows, BLOCK_C: tl.constexpr):
|
| 689 |
+
"""R for one 16-row block. Same values as ``_rev_block`` on those rows."""
|
| 690 |
+
valid = tl.arange(0, BLOCK_C) < n_rows
|
| 691 |
+
g_ref = _row0(gam, BLOCK_C)
|
| 692 |
+
g_s = tl.where(valid[:, None], gam, g_ref[None, :])
|
| 693 |
+
use = tl.sum(started) > 0.5
|
| 694 |
+
g_after_s = tl.where(use, g_after, g_ref)
|
| 695 |
+
carry = tl.where(use, R_after * tl.exp(2.0 * (g_after_s - g_ref)), 0.0)
|
| 696 |
+
w = tl.where(valid[:, None], alpha[:, None] * tl.exp(2.0 * (g_s - g_ref[None, :])), 0.0)
|
| 697 |
+
R = (tl.cumsum(w, axis=0, reverse=True) + carry[None, :]) * tl.exp(2.0 * (g_ref[None, :] - g_s))
|
| 698 |
+
R = tl.where(valid[:, None], R, 0.0)
|
| 699 |
+
alive = started * 0.0 + 1.0
|
| 700 |
+
return R, _row0(R, BLOCK_C), g_ref, alive
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
@triton.jit(do_not_specialize=["T"])
|
| 704 |
+
def trace_bwd_rev_kernel(
|
| 705 |
+
k_ptr, gam_ptr, dk_ptr, dgk_ptr, alpha_ptr, diag_ptr,
|
| 706 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 707 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr,
|
| 708 |
+
):
|
| 709 |
+
"""R and the in-chunk dk / dgk update, one 16-row block at a time."""
|
| 710 |
+
chunk_id = tl.program_id(0)
|
| 711 |
+
bh = tl.program_id(1)
|
| 712 |
+
b_id, h_id = bh // H, bh % H
|
| 713 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 714 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 715 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 716 |
+
vec = (b_id * T * H + h_id) * D
|
| 717 |
+
k_ptr += vec
|
| 718 |
+
gam_ptr += vec
|
| 719 |
+
dk_ptr += vec
|
| 720 |
+
dgk_ptr += vec
|
| 721 |
+
diag_ptr += vec
|
| 722 |
+
alpha_ptr += b_id * T * H + h_id
|
| 723 |
+
for i in tl.range(NUM_D):
|
| 724 |
+
d0 = i * BLOCK_D
|
| 725 |
+
R_after = tl.zeros([BLOCK_D], dtype=tl.float32)
|
| 726 |
+
g_after = tl.zeros([BLOCK_D], dtype=tl.float32)
|
| 727 |
+
started = tl.zeros([1], dtype=tl.float32)
|
| 728 |
+
suf_carry = tl.zeros([BLOCK_D], dtype=tl.float32)
|
| 729 |
+
for bi in tl.range(NUM_C):
|
| 730 |
+
s0 = (NUM_C - 1 - bi) * BLOCK_C
|
| 731 |
+
if s0 < n_valid:
|
| 732 |
+
n_rows = tl.minimum(BLOCK_C, n_valid - s0)
|
| 733 |
+
valid = tl.arange(0, BLOCK_C) < n_rows
|
| 734 |
+
rows = s0 + tl.arange(0, BLOCK_C)
|
| 735 |
+
pa = tl.make_block_ptr(
|
| 736 |
+
alpha_ptr, (T,), (H,),
|
| 737 |
+
(chunk_id * chunk_size + s0,), (BLOCK_C,), (0,),
|
| 738 |
+
)
|
| 739 |
+
alpha = tl.where(rows < n_valid, tl.load(pa, boundary_check=(0,)).to(tl.float32), 0.0)
|
| 740 |
+
gam = _load_bc(
|
| 741 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 742 |
+
)
|
| 743 |
+
k = _load_bc(
|
| 744 |
+
k_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 745 |
+
)
|
| 746 |
+
diag_H = _load_bc(
|
| 747 |
+
diag_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 748 |
+
)
|
| 749 |
+
z = _load_bc(
|
| 750 |
+
dk_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 751 |
+
)
|
| 752 |
+
lin = _load_bc(
|
| 753 |
+
dgk_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 754 |
+
)
|
| 755 |
+
R, R_after, g_after, started = _rev_tile(
|
| 756 |
+
alpha, gam, R_after, g_after, started, n_rows, BLOCK_C,
|
| 757 |
+
)
|
| 758 |
+
x = tl.where(valid[:, None], lin - k * z, 0.0)
|
| 759 |
+
suf = tl.cumsum(x, axis=0, reverse=True) + suf_carry[None, :]
|
| 760 |
+
suf_carry = _row0(suf, BLOCK_C)
|
| 761 |
+
dgk = tl.where(valid[:, None], 0.5 * suf + R * (diag_H - k * k), 0.0)
|
| 762 |
+
dk = tl.where(valid[:, None], z + 2.0 * R * k, 0.0)
|
| 763 |
+
_store_bc(dgk_ptr, dgk, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D)
|
| 764 |
+
_store_bc(dk_ptr, dk, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
@triton.jit(do_not_specialize=["T"])
|
| 768 |
+
def trace_bwd_gpartial_kernel(
|
| 769 |
+
gam_ptr, q_ptr, o1_ptr, o2_ptr, u1_ptr, u2_ptr, u3_ptr, alpha_ptr,
|
| 770 |
+
g_partial_ptr,
|
| 771 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 772 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, N: tl.constexpr, PREC: tl.constexpr,
|
| 773 |
+
):
|
| 774 |
+
"""g_partial[d0, d1] = sum_m (x_m E_d0)^T (u_m E_d1), summed 16 rows at a time."""
|
| 775 |
+
chunk_id = tl.program_id(0)
|
| 776 |
+
bh = tl.program_id(1)
|
| 777 |
+
b_id, h_id = bh // H, bh % H
|
| 778 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 779 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 780 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 781 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 782 |
+
vec = (b_id * T * H + h_id) * D
|
| 783 |
+
gam_ptr += vec
|
| 784 |
+
q_ptr += vec
|
| 785 |
+
o1_ptr += vec
|
| 786 |
+
o2_ptr += vec
|
| 787 |
+
u1_ptr += vec
|
| 788 |
+
u2_ptr += vec
|
| 789 |
+
u3_ptr += vec
|
| 790 |
+
alpha_ptr += b_id * T * H + h_id
|
| 791 |
+
g_partial_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 792 |
+
|
| 793 |
+
for di in tl.range(NUM_D):
|
| 794 |
+
d0 = di * BLOCK_D
|
| 795 |
+
for dj in tl.range(NUM_D):
|
| 796 |
+
d1 = dj * BLOCK_D
|
| 797 |
+
g = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32)
|
| 798 |
+
r0 = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 799 |
+
for kb in tl.range(NUM_C):
|
| 800 |
+
s0 = kb * BLOCK_C
|
| 801 |
+
if s0 < n_valid:
|
| 802 |
+
ei = tl.exp(_load_bc(
|
| 803 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 804 |
+
))
|
| 805 |
+
ej = tl.exp(_load_bc(
|
| 806 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, s0, d1, n_valid, BLOCK_C, BLOCK_D,
|
| 807 |
+
))
|
| 808 |
+
for m in tl.static_range(1, N):
|
| 809 |
+
if m == 1:
|
| 810 |
+
xs = q_ptr
|
| 811 |
+
us = u1_ptr
|
| 812 |
+
elif m == 2:
|
| 813 |
+
xs = o1_ptr
|
| 814 |
+
us = u2_ptr
|
| 815 |
+
else:
|
| 816 |
+
xs = o2_ptr
|
| 817 |
+
us = u3_ptr
|
| 818 |
+
x = _load_bc(
|
| 819 |
+
xs, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 820 |
+
) * ei
|
| 821 |
+
y = _load_bc(
|
| 822 |
+
us, T, H, D, chunk_id, chunk_size, s0, d1, n_valid, BLOCK_C, BLOCK_D,
|
| 823 |
+
) * ej
|
| 824 |
+
g += _dot(tl.trans(x), y, PREC, 5)
|
| 825 |
+
if di == dj:
|
| 826 |
+
rows = s0 + tl.arange(0, BLOCK_C)
|
| 827 |
+
pa = tl.make_block_ptr(
|
| 828 |
+
alpha_ptr, (T,), (H,),
|
| 829 |
+
(chunk_id * chunk_size + s0,), (BLOCK_C,), (0,),
|
| 830 |
+
)
|
| 831 |
+
ab = tl.where(
|
| 832 |
+
rows < n_valid,
|
| 833 |
+
tl.load(pa, boundary_check=(0,)).to(tl.float32),
|
| 834 |
+
0.0,
|
| 835 |
+
)
|
| 836 |
+
r0 += tl.sum(ab[:, None] * ei * ei, axis=0)
|
| 837 |
+
if di == dj:
|
| 838 |
+
eye = tl.arange(0, BLOCK_D)
|
| 839 |
+
g += tl.where(eye[:, None] == eye[None, :], r0[:, None], 0.0)
|
| 840 |
+
_store_mat(g_partial_ptr, g, D, d0, d1, BLOCK_D)
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
@triton.jit
|
| 844 |
+
def _gam_last_of(gam_ptr, b_id, h_id, cid, T, H: tl.constexpr, D: tl.constexpr,
|
| 845 |
+
chunk_size: tl.constexpr, d0, BLOCK: tl.constexpr):
|
| 846 |
+
"""Gam at the last valid token of chunk ``cid``, dims d0:d0+BLOCK."""
|
| 847 |
+
t_last = cid * chunk_size + tl.minimum(chunk_size, T - cid * chunk_size) - 1
|
| 848 |
+
off = ((b_id * T + t_last) * H + h_id).to(tl.int64) * D + d0
|
| 849 |
+
return tl.load(gam_ptr + off + tl.arange(0, BLOCK)).to(tl.float32)
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
@triton.jit
|
| 853 |
+
def _e_last_of(gam_ptr, b_id, h_id, cid, T, H: tl.constexpr, D: tl.constexpr,
|
| 854 |
+
chunk_size: tl.constexpr, d0, BLOCK: tl.constexpr):
|
| 855 |
+
"""exp(Gam) at the last valid token of chunk ``cid``, dims d0:d0+BLOCK."""
|
| 856 |
+
return tl.exp(_gam_last_of(gam_ptr, b_id, h_id, cid, T, H, D, chunk_size, d0, BLOCK))
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
@triton.jit(do_not_specialize=["T"])
|
| 860 |
+
def trace_bwd_scan_kernel(
|
| 861 |
+
g_partial_ptr, gam_ptr, gin_ptr, dht_ptr,
|
| 862 |
+
T, NC, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 863 |
+
BLOCK_S: tl.constexpr, HAS_DHT: tl.constexpr,
|
| 864 |
+
):
|
| 865 |
+
"""gin[c] = g_partial[c+1] + Diag(E_last[c+1]) gin[c+1] Diag(E_last[c+1])."""
|
| 866 |
+
i_bh = tl.program_id(0)
|
| 867 |
+
i_tile = tl.program_id(1)
|
| 868 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 869 |
+
NUM_S: tl.constexpr = D // BLOCK_S
|
| 870 |
+
r0 = (i_tile // NUM_S) * BLOCK_S
|
| 871 |
+
c0 = (i_tile % NUM_S) * BLOCK_S
|
| 872 |
+
G = tl.zeros((BLOCK_S, BLOCK_S), dtype=tl.float32)
|
| 873 |
+
if HAS_DHT:
|
| 874 |
+
p_dht = tl.make_block_ptr(
|
| 875 |
+
dht_ptr + (i_b * H + i_h).to(tl.int64) * D * D,
|
| 876 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 877 |
+
)
|
| 878 |
+
G = tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32)
|
| 879 |
+
last = NC - 1
|
| 880 |
+
p_gin = tl.make_block_ptr(
|
| 881 |
+
gin_ptr + ((i_b * NC + last) * H + i_h).to(tl.int64) * D * D,
|
| 882 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 883 |
+
)
|
| 884 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 885 |
+
for it in tl.range(0, NC - 1):
|
| 886 |
+
cid = NC - 2 - it
|
| 887 |
+
src = cid + 1
|
| 888 |
+
p_gp = tl.make_block_ptr(
|
| 889 |
+
g_partial_ptr + ((i_b * NC + src) * H + i_h).to(tl.int64) * D * D,
|
| 890 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 891 |
+
)
|
| 892 |
+
gp = tl.load(p_gp, boundary_check=(0, 1)).to(tl.float32)
|
| 893 |
+
er = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, r0, BLOCK_S)
|
| 894 |
+
ec = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, c0, BLOCK_S)
|
| 895 |
+
G = gp + er[:, None] * G * ec[None, :]
|
| 896 |
+
p_gin = tl.make_block_ptr(
|
| 897 |
+
gin_ptr + ((i_b * NC + cid) * H + i_h).to(tl.int64) * D * D,
|
| 898 |
+
(D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0),
|
| 899 |
+
)
|
| 900 |
+
tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1))
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
@triton.jit(do_not_specialize=["T"])
|
| 904 |
+
def trace_bwd_gin_kernel(
|
| 905 |
+
h_ptr, k_ptr, gam_ptr, gin_ptr, dk_ptr, dgk_ptr,
|
| 906 |
+
T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 907 |
+
BLOCK_D: tl.constexpr, PREC: tl.constexpr,
|
| 908 |
+
):
|
| 909 |
+
"""Add S_in = Diag(E_C) (gin + gin^T) Diag(E_C) into dk and dgk."""
|
| 910 |
+
chunk_id = tl.program_id(0)
|
| 911 |
+
bh = tl.program_id(1)
|
| 912 |
+
b_id, h_id = bh // H, bh % H
|
| 913 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 914 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 915 |
+
m_t, _ = _masks(chunk_id, chunk_size, T)
|
| 916 |
+
|
| 917 |
+
gam_base = gam_ptr
|
| 918 |
+
vec = (b_id * T * H + h_id) * D
|
| 919 |
+
k_ptr += vec
|
| 920 |
+
gam_ptr += vec
|
| 921 |
+
dk_ptr += vec
|
| 922 |
+
dgk_ptr += vec
|
| 923 |
+
mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D
|
| 924 |
+
h_ptr += mat
|
| 925 |
+
gin_ptr += mat
|
| 926 |
+
|
| 927 |
+
for i in tl.range(NUM_D):
|
| 928 |
+
d0 = i * BLOCK_D
|
| 929 |
+
gam0 = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 930 |
+
el_log0 = _gam_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d0, BLOCK_D)
|
| 931 |
+
el0 = tl.exp(el_log0)
|
| 932 |
+
Za = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 933 |
+
v1 = tl.zeros((BLOCK_D,), dtype=tl.float32)
|
| 934 |
+
for j in tl.range(NUM_D):
|
| 935 |
+
d1 = j * BLOCK_D
|
| 936 |
+
gam1 = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 937 |
+
k1 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 938 |
+
el_log1 = _gam_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d1, BLOCK_D)
|
| 939 |
+
el1 = tl.exp(el_log1)
|
| 940 |
+
w1 = k1 * tl.exp(el_log1[None, :] - gam1)
|
| 941 |
+
sym = _load_mat(gin_ptr, D, d1, d0, BLOCK_D) + tl.trans(_load_mat(gin_ptr, D, d0, d1, BLOCK_D))
|
| 942 |
+
Za += _dot(w1, sym, PREC, 6)
|
| 943 |
+
h_ij = _load_mat(h_ptr, D, d0, d1, BLOCK_D)
|
| 944 |
+
v1 += tl.sum(tl.trans(sym) * el1[None, :] * h_ij, axis=1)
|
| 945 |
+
scale0 = tl.exp(el_log0[None, :] - gam0)
|
| 946 |
+
w0 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * scale0
|
| 947 |
+
dk = _load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 948 |
+
_store_vec(dk_ptr, dk + scale0 * Za, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 949 |
+
dgk = _load_vec(dgk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D)
|
| 950 |
+
dgk += 0.5 * (v1[None, :] * el0[None, :] + _excl(w0 * Za))
|
| 951 |
+
_store_vec(dgk_ptr, dgk, T, H, D, chunk_id, chunk_size, d0, BLOCK_D)
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
@triton.jit(do_not_specialize=["T"])
|
| 956 |
+
def trace_apply_p_block_kernel(
|
| 957 |
+
src_ptr, dst_ptr, k_ptr, gam_ptr, h_ptr, f_ptr, s_ptr,
|
| 958 |
+
T, BH, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 959 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, PREC: tl.constexpr,
|
| 960 |
+
):
|
| 961 |
+
"""One 16-row query block: inter-chunk H plus intra from S. Writes those rows only."""
|
| 962 |
+
chunk_id = tl.program_id(0)
|
| 963 |
+
bh = tl.program_id(1)
|
| 964 |
+
bid = tl.program_id(2)
|
| 965 |
+
s0 = bid * BLOCK_C
|
| 966 |
+
b_id = bh // H
|
| 967 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 968 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 969 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 970 |
+
m_t, _ = _masks(chunk_id, chunk_size, T)
|
| 971 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 972 |
+
vec = (b_id * T * H + (bh % H)) * D
|
| 973 |
+
src_ptr += vec
|
| 974 |
+
dst_ptr += vec
|
| 975 |
+
k_ptr += vec
|
| 976 |
+
gam_ptr += vec
|
| 977 |
+
f_ptr += b_id * T * H + (bh % H)
|
| 978 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + (bh % H)).to(tl.int64) * D * D
|
| 979 |
+
s_ptr += (chunk_id * BH + bh).to(tl.int64) * chunk_size * chunk_size
|
| 980 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 981 |
+
F = tl.where(m_t, F, 1.0)
|
| 982 |
+
for di in tl.range(NUM_D):
|
| 983 |
+
d0 = di * BLOCK_D
|
| 984 |
+
if s0 < n_valid:
|
| 985 |
+
inter = _vh_rows(
|
| 986 |
+
src_ptr, h_ptr, gam_ptr, s0, n_valid, chunk_id, T, H, D, d0,
|
| 987 |
+
BLOCK_C, BLOCK_D, NUM_D, chunk_size, PREC,
|
| 988 |
+
)
|
| 989 |
+
g_ref = _load_gref(gam_ptr, chunk_id, chunk_size, s0, H, D, d0, BLOCK_D)
|
| 990 |
+
acc = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 991 |
+
for kb in tl.range(NUM_C):
|
| 992 |
+
if kb < bid:
|
| 993 |
+
sk = kb * BLOCK_C
|
| 994 |
+
gk = _load_bc(
|
| 995 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 996 |
+
)
|
| 997 |
+
kk = _load_bc(
|
| 998 |
+
k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 999 |
+
)
|
| 1000 |
+
ks = kk * tl.exp(g_ref[None, :] - gk)
|
| 1001 |
+
pS = tl.make_block_ptr(
|
| 1002 |
+
s_ptr, (chunk_size, chunk_size), (chunk_size, 1),
|
| 1003 |
+
(s0, sk), (BLOCK_C, BLOCK_C), (1, 0),
|
| 1004 |
+
)
|
| 1005 |
+
acc += _dot(tl.load(pS, boundary_check=(0, 1)).to(tl.float32), ks, PREC, 2)
|
| 1006 |
+
g_q = _load_bc(
|
| 1007 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 1008 |
+
)
|
| 1009 |
+
k_q = _load_bc(
|
| 1010 |
+
k_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 1011 |
+
)
|
| 1012 |
+
valid = (s0 + tl.arange(0, BLOCK_C)) < n_valid
|
| 1013 |
+
g_q_s = tl.where(valid[:, None], g_q, g_ref[None, :])
|
| 1014 |
+
k_q_s = tl.where(valid[:, None], k_q * tl.exp(g_ref[None, :] - g_q_s), 0.0)
|
| 1015 |
+
pD = tl.make_block_ptr(
|
| 1016 |
+
s_ptr, (chunk_size, chunk_size), (chunk_size, 1),
|
| 1017 |
+
(s0, s0), (BLOCK_C, BLOCK_C), (1, 0),
|
| 1018 |
+
)
|
| 1019 |
+
acc += _dot_diag(tl.load(pD, boundary_check=(0, 1)).to(tl.float32), k_q_s, PREC, 2)
|
| 1020 |
+
intra = tl.where(valid[:, None], tl.exp(g_q_s - g_ref[None, :]) * acc, 0.0)
|
| 1021 |
+
Fb = tl.where(valid, _f_bc(F, s0, chunk_size, BLOCK_C), 1.0)
|
| 1022 |
+
out = tl.where(valid[:, None], (inter * tl.exp(g_q) + intra) / Fb[:, None], 0.0)
|
| 1023 |
+
_store_bc(
|
| 1024 |
+
dst_ptr, out, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D,
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
@triton.jit
|
| 1029 |
+
def _split4(x, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr):
|
| 1030 |
+
"""[4*BLOCK_C, BLOCK_D] -> four [BLOCK_C, BLOCK_D] row blocks, in order."""
|
| 1031 |
+
y = tl.reshape(x, (4, BLOCK_C, BLOCK_D))
|
| 1032 |
+
y = tl.permute(y, (1, 2, 0))
|
| 1033 |
+
y = tl.reshape(y, (BLOCK_C, BLOCK_D, 2, 2))
|
| 1034 |
+
p0, p1 = tl.split(y)
|
| 1035 |
+
b0, b2 = tl.split(p0)
|
| 1036 |
+
b1, b3 = tl.split(p1)
|
| 1037 |
+
return b0, b1, b2, b3
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
@triton.jit
|
| 1041 |
+
def _p_rows(
|
| 1042 |
+
dst_ptr, k_ptr, gam_ptr, s_ptr, inter, F,
|
| 1043 |
+
T, H, D, chunk_id, chunk_size, n_valid, s0, d0,
|
| 1044 |
+
BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr, NUM_C: tl.constexpr, PREC: tl.constexpr,
|
| 1045 |
+
):
|
| 1046 |
+
"""Intra S@k for one query block, added to a precomputed vH tile."""
|
| 1047 |
+
bid = s0 // BLOCK_C
|
| 1048 |
+
g_ref = _load_gref(gam_ptr, chunk_id, chunk_size, s0, H, D, d0, BLOCK_D)
|
| 1049 |
+
acc = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1050 |
+
for kb in tl.range(NUM_C):
|
| 1051 |
+
if kb < bid:
|
| 1052 |
+
sk = kb * BLOCK_C
|
| 1053 |
+
gk = _load_bc(
|
| 1054 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 1055 |
+
)
|
| 1056 |
+
kk = _load_bc(
|
| 1057 |
+
k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 1058 |
+
)
|
| 1059 |
+
pS = tl.make_block_ptr(
|
| 1060 |
+
s_ptr, (chunk_size, chunk_size), (chunk_size, 1),
|
| 1061 |
+
(s0, sk), (BLOCK_C, BLOCK_C), (1, 0),
|
| 1062 |
+
)
|
| 1063 |
+
acc += _dot(
|
| 1064 |
+
tl.load(pS, boundary_check=(0, 1)).to(tl.float32),
|
| 1065 |
+
kk * tl.exp(g_ref[None, :] - gk), PREC, 2,
|
| 1066 |
+
)
|
| 1067 |
+
g_q = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 1068 |
+
k_q = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D)
|
| 1069 |
+
valid = (s0 + tl.arange(0, BLOCK_C)) < n_valid
|
| 1070 |
+
g_q_s = tl.where(valid[:, None], g_q, g_ref[None, :])
|
| 1071 |
+
k_q_s = tl.where(valid[:, None], k_q * tl.exp(g_ref[None, :] - g_q_s), 0.0)
|
| 1072 |
+
pD = tl.make_block_ptr(
|
| 1073 |
+
s_ptr, (chunk_size, chunk_size), (chunk_size, 1),
|
| 1074 |
+
(s0, s0), (BLOCK_C, BLOCK_C), (1, 0),
|
| 1075 |
+
)
|
| 1076 |
+
acc += _dot_diag(tl.load(pD, boundary_check=(0, 1)).to(tl.float32), k_q_s, PREC, 2)
|
| 1077 |
+
intra = tl.where(valid[:, None], tl.exp(g_q_s - g_ref[None, :]) * acc, 0.0)
|
| 1078 |
+
Fb = tl.where(valid, _f_bc(F, s0, chunk_size, BLOCK_C), 1.0)
|
| 1079 |
+
out = tl.where(valid[:, None], (inter * tl.exp(g_q) + intra) / Fb[:, None], 0.0)
|
| 1080 |
+
_store_bc(dst_ptr, out, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D)
|
| 1081 |
+
|
| 1082 |
+
|
| 1083 |
+
@triton.jit(do_not_specialize=["T"])
|
| 1084 |
+
def trace_apply_p_d_kernel(
|
| 1085 |
+
src_ptr, dst_ptr, k_ptr, gam_ptr, h_ptr, f_ptr, s_ptr,
|
| 1086 |
+
T, BH, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 1087 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, PREC: tl.constexpr,
|
| 1088 |
+
):
|
| 1089 |
+
"""One D tile of a chunk: M=chunk H gemm, then the four 16-row intra updates."""
|
| 1090 |
+
chunk_id = tl.program_id(0)
|
| 1091 |
+
bh = tl.program_id(1)
|
| 1092 |
+
d0 = tl.program_id(2) * BLOCK_D
|
| 1093 |
+
b_id = bh // H
|
| 1094 |
+
num_chunks = tl.cdiv(T, chunk_size)
|
| 1095 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1096 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 1097 |
+
m_t, _ = _masks(chunk_id, chunk_size, T)
|
| 1098 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 1099 |
+
vec = (b_id * T * H + (bh % H)) * D
|
| 1100 |
+
src_ptr += vec
|
| 1101 |
+
dst_ptr += vec
|
| 1102 |
+
k_ptr += vec
|
| 1103 |
+
gam_ptr += vec
|
| 1104 |
+
f_ptr += b_id * T * H + (bh % H)
|
| 1105 |
+
h_ptr += ((b_id * num_chunks + chunk_id) * H + (bh % H)).to(tl.int64) * D * D
|
| 1106 |
+
s_ptr += (chunk_id * BH + bh).to(tl.int64) * chunk_size * chunk_size
|
| 1107 |
+
inter = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32)
|
| 1108 |
+
for j in tl.static_range(NUM_D):
|
| 1109 |
+
d1 = j * BLOCK_D
|
| 1110 |
+
gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)
|
| 1111 |
+
v = _load_vec(src_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * tl.exp(gam)
|
| 1112 |
+
h = _load_mat(h_ptr, D, d1, d0, BLOCK_D)
|
| 1113 |
+
inter += _dot(v, h, PREC, 1)
|
| 1114 |
+
b0, b1, b2, b3 = _split4(inter, BLOCK_C, BLOCK_D)
|
| 1115 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 1116 |
+
F = tl.where(m_t, F, 1.0)
|
| 1117 |
+
if 0 < n_valid:
|
| 1118 |
+
_p_rows(
|
| 1119 |
+
dst_ptr, k_ptr, gam_ptr, s_ptr, b0, F,
|
| 1120 |
+
T, H, D, chunk_id, chunk_size, n_valid, 0, d0,
|
| 1121 |
+
BLOCK_C, BLOCK_D, NUM_C, PREC,
|
| 1122 |
+
)
|
| 1123 |
+
if BLOCK_C < n_valid:
|
| 1124 |
+
_p_rows(
|
| 1125 |
+
dst_ptr, k_ptr, gam_ptr, s_ptr, b1, F,
|
| 1126 |
+
T, H, D, chunk_id, chunk_size, n_valid, BLOCK_C, d0,
|
| 1127 |
+
BLOCK_C, BLOCK_D, NUM_C, PREC,
|
| 1128 |
+
)
|
| 1129 |
+
if 2 * BLOCK_C < n_valid:
|
| 1130 |
+
_p_rows(
|
| 1131 |
+
dst_ptr, k_ptr, gam_ptr, s_ptr, b2, F,
|
| 1132 |
+
T, H, D, chunk_id, chunk_size, n_valid, 2 * BLOCK_C, d0,
|
| 1133 |
+
BLOCK_C, BLOCK_D, NUM_C, PREC,
|
| 1134 |
+
)
|
| 1135 |
+
if 3 * BLOCK_C < n_valid:
|
| 1136 |
+
_p_rows(
|
| 1137 |
+
dst_ptr, k_ptr, gam_ptr, s_ptr, b3, F,
|
| 1138 |
+
T, H, D, chunk_id, chunk_size, n_valid, 3 * BLOCK_C, d0,
|
| 1139 |
+
BLOCK_C, BLOCK_D, NUM_C, PREC,
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
@triton.jit(do_not_specialize=["T"])
|
| 1144 |
+
def trace_apply_z_block_kernel(
|
| 1145 |
+
s_ptr, y_ptr, q_ptr, o1_ptr, o2_ptr, gam_ptr, dk_ptr, f_ptr, coeff_ptr,
|
| 1146 |
+
T, BH, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr,
|
| 1147 |
+
BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, N: tl.constexpr,
|
| 1148 |
+
FROM_XT: tl.constexpr, ADD_PREV: tl.constexpr, J: tl.constexpr,
|
| 1149 |
+
SITE: tl.constexpr, PREC: tl.constexpr,
|
| 1150 |
+
):
|
| 1151 |
+
"""One 16-row key block of Z = S^T y, accumulated into dk."""
|
| 1152 |
+
chunk_id = tl.program_id(0)
|
| 1153 |
+
bh = tl.program_id(1)
|
| 1154 |
+
bid = tl.program_id(2)
|
| 1155 |
+
s0 = bid * BLOCK_C
|
| 1156 |
+
b_id = bh // H
|
| 1157 |
+
h_id = bh % H
|
| 1158 |
+
NUM_D: tl.constexpr = D // BLOCK_D
|
| 1159 |
+
NUM_C: tl.constexpr = chunk_size // BLOCK_C
|
| 1160 |
+
m_t, _ = _masks(chunk_id, chunk_size, T)
|
| 1161 |
+
n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size)
|
| 1162 |
+
vec = (b_id * T * H + h_id) * D
|
| 1163 |
+
y_ptr += vec
|
| 1164 |
+
q_ptr += vec
|
| 1165 |
+
o1_ptr += vec
|
| 1166 |
+
o2_ptr += vec
|
| 1167 |
+
gam_ptr += vec
|
| 1168 |
+
dk_ptr += vec
|
| 1169 |
+
f_ptr += b_id * T * H + h_id
|
| 1170 |
+
s_ptr += (chunk_id * BH + bh).to(tl.int64) * chunk_size * chunk_size
|
| 1171 |
+
F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0)
|
| 1172 |
+
F = tl.where(m_t, F, 1.0)
|
| 1173 |
+
for di in tl.range(NUM_D):
|
| 1174 |
+
d0 = di * BLOCK_D
|
| 1175 |
+
if s0 < n_valid:
|
| 1176 |
+
g_ref = _load_gref(gam_ptr, chunk_id, chunk_size, s0, H, D, d0, BLOCK_D)
|
| 1177 |
+
g_k = _load_bc(
|
| 1178 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 1179 |
+
)
|
| 1180 |
+
valid = (s0 + tl.arange(0, BLOCK_C)) < n_valid
|
| 1181 |
+
g_k_s = tl.where(valid[:, None], g_k, g_ref[None, :])
|
| 1182 |
+
acc = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32)
|
| 1183 |
+
for qb in tl.range(NUM_C):
|
| 1184 |
+
if qb >= bid:
|
| 1185 |
+
sq = qb * BLOCK_C
|
| 1186 |
+
if sq < n_valid:
|
| 1187 |
+
if FROM_XT:
|
| 1188 |
+
ca = tl.load(coeff_ptr + h_id * N + J + 1).to(tl.float32)
|
| 1189 |
+
yb = ca * _load_bc(
|
| 1190 |
+
q_ptr, T, H, D, chunk_id, chunk_size, sq, d0, n_valid,
|
| 1191 |
+
BLOCK_C, BLOCK_D,
|
| 1192 |
+
)
|
| 1193 |
+
if J + 2 < N:
|
| 1194 |
+
cb = tl.load(coeff_ptr + h_id * N + J + 2).to(tl.float32)
|
| 1195 |
+
yb += cb * _load_bc(
|
| 1196 |
+
o1_ptr, T, H, D, chunk_id, chunk_size, sq, d0, n_valid,
|
| 1197 |
+
BLOCK_C, BLOCK_D,
|
| 1198 |
+
)
|
| 1199 |
+
if J + 3 < N:
|
| 1200 |
+
cc = tl.load(coeff_ptr + h_id * N + J + 3).to(tl.float32)
|
| 1201 |
+
yb += cc * _load_bc(
|
| 1202 |
+
o2_ptr, T, H, D, chunk_id, chunk_size, sq, d0, n_valid,
|
| 1203 |
+
BLOCK_C, BLOCK_D,
|
| 1204 |
+
)
|
| 1205 |
+
rv = (sq + tl.arange(0, BLOCK_C)) < n_valid
|
| 1206 |
+
Fb = tl.where(rv, _f_bc(F, sq, chunk_size, BLOCK_C), 1.0)
|
| 1207 |
+
yb = yb / Fb[:, None]
|
| 1208 |
+
else:
|
| 1209 |
+
yb = _load_bc(
|
| 1210 |
+
y_ptr, T, H, D, chunk_id, chunk_size, sq, d0, n_valid,
|
| 1211 |
+
BLOCK_C, BLOCK_D,
|
| 1212 |
+
)
|
| 1213 |
+
rv = (sq + tl.arange(0, BLOCK_C)) < n_valid
|
| 1214 |
+
gb = _load_bc(
|
| 1215 |
+
gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, n_valid,
|
| 1216 |
+
BLOCK_C, BLOCK_D,
|
| 1217 |
+
)
|
| 1218 |
+
gb_s = tl.where(rv[:, None], gb, g_ref[None, :])
|
| 1219 |
+
ys = tl.where(rv[:, None], yb * tl.exp(gb_s - g_ref[None, :]), 0.0)
|
| 1220 |
+
pS = tl.make_block_ptr(
|
| 1221 |
+
s_ptr, (chunk_size, chunk_size), (chunk_size, 1),
|
| 1222 |
+
(sq, s0), (BLOCK_C, BLOCK_C), (1, 0),
|
| 1223 |
+
)
|
| 1224 |
+
acc += _dot(
|
| 1225 |
+
tl.trans(tl.load(pS, boundary_check=(0, 1)).to(tl.float32)),
|
| 1226 |
+
ys, PREC, SITE,
|
| 1227 |
+
)
|
| 1228 |
+
z = tl.where(valid[:, None], tl.exp(g_ref[None, :] - g_k_s) * acc, 0.0)
|
| 1229 |
+
if ADD_PREV:
|
| 1230 |
+
z += _load_bc(
|
| 1231 |
+
dk_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, BLOCK_C, BLOCK_D,
|
| 1232 |
+
)
|
| 1233 |
+
_store_bc(dk_ptr, z, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D)
|
| 1234 |
+
|
| 1235 |
+
|
| 1236 |
+
def _score_apply(
|
| 1237 |
+
src, dst, k, gam, h, F, S, y, q, o1, o2, o3, dk, coeff_h,
|
| 1238 |
+
T, H, D, chunk_size, n_coeff, do_p, do_z, from_xt, add_prev, J, site,
|
| 1239 |
+
do_score=True,
|
| 1240 |
+
):
|
| 1241 |
+
"""Score into S, then one 16-row program per block. do_score=False reuses S."""
|
| 1242 |
+
B = q.shape[0]
|
| 1243 |
+
grid = (triton.cdiv(T, chunk_size), B * H)
|
| 1244 |
+
block_d = _choose_block_d(D)
|
| 1245 |
+
block_c = _choose_block_c(chunk_size)
|
| 1246 |
+
grid_b = (grid[0], grid[1], chunk_size // block_c)
|
| 1247 |
+
if do_score:
|
| 1248 |
+
trace_score_kernel[grid](
|
| 1249 |
+
src, k, gam, S,
|
| 1250 |
+
T, B * H, H, D, chunk_size, block_d, block_c, DOT_PRECISION,
|
| 1251 |
+
num_warps=4, num_stages=2,
|
| 1252 |
+
)
|
| 1253 |
+
if do_p and chunk_size == 64:
|
| 1254 |
+
trace_apply_p_d_kernel[(grid[0], grid[1], D // block_d)](
|
| 1255 |
+
src, dst, k, gam, h, F, S,
|
| 1256 |
+
T, B * H, H, D, chunk_size, block_d, block_c, DOT_PRECISION,
|
| 1257 |
+
num_warps=4, num_stages=1,
|
| 1258 |
+
)
|
| 1259 |
+
elif do_p:
|
| 1260 |
+
trace_apply_p_block_kernel[grid_b](
|
| 1261 |
+
src, dst, k, gam, h, F, S,
|
| 1262 |
+
T, B * H, H, D, chunk_size, block_d, block_c, DOT_PRECISION,
|
| 1263 |
+
num_warps=4, num_stages=2,
|
| 1264 |
+
)
|
| 1265 |
+
if do_z:
|
| 1266 |
+
trace_apply_z_block_kernel[grid_b](
|
| 1267 |
+
S, y, q, o1, o2, gam, dk, F, coeff_h,
|
| 1268 |
+
T, B * H, H, D, chunk_size, block_d, block_c, n_coeff,
|
| 1269 |
+
from_xt, add_prev, J, site, DOT_PRECISION,
|
| 1270 |
+
num_warps=4, num_stages=2,
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
def _gin_into(h, k, gam, gin, dk, dgk, chunk_size):
|
| 1275 |
+
"""Add S_in = Diag(E) (gin + gin^T) Diag(E) into dk and dgk.
|
| 1276 |
+
|
| 1277 |
+
Same math as ``trace_bwd_gin_kernel``, but the [C, D] x [D, D] products go
|
| 1278 |
+
through a bf16 batched gemm. The fused kernel keeps several 64x64 tiles
|
| 1279 |
+
live and spills.
|
| 1280 |
+
"""
|
| 1281 |
+
B, T, H, D = k.shape
|
| 1282 |
+
C = chunk_size
|
| 1283 |
+
nc = gin.shape[1]
|
| 1284 |
+
pad = nc * C - T
|
| 1285 |
+
if pad:
|
| 1286 |
+
k = torch.nn.functional.pad(k, (0, 0, 0, 0, 0, pad))
|
| 1287 |
+
gam = torch.nn.functional.pad(gam, (0, 0, 0, 0, 0, pad))
|
| 1288 |
+
last_t = (torch.arange(1, nc + 1, device=gam.device) * C - 1).clamp(max=T - 1)
|
| 1289 |
+
g_last = gam[:, last_t].contiguous()
|
| 1290 |
+
n_valid = (T - torch.arange(nc, device=gam.device) * C).clamp(min=0, max=C)
|
| 1291 |
+
valid = torch.arange(C, device=gam.device)[None, :] < n_valid[:, None]
|
| 1292 |
+
gam_c = gam.view(B, nc, C, H, D)
|
| 1293 |
+
k_c = k.view(B, nc, C, H, D)
|
| 1294 |
+
scale = torch.exp(g_last[:, :, None] - gam_c) * valid[None, :, :, None, None]
|
| 1295 |
+
w_t = k_c * scale
|
| 1296 |
+
w = w_t.permute(0, 1, 3, 2, 4).contiguous()
|
| 1297 |
+
sym = gin + gin.transpose(-1, -2)
|
| 1298 |
+
Za = torch.matmul(
|
| 1299 |
+
w.view(B * nc * H, C, D).to(torch.bfloat16),
|
| 1300 |
+
sym.view(B * nc * H, D, D).to(torch.bfloat16),
|
| 1301 |
+
).float().view(B, nc, H, C, D).permute(0, 1, 3, 2, 4).contiguous()
|
| 1302 |
+
el = g_last.exp()
|
| 1303 |
+
# sym is symmetric, so sym[j, i] == sym[i, j] and the transpose view is unnecessary.
|
| 1304 |
+
v1 = (h * sym * el[..., None, :]).sum(-1)
|
| 1305 |
+
prod = w_t * Za
|
| 1306 |
+
excl = prod.cumsum(dim=2) - prod
|
| 1307 |
+
upd_dk = scale * Za
|
| 1308 |
+
upd_dgk = 0.5 * (v1[:, :, None] * el[:, :, None] + excl)
|
| 1309 |
+
if pad:
|
| 1310 |
+
dk.add_(upd_dk.view(B, nc * C, H, D)[:, :T])
|
| 1311 |
+
dgk.add_(upd_dgk.view(B, nc * C, H, D)[:, :T])
|
| 1312 |
+
else:
|
| 1313 |
+
dk.add_(upd_dk.view(B, T, H, D))
|
| 1314 |
+
dgk.add_(upd_dgk.view(B, T, H, D))
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
def _bwd(k, q, os, dx, F, coeff_h, gam, h, dht, h0, chunk_size, n_coeff, Ss):
|
| 1318 |
+
"""os = (o1, o2[, o3]) in fp32."""
|
| 1319 |
+
B, T, H, D = q.shape
|
| 1320 |
+
C = chunk_size
|
| 1321 |
+
N = n_coeff
|
| 1322 |
+
nc = triton.cdiv(T, C)
|
| 1323 |
+
block_d = _choose_block_d(D)
|
| 1324 |
+
f32 = dict(device=q.device, dtype=torch.float32)
|
| 1325 |
+
o1, o2 = os[0], os[1]
|
| 1326 |
+
o3 = os[2] if N == 4 else o2
|
| 1327 |
+
p1 = torch.empty(B, T, H, D, **f32)
|
| 1328 |
+
p2 = torch.empty(B, T, H, D, **f32)
|
| 1329 |
+
p3 = torch.empty(B, T, H, D, **f32) if N == 4 else p2
|
| 1330 |
+
u1 = torch.empty(B, T, H, D, **f32)
|
| 1331 |
+
u2 = torch.empty(B, T, H, D, **f32)
|
| 1332 |
+
u3 = torch.empty(B, T, H, D, **f32) if N == 4 else u2
|
| 1333 |
+
dq = torch.empty_like(q)
|
| 1334 |
+
dk = torch.empty(B, T, H, D, **f32)
|
| 1335 |
+
dgk = torch.empty(B, T, H, D, **f32)
|
| 1336 |
+
g_partial = torch.empty(B, nc, H, D, D, **f32)
|
| 1337 |
+
gin = torch.empty(B, nc, H, D, D, **f32)
|
| 1338 |
+
dcoeff_part = torch.empty(B, nc, H, N, **f32)
|
| 1339 |
+
alpha = torch.empty(B, T, H, **f32)
|
| 1340 |
+
S = torch.empty(nc, B * H, C, C, **f32)
|
| 1341 |
+
grid = (nc, B * H)
|
| 1342 |
+
block_c = _choose_block_c(C)
|
| 1343 |
+
_score_apply(
|
| 1344 |
+
dx, p1, k, gam, h, F, S, q, q, o1, o2, o3, dk, coeff_h,
|
| 1345 |
+
T, H, D, C, N, 1, 1, 1, 0, 0, 3,
|
| 1346 |
+
)
|
| 1347 |
+
_score_apply(
|
| 1348 |
+
p1, p2, k, gam, h, F, S, q, q, o1, o2, o3, dk, coeff_h,
|
| 1349 |
+
T, H, D, C, N, 1, 1, 1, 1, 1, 3,
|
| 1350 |
+
)
|
| 1351 |
+
if N == 4:
|
| 1352 |
+
_score_apply(
|
| 1353 |
+
p2, p3, k, gam, h, F, S, q, q, o1, o2, o3, dk, coeff_h,
|
| 1354 |
+
T, H, D, C, N, 1, 1, 1, 1, 2, 3,
|
| 1355 |
+
)
|
| 1356 |
+
trace_bwd_mid_kernel[grid](
|
| 1357 |
+
q, o1, o2, o3, dx, F, coeff_h,
|
| 1358 |
+
p1, p2, p3, u1, u2, u3,
|
| 1359 |
+
dq, dgk, alpha, dcoeff_part,
|
| 1360 |
+
T, H, D, C, block_d, N,
|
| 1361 |
+
num_warps=4, num_stages=2,
|
| 1362 |
+
)
|
| 1363 |
+
_score_apply(
|
| 1364 |
+
q, q, k, gam, h, F, Ss[0], u1, q, o1, o2, o3, dk, coeff_h,
|
| 1365 |
+
T, H, D, C, N, 0, 1, 0, 1, 0, 4, do_score=False,
|
| 1366 |
+
)
|
| 1367 |
+
_score_apply(
|
| 1368 |
+
o1, o1, k, gam, h, F, Ss[1], u2, q, o1, o2, o3, dk, coeff_h,
|
| 1369 |
+
T, H, D, C, N, 0, 1, 0, 1, 0, 4, do_score=False,
|
| 1370 |
+
)
|
| 1371 |
+
if N == 4:
|
| 1372 |
+
_score_apply(
|
| 1373 |
+
o2, o2, k, gam, h, F, Ss[2], u3, q, o1, o2, o3, dk, coeff_h,
|
| 1374 |
+
T, H, D, C, N, 0, 1, 0, 1, 0, 4, do_score=False,
|
| 1375 |
+
)
|
| 1376 |
+
diag_h = torch.empty(B, T, H, D, **f32)
|
| 1377 |
+
trace_bwd_diagh_kernel[grid](
|
| 1378 |
+
h, k, gam, diag_h,
|
| 1379 |
+
T, H, D, C, block_d, block_c,
|
| 1380 |
+
num_warps=4, num_stages=2,
|
| 1381 |
+
)
|
| 1382 |
+
trace_bwd_rev_kernel[grid](
|
| 1383 |
+
k, gam, dk, dgk, alpha, diag_h,
|
| 1384 |
+
T, H, D, C, block_d, block_c,
|
| 1385 |
+
num_warps=4, num_stages=2,
|
| 1386 |
+
)
|
| 1387 |
+
trace_bwd_gpartial_kernel[grid](
|
| 1388 |
+
gam, q, o1, o2, u1, u2, u3, alpha, g_partial,
|
| 1389 |
+
T, H, D, C, block_d, block_c, N, DOT_PRECISION,
|
| 1390 |
+
num_warps=4, num_stages=2,
|
| 1391 |
+
)
|
| 1392 |
+
block_s = _choose_scan_block(D)
|
| 1393 |
+
num_s = D // block_s
|
| 1394 |
+
dht_buf = dht.float().contiguous() if dht is not None else gin.new_empty(1)
|
| 1395 |
+
trace_bwd_scan_kernel[(B * H, num_s * num_s)](
|
| 1396 |
+
g_partial, gam, gin, dht_buf,
|
| 1397 |
+
T, nc, H, D, C, block_s, int(dht is not None),
|
| 1398 |
+
num_warps=4, num_stages=1,
|
| 1399 |
+
)
|
| 1400 |
+
if DOT_PRECISION == 0x100:
|
| 1401 |
+
_gin_into(h, k, gam, gin, dk, dgk, C)
|
| 1402 |
+
else:
|
| 1403 |
+
trace_bwd_gin_kernel[grid](
|
| 1404 |
+
h, k, gam, gin, dk, dgk,
|
| 1405 |
+
T, H, D, C, block_d, DOT_PRECISION, num_warps=8, num_stages=1,
|
| 1406 |
+
)
|
| 1407 |
+
dh0 = None
|
| 1408 |
+
if h0 is not None:
|
| 1409 |
+
e0 = gam[:, min(C, T) - 1].exp()
|
| 1410 |
+
dh0 = g_partial[:, 0] + e0[..., :, None] * gin[:, 0] * e0[..., None, :]
|
| 1411 |
+
dh0 = dh0.to(h0.dtype)
|
| 1412 |
+
return dq, dk, dgk, dcoeff_part, dh0
|
| 1413 |
+
|
| 1414 |
+
|
| 1415 |
+
class q_kkt_solve_trace_triton_seg(torch.autograd.Function):
|
| 1416 |
+
"""x, H_T = phi(q, k, gk) with F = tr(H) and per-dimension decay.
|
| 1417 |
+
|
| 1418 |
+
apply(k, q, gk, chunk_size, coeff, h0) -> (x [B, T, H, D], H_T [B, H, D, D])
|
| 1419 |
+
coeff is [N] or [H, N], N = 3 or 4. chunk_size must be 16, 32, or 64.
|
| 1420 |
+
"""
|
| 1421 |
+
|
| 1422 |
+
@staticmethod
|
| 1423 |
+
def forward(ctx, k, q, gk=None, chunk_size: int = 64, coeff=(1.0, -0.5, 0.375), h0=None):
|
| 1424 |
+
if q.ndim != 4:
|
| 1425 |
+
raise ValueError(f"q must be [B, T, H, D], got {tuple(q.shape)}")
|
| 1426 |
+
if chunk_size not in (16, 32, 64):
|
| 1427 |
+
raise ValueError(f"chunk_size must be 16, 32, or 64, got {chunk_size}")
|
| 1428 |
+
k = k.contiguous()
|
| 1429 |
+
q = q.contiguous()
|
| 1430 |
+
B, T, H, D = q.shape
|
| 1431 |
+
coeff_is_tensor = torch.is_tensor(coeff)
|
| 1432 |
+
coeff_shape = tuple(coeff.shape) if coeff_is_tensor else None
|
| 1433 |
+
coeff_dtype = coeff.dtype if coeff_is_tensor else None
|
| 1434 |
+
coeff_h = _normalize_coeff(coeff, H, q.device)
|
| 1435 |
+
n_coeff = coeff_h.shape[-1]
|
| 1436 |
+
|
| 1437 |
+
if gk is None:
|
| 1438 |
+
gam = torch.zeros(B, T, H, D, device=q.device, dtype=torch.float32)
|
| 1439 |
+
gk_arg = gv_arg = None
|
| 1440 |
+
else:
|
| 1441 |
+
gk = gk.contiguous()
|
| 1442 |
+
gam = chunk_local_cumsum(gk, chunk_size=chunk_size, scale=0.5, output_dtype=torch.float32)
|
| 1443 |
+
gk_arg = gv_arg = gam
|
| 1444 |
+
h, ht = chunk_fwd_h(
|
| 1445 |
+
k=k, v=k, gk=gk_arg, gv=gv_arg, h0=h0,
|
| 1446 |
+
output_final_state=True, chunk_size=chunk_size, states_in_fp32=True,
|
| 1447 |
+
)
|
| 1448 |
+
f32 = dict(device=q.device, dtype=torch.float32)
|
| 1449 |
+
o1 = torch.empty(B, T, H, D, **f32)
|
| 1450 |
+
o2 = torch.empty(B, T, H, D, **f32)
|
| 1451 |
+
o3 = torch.empty(B, T, H, D, **f32) if n_coeff == 4 else o2
|
| 1452 |
+
F = torch.empty(B, T, H, **f32)
|
| 1453 |
+
nc = triton.cdiv(T, chunk_size)
|
| 1454 |
+
grid = (nc, B * H)
|
| 1455 |
+
block_d = _choose_block_d(D)
|
| 1456 |
+
block_c = _choose_block_c(chunk_size)
|
| 1457 |
+
trace_fwd_f_kernel[grid](
|
| 1458 |
+
h, k, gam, F, T, H, D, chunk_size, block_d, block_c, EPS,
|
| 1459 |
+
num_warps=4, num_stages=2,
|
| 1460 |
+
)
|
| 1461 |
+
pairs = ((q, o1), (o1, o2))
|
| 1462 |
+
if n_coeff == 4:
|
| 1463 |
+
pairs = pairs + ((o2, o3),)
|
| 1464 |
+
S_saved = []
|
| 1465 |
+
for src, dst in pairs:
|
| 1466 |
+
S = torch.empty(nc, B * H, chunk_size, chunk_size, **f32)
|
| 1467 |
+
_score_apply(
|
| 1468 |
+
src, dst, k, gam, h, F, S, q, q, o1, o2, o3, q, coeff_h,
|
| 1469 |
+
T, H, D, chunk_size, n_coeff, 1, 0, 0, 0, 0, 2,
|
| 1470 |
+
)
|
| 1471 |
+
S_saved.append(S)
|
| 1472 |
+
c = coeff_h
|
| 1473 |
+
acc = c[:, 0].view(1, 1, H, 1) * q.float()
|
| 1474 |
+
acc = acc + c[:, 1].view(1, 1, H, 1) * o1
|
| 1475 |
+
acc = acc + c[:, 2].view(1, 1, H, 1) * o2
|
| 1476 |
+
if n_coeff == 4:
|
| 1477 |
+
acc = acc + c[:, 3].view(1, 1, H, 1) * o3
|
| 1478 |
+
x = acc.to(q.dtype)
|
| 1479 |
+
|
| 1480 |
+
saved = [k, q, o1, o2, F, coeff_h, h, gam]
|
| 1481 |
+
if n_coeff == 4:
|
| 1482 |
+
saved.append(o3)
|
| 1483 |
+
if gk is not None:
|
| 1484 |
+
saved.append(gk)
|
| 1485 |
+
if h0 is not None:
|
| 1486 |
+
saved.append(h0)
|
| 1487 |
+
saved.extend(S_saved)
|
| 1488 |
+
ctx.save_for_backward(*saved)
|
| 1489 |
+
ctx.chunk_size = chunk_size
|
| 1490 |
+
ctx.n_coeff = n_coeff
|
| 1491 |
+
ctx.has_gk = gk is not None
|
| 1492 |
+
ctx.has_h0 = h0 is not None
|
| 1493 |
+
ctx.coeff_is_tensor = coeff_is_tensor
|
| 1494 |
+
ctx.coeff_shape = coeff_shape
|
| 1495 |
+
ctx.coeff_dtype = coeff_dtype
|
| 1496 |
+
return x, ht
|
| 1497 |
+
|
| 1498 |
+
@staticmethod
|
| 1499 |
+
def backward(ctx, dx, dht=None):
|
| 1500 |
+
saved = list(ctx.saved_tensors)
|
| 1501 |
+
nS = ctx.n_coeff - 1
|
| 1502 |
+
Ss = saved[-nS:]
|
| 1503 |
+
saved = saved[:-nS]
|
| 1504 |
+
k, q, o1, o2, F, coeff_h, h, gam = saved[:8]
|
| 1505 |
+
idx = 8
|
| 1506 |
+
o3 = saved[idx] if ctx.n_coeff == 4 else None
|
| 1507 |
+
idx += int(ctx.n_coeff == 4)
|
| 1508 |
+
gk = saved[idx] if ctx.has_gk else None
|
| 1509 |
+
idx += int(ctx.has_gk)
|
| 1510 |
+
h0 = saved[idx] if ctx.has_h0 else None
|
| 1511 |
+
os_ = [o1, o2] + ([o3] if o3 is not None else [])
|
| 1512 |
+
dq, dk, dgk, dcoeff_part, dh0 = _bwd(
|
| 1513 |
+
k, q, os_, dx.contiguous(), F, coeff_h, gam, h,
|
| 1514 |
+
None if dht is None else dht.contiguous(), h0, ctx.chunk_size, ctx.n_coeff,
|
| 1515 |
+
Ss,
|
| 1516 |
+
)
|
| 1517 |
+
dcoeff = None
|
| 1518 |
+
if ctx.coeff_is_tensor and ctx.needs_input_grad[4]:
|
| 1519 |
+
dcoeff_h = dcoeff_part.sum(dim=(0, 1))
|
| 1520 |
+
if len(ctx.coeff_shape) == 1:
|
| 1521 |
+
dcoeff_h = dcoeff_h.sum(0)
|
| 1522 |
+
dcoeff = dcoeff_h.to(ctx.coeff_dtype).reshape(ctx.coeff_shape)
|
| 1523 |
+
dgk_out = dgk.to(gk.dtype) if gk is not None else None
|
| 1524 |
+
return dk.to(k.dtype), dq, dgk_out, None, dcoeff, dh0
|
rebased/naive.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def naive_parallel_rebased(
|
| 10 |
+
q: torch.Tensor,
|
| 11 |
+
k: torch.Tensor,
|
| 12 |
+
v: torch.Tensor,
|
| 13 |
+
scale: Optional[float] = None,
|
| 14 |
+
use_norm: bool = True,
|
| 15 |
+
) -> torch.Tensor:
|
| 16 |
+
if scale is None:
|
| 17 |
+
scale = q.shape[-1] ** -0.5
|
| 18 |
+
q = q * scale
|
| 19 |
+
attn = q @ k.transpose(-2, -1)
|
| 20 |
+
attn = attn ** 2
|
| 21 |
+
attn.masked_fill_(~torch.tril(torch.ones(q.shape[-2], q.shape[-2], dtype=torch.bool, device=q.device)), 0)
|
| 22 |
+
o = attn @ v
|
| 23 |
+
if use_norm:
|
| 24 |
+
z = attn.sum(-1)
|
| 25 |
+
return o / (z[..., None] + 1e-6)
|
| 26 |
+
else:
|
| 27 |
+
return o
|
rebased/parallel.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import triton
|
| 7 |
+
import triton.language as tl
|
| 8 |
+
|
| 9 |
+
from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
|
| 10 |
+
|
| 11 |
+
# Rebased: Linear Transformers with Learnable Kernel Functions are Better In-Context Models
|
| 12 |
+
# https://github.com/corl-team/rebased/blob/main/flash_linear_attention/fla/ops/triton/rebased_fast/parallel.py
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@triton.jit(do_not_specialize=['T'])
|
| 16 |
+
def parallel_rebased_fwd_kernel(
|
| 17 |
+
q,
|
| 18 |
+
k,
|
| 19 |
+
v,
|
| 20 |
+
o,
|
| 21 |
+
z,
|
| 22 |
+
scale,
|
| 23 |
+
T,
|
| 24 |
+
B: tl.constexpr,
|
| 25 |
+
H: tl.constexpr,
|
| 26 |
+
K: tl.constexpr,
|
| 27 |
+
V: tl.constexpr,
|
| 28 |
+
BTL: tl.constexpr,
|
| 29 |
+
BTS: tl.constexpr,
|
| 30 |
+
BK: tl.constexpr,
|
| 31 |
+
BV: tl.constexpr,
|
| 32 |
+
):
|
| 33 |
+
# i_c: chunk index. used for sequence parallelism
|
| 34 |
+
i_kv, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 35 |
+
NV = tl.cdiv(V, BV)
|
| 36 |
+
i_k = i_kv // (NV)
|
| 37 |
+
i_v = i_kv % (NV)
|
| 38 |
+
|
| 39 |
+
p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (i_c*BTL, i_k*BK), (BTL, BK), (1, 0))
|
| 40 |
+
p_k = tl.make_block_ptr(k + i_bh * T*K, (K, T), (1, K), (i_k*BK, 0), (BK, BTS), (0, 1))
|
| 41 |
+
p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (0, i_v*BV), (BTS, BV), (1, 0))
|
| 42 |
+
|
| 43 |
+
# [BQ, BD] block Q, in the shared memory throughout the whole kernel
|
| 44 |
+
b_q = tl.load(p_q, boundary_check=(0, 1))
|
| 45 |
+
b_q = (b_q * scale).to(b_q.dtype)
|
| 46 |
+
b_o = tl.zeros([BTL, BV], dtype=tl.float32)
|
| 47 |
+
b_z = tl.zeros([BTL], dtype=tl.float32)
|
| 48 |
+
|
| 49 |
+
# Q block and K block have no overlap
|
| 50 |
+
# no need for mask, thereby saving flops
|
| 51 |
+
for _ in range(0, i_c*BTL, BTS):
|
| 52 |
+
# [BK, BTS]
|
| 53 |
+
b_k = tl.load(p_k, boundary_check=(0, 1))
|
| 54 |
+
|
| 55 |
+
# [BTS, BV]
|
| 56 |
+
b_v = tl.load(p_v, boundary_check=(0, 1))
|
| 57 |
+
# [BTL, BTS]
|
| 58 |
+
b_s = tl.dot(b_q, (b_k), allow_tf32=False)
|
| 59 |
+
b_s = b_s * b_s
|
| 60 |
+
b_z += tl.sum(b_s, axis=1)
|
| 61 |
+
|
| 62 |
+
# [BQ, BD]
|
| 63 |
+
b_o = b_o + tl.dot(b_s.to(b_v.dtype), b_v, allow_tf32=False)
|
| 64 |
+
p_k = tl.advance(p_k, (0, BTS))
|
| 65 |
+
p_v = tl.advance(p_v, (BTS, 0))
|
| 66 |
+
|
| 67 |
+
# # rescale interchunk output
|
| 68 |
+
tl.debug_barrier()
|
| 69 |
+
o_q = tl.arange(0, BTL)
|
| 70 |
+
# # sync threads, easy for compiler to optimize
|
| 71 |
+
# tl.debug_barrier()
|
| 72 |
+
|
| 73 |
+
o_k = tl.arange(0, BTS)
|
| 74 |
+
p_k = tl.make_block_ptr(k + i_bh * T*K, (K, T), (1, K), (i_k*BK, i_c*BTL), (BK, BTS), (0, 1))
|
| 75 |
+
p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_c*BTL, i_v*BV), (BTS, BV), (1, 0))
|
| 76 |
+
# Q block and K block have overlap. masks required
|
| 77 |
+
for _ in range(i_c*BTL, (i_c + 1) * BTL, BTS):
|
| 78 |
+
# [BK, BTS]
|
| 79 |
+
b_k = tl.load(p_k, boundary_check=(0, 1))
|
| 80 |
+
# [BTS, BV]
|
| 81 |
+
b_v = tl.load(p_v, boundary_check=(0, 1))
|
| 82 |
+
# [BTL, BTS]
|
| 83 |
+
m_s = o_q[:, None] >= o_k[None, :]
|
| 84 |
+
b_s = tl.dot(b_q, b_k, allow_tf32=False)
|
| 85 |
+
b_s = b_s * b_s
|
| 86 |
+
b_s = tl.where(m_s, b_s, 0)
|
| 87 |
+
b_z += tl.sum(b_s, axis=1)
|
| 88 |
+
# [BTL, BV]
|
| 89 |
+
b_o += tl.dot(b_s.to(b_q.dtype), b_v, allow_tf32=False)
|
| 90 |
+
p_k = tl.advance(p_k, (0, BTS))
|
| 91 |
+
p_v = tl.advance(p_v, (BTS, 0))
|
| 92 |
+
o_k += BTS
|
| 93 |
+
|
| 94 |
+
p_o = tl.make_block_ptr(o + (i_bh + B * H * i_k) * T*V, (T, V), (V, 1), (i_c*BTL, i_v*BV), (BTL, BV), (1, 0))
|
| 95 |
+
p_z = z + (i_bh + B * H * i_k) * T + i_c*BTL + tl.arange(0, BTL)
|
| 96 |
+
tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
|
| 97 |
+
tl.store(p_z, b_z.to(p_z.dtype.element_ty), mask=((i_c*BTL + tl.arange(0, BTL)) < T))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@triton.jit(do_not_specialize=['T'])
|
| 101 |
+
def _parallel_rebased_bwd_dq(
|
| 102 |
+
i_bh,
|
| 103 |
+
i_c,
|
| 104 |
+
i_k,
|
| 105 |
+
i_v,
|
| 106 |
+
i_h,
|
| 107 |
+
q,
|
| 108 |
+
k,
|
| 109 |
+
v,
|
| 110 |
+
do,
|
| 111 |
+
dz,
|
| 112 |
+
dq,
|
| 113 |
+
scale,
|
| 114 |
+
T,
|
| 115 |
+
B: tl.constexpr,
|
| 116 |
+
H: tl.constexpr,
|
| 117 |
+
K: tl.constexpr,
|
| 118 |
+
V: tl.constexpr,
|
| 119 |
+
BTL: tl.constexpr,
|
| 120 |
+
BTS: tl.constexpr,
|
| 121 |
+
BK: tl.constexpr,
|
| 122 |
+
BV: tl.constexpr
|
| 123 |
+
):
|
| 124 |
+
p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i_c*BTL, i_v*BV), (BTL, BV), (1, 0))
|
| 125 |
+
p_q = tl.make_block_ptr(q + (i_bh) * T*K, (T, K), (K, 1), (i_c*BTL, i_k*BK), (BTL, BK), (1, 0))
|
| 126 |
+
b_q = tl.load(p_q, boundary_check=(0, 1))
|
| 127 |
+
b_do = tl.load(p_do, boundary_check=(0, 1)).to(b_q.dtype)
|
| 128 |
+
b_q = (b_q * scale).to(b_q.dtype)
|
| 129 |
+
b_dq = tl.zeros([BTL, BK], dtype=tl.float32)
|
| 130 |
+
p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (0, i_k*BK), (BTS, BK), (1, 0))
|
| 131 |
+
p_v = tl.make_block_ptr(v + i_bh * T*V, (V, T), (1, V), (i_v*BV, 0), (BV, BTS), (0, 1))
|
| 132 |
+
p_dz = dz + i_bh * T + i_c*BTL + tl.arange(0, BTL)
|
| 133 |
+
b_dz = tl.load(p_dz, mask=(i_c*BTL + tl.arange(0, BTL)) < T)
|
| 134 |
+
|
| 135 |
+
for _ in range(0, i_c*BTL, BTS):
|
| 136 |
+
# [BTS, BK]
|
| 137 |
+
b_k = tl.load(p_k, boundary_check=(0, 1))
|
| 138 |
+
# [BV, BTS]
|
| 139 |
+
b_v = tl.load(p_v, boundary_check=(0, 1))
|
| 140 |
+
# [BTL, BTS]
|
| 141 |
+
b_ds = tl.dot(b_do, b_v, allow_tf32=False)
|
| 142 |
+
if i_v == 0:
|
| 143 |
+
b_ds += b_dz[:, None]
|
| 144 |
+
else:
|
| 145 |
+
b_ds = b_ds
|
| 146 |
+
b_s = tl.dot(b_q, tl.trans(b_k), allow_tf32=False)
|
| 147 |
+
# [BQ, BD]
|
| 148 |
+
b_dq += tl.dot((2 * b_ds * b_s).to(b_v.dtype), b_k, allow_tf32=False)
|
| 149 |
+
p_k = tl.advance(p_k, (BTS, 0))
|
| 150 |
+
p_v = tl.advance(p_v, (0, BTS))
|
| 151 |
+
|
| 152 |
+
b_dq *= scale
|
| 153 |
+
o_q = tl.arange(0, BTL)
|
| 154 |
+
o_k = tl.arange(0, BTS)
|
| 155 |
+
p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_c*BTL, i_k*BK), (BTS, BK), (1, 0))
|
| 156 |
+
p_v = tl.make_block_ptr(v + i_bh * T*V, (V, T), (1, V), (i_v*BV, i_c*BTL), (BV, BTS), (0, 1))
|
| 157 |
+
# Q block and K block have overlap. masks required
|
| 158 |
+
for _ in range(i_c*BTL, (i_c + 1) * BTL, BTS):
|
| 159 |
+
# [BTS, BK]
|
| 160 |
+
b_k = tl.load(p_k, boundary_check=(0, 1))
|
| 161 |
+
# [BV, BTS]
|
| 162 |
+
b_v = tl.load(p_v, boundary_check=(0, 1))
|
| 163 |
+
# [BTL, BTS]
|
| 164 |
+
m_s = o_q[:, None] >= o_k[None, :]
|
| 165 |
+
b_ds = tl.dot(b_do, b_v, allow_tf32=False)
|
| 166 |
+
if i_v == 0:
|
| 167 |
+
b_ds += b_dz[:, None]
|
| 168 |
+
else:
|
| 169 |
+
b_ds = b_ds
|
| 170 |
+
b_ds = tl.where(m_s, b_ds, 0) * scale
|
| 171 |
+
b_s = tl.dot(b_q, tl.trans(b_k), allow_tf32=False)
|
| 172 |
+
b_s = tl.where(m_s, b_s, 0)
|
| 173 |
+
# [BTL, BK]
|
| 174 |
+
b_dq += tl.dot((2 * b_ds * b_s).to(b_k.dtype),
|
| 175 |
+
b_k, allow_tf32=False)
|
| 176 |
+
p_k = tl.advance(p_k, (BTS, 0))
|
| 177 |
+
p_v = tl.advance(p_v, (0, BTS))
|
| 178 |
+
o_k += BTS
|
| 179 |
+
p_dq = tl.make_block_ptr(dq + (i_bh + B * H * i_v) * T*K, (T, K), (K, 1), (i_c*BTL, i_k*BK), (BTL, BK), (1, 0))
|
| 180 |
+
tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
|
| 181 |
+
return
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@triton.jit(do_not_specialize=['T'])
|
| 185 |
+
def _parallel_rebased_bwd_dkv(
|
| 186 |
+
i_bh,
|
| 187 |
+
i_c,
|
| 188 |
+
i_k,
|
| 189 |
+
i_v,
|
| 190 |
+
i_h,
|
| 191 |
+
q,
|
| 192 |
+
k,
|
| 193 |
+
v,
|
| 194 |
+
do,
|
| 195 |
+
dz,
|
| 196 |
+
dk,
|
| 197 |
+
dv,
|
| 198 |
+
scale,
|
| 199 |
+
T,
|
| 200 |
+
B: tl.constexpr,
|
| 201 |
+
H: tl.constexpr,
|
| 202 |
+
K: tl.constexpr,
|
| 203 |
+
V: tl.constexpr,
|
| 204 |
+
BTL: tl.constexpr,
|
| 205 |
+
BTS: tl.constexpr,
|
| 206 |
+
BK: tl.constexpr,
|
| 207 |
+
BV: tl.constexpr,
|
| 208 |
+
):
|
| 209 |
+
# compute dk dv
|
| 210 |
+
p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_c*BTL, i_k*BK), (BTL, BK), (1, 0))
|
| 211 |
+
p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_c*BTL, i_v*BV), (BTL, BV), (1, 0))
|
| 212 |
+
b_k, b_v = tl.load(p_k, boundary_check=(0, 1)), tl.load(p_v, boundary_check=(0, 1))
|
| 213 |
+
b_dk, b_dv = tl.zeros([BTL, BK], dtype=tl.float32), tl.zeros(
|
| 214 |
+
[BTL, BV], dtype=tl.float32)
|
| 215 |
+
|
| 216 |
+
for i in range((tl.cdiv(T, BTS) * BTS)-BTS, (i_c + 1) * BTL - BTS, -BTS):
|
| 217 |
+
p_q = tl.make_block_ptr(q + i_bh * T*K, (K, T), (1, K), (i_k*BK, i), (BK, BTS), (0, 1))
|
| 218 |
+
p_do = tl.make_block_ptr(do + i_bh * T*V, (V, T), (1, V), (i_v*BV, i), (BV, BTS), (0, 1))
|
| 219 |
+
p_dz = dz + i_bh * T + i + tl.arange(0, BTS)
|
| 220 |
+
# [BK, BTS]
|
| 221 |
+
b_q = tl.load(p_q, boundary_check=(0, 1))
|
| 222 |
+
# [BV, BTS]
|
| 223 |
+
b_do = tl.load(p_do, boundary_check=(0, 1)).to(b_q.dtype)
|
| 224 |
+
b_dz = tl.load(p_dz, mask=(i + tl.arange(0, BTS)) < T)
|
| 225 |
+
# [BTL, BTS]
|
| 226 |
+
b_s = tl.dot(b_k.to(b_q.dtype), b_q, allow_tf32=False) * scale
|
| 227 |
+
b_s2 = b_s * b_s
|
| 228 |
+
b_dv += tl.dot(b_s2.to(b_q.dtype), tl.trans(b_do), allow_tf32=False)
|
| 229 |
+
b_ds = tl.dot(b_v, b_do, allow_tf32=False) * scale
|
| 230 |
+
if i_v == 0:
|
| 231 |
+
b_ds += b_dz[None, :] * scale
|
| 232 |
+
else:
|
| 233 |
+
b_ds = b_ds
|
| 234 |
+
b_dk += tl.dot((2 * b_ds * b_s).to(b_q.dtype), tl.trans(b_q), allow_tf32=False)
|
| 235 |
+
|
| 236 |
+
tl.debug_barrier()
|
| 237 |
+
o_q, o_k = tl.arange(0, BTS), tl.arange(0, BTL)
|
| 238 |
+
for i in range(i_c*BTL, (i_c+1)*BTL, BTS):
|
| 239 |
+
p_q = tl.make_block_ptr(q + i_bh * T*K, (K, T), (1, K), (i_k*BK, i), (BK, BTS), (0, 1))
|
| 240 |
+
p_do = tl.make_block_ptr(do + i_bh * T*V, (V, T), (1, V), (i_v*BV, i), (BV, BTS), (0, 1))
|
| 241 |
+
p_dz = dz + i_bh * T + i + tl.arange(0, BTS)
|
| 242 |
+
b_q = tl.load(p_q, boundary_check=(0, 1)) # [BD, BQ]
|
| 243 |
+
b_do = tl.load(p_do, boundary_check=(0, 1)).to(b_q.dtype)
|
| 244 |
+
b_dz = tl.load(p_dz, mask=(i + tl.arange(0, BTS)) < T)
|
| 245 |
+
# [BK, BQ]
|
| 246 |
+
m_s = o_k[:, None] <= o_q[None, :]
|
| 247 |
+
b_s = tl.dot(b_k, b_q, allow_tf32=False) * scale
|
| 248 |
+
b_s2 = b_s * b_s
|
| 249 |
+
b_s = tl.where(m_s, b_s, 0)
|
| 250 |
+
b_s2 = tl.where(m_s, b_s2, 0)
|
| 251 |
+
|
| 252 |
+
b_ds = tl.dot(b_v, b_do, allow_tf32=False)
|
| 253 |
+
if i_v == 0:
|
| 254 |
+
b_ds += b_dz[None, :]
|
| 255 |
+
else:
|
| 256 |
+
b_ds = b_ds
|
| 257 |
+
b_ds = tl.where(m_s, b_ds, 0) * scale
|
| 258 |
+
# [BK, BD]
|
| 259 |
+
b_dv += tl.dot(b_s2.to(b_q.dtype), tl.trans(b_do), allow_tf32=False)
|
| 260 |
+
b_dk += tl.dot((2 * b_ds * b_s).to(b_q.dtype), tl.trans(b_q), allow_tf32=False)
|
| 261 |
+
o_q += BTS
|
| 262 |
+
|
| 263 |
+
p_dk = tl.make_block_ptr(dk + (i_bh + B * H * i_v) * T*K, (T, K), (K, 1), (i_c*BTL, i_k*BK), (BTL, BK), (1, 0))
|
| 264 |
+
p_dv = tl.make_block_ptr(dv + (i_bh + B * H * i_k) * T*V, (T, V), (V, 1), (i_c*BTL, i_v*BV), (BTL, BV), (1, 0))
|
| 265 |
+
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
|
| 266 |
+
tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
|
| 267 |
+
return
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@triton.jit(do_not_specialize=['T'])
|
| 271 |
+
def parallel_rebased_bwd_kernel(
|
| 272 |
+
q,
|
| 273 |
+
k,
|
| 274 |
+
v,
|
| 275 |
+
do,
|
| 276 |
+
dz,
|
| 277 |
+
dq,
|
| 278 |
+
dk,
|
| 279 |
+
dv,
|
| 280 |
+
scale,
|
| 281 |
+
T,
|
| 282 |
+
B: tl.constexpr,
|
| 283 |
+
H: tl.constexpr,
|
| 284 |
+
K: tl.constexpr,
|
| 285 |
+
V: tl.constexpr,
|
| 286 |
+
BTL: tl.constexpr,
|
| 287 |
+
BTS: tl.constexpr,
|
| 288 |
+
BK: tl.constexpr,
|
| 289 |
+
BV: tl.constexpr
|
| 290 |
+
):
|
| 291 |
+
i_kv, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 292 |
+
NV = tl.cdiv(V, BV)
|
| 293 |
+
i_k = i_kv // (NV)
|
| 294 |
+
i_v = i_kv % (NV)
|
| 295 |
+
i_h = i_bh % H
|
| 296 |
+
_parallel_rebased_bwd_dq(
|
| 297 |
+
i_bh,
|
| 298 |
+
i_c,
|
| 299 |
+
i_k,
|
| 300 |
+
i_v,
|
| 301 |
+
i_h,
|
| 302 |
+
q,
|
| 303 |
+
k,
|
| 304 |
+
v,
|
| 305 |
+
do,
|
| 306 |
+
dz,
|
| 307 |
+
dq,
|
| 308 |
+
scale,
|
| 309 |
+
B=B,
|
| 310 |
+
H=H,
|
| 311 |
+
T=T,
|
| 312 |
+
K=K,
|
| 313 |
+
V=V,
|
| 314 |
+
BTL=BTL,
|
| 315 |
+
BTS=BTS,
|
| 316 |
+
BK=BK,
|
| 317 |
+
BV=BV
|
| 318 |
+
)
|
| 319 |
+
tl.debug_barrier()
|
| 320 |
+
_parallel_rebased_bwd_dkv(
|
| 321 |
+
i_bh,
|
| 322 |
+
i_c,
|
| 323 |
+
i_k,
|
| 324 |
+
i_v,
|
| 325 |
+
i_h,
|
| 326 |
+
q,
|
| 327 |
+
k,
|
| 328 |
+
v,
|
| 329 |
+
do,
|
| 330 |
+
dz,
|
| 331 |
+
dk,
|
| 332 |
+
dv,
|
| 333 |
+
scale,
|
| 334 |
+
B=B,
|
| 335 |
+
H=H,
|
| 336 |
+
T=T,
|
| 337 |
+
K=K,
|
| 338 |
+
V=V,
|
| 339 |
+
BTL=BTL,
|
| 340 |
+
BTS=BTS,
|
| 341 |
+
BK=BK,
|
| 342 |
+
BV=BV
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class ParallelBasedFunction(torch.autograd.Function):
|
| 347 |
+
|
| 348 |
+
@staticmethod
|
| 349 |
+
@input_guard
|
| 350 |
+
@autocast_custom_fwd
|
| 351 |
+
def forward(ctx, q, k, v, scale):
|
| 352 |
+
BTL, BTS = 128, 32
|
| 353 |
+
assert BTL % BTS == 0
|
| 354 |
+
# assert q.shape[-1] % 16 == 0
|
| 355 |
+
BK = min(128, max(triton.next_power_of_2(k.shape[-1]), 16))
|
| 356 |
+
BV = min(128, max(triton.next_power_of_2(v.shape[-1]), 16))
|
| 357 |
+
B, H, T, K, V = *k.shape, v.shape[-1]
|
| 358 |
+
num_stages = 2
|
| 359 |
+
num_warps = 4
|
| 360 |
+
NK = triton.cdiv(K, BK)
|
| 361 |
+
NV = triton.cdiv(V, BV)
|
| 362 |
+
grid = (NK * NV, triton.cdiv(T, BTL), B * H)
|
| 363 |
+
|
| 364 |
+
assert NK == 1, "will encounter some synchronization issue if not."
|
| 365 |
+
|
| 366 |
+
o = torch.empty(NK, B, H, T, V, device=q.device)
|
| 367 |
+
z = torch.empty(NK, B, H, T, device=q.device)
|
| 368 |
+
parallel_rebased_fwd_kernel[grid](
|
| 369 |
+
q,
|
| 370 |
+
k,
|
| 371 |
+
v,
|
| 372 |
+
o,
|
| 373 |
+
z,
|
| 374 |
+
scale,
|
| 375 |
+
T=T,
|
| 376 |
+
B=B,
|
| 377 |
+
H=H,
|
| 378 |
+
K=K,
|
| 379 |
+
V=V,
|
| 380 |
+
BTL=BTL,
|
| 381 |
+
BTS=BTS,
|
| 382 |
+
BK=BK,
|
| 383 |
+
BV=BV,
|
| 384 |
+
num_warps=num_warps,
|
| 385 |
+
num_stages=num_stages
|
| 386 |
+
)
|
| 387 |
+
ctx.save_for_backward(q, k, v)
|
| 388 |
+
ctx.scale = scale
|
| 389 |
+
return o.sum(0).to(q.dtype), z.sum(0).to(q.dtype)
|
| 390 |
+
|
| 391 |
+
@staticmethod
|
| 392 |
+
@input_guard
|
| 393 |
+
@autocast_custom_bwd
|
| 394 |
+
def backward(ctx, do, dz):
|
| 395 |
+
q, k, v = ctx.saved_tensors
|
| 396 |
+
scale = ctx.scale
|
| 397 |
+
BTL, BTS = 64, 32
|
| 398 |
+
assert BTL % BTS == 0
|
| 399 |
+
BK = min(128, max(triton.next_power_of_2(k.shape[-1]), 16))
|
| 400 |
+
BV = min(128, max(triton.next_power_of_2(v.shape[-1]), 16))
|
| 401 |
+
B, H, T, K, V = *k.shape, v.shape[-1]
|
| 402 |
+
num_stages = 2
|
| 403 |
+
num_warps = 4
|
| 404 |
+
NK = triton.cdiv(K, BK)
|
| 405 |
+
NV = triton.cdiv(V, BV)
|
| 406 |
+
grid = (NK * NV, triton.cdiv(T, BTL), B * H)
|
| 407 |
+
|
| 408 |
+
assert NK == 1, "will encounter some synchronization issue if not"
|
| 409 |
+
|
| 410 |
+
dq = torch.empty(NV, B, H, T, K, dtype=q.dtype, device=q.device)
|
| 411 |
+
dk = torch.empty(NV, B, H, T, K, dtype=q.dtype, device=q.device)
|
| 412 |
+
dv = torch.empty(NK, B, H, T, V, dtype=q.dtype, device=q.device)
|
| 413 |
+
|
| 414 |
+
parallel_rebased_bwd_kernel[grid](
|
| 415 |
+
q,
|
| 416 |
+
k,
|
| 417 |
+
v,
|
| 418 |
+
do,
|
| 419 |
+
dz,
|
| 420 |
+
dq,
|
| 421 |
+
dk,
|
| 422 |
+
dv,
|
| 423 |
+
scale,
|
| 424 |
+
T=T,
|
| 425 |
+
B=B,
|
| 426 |
+
H=H,
|
| 427 |
+
K=K,
|
| 428 |
+
V=V,
|
| 429 |
+
BTL=BTL,
|
| 430 |
+
BTS=BTS,
|
| 431 |
+
BK=BK,
|
| 432 |
+
BV=BV,
|
| 433 |
+
num_warps=num_warps,
|
| 434 |
+
num_stages=num_stages
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
return dq.sum(0).to(q.dtype), dk.sum(0).to(k.dtype), dv.sum(0).to(v.dtype), None
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def parallel_rebased(
|
| 441 |
+
q: torch.Tensor,
|
| 442 |
+
k: torch.Tensor,
|
| 443 |
+
v: torch.Tensor,
|
| 444 |
+
eps: float = 1e-5,
|
| 445 |
+
use_scale: bool = True,
|
| 446 |
+
use_normalize: bool = True,
|
| 447 |
+
return_both: bool = False,
|
| 448 |
+
head_first: bool = False
|
| 449 |
+
):
|
| 450 |
+
assert q.shape[-1] <= 128, "only support feature dim up to 128"
|
| 451 |
+
if use_scale:
|
| 452 |
+
scale = q.shape[-1] ** -0.5
|
| 453 |
+
else:
|
| 454 |
+
scale = 1
|
| 455 |
+
if not head_first:
|
| 456 |
+
q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
|
| 457 |
+
o, z = ParallelBasedFunction.apply(q, k, v, scale)
|
| 458 |
+
if return_both:
|
| 459 |
+
return o, z
|
| 460 |
+
if use_normalize:
|
| 461 |
+
o = o / (z[..., None] + eps)
|
| 462 |
+
if not head_first:
|
| 463 |
+
o = o.transpose(1, 2)
|
| 464 |
+
return o.to(q.dtype)
|
retention/chunk.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from fla.ops.simple_gla.chunk import chunk_simple_gla
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@torch.compiler.disable
|
| 13 |
+
def chunk_retention(
|
| 14 |
+
q: torch.Tensor,
|
| 15 |
+
k: torch.Tensor,
|
| 16 |
+
v: torch.Tensor,
|
| 17 |
+
scale: Optional[float] = None,
|
| 18 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 19 |
+
output_final_state: bool = False,
|
| 20 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 21 |
+
head_first: bool = False
|
| 22 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 23 |
+
r"""
|
| 24 |
+
Args:
|
| 25 |
+
q (torch.Tensor):
|
| 26 |
+
queries of shape `[B, T, H, K]`.
|
| 27 |
+
k (torch.Tensor):
|
| 28 |
+
keys of shape `[B, T, H, K]`.
|
| 29 |
+
v (torch.Tensor):
|
| 30 |
+
values of shape `[B, T, H, V]`.
|
| 31 |
+
scale (Optional[float]):
|
| 32 |
+
Scale factor for the attention scores.
|
| 33 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
| 34 |
+
initial_state (Optional[torch.Tensor]):
|
| 35 |
+
Initial state of shape `[N, H, K, V]` for `N` input sequences.
|
| 36 |
+
For equal-length input sequences, `N` equals the batch size `B`.
|
| 37 |
+
Default: `None`.
|
| 38 |
+
output_final_state (Optional[bool]):
|
| 39 |
+
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
|
| 40 |
+
cu_seqlens (torch.LongTensor):
|
| 41 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 42 |
+
consistent with the FlashAttention API.
|
| 43 |
+
head_first (Optional[bool]):
|
| 44 |
+
Whether the inputs are in the head-first format. Default: `False`.
|
| 45 |
+
This argument has been deprecated.
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
o (torch.Tensor):
|
| 49 |
+
Outputs of shape `[B, T, H, V]`.
|
| 50 |
+
final_state (torch.Tensor):
|
| 51 |
+
Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
if head_first:
|
| 55 |
+
raise DeprecationWarning(
|
| 56 |
+
"head_first is deprecated and will be removed in a future version. "
|
| 57 |
+
"Please use head_first=False for now instead."
|
| 58 |
+
)
|
| 59 |
+
if not head_first and q.shape[1] < q.shape[2]:
|
| 60 |
+
warnings.warn(
|
| 61 |
+
f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
|
| 62 |
+
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
|
| 63 |
+
"when head_first=False was specified. "
|
| 64 |
+
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
|
| 65 |
+
)
|
| 66 |
+
g_gamma = (1 - q.new_tensor(2., dtype=torch.float).pow(-5. - q.new_tensor(range(q.shape[2]), dtype=torch.float))).log()
|
| 67 |
+
o, final_state = chunk_simple_gla(
|
| 68 |
+
q=q,
|
| 69 |
+
k=k,
|
| 70 |
+
v=v,
|
| 71 |
+
scale=scale,
|
| 72 |
+
g_gamma=g_gamma,
|
| 73 |
+
initial_state=initial_state,
|
| 74 |
+
output_final_state=output_final_state,
|
| 75 |
+
cu_seqlens=cu_seqlens
|
| 76 |
+
)
|
| 77 |
+
return o, final_state
|
retention/fused_chunk.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from fla.ops.simple_gla import fused_chunk_simple_gla
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@torch.compiler.disable
|
| 13 |
+
def fused_chunk_retention(
|
| 14 |
+
q: torch.Tensor,
|
| 15 |
+
k: torch.Tensor,
|
| 16 |
+
v: torch.Tensor,
|
| 17 |
+
scale: Optional[float] = None,
|
| 18 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 19 |
+
output_final_state: bool = False,
|
| 20 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 21 |
+
head_first: bool = False,
|
| 22 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 23 |
+
r"""
|
| 24 |
+
Args:
|
| 25 |
+
q (torch.Tensor):
|
| 26 |
+
queries of shape `[B, T, H, K]`.
|
| 27 |
+
k (torch.Tensor):
|
| 28 |
+
keys of shape `[B, T, H, K]`.
|
| 29 |
+
v (torch.Tensor):
|
| 30 |
+
values of shape `[B, T, H, V]`.
|
| 31 |
+
scale (Optional[float]):
|
| 32 |
+
Scale factor for the attention scores.
|
| 33 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
| 34 |
+
initial_state (Optional[torch.Tensor]):
|
| 35 |
+
Initial state of shape `[N, H, K, V]` for `N` input sequences.
|
| 36 |
+
For equal-length input sequences, `N` equals the batch size `B`.
|
| 37 |
+
Default: `None`.
|
| 38 |
+
output_final_state (Optional[bool]):
|
| 39 |
+
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
|
| 40 |
+
cu_seqlens (torch.LongTensor):
|
| 41 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 42 |
+
consistent with the FlashAttention API.
|
| 43 |
+
head_first (Optional[bool]):
|
| 44 |
+
Whether the inputs are in the head-first format.
|
| 45 |
+
Default: `False`.
|
| 46 |
+
This argument has been deprecated.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
o (torch.Tensor):
|
| 50 |
+
Outputs of shape `[B, T, H, V]`.
|
| 51 |
+
final_state (torch.Tensor):
|
| 52 |
+
Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
if head_first:
|
| 56 |
+
raise DeprecationWarning(
|
| 57 |
+
"head_first is deprecated and will be removed in a future version. "
|
| 58 |
+
"Please use head_first=False for now instead."
|
| 59 |
+
)
|
| 60 |
+
if not head_first and q.shape[1] < q.shape[2]:
|
| 61 |
+
warnings.warn(
|
| 62 |
+
f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
|
| 63 |
+
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
|
| 64 |
+
"when head_first=False was specified. "
|
| 65 |
+
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
|
| 66 |
+
)
|
| 67 |
+
g_gamma = (1 - q.new_tensor(2., dtype=torch.float).pow(-5. - q.new_tensor(range(q.shape[2]), dtype=torch.float))).log()
|
| 68 |
+
o, final_state = fused_chunk_simple_gla(
|
| 69 |
+
q=q,
|
| 70 |
+
k=k,
|
| 71 |
+
v=v,
|
| 72 |
+
g_gamma=g_gamma,
|
| 73 |
+
scale=scale,
|
| 74 |
+
initial_state=initial_state,
|
| 75 |
+
output_final_state=output_final_state,
|
| 76 |
+
cu_seqlens=cu_seqlens
|
| 77 |
+
)
|
| 78 |
+
return o, final_state
|
retention/naive.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def naive_retention(q, k, v):
|
| 7 |
+
orig_type = q.dtype
|
| 8 |
+
q, k, v = q.float(), k.float(), v.float()
|
| 9 |
+
_, n_heads, seq_len, d_head = q.shape
|
| 10 |
+
s = (1 - q.new_tensor(2., dtype=torch.float).pow(-5. - q.new_tensor(range(n_heads), dtype=torch.float))).log2()
|
| 11 |
+
n = q.new_tensor(range(seq_len), dtype=torch.float)
|
| 12 |
+
n = torch.exp2((n.unsqueeze(-1) - n) * s.view(-1, 1, 1)) * n.unsqueeze(-1).ge(n)
|
| 13 |
+
s = torch.einsum('bhqd,bhkd,hqk->bhqk', q * d_head ** -0.5, k, n.to(q.dtype))
|
| 14 |
+
o = torch.einsum('bhqk,bhkd->bhqd', s, v)
|
| 15 |
+
return o.to(orig_type)
|
retention/parallel.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from fla.ops.simple_gla.parallel import parallel_simple_gla
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parallel_retention(
|
| 13 |
+
q: torch.Tensor,
|
| 14 |
+
k: torch.Tensor,
|
| 15 |
+
v: torch.Tensor,
|
| 16 |
+
scale: Optional[float] = None,
|
| 17 |
+
output_attentions: bool = False,
|
| 18 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 19 |
+
head_first: bool = False
|
| 20 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 21 |
+
r"""
|
| 22 |
+
Args:
|
| 23 |
+
q (torch.Tensor):
|
| 24 |
+
queries of shape `[B, T, H, K]`.
|
| 25 |
+
k (torch.Tensor):
|
| 26 |
+
keys of shape `[B, T, H, K]`.
|
| 27 |
+
v (torch.Tensor):
|
| 28 |
+
values of shape `[B, T, H, V]`.
|
| 29 |
+
scale (Optional[float]):
|
| 30 |
+
Scale factor for attention scores.
|
| 31 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
| 32 |
+
output_attentions (bool):
|
| 33 |
+
Whether to output the materialized attention scores of shape [B, H, T, T]. Default: `False`.
|
| 34 |
+
cu_seqlens (torch.LongTensor):
|
| 35 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 36 |
+
consistent with the FlashAttention API.
|
| 37 |
+
head_first (Optional[bool]):
|
| 38 |
+
Whether the inputs are in the head-first format. Default: `False`.
|
| 39 |
+
This argument has been deprecated.
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
o (torch.Tensor):
|
| 43 |
+
Outputs of shape `[B, T, H, V]`.
|
| 44 |
+
attn (torch.Tensor):
|
| 45 |
+
Attention scores of shape `[B, H, T, T]` if `output_attentions=True` else `None`
|
| 46 |
+
"""
|
| 47 |
+
if head_first:
|
| 48 |
+
raise DeprecationWarning(
|
| 49 |
+
"head_first is deprecated and will be removed in a future version. "
|
| 50 |
+
"Please use head_first=False for now instead."
|
| 51 |
+
)
|
| 52 |
+
if not head_first and q.shape[1] < q.shape[2]:
|
| 53 |
+
warnings.warn(
|
| 54 |
+
f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
|
| 55 |
+
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
|
| 56 |
+
"when head_first=False was specified. "
|
| 57 |
+
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
|
| 58 |
+
)
|
| 59 |
+
s = (1 - q.new_tensor(2., dtype=torch.float).pow(-5. - q.new_tensor(range(q.shape[2]), dtype=torch.float))).log()
|
| 60 |
+
g = s[None, None, :].expand(q.shape[0], q.shape[1], q.shape[2])
|
| 61 |
+
|
| 62 |
+
o, attn = parallel_simple_gla(
|
| 63 |
+
q=q,
|
| 64 |
+
k=k,
|
| 65 |
+
v=v,
|
| 66 |
+
scale=scale,
|
| 67 |
+
g=g,
|
| 68 |
+
output_attentions=output_attentions,
|
| 69 |
+
cu_seqlens=cu_seqlens
|
| 70 |
+
)
|
| 71 |
+
return o, attn
|
rwkv4/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from .fused_recurrent import fused_recurrent_rwkv4
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
'fused_recurrent_rwkv4'
|
| 7 |
+
]
|
rwkv4/fused_recurrent.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2024, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Any, cast
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import triton
|
| 8 |
+
import triton.language as tl
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
from torch.autograd.function import Function, FunctionCtx, once_differentiable
|
| 11 |
+
|
| 12 |
+
from fla.ops.utils.op import exp
|
| 13 |
+
from fla.utils import input_guard
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_block_size_c(chans: int) -> int:
|
| 17 |
+
if chans < 32:
|
| 18 |
+
return 32
|
| 19 |
+
if chans < 64:
|
| 20 |
+
return 64
|
| 21 |
+
return 128
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@triton.jit
|
| 25 |
+
def fused_recurrent_rwkv4_forward_kernel(
|
| 26 |
+
# W
|
| 27 |
+
w_ptr,
|
| 28 |
+
w_s_c,
|
| 29 |
+
# U
|
| 30 |
+
u_ptr,
|
| 31 |
+
u_s_c,
|
| 32 |
+
# K
|
| 33 |
+
k_ptr,
|
| 34 |
+
k_s_b,
|
| 35 |
+
k_s_t,
|
| 36 |
+
k_s_c,
|
| 37 |
+
# V
|
| 38 |
+
v_ptr,
|
| 39 |
+
v_s_b,
|
| 40 |
+
v_s_t,
|
| 41 |
+
v_s_c,
|
| 42 |
+
# State
|
| 43 |
+
state_ptr,
|
| 44 |
+
state_s_b,
|
| 45 |
+
state_s_abe,
|
| 46 |
+
state_s_c,
|
| 47 |
+
# WKV
|
| 48 |
+
wkv_ptr,
|
| 49 |
+
wkv_s_b,
|
| 50 |
+
wkv_s_t,
|
| 51 |
+
wkv_s_c,
|
| 52 |
+
# Output state
|
| 53 |
+
state_out_ptr,
|
| 54 |
+
state_out_s_b,
|
| 55 |
+
state_out_s_abe,
|
| 56 |
+
state_out_s_t,
|
| 57 |
+
state_out_s_c,
|
| 58 |
+
# Params
|
| 59 |
+
chans,
|
| 60 |
+
tsz,
|
| 61 |
+
BLOCK_SIZE_C: tl.constexpr,
|
| 62 |
+
):
|
| 63 |
+
# Parallelize over the batch dimension.
|
| 64 |
+
b_idx = tl.program_id(0)
|
| 65 |
+
c_idx = tl.program_id(1)
|
| 66 |
+
|
| 67 |
+
cs = (c_idx * BLOCK_SIZE_C) + tl.arange(0, BLOCK_SIZE_C)
|
| 68 |
+
cmask = cs < chans
|
| 69 |
+
|
| 70 |
+
# Pointers to the batch (and possibly channel) for the input tensors.
|
| 71 |
+
k_ptr = k_ptr + b_idx * k_s_b
|
| 72 |
+
v_ptr = v_ptr + b_idx * v_s_b
|
| 73 |
+
alpha_ptr = state_ptr + b_idx * state_s_b
|
| 74 |
+
beta_ptr = state_ptr + b_idx * state_s_b + state_s_abe
|
| 75 |
+
eps_ptr = state_ptr + b_idx * state_s_b + 2 * state_s_abe
|
| 76 |
+
|
| 77 |
+
# Pointers to the batch (and possibly channel) for the output tensors.
|
| 78 |
+
wkv_ptr = wkv_ptr + b_idx * wkv_s_b
|
| 79 |
+
alpha_out_ptr = state_out_ptr + b_idx * state_out_s_b
|
| 80 |
+
beta_out_ptr = state_out_ptr + b_idx * state_out_s_b + state_out_s_abe
|
| 81 |
+
eps_out_ptr = state_out_ptr + b_idx * state_out_s_b + 2 * state_out_s_abe
|
| 82 |
+
|
| 83 |
+
# Loads parameters.
|
| 84 |
+
alpha = tl.load(alpha_ptr + cs * state_s_c, mask=cmask).to(tl.float32)
|
| 85 |
+
beta = tl.load(beta_ptr + cs * state_s_c, mask=cmask).to(tl.float32)
|
| 86 |
+
eps = tl.load(eps_ptr + cs * state_s_c, mask=cmask).to(tl.float32)
|
| 87 |
+
w = tl.load(w_ptr + cs * w_s_c, mask=cmask).to(tl.float32)
|
| 88 |
+
u = tl.load(u_ptr + cs * u_s_c, mask=cmask).to(tl.float32)
|
| 89 |
+
|
| 90 |
+
for t in range(tsz):
|
| 91 |
+
kt = tl.load(k_ptr + t * k_s_t + cs * k_s_c, mask=cmask).to(tl.float32)
|
| 92 |
+
vt = tl.load(v_ptr + t * v_s_t + cs * v_s_c, mask=cmask).to(tl.float32)
|
| 93 |
+
|
| 94 |
+
ukt = u + kt
|
| 95 |
+
tau = tl.maximum(ukt, eps)
|
| 96 |
+
e1a = exp(eps - tau)
|
| 97 |
+
e2a = exp(ukt - tau)
|
| 98 |
+
wkv = (e1a * alpha + e2a * vt) / (e1a * beta + e2a)
|
| 99 |
+
tl.store(wkv_ptr + t * wkv_s_t + cs * wkv_s_c, wkv, mask=cmask)
|
| 100 |
+
|
| 101 |
+
w_eps = w + eps
|
| 102 |
+
eps = tl.maximum(w_eps, kt)
|
| 103 |
+
e1b = exp(w_eps - eps)
|
| 104 |
+
e2b = exp(kt - eps)
|
| 105 |
+
alpha = e1b * alpha + e2b * vt
|
| 106 |
+
beta = e1b * beta + e2b
|
| 107 |
+
tl.store(alpha_out_ptr + t * state_out_s_t + cs * state_out_s_c, alpha, mask=cmask)
|
| 108 |
+
tl.store(beta_out_ptr + t * state_out_s_t + cs * state_out_s_c, beta, mask=cmask)
|
| 109 |
+
tl.store(eps_out_ptr + t * state_out_s_t + cs * state_out_s_c, eps, mask=cmask)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def fused_recurrent_rwkv4_forward(
|
| 113 |
+
w: Tensor,
|
| 114 |
+
u: Tensor,
|
| 115 |
+
k: Tensor,
|
| 116 |
+
v: Tensor,
|
| 117 |
+
state: Tensor,
|
| 118 |
+
) -> tuple[Tensor, Tensor]:
|
| 119 |
+
(bsz, tsz, chans) = k.shape
|
| 120 |
+
|
| 121 |
+
# New tensors to output.
|
| 122 |
+
wkvs = k.new_empty(bsz, tsz, chans)
|
| 123 |
+
state_out = k.new_empty(bsz, 3, tsz, chans)
|
| 124 |
+
|
| 125 |
+
# Constants.
|
| 126 |
+
block_size_c = get_block_size_c(chans)
|
| 127 |
+
|
| 128 |
+
def grid(meta: dict[str, Any]) -> tuple[int, ...]:
|
| 129 |
+
return (bsz, triton.cdiv(chans, meta["BLOCK_SIZE_C"]))
|
| 130 |
+
|
| 131 |
+
fused_recurrent_rwkv4_forward_kernel[grid](
|
| 132 |
+
# W
|
| 133 |
+
w,
|
| 134 |
+
w.stride(0),
|
| 135 |
+
# U
|
| 136 |
+
u,
|
| 137 |
+
u.stride(0),
|
| 138 |
+
# K
|
| 139 |
+
k,
|
| 140 |
+
k.stride(0),
|
| 141 |
+
k.stride(1),
|
| 142 |
+
k.stride(2),
|
| 143 |
+
# V
|
| 144 |
+
v,
|
| 145 |
+
v.stride(0),
|
| 146 |
+
v.stride(1),
|
| 147 |
+
v.stride(2),
|
| 148 |
+
# State
|
| 149 |
+
state,
|
| 150 |
+
state.stride(0),
|
| 151 |
+
state.stride(1),
|
| 152 |
+
state.stride(3),
|
| 153 |
+
# WKV
|
| 154 |
+
wkvs,
|
| 155 |
+
wkvs.stride(0),
|
| 156 |
+
wkvs.stride(1),
|
| 157 |
+
wkvs.stride(2),
|
| 158 |
+
# Output state
|
| 159 |
+
state_out,
|
| 160 |
+
state_out.stride(0),
|
| 161 |
+
state_out.stride(1),
|
| 162 |
+
state_out.stride(2),
|
| 163 |
+
state_out.stride(3),
|
| 164 |
+
# Params
|
| 165 |
+
chans,
|
| 166 |
+
tsz,
|
| 167 |
+
BLOCK_SIZE_C=block_size_c,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
state_out = torch.cat((state, state_out), dim=2)
|
| 171 |
+
|
| 172 |
+
return wkvs, state_out
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@triton.jit
|
| 176 |
+
def fused_recurrent_rwkv4_backward_kernel(
|
| 177 |
+
# W
|
| 178 |
+
w_ptr,
|
| 179 |
+
w_s_c,
|
| 180 |
+
# U
|
| 181 |
+
u_ptr,
|
| 182 |
+
u_s_c,
|
| 183 |
+
# K
|
| 184 |
+
k_ptr,
|
| 185 |
+
k_s_b,
|
| 186 |
+
k_s_t,
|
| 187 |
+
k_s_c,
|
| 188 |
+
# V
|
| 189 |
+
v_ptr,
|
| 190 |
+
v_s_b,
|
| 191 |
+
v_s_t,
|
| 192 |
+
v_s_c,
|
| 193 |
+
# State
|
| 194 |
+
state_ptr,
|
| 195 |
+
state_s_b,
|
| 196 |
+
state_s_abe,
|
| 197 |
+
state_s_t,
|
| 198 |
+
state_s_c,
|
| 199 |
+
# WKV grad
|
| 200 |
+
gwkv_ptr,
|
| 201 |
+
gwkv_s_b,
|
| 202 |
+
gwkv_s_t,
|
| 203 |
+
gwkv_s_c,
|
| 204 |
+
# Output state grad
|
| 205 |
+
gstate_out_ptr,
|
| 206 |
+
gstate_out_s_b,
|
| 207 |
+
gstate_out_s_abe,
|
| 208 |
+
gstate_out_s_c,
|
| 209 |
+
# W grad
|
| 210 |
+
gw_ptr,
|
| 211 |
+
gw_s_b,
|
| 212 |
+
gw_s_c,
|
| 213 |
+
# U grad
|
| 214 |
+
gu_ptr,
|
| 215 |
+
gu_s_b,
|
| 216 |
+
gu_s_c,
|
| 217 |
+
# K grad
|
| 218 |
+
gk_ptr,
|
| 219 |
+
gk_s_b,
|
| 220 |
+
gk_s_t,
|
| 221 |
+
gk_s_c,
|
| 222 |
+
# V grad
|
| 223 |
+
gv_ptr,
|
| 224 |
+
gv_s_b,
|
| 225 |
+
gv_s_t,
|
| 226 |
+
gv_s_c,
|
| 227 |
+
# State grad
|
| 228 |
+
gstate_ptr,
|
| 229 |
+
gstate_s_b,
|
| 230 |
+
gstate_s_abe,
|
| 231 |
+
gstate_s_c,
|
| 232 |
+
# Params
|
| 233 |
+
tsz,
|
| 234 |
+
chans,
|
| 235 |
+
BLOCK_SIZE_C: tl.constexpr,
|
| 236 |
+
):
|
| 237 |
+
# Parallelize over the batch dimension.
|
| 238 |
+
b_idx = tl.program_id(0)
|
| 239 |
+
c_idx = tl.program_id(1)
|
| 240 |
+
|
| 241 |
+
cs = (c_idx * BLOCK_SIZE_C) + tl.arange(0, BLOCK_SIZE_C)
|
| 242 |
+
cmask = cs < chans
|
| 243 |
+
|
| 244 |
+
# Pointers to the batch (and possibly channel) for the input tensors.
|
| 245 |
+
k_ptr = k_ptr + b_idx * k_s_b
|
| 246 |
+
v_ptr = v_ptr + b_idx * v_s_b
|
| 247 |
+
alpha_ptr = state_ptr + b_idx * state_s_b
|
| 248 |
+
beta_ptr = state_ptr + b_idx * state_s_b + state_s_abe
|
| 249 |
+
eps_ptr = state_ptr + b_idx * state_s_b + 2 * state_s_abe
|
| 250 |
+
|
| 251 |
+
# Pointers to the batch (and possibly channel) for the output tensors.
|
| 252 |
+
gk_ptr = gk_ptr + b_idx * gk_s_b
|
| 253 |
+
gv_ptr = gv_ptr + b_idx * gv_s_b
|
| 254 |
+
|
| 255 |
+
# Pointers to gradients which were recieved by the function.
|
| 256 |
+
gwkv_ptr = gwkv_ptr + b_idx * gwkv_s_b
|
| 257 |
+
galpha_out_ptr = gstate_out_ptr + b_idx * gstate_out_s_b
|
| 258 |
+
gbeta_out_ptr = gstate_out_ptr + b_idx * gstate_out_s_b + gstate_out_s_abe
|
| 259 |
+
geps_out_ptr = gstate_out_ptr + b_idx * gstate_out_s_b + 2 * gstate_out_s_abe
|
| 260 |
+
|
| 261 |
+
# Loads parameters.
|
| 262 |
+
galpha = tl.load(galpha_out_ptr + gstate_out_s_c * cs, mask=cmask).to(tl.float32)
|
| 263 |
+
gbeta = tl.load(gbeta_out_ptr + gstate_out_s_c * cs, mask=cmask).to(tl.float32)
|
| 264 |
+
geps = tl.load(geps_out_ptr + gstate_out_s_c * cs, mask=cmask).to(tl.float32)
|
| 265 |
+
w = tl.load(w_ptr + w_s_c * cs, mask=cmask).to(tl.float32)
|
| 266 |
+
u = tl.load(u_ptr + u_s_c * cs, mask=cmask).to(tl.float32)
|
| 267 |
+
|
| 268 |
+
# Gradient accumulators.
|
| 269 |
+
gw = tl.zeros_like(w)
|
| 270 |
+
gu = tl.zeros_like(u)
|
| 271 |
+
|
| 272 |
+
alpha_prev = tl.load(alpha_ptr + tsz * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
|
| 273 |
+
beta_prev = tl.load(beta_ptr + tsz * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
|
| 274 |
+
eps_prev = tl.load(eps_ptr + tsz * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
|
| 275 |
+
|
| 276 |
+
for t in range(tsz):
|
| 277 |
+
tc = tsz - t - 1
|
| 278 |
+
|
| 279 |
+
kt = tl.load(k_ptr + tc * k_s_t + k_s_c * cs, mask=cmask).to(tl.float32)
|
| 280 |
+
vt = tl.load(v_ptr + tc * v_s_t + v_s_c * cs, mask=cmask).to(tl.float32)
|
| 281 |
+
|
| 282 |
+
alpha_curr = alpha_prev
|
| 283 |
+
beta_curr = beta_prev
|
| 284 |
+
eps_curr = eps_prev
|
| 285 |
+
|
| 286 |
+
alpha_prev = tl.load(alpha_ptr + tc * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
|
| 287 |
+
beta_prev = tl.load(beta_ptr + tc * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
|
| 288 |
+
eps_prev = tl.load(eps_ptr + tc * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
|
| 289 |
+
|
| 290 |
+
ukt = u + kt
|
| 291 |
+
tau = tl.maximum(ukt, eps_prev)
|
| 292 |
+
e1 = exp(eps_prev - tau)
|
| 293 |
+
e2 = exp(ukt - tau)
|
| 294 |
+
|
| 295 |
+
euke = exp(ukt + eps_prev - 2 * tau)
|
| 296 |
+
|
| 297 |
+
denom = e1 * beta_prev + e2
|
| 298 |
+
denom_sq = denom * denom
|
| 299 |
+
|
| 300 |
+
gwkvt = tl.load(gwkv_ptr + tc * gwkv_s_t + gwkv_s_c * cs, mask=cmask).to(tl.float32)
|
| 301 |
+
|
| 302 |
+
# Backpropagates wkv gradients.
|
| 303 |
+
guk = gwkvt * e2 * (e1 * beta_prev * vt - e1 * alpha_prev) / denom_sq
|
| 304 |
+
gu += guk
|
| 305 |
+
gk = guk
|
| 306 |
+
gv = gwkvt * e2 / denom
|
| 307 |
+
|
| 308 |
+
galpha_wkv = gwkvt * e1 / denom
|
| 309 |
+
gbeta_wkv = -gwkvt * e1 * (e2 * vt + e1 * alpha_prev) / denom_sq
|
| 310 |
+
geps_wkv_denom = e1 * beta_prev + e2
|
| 311 |
+
geps_wkv = gwkvt * euke * (alpha_prev - vt * beta_prev) / (geps_wkv_denom * geps_wkv_denom)
|
| 312 |
+
|
| 313 |
+
e1 = exp(w + eps_prev - eps_curr)
|
| 314 |
+
e2 = exp(kt - eps_curr)
|
| 315 |
+
|
| 316 |
+
# Backpropagates alpha gradients.
|
| 317 |
+
galpha_we = galpha * e1 * alpha_prev
|
| 318 |
+
gw += galpha_we
|
| 319 |
+
gk += galpha * e2 * vt
|
| 320 |
+
gv += galpha * e2
|
| 321 |
+
geps += galpha * -alpha_curr
|
| 322 |
+
|
| 323 |
+
# Backpropagates beta gradients.
|
| 324 |
+
gbeta_we = gbeta * e1 * beta_prev
|
| 325 |
+
gw += gbeta_we
|
| 326 |
+
gk += gbeta * e2
|
| 327 |
+
geps += gbeta * -beta_curr
|
| 328 |
+
|
| 329 |
+
# Backpropagates epsilon gradients.
|
| 330 |
+
geps_mask = w + eps_prev > kt
|
| 331 |
+
geps_we = tl.where(geps_mask, geps, tl.zeros_like(geps))
|
| 332 |
+
gw += geps_we
|
| 333 |
+
gk += tl.where(geps_mask, tl.zeros_like(geps), geps)
|
| 334 |
+
|
| 335 |
+
# Stores the gradients for k and v.
|
| 336 |
+
tl.store(gk_ptr + tc * gk_s_t + gk_s_c * cs, gk, mask=cmask)
|
| 337 |
+
tl.store(gv_ptr + tc * gv_s_t + gv_s_c * cs, gv, mask=cmask)
|
| 338 |
+
|
| 339 |
+
# Computes new gradients for alpha and beta.
|
| 340 |
+
galpha = galpha * e1 + galpha_wkv
|
| 341 |
+
gbeta = gbeta * e1 + gbeta_wkv
|
| 342 |
+
geps = galpha_we + gbeta_we + geps_we + geps_wkv
|
| 343 |
+
|
| 344 |
+
# Stores final gradients for alpha and beta.
|
| 345 |
+
galpha_ptr = gstate_ptr + b_idx * gstate_s_b
|
| 346 |
+
gbeta_ptr = gstate_ptr + b_idx * gstate_s_b + gstate_s_abe
|
| 347 |
+
geps_ptr = gstate_ptr + b_idx * gstate_s_b + 2 * gstate_s_abe
|
| 348 |
+
tl.store(galpha_ptr + gstate_s_c * cs, galpha, mask=cmask)
|
| 349 |
+
tl.store(gbeta_ptr + gstate_s_c * cs, gbeta, mask=cmask)
|
| 350 |
+
tl.store(geps_ptr + gstate_s_c * cs, geps, mask=cmask)
|
| 351 |
+
|
| 352 |
+
# Stores final gradients for w and u.
|
| 353 |
+
tl.store(gw_ptr + gw_s_b * b_idx + gw_s_c * cs, gw*w, mask=cmask)
|
| 354 |
+
tl.store(gu_ptr + gu_s_b * b_idx + gu_s_c * cs, gu, mask=cmask)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def fused_recurrent_rwkv4_backward(
|
| 358 |
+
w: Tensor,
|
| 359 |
+
u: Tensor,
|
| 360 |
+
k: Tensor,
|
| 361 |
+
v: Tensor,
|
| 362 |
+
state: Tensor,
|
| 363 |
+
grad_wkv: Tensor,
|
| 364 |
+
grad_state: Tensor,
|
| 365 |
+
) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
| 366 |
+
bsz, tsz, chans = k.shape
|
| 367 |
+
|
| 368 |
+
gw = w.new_empty(bsz, chans, dtype=torch.float) # New tensors to output.
|
| 369 |
+
gu = u.new_empty(bsz, chans, dtype=torch.float)
|
| 370 |
+
gk = torch.empty_like(k)
|
| 371 |
+
gv = torch.empty_like(v)
|
| 372 |
+
gstate = k.new_empty(bsz, 3, 1, chans)
|
| 373 |
+
|
| 374 |
+
block_size_c = get_block_size_c(chans) # Constants.
|
| 375 |
+
|
| 376 |
+
def grid(meta: dict[str, Any]) -> tuple[int, ...]:
|
| 377 |
+
return (bsz, triton.cdiv(chans, meta["BLOCK_SIZE_C"]))
|
| 378 |
+
|
| 379 |
+
fused_recurrent_rwkv4_backward_kernel[grid](
|
| 380 |
+
# W
|
| 381 |
+
w,
|
| 382 |
+
w.stride(0),
|
| 383 |
+
# U
|
| 384 |
+
u,
|
| 385 |
+
u.stride(0),
|
| 386 |
+
# K
|
| 387 |
+
k,
|
| 388 |
+
k.stride(0),
|
| 389 |
+
k.stride(1),
|
| 390 |
+
k.stride(2),
|
| 391 |
+
# V
|
| 392 |
+
v,
|
| 393 |
+
v.stride(0),
|
| 394 |
+
v.stride(1),
|
| 395 |
+
v.stride(2),
|
| 396 |
+
# State
|
| 397 |
+
state,
|
| 398 |
+
state.stride(0),
|
| 399 |
+
state.stride(1),
|
| 400 |
+
state.stride(2),
|
| 401 |
+
state.stride(3),
|
| 402 |
+
# WKV grad
|
| 403 |
+
grad_wkv,
|
| 404 |
+
grad_wkv.stride(0),
|
| 405 |
+
grad_wkv.stride(1),
|
| 406 |
+
grad_wkv.stride(2),
|
| 407 |
+
# Output state grad
|
| 408 |
+
grad_state,
|
| 409 |
+
grad_state.stride(0),
|
| 410 |
+
grad_state.stride(1),
|
| 411 |
+
grad_state.stride(3),
|
| 412 |
+
# W grad
|
| 413 |
+
gw,
|
| 414 |
+
gw.stride(0),
|
| 415 |
+
gw.stride(1),
|
| 416 |
+
# U grad
|
| 417 |
+
gu,
|
| 418 |
+
gu.stride(0),
|
| 419 |
+
gu.stride(1),
|
| 420 |
+
# K grad
|
| 421 |
+
gk,
|
| 422 |
+
gk.stride(0),
|
| 423 |
+
gk.stride(1),
|
| 424 |
+
gk.stride(2),
|
| 425 |
+
# V grad
|
| 426 |
+
gv,
|
| 427 |
+
gv.stride(0),
|
| 428 |
+
gv.stride(1),
|
| 429 |
+
gv.stride(2),
|
| 430 |
+
# State grad
|
| 431 |
+
gstate,
|
| 432 |
+
gstate.stride(0),
|
| 433 |
+
gstate.stride(1),
|
| 434 |
+
gstate.stride(3),
|
| 435 |
+
# Params
|
| 436 |
+
tsz,
|
| 437 |
+
chans,
|
| 438 |
+
BLOCK_SIZE_C=block_size_c,
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
return gw.sum(0), gu.sum(0), gk, gv, gstate
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
class FusedRecurrentRWKV4Function(Function):
|
| 445 |
+
|
| 446 |
+
@staticmethod
|
| 447 |
+
@input_guard
|
| 448 |
+
def forward(
|
| 449 |
+
ctx: FunctionCtx,
|
| 450 |
+
w: Tensor,
|
| 451 |
+
u: Tensor,
|
| 452 |
+
k: Tensor,
|
| 453 |
+
v: Tensor,
|
| 454 |
+
state: Tensor,
|
| 455 |
+
) -> tuple[Tensor, Tensor]:
|
| 456 |
+
ctx.w_dtype = w.dtype
|
| 457 |
+
w = -torch.exp(w.float())
|
| 458 |
+
wkv, state_out = fused_recurrent_rwkv4_forward(w, u, k, v, state)
|
| 459 |
+
ctx.save_for_backward(w, u, k, v, state_out[:, :, :-1])
|
| 460 |
+
return wkv, state_out[:, :, -1:]
|
| 461 |
+
|
| 462 |
+
@staticmethod
|
| 463 |
+
@once_differentiable
|
| 464 |
+
@input_guard
|
| 465 |
+
def backward(ctx: FunctionCtx, gwkv: Tensor, gstate: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
| 466 |
+
w, u, k, v, state = cast(tuple[Tensor, ...], ctx.saved_tensors)
|
| 467 |
+
gw, gu, gk, gv, gstate = fused_recurrent_rwkv4_backward(w, u, k, v, state, gwkv, gstate)
|
| 468 |
+
return gw.to(ctx.w_dtype), gu.to(u), gk.to(k), gv.to(v), gstate.to(state)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def fused_recurrent_rwkv4(w: Tensor, u: Tensor, k: Tensor, v: Tensor, state: Tensor) -> tuple[Tensor, Tensor]:
|
| 472 |
+
return FusedRecurrentRWKV4Function.apply(w, u, k, v, state)
|
rwkv6/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from .chunk import chunk_rwkv6
|
| 4 |
+
from .fused_recurrent import fused_recurrent_rwkv6
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
'chunk_rwkv6',
|
| 8 |
+
'fused_recurrent_rwkv6'
|
| 9 |
+
]
|
rwkv6/chunk_naive.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from einops import rearrange
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def naive_chunk_rwkv6(
|
| 8 |
+
q: torch.Tensor,
|
| 9 |
+
k: torch.Tensor,
|
| 10 |
+
v: torch.Tensor,
|
| 11 |
+
w: torch.Tensor,
|
| 12 |
+
u: torch.Tensor,
|
| 13 |
+
chunk_size: int = 32
|
| 14 |
+
):
|
| 15 |
+
assert q.shape[-2] % chunk_size == 0
|
| 16 |
+
orig_dtype = q.dtype
|
| 17 |
+
num_chunk = q.shape[-2] // chunk_size
|
| 18 |
+
u = u.unsqueeze(0)
|
| 19 |
+
|
| 20 |
+
q, k, v, w = map(lambda x: rearrange(x, 'b h (n c) d -> b h n c d', c=chunk_size).float(), (q, k, v, w))
|
| 21 |
+
|
| 22 |
+
w_cumsum = w.cumsum(-2)
|
| 23 |
+
|
| 24 |
+
kw = k * (w_cumsum[..., -1, None, :] - w_cumsum).exp()
|
| 25 |
+
wkv = kw.transpose(-1, -2) @ v
|
| 26 |
+
|
| 27 |
+
wkv_new = torch.zeros_like(wkv)
|
| 28 |
+
|
| 29 |
+
for i in range(num_chunk - 1):
|
| 30 |
+
wkv_new[:, :, i+1] = (wkv_new[:, :, i] * w_cumsum[:, :, i, -1, :, None].exp()) + wkv[:, :, i]
|
| 31 |
+
|
| 32 |
+
o_inter = torch.einsum('b h n d p, b h n c d -> b h n c p', wkv_new, (q * (w_cumsum - w).exp()))
|
| 33 |
+
|
| 34 |
+
o_intra = torch.zeros_like(o_inter)
|
| 35 |
+
for i in range(chunk_size):
|
| 36 |
+
attn = (q[:, :, :, i, None] * k * (w_cumsum[:, :, :, i, None] - w[:, :, :, i, None] - w_cumsum).exp()).sum(-1)
|
| 37 |
+
mask = (torch.arange(0, chunk_size) < i).to(attn.device)
|
| 38 |
+
attn.masked_fill_(~mask, 0)
|
| 39 |
+
intra_inter_o = (attn.unsqueeze(-1) * v).sum(-2)
|
| 40 |
+
intra_intra_o = (q[:, :, :, i] * u.unsqueeze(2) * k[:, :, :, i]).sum(-1).unsqueeze(-1) * v[:,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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RWKV7 (Goose) Mechanism: Mathematical Derivation
|
| 2 |
+
|
| 3 |
+
Zhiyuan Li
|
| 4 |
+
|
| 5 |
+
>Special thanks to [Sonta](https://github.com/sustcsonglin) and [Beortust](https://github.com/Beortext), Sonta pointed out the correct notation for the outer product in the formulas, and Beortust corrected a considerable number of typos and also helped to improve the formatting.
|
| 6 |
+
|
| 7 |
+
## Introduction to RWKV-7 Architecture
|
| 8 |
+
|
| 9 |
+
RWKV-7 employs **Dynamic State Evolution** that transcends the fundamental TC0 expressivity limitations of attention/linear attention paradigms. RWKV-7 possesses NC1 expressivity, allowing it to solve many problems that attention mechanisms cannot.
|
| 10 |
+
|
| 11 |
+
In simple terms, traditional attention mechanisms (like Transformer's QKV-softmax-attention) store multiple $\{k,v\}$ (key and value vector pairs), matching queries ($q$ alias named $r$ in RWKV) against keys to retrieve corresponding values.
|
| 12 |
+
|
| 13 |
+
RWKV-7 takes a different approach - rather than directly storing $\{k,v\}$ pairs, it dynamically updates a state by learning relationships between keys and values from context. This updated state then processes new input queries ($q$, or $r$ in RWKV terminology) to produce outputs[^1].
|
| 14 |
+
|
| 15 |
+
[^1]: For a more detailed explanation of this approach, see the original article by the RWKV author: https://mp.weixin.qq.com/s/kC_Z3vuQ5B4PiRwZVeIvHQ
|
| 16 |
+
|
| 17 |
+
Specifically, RWKV-7 maintains an internal model $v \approx k^{\top} S$. It aims to fit a simple objective: for given vector sequences $\{k\}$ and $\{v\}$, use state $S$ to transform $k_i$ into $v_i$, making the output $v$ as close as possible to the target $v$.
|
| 18 |
+
|
| 19 |
+
For clarity on dimensions:
|
| 20 |
+
|
| 21 |
+
$S_t \in \mathbb{R}^{d_v \times d_k}$ is the state matrix
|
| 22 |
+
|
| 23 |
+
$k_t \in \mathbb{R}^{d_k}$ is the key vector
|
| 24 |
+
|
| 25 |
+
$v_t \in \mathbb{R}^{d_v}$ is the value vector
|
| 26 |
+
|
| 27 |
+
$q_t \in \mathbb{R}^{d_k}$ is the query vector (named $r$ in RWKV terminology)
|
| 28 |
+
|
| 29 |
+
To achieve this, during inference with an L2 loss function $L=\frac{1}{2} \left\Vert v − k^{\top} S \right\Vert^2$, RWKV-7 automatically simulates dynamic gradient descent to continuously train its internal model $v \approx k^{\top} S$.
|
| 30 |
+
|
| 31 |
+
The gradient of the L2 loss function with respect to the state matrix $S$ is: $\frac{\partial L}{\partial S} = S k k^{\top} - v k^{\top}$
|
| 32 |
+
|
| 33 |
+
Applying stochastic gradient descent (SGD) with this gradient yields a recurrent update formula that forms the foundation of RWKV-7's mechanism. In standard SGD, we would update the parameters by subtracting the gradient scaled by a learning rate:
|
| 34 |
+
|
| 35 |
+
$$
|
| 36 |
+
S_t = S_{t-1} - \eta_t \cdot \frac{\partial L}{\partial S} , \text{ where } L=L_t \quad S=S_{t-1}
|
| 37 |
+
$$
|
| 38 |
+
|
| 39 |
+
Incorporating weight decay factors $d_t = \exp(-\exp(w_t))$ as a form of time-dependent regularization and learning rate $\eta_t$, the gradient descent update becomes:
|
| 40 |
+
|
| 41 |
+
$$S_t = S_{t-1} \text{Diag}(d_t) - \eta_t \cdot (S_{t-1} k_t k_t^{\top} - v_t k_t^{\top})$$
|
| 42 |
+
|
| 43 |
+
This can be expanded and rearranged as follows:
|
| 44 |
+
|
| 45 |
+
$$S_t = S_{t-1} \text{Diag}(d_t) - \eta_t \cdot S_{t-1} k_t k_t^{\top} + \eta_t \cdot v_t k_t^{\top}$$
|
| 46 |
+
|
| 47 |
+
For notational simplicity, we denote $\text{Diag}(d_t)$ as $D_t$ (the diagonal decay matrix):
|
| 48 |
+
|
| 49 |
+
$$S_t = S_{t-1} D_t - \eta_t \cdot S_{t-1} k_t k_t^{\top} + \eta_t \cdot v_t k_t^{\top}$$
|
| 50 |
+
|
| 51 |
+
In the full RWKV-7 implementation, this update rule is generalized through several key transformations:
|
| 52 |
+
|
| 53 |
+
1. The diagonal decay term $D_t$ remains as a component-wise multiplication with $S_{t-1}$
|
| 54 |
+
|
| 55 |
+
2. The term $-\eta_t \cdot k_t k_t^{\top}$ is generalized to $\alpha_t \beta_t^{\top}$, where:
|
| 56 |
+
|
| 57 |
+
- $\alpha_t$ can be initialized as $-k_t$
|
| 58 |
+
- $\beta_t$ can be initialized as $\eta_t \cdot k_t$
|
| 59 |
+
|
| 60 |
+
3. The term $-\eta_t \cdot S_{t-1} k_t k_t^{\top}$ can be factorized and computed efficiently:
|
| 61 |
+
|
| 62 |
+
- First compute $u_t = S_{t-1} k_t$ (matrix-vector product)
|
| 63 |
+
- Then compute $-\eta_t \cdot u_t k_t^{\top}$ (scaled outer product)
|
| 64 |
+
|
| 65 |
+
4. The term $\eta_t \cdot v_t k_t^{\top}$ is directly implemented as the outer product between the value vector $v_t$ and key vector $k_t$, resulting in a rank-1 update matrix
|
| 66 |
+
|
| 67 |
+
This leads to the final recurrence equation[^2]:
|
| 68 |
+
|
| 69 |
+
$$
|
| 70 |
+
S_t = S_{t-1} D_t + S_{t-1} \alpha_t \beta_t^{\top} + v_t k_t^{\top} \in \mathbb{R}^{d_v \times d_k}
|
| 71 |
+
$$
|
| 72 |
+
|
| 73 |
+
The output at each timestep is computed as:
|
| 74 |
+
$o_t = S_t r_t$
|
| 75 |
+
|
| 76 |
+
Where $r_t \in \mathbb{R}^{d_k}$ is the query vector (named $r$ in RWKV terminology), typically scaled by a factor of $\frac{1}{\sqrt{d_k}}$. This formulation allows RWKV-7 to continuously adapt its internal representation based on context, transcending the limitations of traditional attention mechanisms.
|
| 77 |
+
|
| 78 |
+
[^2]: For a more detailed explanation, see the triton codes. Note: In the optimized Triton implementation, `w` is already the log of the decay factor, so there's only one exponential operation needed. https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/rwkv7/fused_recurrent.py#L94
|
| 79 |
+
|
| 80 |
+
This formulation allows more flexibility in how the state evolves while maintaining the core gradient descent learning dynamics.
|
| 81 |
+
|
| 82 |
+
## 1. Forward Pass Recurrence Equation
|
| 83 |
+
|
| 84 |
+
In the implementation, the state update is defined as:
|
| 85 |
+
|
| 86 |
+
For each batch (bi) and head (hi), at time step t:
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
w_t = torch.exp(-torch.exp(w[bi, hi, t])) # shape [K]
|
| 90 |
+
sa = (state[bi, hi] * a_t[None, :]).sum(dim=1) # shape [V]
|
| 91 |
+
state[bi, hi] = w_t[None, :] * state[bi, hi] + sa[:, None] * b_t[None, :] + k_t[None, :] * v_t[:, None]
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
Where state[bi, hi] has shape [V, K], representing a state matrix that maps from K-dimensional keys to V-dimensional values.
|
| 95 |
+
|
| 96 |
+
## 2. Backward Pass Derivation
|
| 97 |
+
|
| 98 |
+
### 2.1 Gradient of Loss w.r.t. State
|
| 99 |
+
|
| 100 |
+
For time step t, if L is the loss function, dstate_curr = ∂L/∂state[bi, hi, t+1] is the gradient of the current state:
|
| 101 |
+
|
| 102 |
+
```
|
| 103 |
+
dstate_curr = dstate[bi, hi] + q_t[None, :] * doutput[bi, hi, t][:, None]
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
This includes gradients propagated from future time steps dstate[bi, hi] and gradients from the current output.
|
| 107 |
+
|
| 108 |
+
### 2.2 Gradient w.r.t. Query q_t
|
| 109 |
+
|
| 110 |
+
```
|
| 111 |
+
dq[bi, hi, t] = torch.matmul(doutput[bi, hi, t], curr_state) * scale
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
### 2.3 Gradient w.r.t. Decay Parameter w_t
|
| 115 |
+
|
| 116 |
+
For the gradient of w_t, we need to consider how it affects the state update:
|
| 117 |
+
|
| 118 |
+
1. For the `w_t[None, :] * state[bi, hi]` component of the state update:
|
| 119 |
+
|
| 120 |
+
First, compute the derivative of L with respect to w_t:
|
| 121 |
+
|
| 122 |
+
```
|
| 123 |
+
∂L/∂w_t[k] = ∑_v (dstate_curr[v,k] * prev_state[v,k])
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
This equation sums over the v dimension for each position k, resulting in a vector of shape [K].
|
| 127 |
+
|
| 128 |
+
Then, compute the derivative of w_t with respect to w:
|
| 129 |
+
|
| 130 |
+
```
|
| 131 |
+
∂w_t[k]/∂w[k] = -exp(w[k]) * exp(-exp(w[k])) = -exp(w[k]) * w_t[k]
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
Finally, apply the chain rule:
|
| 135 |
+
|
| 136 |
+
```
|
| 137 |
+
∂L/∂w[k] = ∂L/∂w_t[k] * ∂w_t[k]/∂w[k]
|
| 138 |
+
= (∑_v dstate_curr[v,k] * prev_state[v,k]) * (-exp(w[k]) * w_t[k])
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
In code, this is expressed as:
|
| 142 |
+
|
| 143 |
+
```python
|
| 144 |
+
dw[bi, hi, t] += -torch.sum(dstate_curr * prev_state, dim=0) * torch.exp(w[bi, hi, t]) * w_t
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
Or equivalently:
|
| 148 |
+
|
| 149 |
+
```python
|
| 150 |
+
dw[bi, hi, t] += -torch.sum(dstate_curr * prev_state, dim=0) * torch.exp(w[bi, hi, t]) * torch.exp(-torch.exp(w[bi, hi, t]))
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
### 2.4 Gradient w.r.t. k_t and v_t
|
| 154 |
+
|
| 155 |
+
For the `k_t[None, :] * v_t[:, None]` component:
|
| 156 |
+
|
| 157 |
+
```python
|
| 158 |
+
dk[bi, hi, t] += torch.sum(dstate_curr * v_t[:, None], dim=0)
|
| 159 |
+
dv[bi, hi, t] += torch.sum(dstate_curr * k_t[None, :], dim=1)
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
### 2.5 Gradient w.r.t. α_t and β_t (a_t and b_t in code)
|
| 163 |
+
|
| 164 |
+
For the `sa[:, None] * b_t[None, :]` component, where `sa = (state[bi, hi] * a_t[None, :]).sum(dim=1)`:
|
| 165 |
+
|
| 166 |
+
```python
|
| 167 |
+
db[bi, hi, t] += torch.sum(dstate_curr * sa[:, None], dim=0)
|
| 168 |
+
dsa = torch.sum(dstate_curr * b_t[None, :], dim=1)
|
| 169 |
+
da[bi, hi, t] += torch.sum(prev_state * dsa[:, None], dim=0)
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
### 2.6 Gradient w.r.t. Previous State S\_{t-1}
|
| 173 |
+
|
| 174 |
+
Finally, we compute the gradient of the previous state for backpropagation:
|
| 175 |
+
|
| 176 |
+
```python
|
| 177 |
+
dstate_from_sa = a_t[None, :] * dsa[:, None]
|
| 178 |
+
dstate_from_decay = dstate_curr * w_t[None, :]
|
| 179 |
+
dstate[bi, hi] = dstate_from_sa + dstate_from_decay
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
```python
|
| 183 |
+
# -*- coding: utf-8 -*-
|
| 184 |
+
from typing import Optional, Tuple
|
| 185 |
+
|
| 186 |
+
import torch
|
| 187 |
+
|
| 188 |
+
from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def naive_recurrent_rwkv7(
|
| 192 |
+
q: torch.Tensor,
|
| 193 |
+
k: torch.Tensor,
|
| 194 |
+
v: torch.Tensor,
|
| 195 |
+
w: torch.Tensor,
|
| 196 |
+
a: torch.Tensor, # Dynamic learning rate modulator
|
| 197 |
+
b: torch.Tensor, # State update modulator
|
| 198 |
+
scale: float = 1.0,
|
| 199 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 200 |
+
output_final_state: bool = True,
|
| 201 |
+
):
|
| 202 |
+
"""
|
| 203 |
+
Naive recurrent implementation of RWKV-7 (Goose) attention mechanism.
|
| 204 |
+
Modified from bo's code.
|
| 205 |
+
https://github.com/BlinkDL/RWKV-LM/blob/main/RWKV-v7/rwkv_v7_demo.py#L170
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
q, k, v: Query, Key, and Value tensors
|
| 209 |
+
w: Time decay weights
|
| 210 |
+
a: Dynamic learning rate modulator, influences the in-context learning rate
|
| 211 |
+
b: State update modulator, directly participates in state update calculation
|
| 212 |
+
scale: Scaling factor for attention scores
|
| 213 |
+
initial_state: Initial state for the recurrent computation
|
| 214 |
+
output_final_state: Whether to output the final state
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
Attention output and optionally the final state
|
| 218 |
+
"""
|
| 219 |
+
torch_dtype = q.dtype if q.dtype in [torch.float64, torch.float] else torch.float
|
| 220 |
+
orig_dtype = q.dtype
|
| 221 |
+
B, H, L, N, V = q.shape[0], q.shape[1], q.shape[2], q.shape[3], v.shape[-1]
|
| 222 |
+
q, k, v, w, a, b = (x.to(dtype=torch_dtype) for x in (q, k, v, w, a, b))
|
| 223 |
+
# q, k, v, a, b, w,
|
| 224 |
+
# shape: (B, H, L, D), (B, H, L, D), (B, H, T, V), (B, H, L, D), (B, H, L, D), (B, H, L, D)
|
| 225 |
+
state = torch.zeros(B, H, V, N, dtype=torch_dtype, device=q.device)
|
| 226 |
+
o = torch.zeros_like(v)
|
| 227 |
+
|
| 228 |
+
if scale == -1.0:
|
| 229 |
+
scale = N ** -0.5
|
| 230 |
+
|
| 231 |
+
if initial_state is not None:
|
| 232 |
+
state += initial_state.to(dtype=torch_dtype)
|
| 233 |
+
|
| 234 |
+
for t in range(L):
|
| 235 |
+
q_t = q[:, :, t] * scale
|
| 236 |
+
k_t = k[:, :, t]
|
| 237 |
+
v_t = v[:, :, t]
|
| 238 |
+
a_t = a[:, :, t]
|
| 239 |
+
b_t = b[:, :, t]
|
| 240 |
+
|
| 241 |
+
# from bo's code
|
| 242 |
+
sab = torch.einsum('bhik,bhk,bhj->bhij', state, a_t, b_t)
|
| 243 |
+
state = state * torch.exp(-torch.exp(w[:, :, t, None, :])) + sab + torch.einsum('bhj,bhi->bhij', k_t, v_t)
|
| 244 |
+
o[:, :, t] = torch.einsum('bhj,bhij->bhi', q_t, state)
|
| 245 |
+
|
| 246 |
+
if not output_final_state:
|
| 247 |
+
ht = None
|
| 248 |
+
elif initial_state is not None:
|
| 249 |
+
ht = state.to(initial_state.dtype)
|
| 250 |
+
else:
|
| 251 |
+
ht = state.to(orig_dtype)
|
| 252 |
+
|
| 253 |
+
return o.to(orig_dtype), ht
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def naive_recurrent_rwkv7_2(
|
| 257 |
+
q: torch.Tensor,
|
| 258 |
+
k: torch.Tensor,
|
| 259 |
+
v: torch.Tensor,
|
| 260 |
+
w: torch.Tensor,
|
| 261 |
+
a: torch.Tensor, # Dynamic learning rate modulator
|
| 262 |
+
b: torch.Tensor, # State update modulator
|
| 263 |
+
scale: float = 1.0,
|
| 264 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 265 |
+
output_final_state: bool = True,
|
| 266 |
+
):
|
| 267 |
+
"""
|
| 268 |
+
Naive recurrent implementation of RWKV-7 (Goose) attention mechanism.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
q, k, v: Query, Key, and Value tensors
|
| 272 |
+
w: Time decay weights
|
| 273 |
+
a: Dynamic learning rate modulator, influences the in-context learning rate
|
| 274 |
+
b: State update modulator, directly participates in state update calculation
|
| 275 |
+
scale: Scaling factor for attention scores
|
| 276 |
+
initial_state: Initial state for the recurrent computation
|
| 277 |
+
output_final_state: Whether to output the final state
|
| 278 |
+
|
| 279 |
+
Returns:
|
| 280 |
+
Attention output and optionally the final state
|
| 281 |
+
"""
|
| 282 |
+
torch_dtype = q.dtype if q.dtype in [torch.float64, torch.float] else torch.float
|
| 283 |
+
orig_dtype = q.dtype
|
| 284 |
+
B, H, L, N, V = q.shape[0], q.shape[1], q.shape[2], q.shape[3], v.shape[-1]
|
| 285 |
+
q, k, v, w, a, b = (x.to(dtype=torch_dtype) for x in (q, k, v, w, a, b))
|
| 286 |
+
# q, k, v, a, b, w,
|
| 287 |
+
# shape: (B, H, L, D), (B, H, L, D), (B, H, T, V), (B, H, L, D), (B, H, L, D), (B, H, L, D)
|
| 288 |
+
state = torch.zeros(B, H, V, N, dtype=torch_dtype, device=q.device)
|
| 289 |
+
o = torch.zeros_like(v)
|
| 290 |
+
|
| 291 |
+
if scale == -1.0:
|
| 292 |
+
scale = N ** -0.5
|
| 293 |
+
|
| 294 |
+
if initial_state is not None:
|
| 295 |
+
state += initial_state.to(dtype=torch_dtype)
|
| 296 |
+
|
| 297 |
+
for t in range(L):
|
| 298 |
+
for bi in range(B):
|
| 299 |
+
for hi in range(H):
|
| 300 |
+
q_t = q[bi, hi, t] * scale
|
| 301 |
+
k_t = k[bi, hi, t]
|
| 302 |
+
v_t = v[bi, hi, t]
|
| 303 |
+
a_t = a[bi, hi, t]
|
| 304 |
+
b_t = b[bi, hi, t]
|
| 305 |
+
w_t = torch.exp(-torch.exp(w[bi, hi, t]))
|
| 306 |
+
|
| 307 |
+
# h: [V, K], a_t [K] -> [1, K]
|
| 308 |
+
# sa: [V]
|
| 309 |
+
sa = (state[bi, hi] * a_t[None, :]).sum(dim=1)
|
| 310 |
+
|
| 311 |
+
state[bi, hi] = w_t[None, :] * state[bi, hi] + sa[:, None] * b_t[None, :] + k_t[None, :] * v_t[:, None]
|
| 312 |
+
y = (state[bi, hi] * q_t[None, :]).sum(dim=1)
|
| 313 |
+
|
| 314 |
+
o[bi, hi, t] = y
|
| 315 |
+
|
| 316 |
+
ht = state if output_final_state else None
|
| 317 |
+
return o.to(orig_dtype), ht
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
@torch.no_grad()
|
| 321 |
+
def naive_recurrent_rwkv7_2_bwd(
|
| 322 |
+
q: torch.Tensor,
|
| 323 |
+
k: torch.Tensor,
|
| 324 |
+
v: torch.Tensor,
|
| 325 |
+
w: torch.Tensor,
|
| 326 |
+
a: torch.Tensor,
|
| 327 |
+
b: torch.Tensor,
|
| 328 |
+
doutput: torch.Tensor,
|
| 329 |
+
dh_t: Optional[torch.Tensor] = None,
|
| 330 |
+
scale: float = 1.0,
|
| 331 |
+
dtype: Optional[torch.dtype] = None
|
| 332 |
+
):
|
| 333 |
+
"""
|
| 334 |
+
Backward pass for the naive_recurrent_rwkv7_2 implementation.
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
q, k, v, w, a, b: Original forward pass inputs
|
| 338 |
+
doutput: Gradient of the loss with respect to the output
|
| 339 |
+
dh_t: Gradient of the loss with respect to the final state (if any)
|
| 340 |
+
scale: Scaling factor used in the forward pass
|
| 341 |
+
dtype: Optional dtype for computation
|
| 342 |
+
|
| 343 |
+
Returns:
|
| 344 |
+
Gradients with respect to all inputs
|
| 345 |
+
"""
|
| 346 |
+
torch_dtype = q.dtype if q.dtype in [torch.float64, torch.float] else torch.float
|
| 347 |
+
q, k, v, w, a, b, doutput = (x.to(dtype=torch_dtype) for x in (q, k, v, w, a, b, doutput))
|
| 348 |
+
if dh_t is not None:
|
| 349 |
+
dh_t = dh_t.to(dtype=torch_dtype)
|
| 350 |
+
|
| 351 |
+
B, H, L, N, V = q.shape[0], q.shape[1], q.shape[2], q.shape[3], v.shape[-1]
|
| 352 |
+
|
| 353 |
+
# Initialize gradients
|
| 354 |
+
dq = torch.empty_like(q)
|
| 355 |
+
dk = torch.empty_like(k)
|
| 356 |
+
dv = torch.empty_like(v)
|
| 357 |
+
dw = torch.empty_like(w)
|
| 358 |
+
da = torch.empty_like(a)
|
| 359 |
+
db = torch.empty_like(b)
|
| 360 |
+
|
| 361 |
+
# Initialize state gradients
|
| 362 |
+
dstate = torch.zeros(B, H, V, N, dtype=torch_dtype, device=q.device)
|
| 363 |
+
if dh_t is not None:
|
| 364 |
+
dstate += dh_t
|
| 365 |
+
|
| 366 |
+
if scale == -1.0:
|
| 367 |
+
scale = N ** -0.5
|
| 368 |
+
|
| 369 |
+
# First rebuild all states from forward pass
|
| 370 |
+
states = []
|
| 371 |
+
state = torch.zeros(B, H, V, N, dtype=torch_dtype, device=q.device)
|
| 372 |
+
states.append(state.clone())
|
| 373 |
+
|
| 374 |
+
# In practice, we don't recompute all states from the beginning.
|
| 375 |
+
# Instead, we use checkpointing: we save states at regular intervals (e.g., every 16 tokens)
|
| 376 |
+
# during the forward pass, then reconstruct intermediate states during the backward pass
|
| 377 |
+
# by working backwards from the nearest checkpoint.
|
| 378 |
+
#
|
| 379 |
+
# For example, to get state[t-1] from state[t]:
|
| 380 |
+
# state[t-1] = (state[t] - (sa * b_t + k_t * v_t)) / w_t
|
| 381 |
+
#
|
| 382 |
+
# This approach balances memory usage and computational efficiency:
|
| 383 |
+
# - Reduces memory by not storing every state
|
| 384 |
+
# - Maintains numerical stability by limiting the number of backward steps from each checkpoint
|
| 385 |
+
# - Allows efficient gradient computation without recomputing the entire sequence
|
| 386 |
+
for t in range(L):
|
| 387 |
+
for bi in range(B):
|
| 388 |
+
for hi in range(H):
|
| 389 |
+
q_t = q[bi, hi, t] * scale
|
| 390 |
+
k_t = k[bi, hi, t]
|
| 391 |
+
v_t = v[bi, hi, t]
|
| 392 |
+
a_t = a[bi, hi, t]
|
| 393 |
+
b_t = b[bi, hi, t]
|
| 394 |
+
w_t = torch.exp(-torch.exp(w[bi, hi, t]))
|
| 395 |
+
|
| 396 |
+
sa = (state[bi, hi] * a_t[None, :]).sum(dim=1)
|
| 397 |
+
|
| 398 |
+
state[bi, hi] = w_t[None, :] * state[bi, hi] + sa[:, None] * b_t[None, :] + k_t[None, :] * v_t[:, None]
|
| 399 |
+
states.append(state.clone())
|
| 400 |
+
|
| 401 |
+
# Backward pass through time
|
| 402 |
+
for t in range(L-1, -1, -1):
|
| 403 |
+
for bi in range(B):
|
| 404 |
+
for hi in range(H):
|
| 405 |
+
q_t = q[bi, hi, t] * scale
|
| 406 |
+
k_t = k[bi, hi, t]
|
| 407 |
+
v_t = v[bi, hi, t]
|
| 408 |
+
a_t = a[bi, hi, t]
|
| 409 |
+
b_t = b[bi, hi, t]
|
| 410 |
+
w_scalar = w[bi, hi, t]
|
| 411 |
+
w_exp = torch.exp(w_scalar)
|
| 412 |
+
w_t = torch.exp(-w_exp)
|
| 413 |
+
|
| 414 |
+
curr_state = states[t+1][bi, hi] # State after update [V, K]
|
| 415 |
+
prev_state = states[t][bi, hi] # State before update [V, K]
|
| 416 |
+
|
| 417 |
+
dq[bi, hi, t] = (doutput[bi, hi, t][:, None] * curr_state).sum(dim=0) * scale
|
| 418 |
+
|
| 419 |
+
dstate_from_out = q_t[None, :] * doutput[bi, hi, t][:, None] # [V, K]
|
| 420 |
+
|
| 421 |
+
dstate_curr = dstate[bi, hi] + dstate_from_out
|
| 422 |
+
|
| 423 |
+
sa = (prev_state * a_t[None, :]).sum(dim=1) # [V]
|
| 424 |
+
|
| 425 |
+
# state[bi, hi] = w_t[None, :] * prev_state + ...
|
| 426 |
+
dw[bi, hi, t] = -torch.sum(dstate_curr * prev_state, dim=0) * \
|
| 427 |
+
w_t * w_exp
|
| 428 |
+
|
| 429 |
+
# k_t[None, :] * v_t[:, None] -> [V, K]
|
| 430 |
+
dk[bi, hi, t] = torch.sum(dstate_curr * v_t[:, None], dim=0)
|
| 431 |
+
dv[bi, hi, t] = torch.sum(dstate_curr * k_t[None, :], dim=1)
|
| 432 |
+
|
| 433 |
+
# sa[:, None] * b_t[None, :] -> [V, K]
|
| 434 |
+
db[bi, hi, t] = torch.sum(dstate_curr * sa[:, None], dim=0)
|
| 435 |
+
dsa = torch.sum(dstate_curr * b_t[None, :], dim=1) # [V]
|
| 436 |
+
|
| 437 |
+
# sa = (prev_state * a_t[None, :]).sum(dim=1)
|
| 438 |
+
da[bi, hi, t] = torch.sum(prev_state * dsa[:, None], dim=0)
|
| 439 |
+
dstate_from_sa = a_t[None, :] * dsa[:, None] # [V, K]
|
| 440 |
+
|
| 441 |
+
# w_t[None, :] * prev_state
|
| 442 |
+
dstate_from_decay = dstate_curr * w_t[None, :] # [V, K]
|
| 443 |
+
|
| 444 |
+
dstate[bi, hi] = dstate_from_sa + dstate_from_decay
|
| 445 |
+
|
| 446 |
+
return dq, dk, dv, dw, da, db, dstate
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class NativeRecurrentRWKV7Function(torch.autograd.Function):
|
| 450 |
+
@staticmethod
|
| 451 |
+
@input_guard
|
| 452 |
+
@autocast_custom_fwd
|
| 453 |
+
def forward(ctx, q, k, v, w, a, b, scale, initial_state,
|
| 454 |
+
training: bool = True, dtype: Optional[torch.dtype] = None,
|
| 455 |
+
state_ckpt_interval: int = 16):
|
| 456 |
+
o, ht = naive_recurrent_rwkv7_2(q, k, v, w, a, b, scale=scale, initial_state=initial_state)
|
| 457 |
+
if training:
|
| 458 |
+
ctx.save_for_backward(q, k, v, w, a, b)
|
| 459 |
+
ctx.scale = scale
|
| 460 |
+
ctx.dtype = dtype
|
| 461 |
+
ctx.ckpt_interval = state_ckpt_interval
|
| 462 |
+
ctx.use_initial_state = initial_state is not None
|
| 463 |
+
return o, ht
|
| 464 |
+
|
| 465 |
+
@staticmethod
|
| 466 |
+
@autocast_custom_bwd
|
| 467 |
+
def backward(ctx, do, dht):
|
| 468 |
+
q, k, v, w, a, b = ctx.saved_tensors
|
| 469 |
+
dq, dk, dv, dw, da, db, dh = naive_recurrent_rwkv7_2_bwd(
|
| 470 |
+
q, k, v, w, a, b, do, dht, ctx.scale, dtype=ctx.dtype)
|
| 471 |
+
dh = dh if ctx.use_initial_state else None
|
| 472 |
+
return dq, dk, dv, dw, da, db, None, dh, None, None
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def recurrent_rwkv7(
|
| 476 |
+
q: torch.Tensor,
|
| 477 |
+
k: torch.Tensor,
|
| 478 |
+
v: torch.Tensor,
|
| 479 |
+
w: torch.Tensor,
|
| 480 |
+
a: torch.Tensor,
|
| 481 |
+
b: torch.Tensor,
|
| 482 |
+
scale: float = 1.0,
|
| 483 |
+
initial_state: torch.Tensor = None,
|
| 484 |
+
output_final_state: bool = True,
|
| 485 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 486 |
+
head_first: bool = True
|
| 487 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 488 |
+
"""
|
| 489 |
+
Args:
|
| 490 |
+
r (torch.Tensor):
|
| 491 |
+
r of shape `[B, H, T, K]` if `head_first=True` else `[B, T, H, K]`.
|
| 492 |
+
k (torch.Tensor):
|
| 493 |
+
k of shape `[B, H, T, K]` if `head_first=True` else `[B, T, H, K]`.
|
| 494 |
+
v (torch.Tensor):
|
| 495 |
+
v of shape `[B, H, T, V]` if `head_first=True` else `[B, T, H, V]`.
|
| 496 |
+
a (torch.Tensor):
|
| 497 |
+
a of shape `[B, H, T, K]` if `head_first=True` else `[B, T, H, K]`.
|
| 498 |
+
b (torch.Tensor):
|
| 499 |
+
b of shape `[B, H, T, K]` if `head_first=True` else `[B, T, H, K]`.
|
| 500 |
+
w (torch.Tensor):
|
| 501 |
+
decay of shape `[B, H, T, K]` if `head_first=True` else `[B, T, H, K]`, kernel
|
| 502 |
+
will apply log_w = -torch.exp(w)
|
| 503 |
+
log_w (torch.Tensor):
|
| 504 |
+
log decay of shape `[B, H, T, K]` if `head_first=True` else `[B, T, H, K]`.
|
| 505 |
+
scale (float):
|
| 506 |
+
scale of the attention.
|
| 507 |
+
initial_state (Optional[torch.Tensor]):
|
| 508 |
+
Initial state of shape `[N, H, K, V]` for `N` input sequences.
|
| 509 |
+
For equal-length input sequences, `N` equals the batch size `B`.
|
| 510 |
+
Default: `None`.
|
| 511 |
+
output_final_state (Optional[bool]):
|
| 512 |
+
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
|
| 513 |
+
cu_seqlens (torch.LongTensor):
|
| 514 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 515 |
+
consistent with the FlashAttention API.
|
| 516 |
+
head_first (bool):
|
| 517 |
+
whether to use head first. Recommended to be False to avoid extra transposes.
|
| 518 |
+
"""
|
| 519 |
+
assert cu_seqlens is None
|
| 520 |
+
assert head_first is True
|
| 521 |
+
assert w is not None
|
| 522 |
+
if scale == -1.0:
|
| 523 |
+
scale = q.shape[-1] ** -0.5
|
| 524 |
+
o, final_state = NativeRecurrentRWKV7Function.apply(q, k, v, w, a, b, scale, initial_state)
|
| 525 |
+
|
| 526 |
+
return o, final_state
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def test_autograd_function():
|
| 530 |
+
"""Test the custom autograd function implementation"""
|
| 531 |
+
# Set random seed for reproducibility
|
| 532 |
+
torch.manual_seed(42)
|
| 533 |
+
|
| 534 |
+
# Define test dimensions
|
| 535 |
+
B, H, T, D = 1, 1, 128, 64
|
| 536 |
+
V = N = D
|
| 537 |
+
device = 'cpu'
|
| 538 |
+
dtype = torch.float64
|
| 539 |
+
|
| 540 |
+
# Create random test inputs
|
| 541 |
+
q = torch.empty(B, H, T, D, device=device).uniform_(-8, 8).to(dtype=dtype).requires_grad_(True)
|
| 542 |
+
k = torch.empty(B, H, T, D, device=device).uniform_(-8, 8).to(dtype=dtype).requires_grad_(True)
|
| 543 |
+
v = torch.empty(B, H, T, D, device=device).uniform_(-8, 8).to(dtype=dtype).requires_grad_(True)
|
| 544 |
+
w = torch.empty(B, H, T, D, device=device).uniform_(-8, -6).to(dtype=dtype).requires_grad_(True)
|
| 545 |
+
|
| 546 |
+
kk = torch.empty(B, H, T, D, device=device).uniform_(-8, 8)
|
| 547 |
+
kk = torch.nn.functional.normalize(kk, dim=-1).to(dtype=dtype)
|
| 548 |
+
|
| 549 |
+
a = -kk.clone().requires_grad_(True) # -kk
|
| 550 |
+
a_scale = torch.empty(B, H, T, D, device=device).uniform_(0, 0.1).to(dtype=dtype)
|
| 551 |
+
b = (kk * a_scale).requires_grad_(True) # kk*a
|
| 552 |
+
|
| 553 |
+
# Create initial state
|
| 554 |
+
initial_state = torch.zeros(B, H, V, N).to(torch.float64)
|
| 555 |
+
|
| 556 |
+
# Clone inputs for the two paths we're testing
|
| 557 |
+
q1, k1, v1, w1, a1, b1 = q.clone().detach().requires_grad_(True), k.clone().detach().requires_grad_(True), v.clone().detach().requires_grad_(
|
| 558 |
+
True), w.clone().detach().requires_grad_(True), a.clone().detach().requires_grad_(True), b.clone().detach().requires_grad_(True)
|
| 559 |
+
q2, k2, v2, w2, a2, b2 = q.clone().detach().requires_grad_(True), k.clone().detach().requires_grad_(True), v.clone().detach().requires_grad_(
|
| 560 |
+
True), w.clone().detach().requires_grad_(True), a.clone().detach().requires_grad_(True), b.clone().detach().requires_grad_(True)
|
| 561 |
+
|
| 562 |
+
# Path 1: Using naive implementation with autograd
|
| 563 |
+
|
| 564 |
+
output1, state1 = naive_recurrent_rwkv7(q1, k1, v1, w1, a1, b1, initial_state=initial_state.clone())
|
| 565 |
+
|
| 566 |
+
output2, state2 = recurrent_rwkv7(q2, k2, v2, w2, a2, b2, 1.0, initial_state.clone())
|
| 567 |
+
|
| 568 |
+
# Check forward pass equivalence
|
| 569 |
+
output_diff = torch.max(torch.abs(output1 - output2)).item()
|
| 570 |
+
state_diff = torch.max(torch.abs(state1 - state2)).item()
|
| 571 |
+
|
| 572 |
+
print(f"\nAutograd Function test (forward):")
|
| 573 |
+
print(f" Max output difference: {output_diff:.6e}")
|
| 574 |
+
print(f" Max state difference: {state_diff:.6e}")
|
| 575 |
+
|
| 576 |
+
# Create loss function to test backward pass
|
| 577 |
+
def compute_loss(output, state):
|
| 578 |
+
return output.sum() # + state.sum()
|
| 579 |
+
|
| 580 |
+
# Compute loss and gradients for both paths
|
| 581 |
+
loss1 = compute_loss(output1, state1)
|
| 582 |
+
loss1.backward()
|
| 583 |
+
|
| 584 |
+
loss2 = compute_loss(output2, state2)
|
| 585 |
+
loss2.backward()
|
| 586 |
+
|
| 587 |
+
# Compare gradients
|
| 588 |
+
grad_diffs = {
|
| 589 |
+
'q': torch.max(torch.abs(q1.grad - q2.grad)).item(),
|
| 590 |
+
'k': torch.max(torch.abs(k1.grad - k2.grad)).item(),
|
| 591 |
+
'v': torch.max(torch.abs(v1.grad - v2.grad)).item(),
|
| 592 |
+
'w': torch.max(torch.abs(w1.grad - w2.grad)).item(),
|
| 593 |
+
'a': torch.max(torch.abs(a1.grad - a2.grad)).item(),
|
| 594 |
+
'b': torch.max(torch.abs(b1.grad - b2.grad)).item(),
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
print(f"\nAutograd Function test (backward):")
|
| 598 |
+
for param, diff in grad_diffs.items():
|
| 599 |
+
print(f" Max {param} gradient difference: {diff:.6e}")
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
test_autograd_function()
|
| 603 |
+
```
|
rwkv7/fused_k_update.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import triton
|
| 7 |
+
import triton.language as tl
|
| 8 |
+
|
| 9 |
+
from fla.ops.utils import prepare_chunk_indices
|
| 10 |
+
from fla.utils import autotune_cache_kwargs, get_multiprocessor_count, input_guard, is_amd
|
| 11 |
+
|
| 12 |
+
NUM_WARPS_AUTOTUNE = [2, 4, 8, 16] if is_amd else [2, 4, 8, 16, 32]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@torch.jit.script
|
| 16 |
+
def k_update_ref(k: torch.Tensor, a: torch.Tensor, ka: torch.Tensor) -> torch.Tensor:
|
| 17 |
+
return k.addcmul(k * (a - 1), ka)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@triton.heuristics({'IS_VARLEN': lambda args: args['cu_seqlens'] is not None})
|
| 21 |
+
@triton.autotune(
|
| 22 |
+
configs=[
|
| 23 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 24 |
+
for w in NUM_WARPS_AUTOTUNE
|
| 25 |
+
for s in [1, 2, 3]
|
| 26 |
+
],
|
| 27 |
+
key=['BD'],
|
| 28 |
+
**autotune_cache_kwargs
|
| 29 |
+
)
|
| 30 |
+
@triton.jit
|
| 31 |
+
def k_update_fwd_kernel_short(
|
| 32 |
+
k, a, ka, out,
|
| 33 |
+
cu_seqlens,
|
| 34 |
+
T, D,
|
| 35 |
+
BD: tl.constexpr,
|
| 36 |
+
IS_VARLEN: tl.constexpr,
|
| 37 |
+
):
|
| 38 |
+
i_b, i_t = tl.program_id(0), tl.program_id(1)
|
| 39 |
+
|
| 40 |
+
if IS_VARLEN:
|
| 41 |
+
bos = tl.load(cu_seqlens + i_b).to(tl.int32)
|
| 42 |
+
eos = tl.load(cu_seqlens + i_b + 1).to(tl.int32)
|
| 43 |
+
g_t = bos + i_t
|
| 44 |
+
if g_t >= eos:
|
| 45 |
+
return
|
| 46 |
+
offset = g_t * D
|
| 47 |
+
else:
|
| 48 |
+
g_t = i_t
|
| 49 |
+
offset = i_b * T * D + g_t * D
|
| 50 |
+
|
| 51 |
+
o_d = tl.arange(0, BD)
|
| 52 |
+
m_d = o_d < D
|
| 53 |
+
off = offset + o_d
|
| 54 |
+
|
| 55 |
+
b_k = tl.load(k + off, mask=m_d, other=0.).to(tl.float32)
|
| 56 |
+
b_a = tl.load(a + off, mask=m_d, other=0.).to(tl.float32)
|
| 57 |
+
b_ka = tl.load(ka + o_d, mask=m_d, eviction_policy='evict_last').to(tl.float32)
|
| 58 |
+
|
| 59 |
+
out_val = b_k * (1 + (b_a - 1) * b_ka)
|
| 60 |
+
tl.store(out + off, out_val.to(out.dtype.element_ty), mask=m_d)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@triton.heuristics({'IS_VARLEN': lambda args: args['cu_seqlens'] is not None})
|
| 64 |
+
@triton.autotune(
|
| 65 |
+
configs=[
|
| 66 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 67 |
+
for w in NUM_WARPS_AUTOTUNE
|
| 68 |
+
for s in [1, 2, 3]
|
| 69 |
+
],
|
| 70 |
+
key=['BD', 'BT'],
|
| 71 |
+
**autotune_cache_kwargs
|
| 72 |
+
)
|
| 73 |
+
@triton.jit
|
| 74 |
+
def k_update_fwd_kernel_long(
|
| 75 |
+
k, a, ka, out,
|
| 76 |
+
cu_seqlens, chunk_indices,
|
| 77 |
+
T, D,
|
| 78 |
+
BD: tl.constexpr, BT: tl.constexpr,
|
| 79 |
+
IS_VARLEN: tl.constexpr,
|
| 80 |
+
):
|
| 81 |
+
i_d, i_t_blk, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 82 |
+
|
| 83 |
+
if IS_VARLEN:
|
| 84 |
+
i_n, i_t_blk = tl.load(chunk_indices + i_t_blk * 2).to(tl.int32), \
|
| 85 |
+
tl.load(chunk_indices + i_t_blk * 2 + 1).to(tl.int32)
|
| 86 |
+
bos = tl.load(cu_seqlens + i_n).to(tl.int32)
|
| 87 |
+
eos = tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 88 |
+
t_start = i_t_blk * BT
|
| 89 |
+
t_end = tl.minimum(t_start + BT, eos - bos)
|
| 90 |
+
else:
|
| 91 |
+
bos = i_b * T
|
| 92 |
+
eos = (i_b + 1) * T
|
| 93 |
+
t_start = i_t_blk * BT
|
| 94 |
+
t_end = tl.minimum(t_start + BT, T)
|
| 95 |
+
|
| 96 |
+
o_d = i_d * BD + tl.arange(0, BD)
|
| 97 |
+
m_d = o_d < D
|
| 98 |
+
|
| 99 |
+
for t in range(t_start, t_end):
|
| 100 |
+
global_t = bos + t
|
| 101 |
+
off = global_t * D + o_d
|
| 102 |
+
b_k = tl.load(k + off, mask=m_d, other=0.).to(tl.float32)
|
| 103 |
+
b_a = tl.load(a + off, mask=m_d, other=0.).to(tl.float32)
|
| 104 |
+
b_ka = tl.load(ka + o_d, mask=m_d, eviction_policy='evict_last').to(tl.float32)
|
| 105 |
+
out_val = b_k * (1 + (b_a - 1) * b_ka)
|
| 106 |
+
tl.store(out + off, out_val.to(out.dtype.element_ty), mask=m_d)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@triton.heuristics({'IS_VARLEN': lambda args: args['cu_seqlens'] is not None})
|
| 110 |
+
@triton.autotune(
|
| 111 |
+
configs=[
|
| 112 |
+
triton.Config({'BT': BT}, num_warps=w, num_stages=s)
|
| 113 |
+
for w in NUM_WARPS_AUTOTUNE
|
| 114 |
+
for s in [1, 2, 3]
|
| 115 |
+
for BT in [2, 4, 8]
|
| 116 |
+
],
|
| 117 |
+
key=['BD'],
|
| 118 |
+
**autotune_cache_kwargs
|
| 119 |
+
)
|
| 120 |
+
@triton.jit
|
| 121 |
+
def k_update_bwd_kernel_short(
|
| 122 |
+
grad_out, k, a, ka,
|
| 123 |
+
dk, da, dka,
|
| 124 |
+
cu_seqlens,
|
| 125 |
+
T, D,
|
| 126 |
+
BT: tl.constexpr,
|
| 127 |
+
BD: tl.constexpr,
|
| 128 |
+
IS_VARLEN: tl.constexpr,
|
| 129 |
+
):
|
| 130 |
+
i_b, i_t_base = tl.program_id(0), tl.program_id(1) * BT
|
| 131 |
+
|
| 132 |
+
if IS_VARLEN:
|
| 133 |
+
bos = tl.load(cu_seqlens + i_b).to(tl.int32)
|
| 134 |
+
eos = tl.load(cu_seqlens + i_b + 1).to(tl.int32)
|
| 135 |
+
seq_len = eos - bos
|
| 136 |
+
else:
|
| 137 |
+
bos = i_b * T
|
| 138 |
+
eos = (i_b + 1) * T
|
| 139 |
+
seq_len = T
|
| 140 |
+
|
| 141 |
+
t_vec = i_t_base + tl.arange(0, BT)
|
| 142 |
+
mask_t = t_vec < seq_len
|
| 143 |
+
global_t_vec = bos + t_vec
|
| 144 |
+
|
| 145 |
+
o_d = tl.arange(0, BD)[None, :]
|
| 146 |
+
m_d = o_d < D
|
| 147 |
+
off = global_t_vec[:, None] * D + o_d
|
| 148 |
+
|
| 149 |
+
b_go = tl.load(grad_out + off, mask=mask_t[:, None] & m_d, other=0.).to(tl.float32)
|
| 150 |
+
b_k = tl.load(k + off, mask=mask_t[:, None] & m_d, other=0.).to(tl.float32)
|
| 151 |
+
b_a = tl.load(a + off, mask=mask_t[:, None] & m_d, other=0.).to(tl.float32)
|
| 152 |
+
b_ka = tl.load(ka + o_d, mask=m_d, eviction_policy='evict_last').to(tl.float32) # [1, BD]
|
| 153 |
+
|
| 154 |
+
dk_vec = b_go * (1 + (b_a - 1) * b_ka)
|
| 155 |
+
da_vec = b_go * b_k * b_ka
|
| 156 |
+
dka_vec = b_go * b_k * (b_a - 1)
|
| 157 |
+
tl.store(dk + off, dk_vec.to(dk.dtype.element_ty), mask=mask_t[:, None] & m_d)
|
| 158 |
+
tl.store(da + off, da_vec.to(da.dtype.element_ty), mask=mask_t[:, None] & m_d)
|
| 159 |
+
tl.store(dka + off, dka_vec.to(dka.dtype.element_ty), mask=mask_t[:, None] & m_d)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@triton.heuristics({'IS_VARLEN': lambda args: args['cu_seqlens'] is not None})
|
| 163 |
+
@triton.autotune(
|
| 164 |
+
configs=[
|
| 165 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 166 |
+
for w in NUM_WARPS_AUTOTUNE
|
| 167 |
+
for s in [1, 2, 3]
|
| 168 |
+
],
|
| 169 |
+
key=['BD', 'BT'],
|
| 170 |
+
**autotune_cache_kwargs
|
| 171 |
+
)
|
| 172 |
+
@triton.jit
|
| 173 |
+
def k_update_bwd_kernel_long(
|
| 174 |
+
grad_out, k, a, ka,
|
| 175 |
+
dk, da, dka,
|
| 176 |
+
cu_seqlens, chunk_indices,
|
| 177 |
+
T, D,
|
| 178 |
+
BD: tl.constexpr, BT: tl.constexpr,
|
| 179 |
+
IS_VARLEN: tl.constexpr,
|
| 180 |
+
):
|
| 181 |
+
i_d, i_t_blk, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 182 |
+
|
| 183 |
+
if IS_VARLEN:
|
| 184 |
+
i_n, i_t_blk = tl.load(chunk_indices + i_t_blk * 2).to(tl.int32), \
|
| 185 |
+
tl.load(chunk_indices + i_t_blk * 2 + 1).to(tl.int32)
|
| 186 |
+
bos = tl.load(cu_seqlens + i_n).to(tl.int32)
|
| 187 |
+
eos = tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 188 |
+
t_start = i_t_blk * BT
|
| 189 |
+
t_end = tl.minimum(t_start + BT, eos - bos)
|
| 190 |
+
else:
|
| 191 |
+
bos = i_b * T
|
| 192 |
+
eos = (i_b + 1) * T
|
| 193 |
+
t_start = i_t_blk * BT
|
| 194 |
+
t_end = tl.minimum(t_start + BT, T)
|
| 195 |
+
|
| 196 |
+
o_d = i_d * BD + tl.arange(0, BD)
|
| 197 |
+
m_d = o_d < D
|
| 198 |
+
|
| 199 |
+
for t in range(t_start, t_end):
|
| 200 |
+
global_t = bos + t
|
| 201 |
+
off = global_t * D + o_d
|
| 202 |
+
|
| 203 |
+
b_go = tl.load(grad_out + off, mask=m_d, other=0.).to(tl.float32)
|
| 204 |
+
b_k = tl.load(k + off, mask=m_d, other=0.).to(tl.float32)
|
| 205 |
+
b_a = tl.load(a + off, mask=m_d, other=0.).to(tl.float32)
|
| 206 |
+
b_ka = tl.load(ka + o_d, mask=m_d, eviction_policy='evict_last').to(tl.float32)
|
| 207 |
+
|
| 208 |
+
tl.store(dk + off, (b_go * (1 + (b_a - 1) * b_ka)).to(dk.dtype.element_ty), mask=m_d)
|
| 209 |
+
tl.store(da + off, (b_go * b_k * b_ka).to(da.dtype.element_ty), mask=m_d)
|
| 210 |
+
tl.store(dka + off, (b_go * b_k * (b_a - 1)).to(dka.dtype.element_ty), mask=m_d)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def k_update_fwd(
|
| 214 |
+
k: torch.Tensor,
|
| 215 |
+
a: torch.Tensor,
|
| 216 |
+
ka: torch.Tensor,
|
| 217 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 218 |
+
) -> torch.Tensor:
|
| 219 |
+
B, T, D = k.shape
|
| 220 |
+
out = torch.empty_like(k)
|
| 221 |
+
use_short = T <= 512
|
| 222 |
+
|
| 223 |
+
if use_short:
|
| 224 |
+
if cu_seqlens is not None:
|
| 225 |
+
N = len(cu_seqlens) - 1
|
| 226 |
+
else:
|
| 227 |
+
N = B
|
| 228 |
+
BD = triton.next_power_of_2(D)
|
| 229 |
+
grid = (N, T)
|
| 230 |
+
k_update_fwd_kernel_short[grid](
|
| 231 |
+
k, a, ka, out,
|
| 232 |
+
cu_seqlens,
|
| 233 |
+
T, D,
|
| 234 |
+
BD=BD,
|
| 235 |
+
)
|
| 236 |
+
else:
|
| 237 |
+
BT = min(64, triton.next_power_of_2(
|
| 238 |
+
triton.cdiv(max(16, B * T), get_multiprocessor_count(k.device.index))
|
| 239 |
+
))
|
| 240 |
+
if cu_seqlens is not None:
|
| 241 |
+
chunk_idx = prepare_chunk_indices(cu_seqlens, BT)
|
| 242 |
+
NT = len(chunk_idx)
|
| 243 |
+
N = len(cu_seqlens) - 1
|
| 244 |
+
else:
|
| 245 |
+
chunk_idx = None
|
| 246 |
+
NT = triton.cdiv(T, BT)
|
| 247 |
+
N = B
|
| 248 |
+
|
| 249 |
+
BD = triton.next_power_of_2(D)
|
| 250 |
+
|
| 251 |
+
def grid(meta):
|
| 252 |
+
return (triton.cdiv(D, meta['BD']), NT, N)
|
| 253 |
+
|
| 254 |
+
k_update_fwd_kernel_long[grid](
|
| 255 |
+
k, a, ka, out,
|
| 256 |
+
cu_seqlens, chunk_idx,
|
| 257 |
+
T, D,
|
| 258 |
+
BD=BD, BT=BT,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
return out, use_short, N, T
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def k_update_bwd(
|
| 265 |
+
grad_out: torch.Tensor,
|
| 266 |
+
k: torch.Tensor,
|
| 267 |
+
a: torch.Tensor,
|
| 268 |
+
ka: torch.Tensor,
|
| 269 |
+
cu_seqlens: Optional[torch.Tensor],
|
| 270 |
+
use_short: bool,
|
| 271 |
+
N: int,
|
| 272 |
+
T: int,
|
| 273 |
+
):
|
| 274 |
+
B, _, D = grad_out.shape
|
| 275 |
+
dk = torch.empty_like(k)
|
| 276 |
+
da = torch.empty_like(a)
|
| 277 |
+
dka_tmp = torch.empty_like(k, dtype=torch.float32)
|
| 278 |
+
|
| 279 |
+
if use_short:
|
| 280 |
+
BD = triton.next_power_of_2(D)
|
| 281 |
+
def grid(meta): return (N, triton.cdiv(T, meta['BT']))
|
| 282 |
+
k_update_bwd_kernel_short[grid](
|
| 283 |
+
grad_out, k, a, ka,
|
| 284 |
+
dk, da, dka_tmp,
|
| 285 |
+
cu_seqlens,
|
| 286 |
+
T, D,
|
| 287 |
+
BD=BD,
|
| 288 |
+
)
|
| 289 |
+
else:
|
| 290 |
+
BT = min(64, triton.next_power_of_2(
|
| 291 |
+
triton.cdiv(max(16, B * T), get_multiprocessor_count(grad_out.device.index))
|
| 292 |
+
))
|
| 293 |
+
if cu_seqlens is not None:
|
| 294 |
+
chunk_idx = prepare_chunk_indices(cu_seqlens, BT)
|
| 295 |
+
NT = len(chunk_idx)
|
| 296 |
+
else:
|
| 297 |
+
chunk_idx = None
|
| 298 |
+
NT = triton.cdiv(T, BT)
|
| 299 |
+
|
| 300 |
+
BD = triton.next_power_of_2(D)
|
| 301 |
+
|
| 302 |
+
def grid(meta):
|
| 303 |
+
return (triton.cdiv(D, meta['BD']), NT, N)
|
| 304 |
+
|
| 305 |
+
k_update_bwd_kernel_long[grid](
|
| 306 |
+
grad_out, k, a, ka,
|
| 307 |
+
dk, da, dka_tmp,
|
| 308 |
+
cu_seqlens, chunk_idx,
|
| 309 |
+
T, D,
|
| 310 |
+
BD=BD, BT=BT,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
if dka_tmp.dim() == 3:
|
| 314 |
+
dka = dka_tmp.sum(dim=(0, 1), keepdim=True).type_as(ka)
|
| 315 |
+
else:
|
| 316 |
+
dka = dka_tmp.sum(dim=(0, 1)).type_as(ka)
|
| 317 |
+
|
| 318 |
+
return dk, da, dka
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class KUpdateFunction(torch.autograd.Function):
|
| 322 |
+
@staticmethod
|
| 323 |
+
@input_guard
|
| 324 |
+
def forward(ctx, k, a, ka, cu_seqlens=None):
|
| 325 |
+
out, use_short, N, T = k_update_fwd(k, a, ka, cu_seqlens)
|
| 326 |
+
ctx.save_for_backward(k, a, ka)
|
| 327 |
+
ctx.use_short = use_short
|
| 328 |
+
ctx.N = N
|
| 329 |
+
ctx.T = T
|
| 330 |
+
ctx.cu_seqlens = cu_seqlens
|
| 331 |
+
return out
|
| 332 |
+
|
| 333 |
+
@staticmethod
|
| 334 |
+
@input_guard
|
| 335 |
+
def backward(ctx, grad_output):
|
| 336 |
+
k, a, ka = ctx.saved_tensors
|
| 337 |
+
dk, da, dka = k_update_bwd(
|
| 338 |
+
grad_output, k, a, ka,
|
| 339 |
+
ctx.cu_seqlens,
|
| 340 |
+
ctx.use_short,
|
| 341 |
+
ctx.N,
|
| 342 |
+
ctx.T,
|
| 343 |
+
)
|
| 344 |
+
return dk, da, dka, None
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def fused_k_rwkv7(k, a, ka, cu_seqlens=None):
|
| 348 |
+
if k.shape[1] == 1:
|
| 349 |
+
return k_update_ref(k, a, ka)
|
| 350 |
+
return KUpdateFunction.apply(k, a, ka, cu_seqlens)
|
rwkv7/fused_recurrent.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import triton
|
| 9 |
+
import triton.language as tl
|
| 10 |
+
|
| 11 |
+
from fla.ops.generalized_delta_rule import fused_recurrent_dplr_delta_rule
|
| 12 |
+
from fla.ops.utils.op import exp
|
| 13 |
+
from fla.utils import autotune_cache_kwargs, input_guard, use_cuda_graph
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@triton.heuristics({
|
| 17 |
+
'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
|
| 18 |
+
'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
|
| 19 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
| 20 |
+
})
|
| 21 |
+
@triton.autotune(
|
| 22 |
+
configs=[
|
| 23 |
+
triton.Config({'BV': BV}, num_warps=num_warps, num_stages=num_stages)
|
| 24 |
+
for BV in [16, 32, 64]
|
| 25 |
+
for num_warps in [2, 4, 8, 16]
|
| 26 |
+
for num_stages in [2, 3, 4]
|
| 27 |
+
],
|
| 28 |
+
key=['BK'],
|
| 29 |
+
use_cuda_graph=use_cuda_graph,
|
| 30 |
+
**autotune_cache_kwargs
|
| 31 |
+
)
|
| 32 |
+
@triton.jit(do_not_specialize=['T'])
|
| 33 |
+
def fused_recurrent_rwkv7_fwd_kernel(
|
| 34 |
+
r,
|
| 35 |
+
w,
|
| 36 |
+
k,
|
| 37 |
+
v,
|
| 38 |
+
kk,
|
| 39 |
+
a,
|
| 40 |
+
o,
|
| 41 |
+
h0,
|
| 42 |
+
ht,
|
| 43 |
+
cu_seqlens,
|
| 44 |
+
scale,
|
| 45 |
+
T,
|
| 46 |
+
B: tl.constexpr,
|
| 47 |
+
H: tl.constexpr,
|
| 48 |
+
K: tl.constexpr,
|
| 49 |
+
V: tl.constexpr,
|
| 50 |
+
BK: tl.constexpr,
|
| 51 |
+
BV: tl.constexpr,
|
| 52 |
+
REVERSE: tl.constexpr,
|
| 53 |
+
USE_INITIAL_STATE: tl.constexpr,
|
| 54 |
+
STORE_FINAL_STATE: tl.constexpr,
|
| 55 |
+
IS_VARLEN: tl.constexpr,
|
| 56 |
+
IS_DECODE: tl.constexpr,
|
| 57 |
+
):
|
| 58 |
+
i_v, i_nh = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
|
| 59 |
+
i_n, i_h = i_nh // H, i_nh % H
|
| 60 |
+
|
| 61 |
+
if IS_VARLEN:
|
| 62 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
|
| 63 |
+
T = eos - bos
|
| 64 |
+
else:
|
| 65 |
+
bos, eos = i_n * T, i_n * T + T
|
| 66 |
+
|
| 67 |
+
o_k = tl.arange(0, BK)
|
| 68 |
+
o_v = i_v * BV + tl.arange(0, BV)
|
| 69 |
+
p_r = r + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
| 70 |
+
p_w = w + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
| 71 |
+
p_k = k + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
| 72 |
+
p_v = v + (bos + ((T - 1) if REVERSE else 0)) * H*V + i_h * V + o_v
|
| 73 |
+
p_a = a + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
| 74 |
+
p_kk = kk + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
| 75 |
+
|
| 76 |
+
p_o = o + (bos + ((T - 1) if REVERSE else 0)) * H*V + i_h * V + o_v
|
| 77 |
+
|
| 78 |
+
mask_k = o_k < K
|
| 79 |
+
mask_v = o_v < V
|
| 80 |
+
mask_h = mask_k[:, None] & mask_v[None, :]
|
| 81 |
+
b_h = tl.zeros([BK, BV], dtype=tl.float32)
|
| 82 |
+
|
| 83 |
+
if USE_INITIAL_STATE:
|
| 84 |
+
p_h0 = h0 + i_nh * K*V + o_k[:, None] * V + o_v
|
| 85 |
+
b_h += tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
|
| 86 |
+
|
| 87 |
+
if IS_DECODE:
|
| 88 |
+
b_r = tl.load(p_r, mask=mask_k, other=0).to(tl.float32) * scale
|
| 89 |
+
b_w = tl.load(p_w, mask=mask_k, other=0).to(tl.float32)
|
| 90 |
+
b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
|
| 91 |
+
b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
|
| 92 |
+
b_a = tl.load(p_a, mask=mask_k, other=0).to(tl.float32)
|
| 93 |
+
b_kk = tl.load(p_kk, mask=mask_k, other=0).to(tl.float32)
|
| 94 |
+
b_act_a = -b_kk
|
| 95 |
+
b_b = b_kk * b_a
|
| 96 |
+
|
| 97 |
+
b_h = exp(b_w)[:, None] * b_h + b_b[:, None] * tl.sum(b_act_a[:, None] * b_h, 0)[None, :]
|
| 98 |
+
b_h += b_k[:, None] * b_v[None, :]
|
| 99 |
+
b_o = tl.sum(b_h * b_r[:, None], 0)
|
| 100 |
+
|
| 101 |
+
tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
|
| 102 |
+
else:
|
| 103 |
+
for _ in range(0, T):
|
| 104 |
+
b_r = tl.load(p_r, mask=mask_k, other=0).to(tl.float32) * scale
|
| 105 |
+
b_w = tl.load(p_w, mask=mask_k, other=0).to(tl.float32)
|
| 106 |
+
b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
|
| 107 |
+
b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
|
| 108 |
+
b_a = tl.load(p_a, mask=mask_k, other=0).to(tl.float32)
|
| 109 |
+
b_kk = tl.load(p_kk, mask=mask_k, other=0).to(tl.float32)
|
| 110 |
+
b_act_a = -b_kk
|
| 111 |
+
b_b = b_kk * b_a
|
| 112 |
+
|
| 113 |
+
b_h = exp(b_w)[:, None] * b_h + b_b[:, None] * tl.sum(b_act_a[:, None] * b_h, 0)[None, :]
|
| 114 |
+
b_h += b_k[:, None] * b_v[None, :]
|
| 115 |
+
b_o = tl.sum(b_h * b_r[:, None], 0)
|
| 116 |
+
|
| 117 |
+
tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
|
| 118 |
+
p_r += (-1 if REVERSE else 1) * H*K
|
| 119 |
+
p_w += (-1 if REVERSE else 1) * H*K
|
| 120 |
+
p_k += (-1 if REVERSE else 1) * H*K
|
| 121 |
+
p_v += (-1 if REVERSE else 1) * H*V
|
| 122 |
+
p_a += (-1 if REVERSE else 1) * H*K
|
| 123 |
+
p_kk += (-1 if REVERSE else 1) * H*K
|
| 124 |
+
p_o += (-1 if REVERSE else 1) * H*V
|
| 125 |
+
|
| 126 |
+
if STORE_FINAL_STATE:
|
| 127 |
+
p_ht = ht + i_nh * K*V + o_k[:, None] * V + o_v
|
| 128 |
+
tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@input_guard
|
| 132 |
+
def fused_recurrent_rwkv7_fwd(
|
| 133 |
+
r: torch.Tensor,
|
| 134 |
+
w: torch.Tensor,
|
| 135 |
+
k: torch.Tensor,
|
| 136 |
+
v: torch.Tensor,
|
| 137 |
+
kk: torch.Tensor,
|
| 138 |
+
a: torch.Tensor,
|
| 139 |
+
scale: Optional[float] = 1.0,
|
| 140 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 141 |
+
output_final_state: bool = False,
|
| 142 |
+
reverse: bool = False,
|
| 143 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 144 |
+
):
|
| 145 |
+
B, T, H, K, V = *k.shape, v.shape[-1]
|
| 146 |
+
N = B if cu_seqlens is None else len(cu_seqlens) - 1
|
| 147 |
+
BK = triton.next_power_of_2(K)
|
| 148 |
+
IS_DECODE = (T == 1)
|
| 149 |
+
|
| 150 |
+
h0 = initial_state
|
| 151 |
+
if not output_final_state:
|
| 152 |
+
ht = None
|
| 153 |
+
else:
|
| 154 |
+
ht = r.new_empty(N, H, K, V, dtype=torch.float32)
|
| 155 |
+
o = torch.empty_like(v)
|
| 156 |
+
|
| 157 |
+
def grid(meta): return (triton.cdiv(V, meta['BV']), N * H)
|
| 158 |
+
fused_recurrent_rwkv7_fwd_kernel[grid](
|
| 159 |
+
r,
|
| 160 |
+
w,
|
| 161 |
+
k,
|
| 162 |
+
v,
|
| 163 |
+
kk,
|
| 164 |
+
a,
|
| 165 |
+
o,
|
| 166 |
+
h0,
|
| 167 |
+
ht,
|
| 168 |
+
cu_seqlens,
|
| 169 |
+
scale,
|
| 170 |
+
T=T,
|
| 171 |
+
B=B,
|
| 172 |
+
H=H,
|
| 173 |
+
K=K,
|
| 174 |
+
V=V,
|
| 175 |
+
BK=BK,
|
| 176 |
+
REVERSE=reverse,
|
| 177 |
+
IS_DECODE=IS_DECODE
|
| 178 |
+
)
|
| 179 |
+
return o, ht
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def fused_recurrent_rwkv7(
|
| 183 |
+
r: torch.Tensor,
|
| 184 |
+
w: torch.Tensor,
|
| 185 |
+
k: torch.Tensor,
|
| 186 |
+
v: torch.Tensor,
|
| 187 |
+
a: torch.Tensor,
|
| 188 |
+
b: torch.Tensor,
|
| 189 |
+
scale: Optional[float] = None,
|
| 190 |
+
initial_state: torch.Tensor = None,
|
| 191 |
+
output_final_state: bool = True,
|
| 192 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 193 |
+
head_first: bool = False,
|
| 194 |
+
):
|
| 195 |
+
"""
|
| 196 |
+
Args:
|
| 197 |
+
r (torch.Tensor):
|
| 198 |
+
r of shape `[B, T, H, K]`.
|
| 199 |
+
w (torch.Tensor):
|
| 200 |
+
log decay of shape `[B, T, H, K]`.
|
| 201 |
+
k (torch.Tensor):
|
| 202 |
+
k of shape `[B, T, H, K]`.
|
| 203 |
+
v (torch.Tensor):
|
| 204 |
+
v of shape `[B, T, H, V]`.
|
| 205 |
+
a (torch.Tensor):
|
| 206 |
+
a of shape `[B, T, H, K]`.
|
| 207 |
+
b (torch.Tensor):
|
| 208 |
+
b of shape `[B, T, H, K]`.
|
| 209 |
+
scale (float):
|
| 210 |
+
scale of the attention.
|
| 211 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
| 212 |
+
initial_state (torch.Tensor):
|
| 213 |
+
initial state of shape `[B, H, K, V]` if cu_seqlens is None else `[N, H, K, V]` where N = len(cu_seqlens) - 1.
|
| 214 |
+
output_final_state (bool):
|
| 215 |
+
whether to output the final state.
|
| 216 |
+
cu_seqlens (torch.LongTensor):
|
| 217 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 218 |
+
consistent with the FlashAttention API.
|
| 219 |
+
head_first (Optional[bool]):
|
| 220 |
+
Whether the inputs are in the head-first format. Default: `False`.
|
| 221 |
+
This argument has been deprecated.
|
| 222 |
+
"""
|
| 223 |
+
if head_first:
|
| 224 |
+
raise DeprecationWarning(
|
| 225 |
+
"head_first is deprecated and will be removed in a future version. "
|
| 226 |
+
"Please use head_first=False for now instead."
|
| 227 |
+
)
|
| 228 |
+
elif r.shape[1] < r.shape[2]:
|
| 229 |
+
warnings.warn(
|
| 230 |
+
f"Input tensor shape suggests potential format mismatch: seq_len ({r.shape[1]}) < num_heads ({r.shape[2]}). "
|
| 231 |
+
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
|
| 232 |
+
"when head_first=False was specified. "
|
| 233 |
+
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
|
| 234 |
+
)
|
| 235 |
+
return fused_recurrent_dplr_delta_rule(
|
| 236 |
+
q=r,
|
| 237 |
+
k=k,
|
| 238 |
+
v=v,
|
| 239 |
+
a=a,
|
| 240 |
+
b=b,
|
| 241 |
+
gk=w,
|
| 242 |
+
scale=scale,
|
| 243 |
+
initial_state=initial_state,
|
| 244 |
+
output_final_state=output_final_state,
|
| 245 |
+
cu_seqlens=cu_seqlens,
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def fused_mul_recurrent_rwkv7(
|
| 250 |
+
r: torch.Tensor,
|
| 251 |
+
w: torch.Tensor,
|
| 252 |
+
k: torch.Tensor,
|
| 253 |
+
v: torch.Tensor,
|
| 254 |
+
kk: torch.Tensor,
|
| 255 |
+
a: torch.Tensor,
|
| 256 |
+
scale: Optional[float] = 1.0,
|
| 257 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 258 |
+
output_final_state: bool = False,
|
| 259 |
+
reverse: bool = False,
|
| 260 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 261 |
+
head_first: bool = False,
|
| 262 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 263 |
+
r"""
|
| 264 |
+
This function computes the recurrence S_t = S_t @ (I + a_t b_t^T) + v_t k_t^T in a recurrent manner.
|
| 265 |
+
|
| 266 |
+
Args:
|
| 267 |
+
r (torch.Tensor):
|
| 268 |
+
queries of shape `[B, T, H, K]`.
|
| 269 |
+
w (torch.Tensor):
|
| 270 |
+
keys of shape `[B, T, H, K]`.
|
| 271 |
+
k (torch.Tensor):
|
| 272 |
+
values of shape `[B, T, H, V]`.
|
| 273 |
+
v (torch.Tensor):
|
| 274 |
+
a of shape `[B, T, H, K]`.
|
| 275 |
+
kk (torch.Tensor):
|
| 276 |
+
b of shape `[B, T, H, K]`.
|
| 277 |
+
a (torch.Tensor):
|
| 278 |
+
gk of shape `[B, T, H, K]`. decay term in log space!
|
| 279 |
+
scale (Optional[float]):
|
| 280 |
+
Scale factor for the RetNet attention scores.
|
| 281 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: 1.
|
| 282 |
+
initial_state (Optional[torch.Tensor]):
|
| 283 |
+
Initial state of shape `[N, H, K, V]` for `N` input sequences.
|
| 284 |
+
For equal-length input sequences, `N` equals the batch size `B`.
|
| 285 |
+
Default: `None`.
|
| 286 |
+
output_final_state (Optional[bool]):
|
| 287 |
+
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
|
| 288 |
+
reverse (Optional[bool]):
|
| 289 |
+
If `True`, process the state passing in reverse order. Default: `False`.
|
| 290 |
+
cu_seqlens (Optional[torch.Tensor]):
|
| 291 |
+
Cumulative sequence lengths of shape `[N + 1]` used for variable-length training,
|
| 292 |
+
consistent with the FlashAttention API.
|
| 293 |
+
head_first (Optional[bool]):
|
| 294 |
+
Whether the inputs are in the head-first format. Default: `False`.
|
| 295 |
+
This argument has been deprecated.
|
| 296 |
+
"""
|
| 297 |
+
if head_first:
|
| 298 |
+
raise DeprecationWarning(
|
| 299 |
+
"head_first is deprecated and will be removed in a future version. "
|
| 300 |
+
"Please use head_first=False for now instead."
|
| 301 |
+
)
|
| 302 |
+
elif r.shape[1] < r.shape[2]:
|
| 303 |
+
warnings.warn(
|
| 304 |
+
f"Input tensor shape suggests potential format mismatch: seq_len ({r.shape[1]}) < num_heads ({r.shape[2]}). "
|
| 305 |
+
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
|
| 306 |
+
"when head_first=False was specified. "
|
| 307 |
+
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
|
| 308 |
+
)
|
| 309 |
+
if cu_seqlens is not None:
|
| 310 |
+
if r.shape[0] != 1:
|
| 311 |
+
raise ValueError(
|
| 312 |
+
f"The batch size is expected to be 1 rather than {r.shape[0]} when using `cu_seqlens`."
|
| 313 |
+
f"Please flatten variable-length inputs before processing."
|
| 314 |
+
)
|
| 315 |
+
if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
|
| 316 |
+
raise ValueError(
|
| 317 |
+
f"The number of initial states is expected to be equal to the number of input sequences, "
|
| 318 |
+
f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
|
| 319 |
+
)
|
| 320 |
+
if scale is None:
|
| 321 |
+
scale = r.shape[-1] ** -0.5
|
| 322 |
+
o, final_state = fused_recurrent_rwkv7_fwd(
|
| 323 |
+
r,
|
| 324 |
+
w,
|
| 325 |
+
k,
|
| 326 |
+
v,
|
| 327 |
+
kk,
|
| 328 |
+
a,
|
| 329 |
+
scale,
|
| 330 |
+
initial_state,
|
| 331 |
+
output_final_state,
|
| 332 |
+
reverse,
|
| 333 |
+
cu_seqlens,
|
| 334 |
+
)
|
| 335 |
+
return o, final_state
|
simple_gla/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from .chunk import chunk_simple_gla
|
| 4 |
+
from .fused_chunk import fused_chunk_simple_gla
|
| 5 |
+
from .fused_recurrent import fused_recurrent_simple_gla
|
| 6 |
+
from .parallel import parallel_simple_gla
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
'chunk_simple_gla',
|
| 10 |
+
'fused_chunk_simple_gla',
|
| 11 |
+
'fused_recurrent_simple_gla',
|
| 12 |
+
'parallel_simple_gla'
|
| 13 |
+
]
|
simple_gla/fused_chunk.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from fla.ops.common.fused_chunk import fused_chunk
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def fused_chunk_simple_gla(
|
| 12 |
+
q: torch.Tensor,
|
| 13 |
+
k: torch.Tensor,
|
| 14 |
+
v: torch.Tensor,
|
| 15 |
+
g: torch.Tensor = None,
|
| 16 |
+
g_gamma: torch.Tensor = None,
|
| 17 |
+
scale: Optional[float] = None,
|
| 18 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 19 |
+
output_final_state: bool = False,
|
| 20 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 21 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 22 |
+
r"""
|
| 23 |
+
Args:
|
| 24 |
+
q (torch.Tensor):
|
| 25 |
+
queries of shape `[B, T, H, K]`.
|
| 26 |
+
k (torch.Tensor):
|
| 27 |
+
keys of shape `[B, T, H, K]`.
|
| 28 |
+
v (torch.Tensor):
|
| 29 |
+
values of shape `[B, T, H, V]`.
|
| 30 |
+
g (torch.Tensor):
|
| 31 |
+
Forget gates of shape `[B, T, H]`.
|
| 32 |
+
Compared to GLA, the gating is head-wise instead of elementwise.
|
| 33 |
+
g_gamma (torch.Tensor):
|
| 34 |
+
Log decay of shape `[H]`.
|
| 35 |
+
Head-wise data-independent decay is used if `g_gamma` is provided.
|
| 36 |
+
Only one of `g` or `g_gamma` should be provided.
|
| 37 |
+
scale (Optional[int]):
|
| 38 |
+
Scale factor for the attention scores.
|
| 39 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
| 40 |
+
initial_state (Optional[torch.Tensor]):
|
| 41 |
+
Initial state of shape `[N, H, K, V]` for `N` input sequences.
|
| 42 |
+
For equal-length input sequences, `N` equals the batch size `B`.
|
| 43 |
+
Default: `None`.
|
| 44 |
+
output_final_state (Optional[bool]):
|
| 45 |
+
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
|
| 46 |
+
cu_seqlens (torch.LongTensor):
|
| 47 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 48 |
+
consistent with the FlashAttention API.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
o (torch.Tensor):
|
| 52 |
+
Outputs of shape `[B, T, H, V]`.
|
| 53 |
+
final_state (torch.Tensor):
|
| 54 |
+
Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
|
| 55 |
+
|
| 56 |
+
Examples::
|
| 57 |
+
>>> import torch
|
| 58 |
+
>>> import torch.nn.functional as F
|
| 59 |
+
>>> from einops import rearrange
|
| 60 |
+
>>> from fla.ops.simple_gla import fused_chunk_simple_gla
|
| 61 |
+
# inputs with equal lengths
|
| 62 |
+
>>> B, T, H, K, V = 4, 2048, 4, 512, 512
|
| 63 |
+
>>> q = torch.randn(B, T, H, K, device='cuda')
|
| 64 |
+
>>> k = torch.randn(B, T, H, K, device='cuda')
|
| 65 |
+
>>> v = torch.randn(B, T, H, V, device='cuda')
|
| 66 |
+
>>> g = F.logsigmoid(torch.randn(B, T, H, device='cuda'))
|
| 67 |
+
>>> h0 = torch.randn(B, H, K, V, device='cuda')
|
| 68 |
+
>>> o, ht = fused_chunk_simple_gla(
|
| 69 |
+
q, k, v, g,
|
| 70 |
+
initial_state=h0,
|
| 71 |
+
output_final_state=True
|
| 72 |
+
)
|
| 73 |
+
# for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
|
| 74 |
+
>>> q, k, v, g = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (q, k, v, g))
|
| 75 |
+
# for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
|
| 76 |
+
>>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
|
| 77 |
+
>>> o, ht = fused_chunk_simple_gla(
|
| 78 |
+
q, k, v, g,
|
| 79 |
+
initial_state=h0,
|
| 80 |
+
output_final_state=True,
|
| 81 |
+
cu_seqlens=cu_seqlens
|
| 82 |
+
)
|
| 83 |
+
"""
|
| 84 |
+
if cu_seqlens is not None:
|
| 85 |
+
if q.shape[0] != 1:
|
| 86 |
+
raise ValueError(
|
| 87 |
+
f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
|
| 88 |
+
f"Please flatten variable-length inputs before processing."
|
| 89 |
+
)
|
| 90 |
+
if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
|
| 91 |
+
raise ValueError(
|
| 92 |
+
f"The number of initial states is expected to be equal to the number of input sequences, "
|
| 93 |
+
f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
|
| 94 |
+
)
|
| 95 |
+
if scale is None:
|
| 96 |
+
scale = k.shape[-1] ** -0.5
|
| 97 |
+
o, final_state = fused_chunk(
|
| 98 |
+
q=q,
|
| 99 |
+
k=k,
|
| 100 |
+
v=v,
|
| 101 |
+
g=g,
|
| 102 |
+
g_gamma=g_gamma,
|
| 103 |
+
scale=scale,
|
| 104 |
+
initial_state=initial_state,
|
| 105 |
+
output_final_state=output_final_state,
|
| 106 |
+
cu_seqlens=cu_seqlens
|
| 107 |
+
)
|
| 108 |
+
return o, final_state
|
state_org/fused_recurrent.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2024, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from fla.ops.common.fused_recurrent import fused_recurrent
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def fused_recurrent_gla(
|
| 12 |
+
q: torch.Tensor,
|
| 13 |
+
k: torch.Tensor,
|
| 14 |
+
v: torch.Tensor,
|
| 15 |
+
gk: Optional[torch.Tensor] = None,
|
| 16 |
+
gv: Optional[torch.Tensor] = None,
|
| 17 |
+
scale: Optional[int] = None,
|
| 18 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 19 |
+
output_final_state: bool = False,
|
| 20 |
+
reverse: bool = False,
|
| 21 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 22 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 23 |
+
r"""
|
| 24 |
+
Args:
|
| 25 |
+
q (torch.Tensor):
|
| 26 |
+
queries of shape `[B, T, H, K]`.
|
| 27 |
+
k (torch.Tensor):
|
| 28 |
+
keys of shape `[B, T, H, K]`.
|
| 29 |
+
v (torch.Tensor):
|
| 30 |
+
values of shape `[B, T, H, V]`.
|
| 31 |
+
gk (torch.Tensor):
|
| 32 |
+
Forget gates of shape `[B, T, H, K]`.
|
| 33 |
+
gv (torch.Tensor):
|
| 34 |
+
Forget gates of shape `[B, T, H, V]` applied to values.
|
| 35 |
+
scale (Optional[float]):
|
| 36 |
+
Scale factor for the attention scores.
|
| 37 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
| 38 |
+
initial_state (Optional[torch.Tensor]):
|
| 39 |
+
Initial state of shape `[N, H, K, V]` for `N` input sequences.
|
| 40 |
+
For equal-length input sequences, `N` equals the batch size `B`.
|
| 41 |
+
Default: `None`.
|
| 42 |
+
output_final_state (Optional[bool]):
|
| 43 |
+
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
|
| 44 |
+
reverse (Optional[bool]):
|
| 45 |
+
If `True`, process the state passing in reverse order. Default: `False`.
|
| 46 |
+
cu_seqlens (torch.LongTensor):
|
| 47 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 48 |
+
consistent with the FlashAttention API.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
o (torch.Tensor):
|
| 52 |
+
Outputs of shape `[B, T, H, V]`.
|
| 53 |
+
final_state (torch.Tensor):
|
| 54 |
+
Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
|
| 55 |
+
|
| 56 |
+
Examples::
|
| 57 |
+
>>> import torch
|
| 58 |
+
>>> import torch.nn.functional as F
|
| 59 |
+
>>> from einops import rearrange
|
| 60 |
+
>>> from fla.ops.gla import fused_recurrent_gla
|
| 61 |
+
# inputs with equal lengths
|
| 62 |
+
>>> B, T, H, K, V = 4, 2048, 4, 512, 512
|
| 63 |
+
>>> q = torch.randn(B, T, H, K, device='cuda')
|
| 64 |
+
>>> k = torch.randn(B, T, H, K, device='cuda')
|
| 65 |
+
>>> v = torch.randn(B, T, H, V, device='cuda')
|
| 66 |
+
>>> g = F.logsigmoid(torch.randn(B, T, H, K, device='cuda'))
|
| 67 |
+
>>> h0 = torch.randn(B, H, K, V, device='cuda')
|
| 68 |
+
>>> o, ht = fused_recurrent_gla(
|
| 69 |
+
q, k, v, g,
|
| 70 |
+
initial_state=h0,
|
| 71 |
+
output_final_state=True
|
| 72 |
+
)
|
| 73 |
+
# for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
|
| 74 |
+
>>> q, k, v, g = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (q, k, v, g))
|
| 75 |
+
# for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
|
| 76 |
+
>>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
|
| 77 |
+
>>> o_var, ht_var = fused_recurrent_gla(
|
| 78 |
+
q, k, v, g,
|
| 79 |
+
initial_state=h0,
|
| 80 |
+
output_final_state=True,
|
| 81 |
+
cu_seqlens=cu_seqlens
|
| 82 |
+
)
|
| 83 |
+
>>> assert o.allclose(o_var.view(o.shape))
|
| 84 |
+
"""
|
| 85 |
+
if cu_seqlens is not None:
|
| 86 |
+
if q.shape[0] != 1:
|
| 87 |
+
raise ValueError(
|
| 88 |
+
f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
|
| 89 |
+
f"Please flatten variable-length inputs before processing."
|
| 90 |
+
)
|
| 91 |
+
if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
|
| 92 |
+
raise ValueError(
|
| 93 |
+
f"The number of initial states is expected to be equal to the number of input sequences, "
|
| 94 |
+
f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
|
| 95 |
+
)
|
| 96 |
+
if scale is None:
|
| 97 |
+
scale = k.shape[-1] ** -0.5
|
| 98 |
+
o, final_state = fused_recurrent(
|
| 99 |
+
q=q,
|
| 100 |
+
k=k,
|
| 101 |
+
v=v,
|
| 102 |
+
g=None,
|
| 103 |
+
gk=gk,
|
| 104 |
+
gv=gv,
|
| 105 |
+
scale=scale,
|
| 106 |
+
initial_state=initial_state,
|
| 107 |
+
output_final_state=output_final_state,
|
| 108 |
+
reverse=reverse,
|
| 109 |
+
cu_seqlens=cu_seqlens,
|
| 110 |
+
)
|
| 111 |
+
return o, final_state
|
state_org/naive.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def ceildiv(a, b):
|
| 9 |
+
return -(a // -b)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def naive_recurrent_gla(
|
| 13 |
+
q: torch.Tensor,
|
| 14 |
+
k: torch.Tensor,
|
| 15 |
+
v: torch.Tensor,
|
| 16 |
+
gk: torch.Tensor,
|
| 17 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 18 |
+
output_final_state: bool = False
|
| 19 |
+
):
|
| 20 |
+
dtype = q.dtype
|
| 21 |
+
q, k, v, gk = map(lambda x: x.transpose(1, 2).float(), (q, k, v, gk))
|
| 22 |
+
B, H, T, K, V = *q.shape, v.shape[-1]
|
| 23 |
+
o = torch.zeros_like(v)
|
| 24 |
+
scale = K ** -0.5
|
| 25 |
+
|
| 26 |
+
h = q.new_zeros(B, H, K, V, dtype=torch.float32)
|
| 27 |
+
if initial_state is not None:
|
| 28 |
+
h += initial_state.float()
|
| 29 |
+
|
| 30 |
+
for i in range(T):
|
| 31 |
+
q_i = q[:, :, i] * scale
|
| 32 |
+
k_i = k[:, :, i]
|
| 33 |
+
v_i = v[:, :, i]
|
| 34 |
+
gk_i = gk[:, :, i].exp()
|
| 35 |
+
kv_i = k_i[..., None] * v_i[..., None, :]
|
| 36 |
+
h = h * gk_i[..., None] + kv_i
|
| 37 |
+
o[:, :, i] = (q_i[..., None] * h).sum(-2)
|
| 38 |
+
|
| 39 |
+
if not output_final_state:
|
| 40 |
+
h = None
|
| 41 |
+
return o.transpose(1, 2).to(dtype), h
|
titans/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from .naive import chunk_titans_linear
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
'chunk_titans_linear'
|
| 7 |
+
]
|
ttt/__init__.py
ADDED
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang, Yuqi Pan
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import triton
|
| 10 |
+
import triton.language as tl
|
| 11 |
+
|
| 12 |
+
from fla.modules.layernorm import group_norm
|
| 13 |
+
from fla.ops.utils import prepare_chunk_indices, prepare_chunk_offsets
|
| 14 |
+
from fla.utils import autocast_custom_bwd, autocast_custom_fwd, autotune_cache_kwargs, input_guard
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@triton.heuristics({
|
| 18 |
+
'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
|
| 19 |
+
'USE_INITIAL_STATE_B': lambda args: args['hb0'] is not None,
|
| 20 |
+
'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
|
| 21 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
| 22 |
+
})
|
| 23 |
+
@triton.autotune(
|
| 24 |
+
configs=[
|
| 25 |
+
triton.Config({}, num_warps=num_warps)
|
| 26 |
+
for num_warps in [1, 2, 4, 8]
|
| 27 |
+
],
|
| 28 |
+
key=['BT', 'BK', 'BV'],
|
| 29 |
+
**autotune_cache_kwargs
|
| 30 |
+
)
|
| 31 |
+
@triton.jit(do_not_specialize=['T'])
|
| 32 |
+
def chunk_ttt_linear_fwd_kernel_h(
|
| 33 |
+
k,
|
| 34 |
+
v,
|
| 35 |
+
v_new,
|
| 36 |
+
eta,
|
| 37 |
+
w,
|
| 38 |
+
b,
|
| 39 |
+
eps,
|
| 40 |
+
h,
|
| 41 |
+
hb,
|
| 42 |
+
h0,
|
| 43 |
+
hb0,
|
| 44 |
+
ht,
|
| 45 |
+
hbt,
|
| 46 |
+
cu_seqlens,
|
| 47 |
+
chunk_offsets,
|
| 48 |
+
T,
|
| 49 |
+
H: tl.constexpr,
|
| 50 |
+
K: tl.constexpr,
|
| 51 |
+
V: tl.constexpr,
|
| 52 |
+
BT: tl.constexpr,
|
| 53 |
+
BK: tl.constexpr,
|
| 54 |
+
BV: tl.constexpr,
|
| 55 |
+
USE_INITIAL_STATE: tl.constexpr,
|
| 56 |
+
USE_INITIAL_STATE_B: tl.constexpr,
|
| 57 |
+
STORE_FINAL_STATE: tl.constexpr,
|
| 58 |
+
IS_VARLEN: tl.constexpr,
|
| 59 |
+
):
|
| 60 |
+
i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 61 |
+
i_n, i_h = i_nh // H, i_nh % H
|
| 62 |
+
if IS_VARLEN:
|
| 63 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 64 |
+
T = eos - bos
|
| 65 |
+
NT = tl.cdiv(T, BT)
|
| 66 |
+
boh = tl.load(chunk_offsets + i_n).to(tl.int32)
|
| 67 |
+
else:
|
| 68 |
+
bos, eos = i_n * T, i_n * T + T
|
| 69 |
+
NT = tl.cdiv(T, BT)
|
| 70 |
+
boh = i_n * NT
|
| 71 |
+
|
| 72 |
+
# [BK, BV]
|
| 73 |
+
b_h = tl.zeros([BK, BV], dtype=tl.float32)
|
| 74 |
+
# [BV]
|
| 75 |
+
b_hb = tl.zeros([BV], dtype=tl.float32)
|
| 76 |
+
if USE_INITIAL_STATE:
|
| 77 |
+
p_h0 = tl.make_block_ptr(h0 + i_nh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 78 |
+
b_h = tl.load(p_h0, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
|
| 79 |
+
if USE_INITIAL_STATE_B:
|
| 80 |
+
p_hb0 = tl.make_block_ptr(hb0 + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 81 |
+
b_hb = tl.load(p_hb0, boundary_check=(0,), padding_option="zero").to(tl.float32)
|
| 82 |
+
|
| 83 |
+
offs = tl.arange(0, BV)
|
| 84 |
+
b_w = tl.load(w + i_h * V + offs, mask=offs < V, other=0.)
|
| 85 |
+
b_b = tl.load(b + i_h * V + offs, mask=offs < V, other=0.)
|
| 86 |
+
|
| 87 |
+
for i_t in range(NT):
|
| 88 |
+
p_h = tl.make_block_ptr(h + ((boh + i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 89 |
+
p_hb = tl.make_block_ptr(hb + ((boh + i_t) * H + i_h) * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 90 |
+
tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
|
| 91 |
+
tl.store(p_hb, b_hb.to(p_hb.dtype.element_ty), boundary_check=(0,))
|
| 92 |
+
p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
|
| 93 |
+
p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 94 |
+
p_v_new = tl.make_block_ptr(v_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
|
| 95 |
+
p_eta_last = eta+bos*H+i_h + (T-1)*H if i_t == NT-1 else eta+bos*H+i_h + (i_t*BT+BT-1)*H
|
| 96 |
+
b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
|
| 97 |
+
b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
|
| 98 |
+
|
| 99 |
+
b_kh = tl.dot(tl.trans(b_k), b_h.to(b_k.dtype), allow_tf32=False).to(tl.float32) + b_hb[None, :]
|
| 100 |
+
b_kh = tl.where((offs < V)[None, :], b_kh, 0.)
|
| 101 |
+
mean = tl.sum(b_kh, axis=1, keep_dims=True) / V
|
| 102 |
+
xbar = tl.where((offs < V)[None, :], b_kh - mean, 0.)
|
| 103 |
+
var = tl.sum(xbar * xbar, axis=1, keep_dims=True) / V
|
| 104 |
+
rstd = 1 / tl.sqrt(var.to(tl.float32) + eps)
|
| 105 |
+
b_kh_hat = (b_kh - mean) * rstd
|
| 106 |
+
|
| 107 |
+
b_v = b_kh_hat.to(b_k.dtype) * b_w[None, :].to(b_k.dtype) + \
|
| 108 |
+
b_b[None, :].to(b_k.dtype) - b_v.to(b_k.dtype) + tl.trans(b_k)
|
| 109 |
+
b_v = tl.where((offs < V)[None, :], b_v * b_w[None, :].to(b_k.dtype), 0.)
|
| 110 |
+
b_v2 = rstd * (V * b_v - tl.sum(b_v, axis=1, keep_dims=True) - b_kh_hat.to(b_k.dtype)
|
| 111 |
+
* tl.sum(b_v * b_kh_hat.to(b_k.dtype), axis=1, keep_dims=True)) / V
|
| 112 |
+
tl.store(p_v_new, b_v2.to(p_v_new.dtype.element_ty), boundary_check=(0, 1))
|
| 113 |
+
b_eta_last = tl.load(p_eta_last)
|
| 114 |
+
b_h = b_h - tl.dot(b_eta_last * b_k, b_v2.to(b_k.dtype), allow_tf32=False)
|
| 115 |
+
b_hb = b_hb - tl.sum(b_eta_last * b_v2.to(b_k.dtype), axis=0)
|
| 116 |
+
|
| 117 |
+
if STORE_FINAL_STATE:
|
| 118 |
+
p_ht = tl.make_block_ptr(ht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 119 |
+
p_hbt = tl.make_block_ptr(hbt + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 120 |
+
tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
|
| 121 |
+
tl.store(p_hbt, b_hb.to(p_hbt.dtype.element_ty), boundary_check=(0,))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@triton.heuristics({
|
| 125 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
| 126 |
+
})
|
| 127 |
+
@triton.autotune(
|
| 128 |
+
configs=[
|
| 129 |
+
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
| 130 |
+
for num_warps in [2, 4, 8]
|
| 131 |
+
for num_stages in [2, 3]
|
| 132 |
+
],
|
| 133 |
+
key=['BT'],
|
| 134 |
+
**autotune_cache_kwargs
|
| 135 |
+
)
|
| 136 |
+
@triton.jit(do_not_specialize=['T'])
|
| 137 |
+
def chunk_ttt_linear_fwd_kernel_o(
|
| 138 |
+
q,
|
| 139 |
+
k,
|
| 140 |
+
v,
|
| 141 |
+
eta,
|
| 142 |
+
h,
|
| 143 |
+
hb,
|
| 144 |
+
o,
|
| 145 |
+
cu_seqlens,
|
| 146 |
+
chunk_indices,
|
| 147 |
+
scale,
|
| 148 |
+
T,
|
| 149 |
+
H: tl.constexpr,
|
| 150 |
+
K: tl.constexpr,
|
| 151 |
+
V: tl.constexpr,
|
| 152 |
+
BT: tl.constexpr,
|
| 153 |
+
BK: tl.constexpr,
|
| 154 |
+
BV: tl.constexpr,
|
| 155 |
+
IS_VARLEN: tl.constexpr,
|
| 156 |
+
):
|
| 157 |
+
i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 158 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 159 |
+
|
| 160 |
+
if IS_VARLEN:
|
| 161 |
+
i_tg = i_t
|
| 162 |
+
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
| 163 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 164 |
+
T = eos - bos
|
| 165 |
+
NT = tl.cdiv(T, BT)
|
| 166 |
+
else:
|
| 167 |
+
NT = tl.cdiv(T, BT)
|
| 168 |
+
i_tg = i_b * NT + i_t
|
| 169 |
+
bos, eos = i_b * T, i_b * T + T
|
| 170 |
+
|
| 171 |
+
# offset calculation
|
| 172 |
+
q += (bos * H + i_h) * K
|
| 173 |
+
k += (bos * H + i_h) * K
|
| 174 |
+
v += (bos * H + i_h) * V
|
| 175 |
+
eta += bos * H + i_h
|
| 176 |
+
o += (bos * H + i_h) * V
|
| 177 |
+
h += (i_tg * H + i_h) * K * V
|
| 178 |
+
hb += (i_tg * H + i_h) * V
|
| 179 |
+
stride_qk = H*K
|
| 180 |
+
stride_vo = H*V
|
| 181 |
+
stride_eta = H
|
| 182 |
+
|
| 183 |
+
p_q = tl.make_block_ptr(q, (T, K), (stride_qk, 1), (i_t * BT, 0), (BT, BK), (1, 0))
|
| 184 |
+
p_k = tl.make_block_ptr(k, (K, T), (1, stride_qk), (0, i_t * BT), (BK, BT), (0, 1))
|
| 185 |
+
p_eta = tl.make_block_ptr(eta, (T,), (stride_eta,), (i_t * BT,), (BT,), (0,))
|
| 186 |
+
p_h = tl.make_block_ptr(h, (K, V), (V, 1), (0, i_v * BV), (BK, BV), (1, 0))
|
| 187 |
+
p_hb = tl.make_block_ptr(hb, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 188 |
+
# [BT, BK]
|
| 189 |
+
b_q = tl.load(p_q, boundary_check=(0, 1), padding_option="zero")
|
| 190 |
+
# [BK, BT]
|
| 191 |
+
b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
|
| 192 |
+
# [BT, 1]
|
| 193 |
+
b_eta = tl.load(p_eta, boundary_check=(0,), padding_option="zero")
|
| 194 |
+
# [BK, BV]
|
| 195 |
+
b_h = tl.load(p_h, boundary_check=(0, 1), padding_option="zero")
|
| 196 |
+
# [BV]
|
| 197 |
+
b_hb = tl.load(p_hb, boundary_check=(0,), padding_option="zero")
|
| 198 |
+
# [BT, BK] @ [BK, BV] -> [BT, BV]
|
| 199 |
+
b_o = tl.dot(b_q, b_h, allow_tf32=False)
|
| 200 |
+
# [BT, BK] @ [BK, BT] -> [BT, BT]
|
| 201 |
+
b_A = tl.dot(b_q, b_k, allow_tf32=False)
|
| 202 |
+
|
| 203 |
+
o_i = tl.arange(0, BT)
|
| 204 |
+
m_A = o_i[:, None] >= o_i[None, :]
|
| 205 |
+
b_A = tl.where(m_A, b_A, 0)
|
| 206 |
+
b_Ae = tl.where(m_A, b_eta[:, None], 0.0)
|
| 207 |
+
|
| 208 |
+
p_v = tl.make_block_ptr(v, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 209 |
+
p_o = tl.make_block_ptr(o, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 210 |
+
b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
|
| 211 |
+
b_o = (b_o - tl.dot(b_eta[:, None] * b_A.to(b_v.dtype), b_v, allow_tf32=False)) * scale
|
| 212 |
+
b_o += b_hb[None, :] - tl.dot(b_Ae.to(b_v.dtype), b_v, allow_tf32=False)
|
| 213 |
+
tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@triton.heuristics({
|
| 217 |
+
'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
|
| 218 |
+
'USE_INITIAL_STATE_B': lambda args: args['hb0'] is not None,
|
| 219 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
| 220 |
+
})
|
| 221 |
+
@triton.autotune(
|
| 222 |
+
configs=[
|
| 223 |
+
triton.Config({}, num_warps=num_warps)
|
| 224 |
+
for num_warps in [1, 2, 4, 8]
|
| 225 |
+
],
|
| 226 |
+
key=['BT', 'BK', 'BV'],
|
| 227 |
+
**autotune_cache_kwargs
|
| 228 |
+
)
|
| 229 |
+
@triton.jit(do_not_specialize=['T'])
|
| 230 |
+
def chunk_ttt_linear_bwd_kernel_h(
|
| 231 |
+
k,
|
| 232 |
+
v,
|
| 233 |
+
v_new,
|
| 234 |
+
eta,
|
| 235 |
+
w,
|
| 236 |
+
b,
|
| 237 |
+
eps,
|
| 238 |
+
h,
|
| 239 |
+
h0,
|
| 240 |
+
hb0,
|
| 241 |
+
x,
|
| 242 |
+
y,
|
| 243 |
+
r,
|
| 244 |
+
cu_seqlens,
|
| 245 |
+
chunk_offsets,
|
| 246 |
+
T,
|
| 247 |
+
H: tl.constexpr,
|
| 248 |
+
K: tl.constexpr,
|
| 249 |
+
V: tl.constexpr,
|
| 250 |
+
BT: tl.constexpr,
|
| 251 |
+
BK: tl.constexpr,
|
| 252 |
+
BV: tl.constexpr,
|
| 253 |
+
NT: tl.constexpr,
|
| 254 |
+
USE_INITIAL_STATE: tl.constexpr,
|
| 255 |
+
USE_INITIAL_STATE_B: tl.constexpr,
|
| 256 |
+
IS_VARLEN: tl.constexpr,
|
| 257 |
+
):
|
| 258 |
+
i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 259 |
+
i_n, i_h = i_nh // H, i_nh % H
|
| 260 |
+
if IS_VARLEN:
|
| 261 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 262 |
+
T = eos - bos
|
| 263 |
+
NT = tl.cdiv(T, BT)
|
| 264 |
+
boh = tl.load(chunk_offsets + i_n).to(tl.int32)
|
| 265 |
+
else:
|
| 266 |
+
bos, eos = i_n * T, i_n * T + T
|
| 267 |
+
NT = tl.cdiv(T, BT)
|
| 268 |
+
boh = i_n * NT
|
| 269 |
+
|
| 270 |
+
# [BK, BV]
|
| 271 |
+
b_h = tl.zeros([BK, BV], dtype=tl.float32)
|
| 272 |
+
# [BV]
|
| 273 |
+
b_hb = tl.zeros([BV], dtype=tl.float32)
|
| 274 |
+
if USE_INITIAL_STATE:
|
| 275 |
+
p_h0 = tl.make_block_ptr(h0 + i_nh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 276 |
+
b_h = tl.load(p_h0, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
|
| 277 |
+
if USE_INITIAL_STATE_B:
|
| 278 |
+
p_hb0 = tl.make_block_ptr(hb0 + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 279 |
+
b_hb = tl.load(p_hb0, boundary_check=(0,), padding_option="zero").to(tl.float32)
|
| 280 |
+
|
| 281 |
+
offs = tl.arange(0, BV)
|
| 282 |
+
b_w = tl.load(w + i_h * V + offs, mask=offs < V, other=0.)
|
| 283 |
+
b_b = tl.load(b + i_h * V + offs, mask=offs < V, other=0.)
|
| 284 |
+
|
| 285 |
+
for i_t in range(NT):
|
| 286 |
+
p_h = tl.make_block_ptr(h + ((boh + i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 287 |
+
tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
|
| 288 |
+
p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
|
| 289 |
+
p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 290 |
+
p_v_new = tl.make_block_ptr(v_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
|
| 291 |
+
p_x = tl.make_block_ptr(x+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
|
| 292 |
+
p_y = tl.make_block_ptr(y+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
|
| 293 |
+
p_r = tl.make_block_ptr(r+bos*H+i_h, (T, 1), (H, 1), (i_t*BT, 0), (BT, 1), (1, 0))
|
| 294 |
+
p_eta_last = eta+bos*H+i_h + (T-1)*H if i_t == NT-1 else eta+bos*H+i_h + (i_t*BT+BT-1)*H
|
| 295 |
+
b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
|
| 296 |
+
b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
|
| 297 |
+
|
| 298 |
+
b_kh = tl.dot(tl.trans(b_k), b_h.to(b_k.dtype), allow_tf32=False).to(tl.float32) + b_hb[None, :]
|
| 299 |
+
b_kh = tl.where((offs < V)[None, :], b_kh, 0.)
|
| 300 |
+
mean = tl.sum(b_kh, axis=1, keep_dims=True) / V
|
| 301 |
+
xbar = tl.where((offs < V)[None, :], b_kh - mean, 0.)
|
| 302 |
+
var = tl.sum(xbar * xbar, axis=1, keep_dims=True) / V
|
| 303 |
+
rstd = 1 / tl.sqrt(var.to(tl.float32) + eps)
|
| 304 |
+
b_kh_hat = (b_kh - mean) * rstd
|
| 305 |
+
|
| 306 |
+
b_v = b_kh_hat.to(b_k.dtype) * b_w[None, :].to(b_k.dtype) + \
|
| 307 |
+
b_b[None, :].to(b_k.dtype) - b_v.to(b_k.dtype) + tl.trans(b_k)
|
| 308 |
+
b_v = tl.where((offs < V)[None, :], b_v * b_w[None, :].to(b_k.dtype), 0.)
|
| 309 |
+
b_v2 = rstd * (V * b_v - tl.sum(b_v, axis=1, keep_dims=True) - b_kh_hat.to(b_k.dtype)
|
| 310 |
+
* tl.sum(b_v * b_kh_hat.to(b_k.dtype), axis=1, keep_dims=True)) / V
|
| 311 |
+
tl.store(p_x, b_kh_hat.to(p_x.dtype.element_ty), boundary_check=(0, 1))
|
| 312 |
+
tl.store(p_y, b_v.to(p_y.dtype.element_ty), boundary_check=(0, 1))
|
| 313 |
+
tl.store(p_r, rstd.to(p_r.dtype.element_ty), boundary_check=(0, 1))
|
| 314 |
+
tl.store(p_v_new, b_v2.to(p_v_new.dtype.element_ty), boundary_check=(0, 1))
|
| 315 |
+
b_eta_last = tl.load(p_eta_last)
|
| 316 |
+
b_h = b_h - tl.dot(b_eta_last * b_k, b_v2.to(b_k.dtype), allow_tf32=False)
|
| 317 |
+
b_hb = b_hb - tl.sum(b_eta_last * b_v2.to(b_k.dtype), axis=0)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
@triton.heuristics({
|
| 321 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
| 322 |
+
})
|
| 323 |
+
@triton.autotune(
|
| 324 |
+
configs=[
|
| 325 |
+
triton.Config({}, num_warps=num_warps)
|
| 326 |
+
for num_warps in [4]
|
| 327 |
+
],
|
| 328 |
+
key=['BT', 'BK', 'BV'],
|
| 329 |
+
**autotune_cache_kwargs
|
| 330 |
+
)
|
| 331 |
+
@triton.jit(do_not_specialize=['T'])
|
| 332 |
+
def chunk_ttt_linear_bwd_kernel_dv_local(
|
| 333 |
+
q,
|
| 334 |
+
k,
|
| 335 |
+
eta,
|
| 336 |
+
do,
|
| 337 |
+
dv,
|
| 338 |
+
cu_seqlens,
|
| 339 |
+
chunk_indices,
|
| 340 |
+
scale,
|
| 341 |
+
T,
|
| 342 |
+
H: tl.constexpr,
|
| 343 |
+
K: tl.constexpr,
|
| 344 |
+
V: tl.constexpr,
|
| 345 |
+
BT: tl.constexpr,
|
| 346 |
+
BK: tl.constexpr,
|
| 347 |
+
BV: tl.constexpr,
|
| 348 |
+
IS_VARLEN: tl.constexpr,
|
| 349 |
+
):
|
| 350 |
+
i_t, i_bh = tl.program_id(0), tl.program_id(1)
|
| 351 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 352 |
+
if IS_VARLEN:
|
| 353 |
+
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
| 354 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 355 |
+
T = eos - bos
|
| 356 |
+
else:
|
| 357 |
+
bos, eos = i_b * T, i_b * T + T
|
| 358 |
+
|
| 359 |
+
# offset calculation
|
| 360 |
+
q += (bos * H + i_h) * K
|
| 361 |
+
k += (bos * H + i_h) * K
|
| 362 |
+
eta += bos * H + i_h
|
| 363 |
+
do += (bos * H + i_h) * V
|
| 364 |
+
dv += (bos * H + i_h) * V
|
| 365 |
+
stride_qk = H*K
|
| 366 |
+
stride_vo = H*V
|
| 367 |
+
stride_eta = H
|
| 368 |
+
|
| 369 |
+
b_A = tl.zeros([BT, BT], dtype=tl.float32)
|
| 370 |
+
for i_k in range(tl.cdiv(K, BK)):
|
| 371 |
+
p_k = tl.make_block_ptr(k, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
| 372 |
+
p_q = tl.make_block_ptr(q, (K, T), (1, stride_qk), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
|
| 373 |
+
b_q = tl.load(p_q, boundary_check=(0, 1))
|
| 374 |
+
b_k = tl.load(p_k, boundary_check=(0, 1))
|
| 375 |
+
b_A += tl.dot(b_k, b_q)
|
| 376 |
+
|
| 377 |
+
p_eta = tl.make_block_ptr(eta, (T,), (stride_eta,), (i_t * BT,), (BT,), (0,))
|
| 378 |
+
b_eta = tl.load(p_eta, boundary_check=(0,))
|
| 379 |
+
mask = (tl.arange(0, BT)[:, None] <= tl.arange(0, BT)[None, :])
|
| 380 |
+
b_A = - tl.where(mask, b_A * scale * b_eta[None, :], 0).to(do.dtype.element_ty)
|
| 381 |
+
b_Ae = - tl.where(mask, b_eta[None, :], 0).to(do.dtype.element_ty)
|
| 382 |
+
|
| 383 |
+
for i_v in range(tl.cdiv(V, BV)):
|
| 384 |
+
p_do = tl.make_block_ptr(do, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 385 |
+
p_dv = tl.make_block_ptr(dv, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 386 |
+
b_do = tl.load(p_do, boundary_check=(0, 1))
|
| 387 |
+
b_dv = tl.dot(b_A.to(b_do.dtype), b_do) + tl.dot(b_Ae.to(b_do.dtype), b_do)
|
| 388 |
+
tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@triton.heuristics({
|
| 392 |
+
'USE_FINAL_STATE_GRADIENT': lambda args: args['dht'] is not None,
|
| 393 |
+
'USE_FINAL_STATE_GRADIENT_B': lambda args: args['dhbt'] is not None,
|
| 394 |
+
'USE_INITIAL_STATE': lambda args: args['dh0'] is not None,
|
| 395 |
+
'USE_INITIAL_STATE_B': lambda args: args['dhb0'] is not None,
|
| 396 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
| 397 |
+
})
|
| 398 |
+
@triton.autotune(
|
| 399 |
+
configs=[
|
| 400 |
+
triton.Config({}, num_warps=num_warps)
|
| 401 |
+
for num_warps in [2, 4, 8, 16]
|
| 402 |
+
],
|
| 403 |
+
key=['BT', 'BK', 'BV'],
|
| 404 |
+
**autotune_cache_kwargs
|
| 405 |
+
)
|
| 406 |
+
@triton.jit(do_not_specialize=['T'])
|
| 407 |
+
def chunk_ttt_linear_bwd_kernel_norm(
|
| 408 |
+
q,
|
| 409 |
+
k,
|
| 410 |
+
v,
|
| 411 |
+
v_new,
|
| 412 |
+
x,
|
| 413 |
+
y,
|
| 414 |
+
r,
|
| 415 |
+
w,
|
| 416 |
+
b,
|
| 417 |
+
eta,
|
| 418 |
+
h,
|
| 419 |
+
dht,
|
| 420 |
+
dhbt,
|
| 421 |
+
dh0,
|
| 422 |
+
dhb0,
|
| 423 |
+
do,
|
| 424 |
+
dh,
|
| 425 |
+
dhb,
|
| 426 |
+
dv,
|
| 427 |
+
dv_new,
|
| 428 |
+
dk,
|
| 429 |
+
dw,
|
| 430 |
+
db,
|
| 431 |
+
cu_seqlens,
|
| 432 |
+
chunk_offsets,
|
| 433 |
+
scale,
|
| 434 |
+
T,
|
| 435 |
+
H: tl.constexpr,
|
| 436 |
+
K: tl.constexpr,
|
| 437 |
+
V: tl.constexpr,
|
| 438 |
+
BT: tl.constexpr,
|
| 439 |
+
BK: tl.constexpr,
|
| 440 |
+
BV: tl.constexpr,
|
| 441 |
+
USE_FINAL_STATE_GRADIENT: tl.constexpr,
|
| 442 |
+
USE_FINAL_STATE_GRADIENT_B: tl.constexpr,
|
| 443 |
+
USE_INITIAL_STATE: tl.constexpr,
|
| 444 |
+
USE_INITIAL_STATE_B: tl.constexpr,
|
| 445 |
+
IS_VARLEN: tl.constexpr,
|
| 446 |
+
):
|
| 447 |
+
i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 448 |
+
i_n, i_h = i_nh // H, i_nh % H
|
| 449 |
+
if IS_VARLEN:
|
| 450 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 451 |
+
T = eos - bos
|
| 452 |
+
NT = tl.cdiv(T, BT)
|
| 453 |
+
boh = tl.load(chunk_offsets + i_n).to(tl.int32)
|
| 454 |
+
else:
|
| 455 |
+
bos, eos = i_n * T, i_n * T + T
|
| 456 |
+
NT = tl.cdiv(T, BT)
|
| 457 |
+
boh = i_n * NT
|
| 458 |
+
|
| 459 |
+
# [BK, BV]
|
| 460 |
+
b_dh = tl.zeros([BK, BV], dtype=tl.float32)
|
| 461 |
+
# [BV]
|
| 462 |
+
b_dhb = tl.zeros([BV], dtype=tl.float32)
|
| 463 |
+
if USE_FINAL_STATE_GRADIENT:
|
| 464 |
+
p_dht = tl.make_block_ptr(dht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 465 |
+
b_dh += tl.load(p_dht, boundary_check=(0, 1), padding_option="zero")
|
| 466 |
+
if USE_FINAL_STATE_GRADIENT_B:
|
| 467 |
+
p_dhbt = tl.make_block_ptr(dhbt + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 468 |
+
b_dhb += tl.load(p_dhbt, boundary_check=(0,), padding_option="zero")
|
| 469 |
+
|
| 470 |
+
# [BV]
|
| 471 |
+
offs_v = tl.arange(0, BV)
|
| 472 |
+
offs_t = tl.arange(0, BT)
|
| 473 |
+
b_w = tl.load(w + i_h * V + offs_v, mask=offs_v < V, other=0.)
|
| 474 |
+
b_b = tl.load(b + i_h * V + offs_v, mask=offs_v < V, other=0.)
|
| 475 |
+
b_dw = tl.zeros([BV,], dtype=b_w.dtype)
|
| 476 |
+
b_db = tl.zeros([BV,], dtype=b_b.dtype)
|
| 477 |
+
p_dw = tl.make_block_ptr(dw + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 478 |
+
p_db = tl.make_block_ptr(db + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 479 |
+
|
| 480 |
+
for i_t in range(NT - 1, -1, -1):
|
| 481 |
+
p_h = tl.make_block_ptr(h + ((boh+i_t) * H + i_h) * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
|
| 482 |
+
p_dh = tl.make_block_ptr(dh + ((boh+i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 483 |
+
p_dhb = tl.make_block_ptr(dhb + ((boh+i_t) * H + i_h) * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 484 |
+
tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
|
| 485 |
+
tl.store(p_dhb, b_dhb.to(p_dhb.dtype.element_ty), boundary_check=(0,))
|
| 486 |
+
p_q = tl.make_block_ptr(q+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
|
| 487 |
+
p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
| 488 |
+
p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 489 |
+
p_v_new = tl.make_block_ptr(v_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 490 |
+
p_x = tl.make_block_ptr(x+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 491 |
+
p_y = tl.make_block_ptr(y+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 492 |
+
p_dv_new = tl.make_block_ptr(dv_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
|
| 493 |
+
p_dv = tl.make_block_ptr(dv+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
|
| 494 |
+
p_dk = tl.make_block_ptr(dk+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT, i_k * BK), (BT, BK), (1, 0))
|
| 495 |
+
p_do = tl.make_block_ptr(do+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
|
| 496 |
+
p_r = tl.make_block_ptr(r+bos*H+i_h, (T, 1), (H, 1), (i_t*BT, 0), (BT, 1), (1, 0))
|
| 497 |
+
p_eta_last = eta+bos*H+i_h + (T-1)*H if i_t == NT-1 else eta+bos*H+i_h + (i_t*BT+BT-1)*H
|
| 498 |
+
b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
|
| 499 |
+
b_dv_new = tl.load(p_dv_new, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
|
| 500 |
+
b_eta_last = tl.load(p_eta_last)
|
| 501 |
+
b_dv_new -= tl.dot(b_eta_last * b_k, b_dh.to(b_k.dtype))
|
| 502 |
+
b_dv_new -= b_eta_last * b_dhb.to(b_k.dtype)[None, :]
|
| 503 |
+
|
| 504 |
+
b_v_new = tl.load(p_v_new, boundary_check=(0, 1), padding_option="zero")
|
| 505 |
+
b_x = tl.load(p_x, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
|
| 506 |
+
b_y = tl.load(p_y, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
|
| 507 |
+
b_rstd = tl.load(p_r, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
|
| 508 |
+
b_dy = b_rstd * (b_dv_new * V - tl.sum(b_dv_new, axis=1, keep_dims=True) -
|
| 509 |
+
b_x * tl.sum(b_dv_new * b_x, axis=1, keep_dims=True)) / V
|
| 510 |
+
b_dx = -b_rstd * (b_dv_new * tl.sum(b_x * b_y, axis=1, keep_dims=True) +
|
| 511 |
+
b_y * tl.sum(b_dv_new * b_x, axis=1, keep_dims=True)) / V
|
| 512 |
+
b_drstd = tl.sum(b_dv_new.to(b_rstd.dtype) * b_v_new.to(b_rstd.dtype) / b_rstd, axis=1, keep_dims=True)
|
| 513 |
+
|
| 514 |
+
b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
|
| 515 |
+
b_w = b_w.to(b_k.dtype)
|
| 516 |
+
b_b = b_b.to(b_k.dtype)
|
| 517 |
+
b_dv = -b_w * b_dy.to(b_k.dtype)
|
| 518 |
+
b_dk = b_w * b_dy.to(b_k.dtype)
|
| 519 |
+
b_dw += tl.sum(2 * b_w * b_x * b_dy.to(b_k.dtype) +
|
| 520 |
+
(b_b - b_v.to(b_k.dtype) + b_k) * b_dy.to(b_k.dtype), axis=0).to(b_dw.dtype)
|
| 521 |
+
b_db += tl.sum(b_w * b_dy.to(b_k.dtype), axis=0).to(b_db.dtype)
|
| 522 |
+
b_dx = b_dx.to(b_k.dtype) + b_w * b_w * b_dy.to(b_k.dtype)
|
| 523 |
+
|
| 524 |
+
# d_rstd, dx --> dkh --> dk, dh
|
| 525 |
+
b_q = tl.load(p_q, boundary_check=(0, 1), padding_option="zero")
|
| 526 |
+
b_h = tl.load(p_h, boundary_check=(0, 1), padding_option="zero")
|
| 527 |
+
b_do = tl.load(p_do, boundary_check=(0, 1), padding_option="zero")
|
| 528 |
+
b_q = (b_q * scale).to(b_q.dtype)
|
| 529 |
+
b_dkh = b_rstd * (V * b_dx - tl.sum(b_dx, axis=1, keep_dims=True) -
|
| 530 |
+
b_x * tl.sum(b_x * b_dx, axis=1, keep_dims=True)) / V
|
| 531 |
+
b_dkh -= b_rstd * b_rstd * b_drstd * b_x / V
|
| 532 |
+
b_dkh = tl.where((offs_v < V)[None, :] * (offs_t < T-i_t*BT)[:, None], b_dkh, 0.)
|
| 533 |
+
b_dk += tl.dot(b_dkh, b_h.to(b_dkh.dtype)).to(b_k.dtype)
|
| 534 |
+
b_dh += tl.dot(b_q, b_do.to(b_q.dtype)) + tl.dot(tl.trans(b_k).to(b_dkh.dtype), b_dkh)
|
| 535 |
+
b_dhb += tl.sum(b_do + b_dkh, axis=0)
|
| 536 |
+
b_dh = tl.where((offs_v < V)[None, :], b_dh, 0.)
|
| 537 |
+
b_dhb = tl.where((offs_v < V), b_dhb, 0.)
|
| 538 |
+
|
| 539 |
+
tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
|
| 540 |
+
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
|
| 541 |
+
tl.store(p_dw, b_dw.to(p_dw.dtype.element_ty), boundary_check=(0,))
|
| 542 |
+
tl.store(p_db, b_db.to(p_db.dtype.element_ty), boundary_check=(0,))
|
| 543 |
+
|
| 544 |
+
if USE_INITIAL_STATE:
|
| 545 |
+
p_dh0 = tl.make_block_ptr(dh0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
|
| 546 |
+
tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
|
| 547 |
+
if USE_INITIAL_STATE_B:
|
| 548 |
+
p_dhb0 = tl.make_block_ptr(dhb0+i_nh*V, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 549 |
+
tl.store(p_dhb0, b_dhb.to(p_dhb0.dtype.element_ty), boundary_check=(0,))
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
@triton.heuristics({
|
| 553 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
| 554 |
+
})
|
| 555 |
+
@triton.autotune(
|
| 556 |
+
configs=[
|
| 557 |
+
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
| 558 |
+
for num_warps in [2, 4, 8]
|
| 559 |
+
for num_stages in [2, 3]
|
| 560 |
+
],
|
| 561 |
+
key=['BT', 'BK', 'BV'],
|
| 562 |
+
**autotune_cache_kwargs
|
| 563 |
+
)
|
| 564 |
+
@triton.jit(do_not_specialize=['T'])
|
| 565 |
+
def chunk_bwd_kernel_dqke(
|
| 566 |
+
q,
|
| 567 |
+
k,
|
| 568 |
+
v,
|
| 569 |
+
e,
|
| 570 |
+
h,
|
| 571 |
+
do,
|
| 572 |
+
dh,
|
| 573 |
+
dhb,
|
| 574 |
+
dq,
|
| 575 |
+
dk,
|
| 576 |
+
de,
|
| 577 |
+
cu_seqlens,
|
| 578 |
+
chunk_indices,
|
| 579 |
+
scale,
|
| 580 |
+
T,
|
| 581 |
+
B: tl.constexpr,
|
| 582 |
+
H: tl.constexpr,
|
| 583 |
+
K: tl.constexpr,
|
| 584 |
+
V: tl.constexpr,
|
| 585 |
+
BT: tl.constexpr,
|
| 586 |
+
BK: tl.constexpr,
|
| 587 |
+
BV: tl.constexpr,
|
| 588 |
+
IS_VARLEN: tl.constexpr,
|
| 589 |
+
):
|
| 590 |
+
i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 591 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 592 |
+
if IS_VARLEN:
|
| 593 |
+
i_tg = i_t
|
| 594 |
+
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
| 595 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 596 |
+
T = eos - bos
|
| 597 |
+
NT = tl.cdiv(T, BT)
|
| 598 |
+
else:
|
| 599 |
+
NT = tl.cdiv(T, BT)
|
| 600 |
+
i_tg = i_b * NT + i_t
|
| 601 |
+
bos, eos = i_b * T, i_b * T + T
|
| 602 |
+
|
| 603 |
+
# offset calculation
|
| 604 |
+
v += (bos * H + i_h) * V
|
| 605 |
+
do += (bos * H + i_h) * V
|
| 606 |
+
h += (i_tg * H + i_h) * K * V
|
| 607 |
+
dh += (i_tg * H + i_h) * K * V
|
| 608 |
+
dhb += (i_tg * H + i_h) * V
|
| 609 |
+
q += (bos * H + i_h) * K
|
| 610 |
+
k += (bos * H + i_h) * K
|
| 611 |
+
dq += (bos * H + i_h) * K
|
| 612 |
+
dk += (bos * H + i_h) * K
|
| 613 |
+
e += bos * H + i_h
|
| 614 |
+
de += bos * H + i_h
|
| 615 |
+
stride_qk = H*K
|
| 616 |
+
stride_vo = H*V
|
| 617 |
+
stride_e = H
|
| 618 |
+
|
| 619 |
+
b_dq = tl.zeros([BT, BK], dtype=tl.float32)
|
| 620 |
+
b_dk = tl.zeros([BT, BK], dtype=tl.float32)
|
| 621 |
+
b_ds = tl.zeros([BT, BT], dtype=tl.float32)
|
| 622 |
+
b_de = tl.zeros([BT,], dtype=tl.float32)
|
| 623 |
+
|
| 624 |
+
p_k = tl.make_block_ptr(k, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
| 625 |
+
b_k = tl.load(p_k, boundary_check=(0, 1))
|
| 626 |
+
p_e_last = (e + (i_t*BT+BT-1)*stride_e) if (i_t*BT+BT) <= T else (e + (T-1)*stride_e)
|
| 627 |
+
i_last = (BT-1) if (i_t*BT+BT) <= T else (T % BT-1)
|
| 628 |
+
mask = (tl.arange(0, BT) == i_last)
|
| 629 |
+
b_e_last = tl.load(p_e_last)
|
| 630 |
+
|
| 631 |
+
for i_v in range(tl.cdiv(V, BV)):
|
| 632 |
+
p_v = tl.make_block_ptr(v, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 633 |
+
p_do = tl.make_block_ptr(do, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
|
| 634 |
+
p_h = tl.make_block_ptr(h, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
|
| 635 |
+
p_dh = tl.make_block_ptr(dh, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
|
| 636 |
+
p_dhb = tl.make_block_ptr(dhb, (V,), (1,), (i_v * BV,), (BV,), (0,))
|
| 637 |
+
# [BT, BV]
|
| 638 |
+
b_v = tl.load(p_v, boundary_check=(0, 1))
|
| 639 |
+
b_do = tl.load(p_do, boundary_check=(0, 1))
|
| 640 |
+
# [BV, BK]
|
| 641 |
+
b_h = tl.load(p_h, boundary_check=(0, 1))
|
| 642 |
+
b_dh = tl.load(p_dh, boundary_check=(0, 1))
|
| 643 |
+
# [BV]
|
| 644 |
+
b_dhb = tl.load(p_dhb, boundary_check=(0,))
|
| 645 |
+
# [BT, BV] @ [BV, BT] -> [BT, BT]
|
| 646 |
+
b_ds += tl.dot(b_do, tl.trans(b_v))
|
| 647 |
+
# [BT, BV] @ [BV, BK] -> [BT, BK]
|
| 648 |
+
b_dq += tl.dot(b_do, b_h.to(b_do.dtype))
|
| 649 |
+
# [BT, BV] @ [BV, BK] -> [BT, BK]
|
| 650 |
+
b_dk -= b_e_last * tl.dot(b_v, b_dh.to(b_v.dtype))
|
| 651 |
+
b_de -= mask * tl.sum(tl.trans(b_dh) * tl.dot(tl.trans(b_k), b_v.to(b_k.dtype)))
|
| 652 |
+
b_de -= mask * tl.sum(b_dhb * tl.sum(b_v, axis=0).to(b_k.dtype))
|
| 653 |
+
|
| 654 |
+
o_i = tl.arange(0, BT)
|
| 655 |
+
p_q = tl.make_block_ptr(q, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
| 656 |
+
p_e = tl.make_block_ptr(e, (T,), (stride_e,), (i_t * BT,), (BT,), (0,))
|
| 657 |
+
b_q = tl.load(p_q, boundary_check=(0, 1))
|
| 658 |
+
b_e = tl.load(p_e, boundary_check=(0,))
|
| 659 |
+
|
| 660 |
+
p_dq = tl.make_block_ptr(dq, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
| 661 |
+
p_dk = tl.make_block_ptr(dk, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
| 662 |
+
p_de = tl.make_block_ptr(de, (T,), (stride_e,), (i_t * BT,), (BT,), (0,))
|
| 663 |
+
|
| 664 |
+
b_ds = tl.where(o_i[:, None] >= o_i[None, :], b_ds, 0)
|
| 665 |
+
b_ds = b_ds.to(b_k.dtype)
|
| 666 |
+
b_dq -= tl.dot(b_ds, b_k) * b_e[:, None]
|
| 667 |
+
b_dk -= tl.dot(tl.trans(b_ds), b_q * b_e[:, None]) * scale
|
| 668 |
+
b_de -= tl.sum(scale * tl.dot(b_ds, b_k) * b_q, axis=1)
|
| 669 |
+
b_de -= tl.sum(b_ds, axis=1)
|
| 670 |
+
b_dq *= scale
|
| 671 |
+
tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
|
| 672 |
+
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
|
| 673 |
+
tl.store(p_de, b_de.to(p_de.dtype.element_ty), boundary_check=(0,))
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def chunk_ttt_linear_fwd_h(
|
| 677 |
+
k: torch.Tensor,
|
| 678 |
+
v: torch.Tensor,
|
| 679 |
+
w: torch.Tensor,
|
| 680 |
+
b: torch.Tensor,
|
| 681 |
+
eta: torch.Tensor,
|
| 682 |
+
eps: float,
|
| 683 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 684 |
+
initial_state_bias: Optional[torch.Tensor] = None,
|
| 685 |
+
output_final_state: bool = False,
|
| 686 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 687 |
+
chunk_size: int = 16,
|
| 688 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 689 |
+
B, T, H, K, V = *k.shape, v.shape[-1]
|
| 690 |
+
BT = chunk_size
|
| 691 |
+
|
| 692 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 693 |
+
# N: the actual number of sequences in the batch with either equal or variable lengths
|
| 694 |
+
if cu_seqlens is None:
|
| 695 |
+
N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
|
| 696 |
+
else:
|
| 697 |
+
N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
|
| 698 |
+
BK = max(triton.next_power_of_2(K), 16)
|
| 699 |
+
BV = max(triton.next_power_of_2(V), 16)
|
| 700 |
+
assert max(BK, BV) <= 128, "current kernel does not support head dimension larger than 128."
|
| 701 |
+
NK = triton.cdiv(K, BK)
|
| 702 |
+
NV = triton.cdiv(V, BV)
|
| 703 |
+
assert NK == 1, 'NK > 1 is not supported because it involves time-consuming synchronization'
|
| 704 |
+
assert NV == 1, 'NV > 1 is not supported by TTT update rule.'
|
| 705 |
+
|
| 706 |
+
h = k.new_empty(B, NT, H, K, V)
|
| 707 |
+
hb = k.new_empty(B, NT, H, 1, V)
|
| 708 |
+
final_state = k.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
|
| 709 |
+
final_state_bias = k.new_empty(N, H, 1, V, dtype=torch.float32) if output_final_state else None
|
| 710 |
+
|
| 711 |
+
v_new = torch.empty_like(v)
|
| 712 |
+
grid = (NK, NV, N * H)
|
| 713 |
+
|
| 714 |
+
chunk_ttt_linear_fwd_kernel_h[grid](
|
| 715 |
+
k=k,
|
| 716 |
+
v=v,
|
| 717 |
+
v_new=v_new,
|
| 718 |
+
eta=eta,
|
| 719 |
+
w=w,
|
| 720 |
+
b=b,
|
| 721 |
+
eps=eps,
|
| 722 |
+
h=h,
|
| 723 |
+
hb=hb,
|
| 724 |
+
h0=initial_state,
|
| 725 |
+
hb0=initial_state_bias,
|
| 726 |
+
ht=final_state,
|
| 727 |
+
hbt=final_state_bias,
|
| 728 |
+
cu_seqlens=cu_seqlens,
|
| 729 |
+
chunk_offsets=chunk_offsets,
|
| 730 |
+
T=T,
|
| 731 |
+
H=H,
|
| 732 |
+
K=K,
|
| 733 |
+
V=V,
|
| 734 |
+
BT=BT,
|
| 735 |
+
BK=BK,
|
| 736 |
+
BV=BV,
|
| 737 |
+
)
|
| 738 |
+
return h, hb, v_new, final_state, final_state_bias
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def chunk_ttt_linear_fwd_o(
|
| 742 |
+
q: torch.Tensor,
|
| 743 |
+
k: torch.Tensor,
|
| 744 |
+
v: torch.Tensor,
|
| 745 |
+
eta: torch.Tensor,
|
| 746 |
+
h: torch.Tensor,
|
| 747 |
+
hb: torch.Tensor,
|
| 748 |
+
scale: Optional[float] = None,
|
| 749 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 750 |
+
chunk_size: int = 64
|
| 751 |
+
) -> torch.Tensor:
|
| 752 |
+
B, T, H, K, V = *q.shape, v.shape[-1]
|
| 753 |
+
if scale is None:
|
| 754 |
+
scale = k.shape[-1] ** -0.5
|
| 755 |
+
BT = chunk_size
|
| 756 |
+
|
| 757 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 758 |
+
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
|
| 759 |
+
BK = max(triton.next_power_of_2(K), 16)
|
| 760 |
+
BV = max(triton.next_power_of_2(V), 16)
|
| 761 |
+
NK = triton.cdiv(K, BK)
|
| 762 |
+
NV = triton.cdiv(V, BV)
|
| 763 |
+
assert NK == 1, 'NK > 1 is not supported because it involves time-consuming synchronization'
|
| 764 |
+
assert NV == 1, 'NV > 1 is not supported by TTT update rule.'
|
| 765 |
+
|
| 766 |
+
o = torch.empty_like(v)
|
| 767 |
+
|
| 768 |
+
grid = (NV, NT, B * H)
|
| 769 |
+
chunk_ttt_linear_fwd_kernel_o[grid](
|
| 770 |
+
q,
|
| 771 |
+
k,
|
| 772 |
+
v,
|
| 773 |
+
eta,
|
| 774 |
+
h,
|
| 775 |
+
hb,
|
| 776 |
+
o,
|
| 777 |
+
cu_seqlens,
|
| 778 |
+
chunk_indices,
|
| 779 |
+
scale,
|
| 780 |
+
T=T,
|
| 781 |
+
H=H,
|
| 782 |
+
K=K,
|
| 783 |
+
V=V,
|
| 784 |
+
BT=BT,
|
| 785 |
+
BK=BK,
|
| 786 |
+
BV=BV,
|
| 787 |
+
)
|
| 788 |
+
return o
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def chunk_ttt_linear_bwd_h(
|
| 792 |
+
k: torch.Tensor,
|
| 793 |
+
v: torch.Tensor,
|
| 794 |
+
w: torch.Tensor,
|
| 795 |
+
b: torch.Tensor,
|
| 796 |
+
eta: torch.Tensor,
|
| 797 |
+
eps: float,
|
| 798 |
+
initial_state: Optional[torch.Tensor] = None,
|
| 799 |
+
initial_state_bias: Optional[torch.Tensor] = None,
|
| 800 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 801 |
+
chunk_size: int = 16,
|
| 802 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 803 |
+
B, T, H, K, V = *k.shape, v.shape[-1]
|
| 804 |
+
BT = chunk_size
|
| 805 |
+
|
| 806 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 807 |
+
# N: the actual number of sequences in the batch with either equal or variable lengths
|
| 808 |
+
if cu_seqlens is None:
|
| 809 |
+
N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
|
| 810 |
+
else:
|
| 811 |
+
N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
|
| 812 |
+
BK = max(triton.next_power_of_2(K), 16)
|
| 813 |
+
BV = max(triton.next_power_of_2(V), 16)
|
| 814 |
+
assert max(BK, BV) <= 128, "current kernel does not support head dimension larger than 128."
|
| 815 |
+
NK = triton.cdiv(K, BK)
|
| 816 |
+
NV = triton.cdiv(V, BV)
|
| 817 |
+
assert NK == 1, 'NK > 1 is not supported because it involves time-consuming synchronization'
|
| 818 |
+
assert NV == 1, 'NV > 1 is not supported by TTT update rule.'
|
| 819 |
+
|
| 820 |
+
h = k.new_empty(B, NT, H, K, V)
|
| 821 |
+
rstd = v.new_empty(B, T, H, 1, dtype=torch.float32)
|
| 822 |
+
x = torch.empty_like(v)
|
| 823 |
+
y = torch.empty_like(v)
|
| 824 |
+
|
| 825 |
+
v_new = torch.empty_like(v)
|
| 826 |
+
grid = (NK, NV, N * H)
|
| 827 |
+
|
| 828 |
+
chunk_ttt_linear_bwd_kernel_h[grid](
|
| 829 |
+
k=k,
|
| 830 |
+
v=v,
|
| 831 |
+
v_new=v_new,
|
| 832 |
+
eta=eta,
|
| 833 |
+
w=w,
|
| 834 |
+
b=b,
|
| 835 |
+
eps=eps,
|
| 836 |
+
h=h,
|
| 837 |
+
h0=initial_state,
|
| 838 |
+
hb0=initial_state_bias,
|
| 839 |
+
x=x,
|
| 840 |
+
y=y,
|
| 841 |
+
r=rstd,
|
| 842 |
+
cu_seqlens=cu_seqlens,
|
| 843 |
+
chunk_offsets=chunk_offsets,
|
| 844 |
+
T=T,
|
| 845 |
+
H=H,
|
| 846 |
+
K=K,
|
| 847 |
+
V=V,
|
| 848 |
+
BT=BT,
|
| 849 |
+
BK=BK,
|
| 850 |
+
BV=BV,
|
| 851 |
+
NT=NT,
|
| 852 |
+
)
|
| 853 |
+
return h, v_new, x, y, rstd
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
def chunk_ttt_linear_bwd_dv_local(
|
| 857 |
+
q: torch.Tensor,
|
| 858 |
+
k: torch.Tensor,
|
| 859 |
+
eta: torch.Tensor,
|
| 860 |
+
do: torch.Tensor,
|
| 861 |
+
scale: float,
|
| 862 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 863 |
+
chunk_size: int = 16
|
| 864 |
+
) -> torch.Tensor:
|
| 865 |
+
B, T, H, K, V = *k.shape, do.shape[-1]
|
| 866 |
+
BT = chunk_size
|
| 867 |
+
|
| 868 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 869 |
+
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
|
| 870 |
+
BK = min(max(triton.next_power_of_2(K), 16), 128)
|
| 871 |
+
BV = min(max(triton.next_power_of_2(V), 16), 128)
|
| 872 |
+
|
| 873 |
+
dv = torch.empty_like(do)
|
| 874 |
+
grid = (NT, B * H)
|
| 875 |
+
chunk_ttt_linear_bwd_kernel_dv_local[grid](
|
| 876 |
+
q,
|
| 877 |
+
k,
|
| 878 |
+
eta,
|
| 879 |
+
do,
|
| 880 |
+
dv,
|
| 881 |
+
cu_seqlens,
|
| 882 |
+
chunk_indices,
|
| 883 |
+
scale,
|
| 884 |
+
T=T,
|
| 885 |
+
H=H,
|
| 886 |
+
K=K,
|
| 887 |
+
V=V,
|
| 888 |
+
BT=BT,
|
| 889 |
+
BK=BK,
|
| 890 |
+
BV=BV,
|
| 891 |
+
)
|
| 892 |
+
return dv
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def chunk_ttt_linear_bwd_norm(
|
| 896 |
+
q: torch.Tensor, # [B, H, L, D]
|
| 897 |
+
k: torch.Tensor, # [B, H, L, D]
|
| 898 |
+
v: torch.Tensor, # [B, H, L, D]
|
| 899 |
+
v_new: torch.Tensor, # [B, H, L, D]
|
| 900 |
+
x: torch.Tensor, # [B, H, L, D]
|
| 901 |
+
y: torch.Tensor, # [B, H, L, D]
|
| 902 |
+
rstd: torch.Tensor, # [B, H, L, 1]
|
| 903 |
+
w: torch.Tensor, # [H, D]
|
| 904 |
+
b: torch.Tensor, # [H, D]
|
| 905 |
+
eta: torch.Tensor, # [B, H, L, 1]
|
| 906 |
+
h0: torch.Tensor, # [B, H, D, D]
|
| 907 |
+
hb0: torch.Tensor, # [B, H, 1, D]
|
| 908 |
+
h: torch.Tensor, # [B, H, NT, D, D]
|
| 909 |
+
dht: Optional[torch.Tensor], # [B, H, D, D]
|
| 910 |
+
dhbt: Optional[torch.Tensor], # [B, H, 1, D]
|
| 911 |
+
dv_new: Optional[torch.Tensor], # [B, H, L, D]
|
| 912 |
+
do: torch.Tensor, # [B, H, L, D]
|
| 913 |
+
scale: float,
|
| 914 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 915 |
+
chunk_size: int = 16
|
| 916 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 917 |
+
# torch implementation of `dkh, dw, db, dk, dv` for LN^2
|
| 918 |
+
assert cu_seqlens is None, "bwd of varlen is not implemented yet."
|
| 919 |
+
B, T, H, K, V = *q.shape, do.shape[-1]
|
| 920 |
+
BT = chunk_size
|
| 921 |
+
|
| 922 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 923 |
+
if cu_seqlens is None:
|
| 924 |
+
N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
|
| 925 |
+
else:
|
| 926 |
+
N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
|
| 927 |
+
|
| 928 |
+
BK = max(triton.next_power_of_2(K), 16)
|
| 929 |
+
BV = max(triton.next_power_of_2(V), 16)
|
| 930 |
+
NK = triton.cdiv(K, BK)
|
| 931 |
+
NV = triton.cdiv(V, BV)
|
| 932 |
+
assert NK == 1, 'NK > 1 is not supported by TTT.'
|
| 933 |
+
assert NV == 1, 'NV > 1 is not supported by TTT.'
|
| 934 |
+
|
| 935 |
+
dh = q.new_empty(B, NT, H, K, V)
|
| 936 |
+
dhb = q.new_empty(B, NT, H, 1, V)
|
| 937 |
+
dh0 = torch.empty_like(h0, dtype=torch.float32) if h0 is not None else None
|
| 938 |
+
dhb0 = torch.empty_like(hb0, dtype=torch.float32) if hb0 is not None else None
|
| 939 |
+
dv = torch.empty_like(v)
|
| 940 |
+
dk = torch.empty_like(k)
|
| 941 |
+
dw = w.new_empty(B, H, V)
|
| 942 |
+
db = b.new_empty(B, H, V)
|
| 943 |
+
|
| 944 |
+
grid = (NK, NV, N * H)
|
| 945 |
+
chunk_ttt_linear_bwd_kernel_norm[grid](
|
| 946 |
+
q=q,
|
| 947 |
+
k=k,
|
| 948 |
+
v=v,
|
| 949 |
+
v_new=v_new,
|
| 950 |
+
x=x,
|
| 951 |
+
y=y,
|
| 952 |
+
r=rstd,
|
| 953 |
+
w=w,
|
| 954 |
+
b=b,
|
| 955 |
+
eta=eta,
|
| 956 |
+
h=h,
|
| 957 |
+
dht=dht,
|
| 958 |
+
dhbt=dhbt,
|
| 959 |
+
dh0=dh0,
|
| 960 |
+
dhb0=dhb0,
|
| 961 |
+
do=do,
|
| 962 |
+
dh=dh,
|
| 963 |
+
dhb=dhb,
|
| 964 |
+
dv=dv,
|
| 965 |
+
dv_new=dv_new,
|
| 966 |
+
dk=dk,
|
| 967 |
+
dw=dw,
|
| 968 |
+
db=db,
|
| 969 |
+
cu_seqlens=cu_seqlens,
|
| 970 |
+
chunk_offsets=chunk_offsets,
|
| 971 |
+
scale=scale,
|
| 972 |
+
T=T,
|
| 973 |
+
H=H,
|
| 974 |
+
K=K,
|
| 975 |
+
V=V,
|
| 976 |
+
BT=BT,
|
| 977 |
+
BK=BK,
|
| 978 |
+
BV=BV,
|
| 979 |
+
)
|
| 980 |
+
dw = dw.sum(dim=0)
|
| 981 |
+
db = db.sum(dim=0)
|
| 982 |
+
return dh, dhb, dh0, dhb0, dv, dk, dw, db
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
def chunk_ttt_linear_bwd_norm_ref(
|
| 986 |
+
q: torch.Tensor, # [B, H, L, D]
|
| 987 |
+
k: torch.Tensor, # [B, H, L, D]
|
| 988 |
+
v: torch.Tensor, # [B, H, L, D]
|
| 989 |
+
v_new: torch.Tensor, # [B, H, L, D]
|
| 990 |
+
kh: torch.Tensor, # [B, H, L, D]
|
| 991 |
+
y: torch.Tensor, # [B, H, L, D]
|
| 992 |
+
w: torch.Tensor, # [H, D]
|
| 993 |
+
b: torch.Tensor, # [H, D]
|
| 994 |
+
eta: torch.Tensor, # [B, H, L, 1]
|
| 995 |
+
h0: torch.Tensor, # [B, H, D, D]
|
| 996 |
+
h: torch.Tensor, # [B, H, NT, D, D]
|
| 997 |
+
dht: Optional[torch.Tensor], # [B, H, D, D]
|
| 998 |
+
dv_new: Optional[torch.Tensor], # [B, H, L, D]
|
| 999 |
+
do: torch.Tensor, # [B, H, L, D]
|
| 1000 |
+
scale: float,
|
| 1001 |
+
eps: float,
|
| 1002 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 1003 |
+
chunk_size: int = 16
|
| 1004 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 1005 |
+
# torch implementation of `dkh, dw, db, dk, dv` for LN^2
|
| 1006 |
+
assert cu_seqlens is None, "bwd of varlen is not implemented yet."
|
| 1007 |
+
B, T, H, K, V = *q.shape, do.shape[-1]
|
| 1008 |
+
# [B, L, H, D] -> [B, H, L, D]
|
| 1009 |
+
q, k, v, v_new, kh, y, h, eta, dv_new, do = [
|
| 1010 |
+
x.transpose(1, 2) for x in
|
| 1011 |
+
[q, k, v, v_new, kh, y, h, eta, dv_new, do]
|
| 1012 |
+
]
|
| 1013 |
+
BT = chunk_size
|
| 1014 |
+
|
| 1015 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 1016 |
+
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
|
| 1017 |
+
pad_len = (BT - (T % BT)) % BT
|
| 1018 |
+
if pad_len > 0:
|
| 1019 |
+
q, k, v, v_new, kh, y, eta, dv_new, do = [
|
| 1020 |
+
F.pad(x, (0, 0, 0, pad_len)) for x in
|
| 1021 |
+
[q, k, v, v_new, kh, y, eta, dv_new, do]
|
| 1022 |
+
]
|
| 1023 |
+
eta[:, :, -1, :] = eta[:, :, -(pad_len+1), :]
|
| 1024 |
+
# [NT, B, H, BT, D]
|
| 1025 |
+
q, k, v, v_new, kh, y, eta, dv_new, do = [
|
| 1026 |
+
x.reshape(B, H, NT, BT, -1).permute(2, 0, 1, 3, 4) for x in
|
| 1027 |
+
[q, k, v, v_new, kh, y, eta, dv_new, do]
|
| 1028 |
+
]
|
| 1029 |
+
h = h.permute(2, 0, 1, 3, 4)
|
| 1030 |
+
|
| 1031 |
+
# allocate
|
| 1032 |
+
dh = q.new_zeros(NT, B, H, K, V)
|
| 1033 |
+
dv = torch.zeros_like(v)
|
| 1034 |
+
dk = torch.zeros_like(k)
|
| 1035 |
+
dw = torch.zeros_like(w)
|
| 1036 |
+
db = torch.zeros_like(b)
|
| 1037 |
+
# recurrent state
|
| 1038 |
+
b_dh = dht if dht is not None else torch.zeros_like(dh[0])
|
| 1039 |
+
b_dh = b_dh.to(torch.float32)
|
| 1040 |
+
|
| 1041 |
+
# [H, 1, D]
|
| 1042 |
+
_w = w.reshape(H, 1, V).to(torch.float32)
|
| 1043 |
+
_b = b.reshape(H, 1, V).to(torch.float32)
|
| 1044 |
+
|
| 1045 |
+
# d_state passing
|
| 1046 |
+
for i_t in range(NT - 1, -1, -1):
|
| 1047 |
+
dh[i_t] = b_dh.to(dh.dtype)
|
| 1048 |
+
# [B, H, BT, D]
|
| 1049 |
+
_q, _k, _v, _v_new, _kh, _y, _h, _eta, _dv_new, _do = [
|
| 1050 |
+
x[i_t].to(torch.float32) for x in
|
| 1051 |
+
(q, k, v, v_new, kh, y, h, eta, dv_new, do)
|
| 1052 |
+
]
|
| 1053 |
+
_dv_new -= (_eta[:, :, -1, :, None] * _k) @ b_dh
|
| 1054 |
+
|
| 1055 |
+
mean = _kh.mean(dim=-1, keepdim=True)
|
| 1056 |
+
var = _kh.var(dim=-1, unbiased=False, keepdim=True).to(torch.float32)
|
| 1057 |
+
rstd = 1 / torch.sqrt(var + eps).to(torch.float32)
|
| 1058 |
+
x = (_kh - mean) * rstd
|
| 1059 |
+
# [B, H, BT, D]
|
| 1060 |
+
dy = rstd * (_dv_new*V - _dv_new.sum(dim=-1, keepdim=True) - x*(x*_dv_new).sum(dim=-1, keepdim=True)) / V
|
| 1061 |
+
dx = -rstd * (_dv_new*(x*_y).sum(dim=-1, keepdim=True) + _y*(x*_dv_new).sum(dim=-1, keepdim=True)) / V
|
| 1062 |
+
d_rstd = (_dv_new * _v_new / rstd).sum(dim=-1, keepdim=True)
|
| 1063 |
+
|
| 1064 |
+
dv[i_t] = (-_w*dy).to(dv.dtype)
|
| 1065 |
+
dk[i_t] += (_w*dy).to(dk.dtype)
|
| 1066 |
+
dw += (2*_w*x*dy+(_b-_v+_k)*dy).sum(dim=(0, 2)).to(dw.dtype)
|
| 1067 |
+
db += (_w*dy).sum(dim=(0, 2)).to(db.dtype)
|
| 1068 |
+
dx += _w*_w*dy
|
| 1069 |
+
|
| 1070 |
+
# d_rstd, dx --> dkh --> dk, dh
|
| 1071 |
+
dkh = rstd * (V * dx - dx.sum(dim=-1, keepdim=True) - x * (x * dx).sum(dim=-1, keepdim=True)) / V
|
| 1072 |
+
dkh -= rstd**2 * d_rstd * x / V
|
| 1073 |
+
dk[i_t] += (dkh @ _h.transpose(-2, -1)).to(dk.dtype)
|
| 1074 |
+
b_dh += (_q.transpose(-2, -1) * scale) @ _do + _k.transpose(-2, -1) @ dkh
|
| 1075 |
+
dh0 = b_dh.to(torch.float32) if h0 is not None else None
|
| 1076 |
+
|
| 1077 |
+
# [NT, B, H, BT, D] -> [B, H, T, D]
|
| 1078 |
+
dv = dv.permute(1, 2, 0, 3, 4).reshape(B, H, -1, V)[:, :, :T, :]
|
| 1079 |
+
dk = dk.permute(1, 2, 0, 3, 4).reshape(B, H, -1, K)[:, :, :T, :]
|
| 1080 |
+
# [B, H, NT, D, D]
|
| 1081 |
+
dh = dh.permute(1, 2, 0, 3, 4)
|
| 1082 |
+
dv, dk, dh = [x.transpose(1, 2) for x in (dv, dk, dh)]
|
| 1083 |
+
dh, dv, dk, dw, db = [x.contiguous() for x in (dh, dv, dk, dw, db)]
|
| 1084 |
+
dh0 = dh0.contiguous() if h0 is not None else None
|
| 1085 |
+
return dh, dh0, dv, dk, dw, db
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
def chunk_ttt_linear_bwd_dqke(
|
| 1089 |
+
q: torch.Tensor,
|
| 1090 |
+
k: torch.Tensor,
|
| 1091 |
+
v: torch.Tensor,
|
| 1092 |
+
eta: torch.Tensor,
|
| 1093 |
+
h: torch.Tensor,
|
| 1094 |
+
do: torch.Tensor,
|
| 1095 |
+
dh: torch.Tensor,
|
| 1096 |
+
dhb: torch.Tensor,
|
| 1097 |
+
scale: float,
|
| 1098 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 1099 |
+
chunk_size: int = 16,
|
| 1100 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 1101 |
+
B, T, H, K, V = *k.shape, v.shape[-1]
|
| 1102 |
+
BT = chunk_size
|
| 1103 |
+
|
| 1104 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 1105 |
+
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
|
| 1106 |
+
|
| 1107 |
+
BK = max(triton.next_power_of_2(K), 16)
|
| 1108 |
+
BV = min(max(triton.next_power_of_2(V), 16), 64)
|
| 1109 |
+
NK = triton.cdiv(K, BK)
|
| 1110 |
+
assert NK == 1, "NK > 1 is not supported."
|
| 1111 |
+
|
| 1112 |
+
dq = torch.empty_like(q)
|
| 1113 |
+
dk = torch.empty_like(k)
|
| 1114 |
+
de = torch.empty_like(eta)
|
| 1115 |
+
grid = (NK, NT, B * H)
|
| 1116 |
+
|
| 1117 |
+
chunk_bwd_kernel_dqke[grid](
|
| 1118 |
+
q=q,
|
| 1119 |
+
k=k,
|
| 1120 |
+
v=v,
|
| 1121 |
+
e=eta,
|
| 1122 |
+
h=h,
|
| 1123 |
+
do=do,
|
| 1124 |
+
dh=dh,
|
| 1125 |
+
dhb=dhb,
|
| 1126 |
+
dq=dq,
|
| 1127 |
+
dk=dk,
|
| 1128 |
+
de=de,
|
| 1129 |
+
cu_seqlens=cu_seqlens,
|
| 1130 |
+
chunk_indices=chunk_indices,
|
| 1131 |
+
scale=scale,
|
| 1132 |
+
B=B,
|
| 1133 |
+
T=T,
|
| 1134 |
+
H=H,
|
| 1135 |
+
K=K,
|
| 1136 |
+
V=V,
|
| 1137 |
+
BT=BT,
|
| 1138 |
+
BK=BK,
|
| 1139 |
+
BV=BV,
|
| 1140 |
+
)
|
| 1141 |
+
return dq, dk, de
|
| 1142 |
+
|
| 1143 |
+
|
| 1144 |
+
def chunk_ttt_linear_fwd(
|
| 1145 |
+
q: torch.Tensor,
|
| 1146 |
+
k: torch.Tensor,
|
| 1147 |
+
v: torch.Tensor,
|
| 1148 |
+
w: torch.Tensor,
|
| 1149 |
+
b: torch.Tensor,
|
| 1150 |
+
eta: torch.Tensor,
|
| 1151 |
+
scale: float,
|
| 1152 |
+
eps: float,
|
| 1153 |
+
initial_state: torch.Tensor,
|
| 1154 |
+
initial_state_bias: torch.Tensor,
|
| 1155 |
+
output_final_state: bool,
|
| 1156 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 1157 |
+
chunk_size: int = 16
|
| 1158 |
+
):
|
| 1159 |
+
BT = chunk_size
|
| 1160 |
+
h, hb, v_new, final_state, final_state_bias = chunk_ttt_linear_fwd_h(
|
| 1161 |
+
k=k,
|
| 1162 |
+
v=v,
|
| 1163 |
+
w=w,
|
| 1164 |
+
b=b,
|
| 1165 |
+
eta=eta,
|
| 1166 |
+
eps=eps,
|
| 1167 |
+
initial_state=initial_state,
|
| 1168 |
+
initial_state_bias=initial_state_bias,
|
| 1169 |
+
output_final_state=output_final_state,
|
| 1170 |
+
cu_seqlens=cu_seqlens,
|
| 1171 |
+
chunk_size=BT
|
| 1172 |
+
)
|
| 1173 |
+
o = chunk_ttt_linear_fwd_o(
|
| 1174 |
+
q=q,
|
| 1175 |
+
k=k,
|
| 1176 |
+
v=v_new,
|
| 1177 |
+
eta=eta,
|
| 1178 |
+
h=h,
|
| 1179 |
+
hb=hb,
|
| 1180 |
+
scale=scale,
|
| 1181 |
+
cu_seqlens=cu_seqlens,
|
| 1182 |
+
chunk_size=BT
|
| 1183 |
+
)
|
| 1184 |
+
return o, final_state, final_state_bias
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
def chunk_ttt_linear_bwd(
|
| 1188 |
+
q: torch.Tensor,
|
| 1189 |
+
k: torch.Tensor,
|
| 1190 |
+
v: torch.Tensor,
|
| 1191 |
+
w: torch.Tensor,
|
| 1192 |
+
b: torch.Tensor,
|
| 1193 |
+
eta: torch.Tensor,
|
| 1194 |
+
scale: float,
|
| 1195 |
+
eps: float,
|
| 1196 |
+
do: torch.Tensor,
|
| 1197 |
+
dht: torch.Tensor,
|
| 1198 |
+
dhbt: torch.Tensor,
|
| 1199 |
+
chunk_size: int = 16,
|
| 1200 |
+
initial_state: torch.Tensor = None,
|
| 1201 |
+
initial_state_bias: torch.Tensor = None,
|
| 1202 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 1203 |
+
):
|
| 1204 |
+
BT = chunk_size
|
| 1205 |
+
h, v_new, x, y, rstd = chunk_ttt_linear_bwd_h(
|
| 1206 |
+
k=k,
|
| 1207 |
+
v=v,
|
| 1208 |
+
w=w,
|
| 1209 |
+
b=b,
|
| 1210 |
+
eta=eta,
|
| 1211 |
+
eps=eps,
|
| 1212 |
+
initial_state=initial_state,
|
| 1213 |
+
initial_state_bias=initial_state_bias,
|
| 1214 |
+
cu_seqlens=cu_seqlens,
|
| 1215 |
+
chunk_size=BT
|
| 1216 |
+
)
|
| 1217 |
+
dv_new = chunk_ttt_linear_bwd_dv_local(
|
| 1218 |
+
q=q,
|
| 1219 |
+
k=k,
|
| 1220 |
+
eta=eta,
|
| 1221 |
+
do=do,
|
| 1222 |
+
scale=scale,
|
| 1223 |
+
cu_seqlens=cu_seqlens,
|
| 1224 |
+
chunk_size=BT
|
| 1225 |
+
)
|
| 1226 |
+
dh, dhb, dh0, dhb0, dv, dk, dw, db = chunk_ttt_linear_bwd_norm(
|
| 1227 |
+
q=q,
|
| 1228 |
+
k=k,
|
| 1229 |
+
v=v,
|
| 1230 |
+
v_new=v_new,
|
| 1231 |
+
x=x,
|
| 1232 |
+
y=y,
|
| 1233 |
+
rstd=rstd,
|
| 1234 |
+
w=w,
|
| 1235 |
+
b=b,
|
| 1236 |
+
eta=eta,
|
| 1237 |
+
h0=initial_state,
|
| 1238 |
+
hb0=initial_state_bias,
|
| 1239 |
+
h=h,
|
| 1240 |
+
dht=dht,
|
| 1241 |
+
dhbt=dhbt,
|
| 1242 |
+
dv_new=dv_new,
|
| 1243 |
+
do=do,
|
| 1244 |
+
scale=scale,
|
| 1245 |
+
cu_seqlens=cu_seqlens,
|
| 1246 |
+
chunk_size=BT
|
| 1247 |
+
)
|
| 1248 |
+
dq, dk2, de = chunk_ttt_linear_bwd_dqke(
|
| 1249 |
+
q=q,
|
| 1250 |
+
k=k,
|
| 1251 |
+
v=v_new,
|
| 1252 |
+
eta=eta,
|
| 1253 |
+
h=h,
|
| 1254 |
+
do=do,
|
| 1255 |
+
dh=dh,
|
| 1256 |
+
dhb=dhb,
|
| 1257 |
+
scale=scale,
|
| 1258 |
+
cu_seqlens=cu_seqlens,
|
| 1259 |
+
chunk_size=BT
|
| 1260 |
+
)
|
| 1261 |
+
dk.add_(dk2)
|
| 1262 |
+
return dq, dk, dv, de, dw, db, dh0, dhb0
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
class ChunkTTTLinearFunction(torch.autograd.Function):
|
| 1266 |
+
|
| 1267 |
+
@staticmethod
|
| 1268 |
+
@input_guard
|
| 1269 |
+
@autocast_custom_fwd
|
| 1270 |
+
def forward(
|
| 1271 |
+
ctx,
|
| 1272 |
+
q,
|
| 1273 |
+
k,
|
| 1274 |
+
v,
|
| 1275 |
+
w,
|
| 1276 |
+
b,
|
| 1277 |
+
chunk_size,
|
| 1278 |
+
eta,
|
| 1279 |
+
scale,
|
| 1280 |
+
eps,
|
| 1281 |
+
initial_state,
|
| 1282 |
+
initial_state_bias,
|
| 1283 |
+
output_final_state,
|
| 1284 |
+
cu_seqlens
|
| 1285 |
+
):
|
| 1286 |
+
o, final_state, final_state_bias = chunk_ttt_linear_fwd(
|
| 1287 |
+
q=q,
|
| 1288 |
+
k=k,
|
| 1289 |
+
v=v,
|
| 1290 |
+
w=w,
|
| 1291 |
+
b=b,
|
| 1292 |
+
eta=eta,
|
| 1293 |
+
scale=scale,
|
| 1294 |
+
eps=eps,
|
| 1295 |
+
chunk_size=chunk_size,
|
| 1296 |
+
initial_state=initial_state,
|
| 1297 |
+
initial_state_bias=initial_state_bias,
|
| 1298 |
+
output_final_state=output_final_state,
|
| 1299 |
+
cu_seqlens=cu_seqlens,
|
| 1300 |
+
)
|
| 1301 |
+
ctx.save_for_backward(q, k, v, eta, w, b, initial_state, initial_state_bias)
|
| 1302 |
+
ctx.chunk_size = chunk_size
|
| 1303 |
+
ctx.scale = scale
|
| 1304 |
+
ctx.eps = eps
|
| 1305 |
+
ctx.cu_seqlens = cu_seqlens
|
| 1306 |
+
return o.to(q.dtype), final_state, final_state_bias
|
| 1307 |
+
|
| 1308 |
+
@staticmethod
|
| 1309 |
+
@input_guard
|
| 1310 |
+
@autocast_custom_bwd
|
| 1311 |
+
def backward(ctx, do, dht, dhbt):
|
| 1312 |
+
q, k, v, eta, w, b, initial_state, initial_state_bias = ctx.saved_tensors
|
| 1313 |
+
dq, dk, dv, de, dw, db, dh0, dhb0 = chunk_ttt_linear_bwd(
|
| 1314 |
+
q=q,
|
| 1315 |
+
k=k,
|
| 1316 |
+
v=v,
|
| 1317 |
+
w=w,
|
| 1318 |
+
b=b,
|
| 1319 |
+
eta=eta,
|
| 1320 |
+
scale=ctx.scale,
|
| 1321 |
+
eps=ctx.eps,
|
| 1322 |
+
do=do,
|
| 1323 |
+
dht=dht,
|
| 1324 |
+
dhbt=dhbt,
|
| 1325 |
+
chunk_size=ctx.chunk_size,
|
| 1326 |
+
initial_state=initial_state,
|
| 1327 |
+
initial_state_bias=initial_state_bias,
|
| 1328 |
+
cu_seqlens=ctx.cu_seqlens,
|
| 1329 |
+
)
|
| 1330 |
+
return dq.to(q), dk.to(k), dv.to(v), dw.to(w), db.to(b), None, de.to(eta), None, None, dh0, dhb0, None, None, None
|
| 1331 |
+
|
| 1332 |
+
|
| 1333 |
+
def norm_residual(x, weight, bias, eps):
|
| 1334 |
+
# GroupNorm and Residual
|
| 1335 |
+
B, T, H, D = x.shape
|
| 1336 |
+
x += group_norm(
|
| 1337 |
+
x.reshape(B, T, -1).clone(),
|
| 1338 |
+
weight=weight.reshape(-1).clone(),
|
| 1339 |
+
bias=bias.reshape(-1).clone(),
|
| 1340 |
+
eps=eps,
|
| 1341 |
+
num_groups=H,
|
| 1342 |
+
).reshape(x.shape)
|
| 1343 |
+
return x
|
| 1344 |
+
|
| 1345 |
+
|
| 1346 |
+
def chunk_ttt_linear(
|
| 1347 |
+
q: torch.Tensor,
|
| 1348 |
+
k: torch.Tensor,
|
| 1349 |
+
v: torch.Tensor,
|
| 1350 |
+
w: torch.Tensor,
|
| 1351 |
+
b: torch.Tensor,
|
| 1352 |
+
eta: torch.Tensor,
|
| 1353 |
+
scale: float = None,
|
| 1354 |
+
eps: float = 1e-6,
|
| 1355 |
+
chunk_size: int = 16,
|
| 1356 |
+
initial_state: torch.Tensor = None,
|
| 1357 |
+
initial_state_bias: torch.Tensor = None,
|
| 1358 |
+
output_final_state: bool = False,
|
| 1359 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 1360 |
+
head_first: bool = False,
|
| 1361 |
+
):
|
| 1362 |
+
r"""
|
| 1363 |
+
Args:
|
| 1364 |
+
q (torch.Tensor):
|
| 1365 |
+
queries of shape `(B, H, T, K)`
|
| 1366 |
+
k (torch.Tensor):
|
| 1367 |
+
keys of shape `(B, H, T, K)`
|
| 1368 |
+
v (torch.Tensor):
|
| 1369 |
+
values of shape `(B, H, T, V)`
|
| 1370 |
+
w (torch.Tensor):
|
| 1371 |
+
layer norm weight of shape `(H, V)`
|
| 1372 |
+
b (torch.Tensor):
|
| 1373 |
+
layer norm bias of shape `(H, V)`
|
| 1374 |
+
eta (torch.Tensor):
|
| 1375 |
+
Learning rate for hidden state, of shape `(B, H, T, 1)`.
|
| 1376 |
+
scale (Optional[float]):
|
| 1377 |
+
Scale factor for the RetNet attention scores.
|
| 1378 |
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
| 1379 |
+
chunk_size (int):
|
| 1380 |
+
chunk size. Default: `16`.
|
| 1381 |
+
initial_state (Optional[torch.Tensor]):
|
| 1382 |
+
Initial state of shape `(B, H, K, V)`. Default: `None`.
|
| 1383 |
+
initial_state_bias (Optional[torch.Tensor]):
|
| 1384 |
+
Initial state bias of shape `(B, H, 1, V)`. Default: `None`.
|
| 1385 |
+
output_final_state (Optional[bool]):
|
| 1386 |
+
Whether to output the final state of shape `(B, H, K, V)`. Default: `False`.
|
| 1387 |
+
cu_seqlens (torch.LongTensor):
|
| 1388 |
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
| 1389 |
+
consistent with the FlashAttention API.
|
| 1390 |
+
head_first (Optional[bool]):
|
| 1391 |
+
Whether the inputs are in the head-first format. Default: `False`.
|
| 1392 |
+
This argument has been deprecated.
|
| 1393 |
+
|
| 1394 |
+
Returns:
|
| 1395 |
+
o (torch.Tensor):
|
| 1396 |
+
Outputs of shape `[B, H, T, V]`
|
| 1397 |
+
final_state (torch.Tensor):
|
| 1398 |
+
Final state of shape `[B, H, K, V]` if `output_final_state=True` else `None`
|
| 1399 |
+
"""
|
| 1400 |
+
assert q.dtype == k.dtype == v.dtype
|
| 1401 |
+
assert k.shape[-1] == v.shape[-1], "DK must equal to DV."
|
| 1402 |
+
if isinstance(eta, float):
|
| 1403 |
+
eta = torch.full_like(q[:, :, :, :1], eta)
|
| 1404 |
+
if head_first:
|
| 1405 |
+
raise DeprecationWarning(
|
| 1406 |
+
"head_first is deprecated and will be removed in a future version. "
|
| 1407 |
+
"Please use head_first=False for now instead."
|
| 1408 |
+
)
|
| 1409 |
+
if not head_first and q.shape[1] < q.shape[2]:
|
| 1410 |
+
warnings.warn(
|
| 1411 |
+
f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
|
| 1412 |
+
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
|
| 1413 |
+
"when head_first=False was specified. "
|
| 1414 |
+
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
|
| 1415 |
+
)
|
| 1416 |
+
if cu_seqlens is not None:
|
| 1417 |
+
if q.shape[0] != 1:
|
| 1418 |
+
raise ValueError(
|
| 1419 |
+
f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
|
| 1420 |
+
f"Please flatten variable-length inputs before processing."
|
| 1421 |
+
)
|
| 1422 |
+
if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
|
| 1423 |
+
raise ValueError(
|
| 1424 |
+
f"The number of initial states is expected to be equal to the number of input sequences, "
|
| 1425 |
+
f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
|
| 1426 |
+
)
|
| 1427 |
+
if scale is None:
|
| 1428 |
+
scale = k.shape[-1] ** -0.5
|
| 1429 |
+
else:
|
| 1430 |
+
assert scale > 0, "Scale must be positive."
|
| 1431 |
+
o, final_state, final_state_bias = ChunkTTTLinearFunction.apply(
|
| 1432 |
+
q,
|
| 1433 |
+
k,
|
| 1434 |
+
v,
|
| 1435 |
+
w,
|
| 1436 |
+
b,
|
| 1437 |
+
chunk_size,
|
| 1438 |
+
eta,
|
| 1439 |
+
scale,
|
| 1440 |
+
eps,
|
| 1441 |
+
initial_state,
|
| 1442 |
+
initial_state_bias,
|
| 1443 |
+
output_final_state,
|
| 1444 |
+
cu_seqlens,
|
| 1445 |
+
)
|
| 1446 |
+
o = norm_residual(o, w, b, eps)
|
| 1447 |
+
return o, final_state, final_state_bias
|
utils/__init__.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from .cumsum import (
|
| 4 |
+
chunk_global_cumsum,
|
| 5 |
+
chunk_global_cumsum_scalar,
|
| 6 |
+
chunk_global_cumsum_vector,
|
| 7 |
+
chunk_local_cumsum,
|
| 8 |
+
chunk_local_cumsum_scalar,
|
| 9 |
+
chunk_local_cumsum_vector
|
| 10 |
+
)
|
| 11 |
+
from .index import (
|
| 12 |
+
get_max_num_splits,
|
| 13 |
+
prepare_chunk_indices,
|
| 14 |
+
prepare_chunk_offsets,
|
| 15 |
+
prepare_cu_seqlens_from_lens,
|
| 16 |
+
prepare_cu_seqlens_from_mask,
|
| 17 |
+
prepare_lens,
|
| 18 |
+
prepare_lens_from_cu_seqlens,
|
| 19 |
+
prepare_lens_from_mask,
|
| 20 |
+
prepare_position_ids,
|
| 21 |
+
prepare_sequence_ids,
|
| 22 |
+
prepare_token_indices
|
| 23 |
+
)
|
| 24 |
+
from .logsumexp import logsumexp_fwd
|
| 25 |
+
from .matmul import addmm, matmul
|
| 26 |
+
from .pack import pack_sequence, unpack_sequence
|
| 27 |
+
from .pooling import mean_pooling
|
| 28 |
+
from .softmax import softmax_bwd, softmax_fwd
|
| 29 |
+
from .solve_tril import solve_tril
|
| 30 |
+
|
| 31 |
+
__all__ = [
|
| 32 |
+
'chunk_global_cumsum',
|
| 33 |
+
'chunk_global_cumsum_scalar',
|
| 34 |
+
'chunk_global_cumsum_vector',
|
| 35 |
+
'chunk_local_cumsum',
|
| 36 |
+
'chunk_local_cumsum_scalar',
|
| 37 |
+
'chunk_local_cumsum_vector',
|
| 38 |
+
'pack_sequence',
|
| 39 |
+
'unpack_sequence',
|
| 40 |
+
'prepare_chunk_indices',
|
| 41 |
+
'prepare_chunk_offsets',
|
| 42 |
+
'prepare_cu_seqlens_from_lens',
|
| 43 |
+
'prepare_cu_seqlens_from_mask',
|
| 44 |
+
'prepare_lens',
|
| 45 |
+
'prepare_lens_from_cu_seqlens',
|
| 46 |
+
'prepare_lens_from_mask',
|
| 47 |
+
'prepare_position_ids',
|
| 48 |
+
'prepare_sequence_ids',
|
| 49 |
+
'prepare_token_indices',
|
| 50 |
+
'logsumexp_fwd',
|
| 51 |
+
'addmm',
|
| 52 |
+
'matmul',
|
| 53 |
+
'mean_pooling',
|
| 54 |
+
'softmax_bwd',
|
| 55 |
+
'softmax_fwd',
|
| 56 |
+
'solve_tril',
|
| 57 |
+
'get_max_num_splits'
|
| 58 |
+
]
|
utils/__pycache__/cumsum.cpython-312.pyc
ADDED
|
Binary file (22 kB). View file
|
|
|
utils/__pycache__/matmul.cpython-312.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
utils/__pycache__/softmax.cpython-312.pyc
ADDED
|
Binary file (4.7 kB). View file
|
|
|
utils/__pycache__/solve_tril.cpython-312.pyc
ADDED
|
Binary file (27.8 kB). View file
|
|
|
utils/constant.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# Approximate value of 1/ln(2), used for log/exp base conversion
|
| 5 |
+
# Best FP32 approximation: 1.4426950216 (hex 0x3FB8AA3B)
|
| 6 |
+
RCP_LN2 = 1.4426950216
|
utils/index.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import triton
|
| 9 |
+
import triton.language as tl
|
| 10 |
+
|
| 11 |
+
from fla.utils import autotune_cache_kwargs, tensor_cache
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@triton.autotune(
|
| 15 |
+
configs=[
|
| 16 |
+
triton.Config({}, num_warps=num_warps)
|
| 17 |
+
for num_warps in [4, 8, 16, 32]
|
| 18 |
+
],
|
| 19 |
+
key=['B'],
|
| 20 |
+
**autotune_cache_kwargs
|
| 21 |
+
)
|
| 22 |
+
@triton.jit
|
| 23 |
+
def prepare_position_ids_kernel(
|
| 24 |
+
y,
|
| 25 |
+
cu_seqlens,
|
| 26 |
+
B: tl.constexpr
|
| 27 |
+
):
|
| 28 |
+
i_n = tl.program_id(0)
|
| 29 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 30 |
+
T = eos - bos
|
| 31 |
+
|
| 32 |
+
o = tl.arange(0, B)
|
| 33 |
+
for i in range(0, tl.cdiv(T, B) * B, B):
|
| 34 |
+
o_i = o + i
|
| 35 |
+
tl.store(y + bos + o_i, o_i, o_i < T)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@tensor_cache
|
| 39 |
+
def prepare_lens(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
| 40 |
+
return cu_seqlens[1:] - cu_seqlens[:-1]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@tensor_cache
|
| 44 |
+
def prepare_lens_from_mask(mask: torch.BoolTensor) -> torch.LongTensor:
|
| 45 |
+
return mask.sum(dim=-1, dtype=torch.int32)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@tensor_cache
|
| 49 |
+
def prepare_cu_seqlens_from_lens(
|
| 50 |
+
lens: torch.LongTensor,
|
| 51 |
+
dtype: Optional[torch.dtype] = torch.int32
|
| 52 |
+
) -> torch.LongTensor:
|
| 53 |
+
return F.pad(lens.cumsum(dim=0, dtype=dtype), (1, 0))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@tensor_cache
|
| 57 |
+
def prepare_cu_seqlens_from_mask(
|
| 58 |
+
mask: torch.BoolTensor,
|
| 59 |
+
dtype: Optional[torch.dtype] = torch.int32
|
| 60 |
+
) -> torch.LongTensor:
|
| 61 |
+
return prepare_cu_seqlens_from_lens(prepare_lens_from_mask(mask), dtype)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@tensor_cache
|
| 65 |
+
def prepare_lens_from_cu_seqlens(
|
| 66 |
+
cu_seqlens: torch.LongTensor,
|
| 67 |
+
) -> torch.LongTensor:
|
| 68 |
+
return cu_seqlens[1:] - cu_seqlens[:-1]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@tensor_cache
|
| 72 |
+
def prepare_split_cu_seqlens(
|
| 73 |
+
batch_size: int,
|
| 74 |
+
seq_len: int,
|
| 75 |
+
split_size: int,
|
| 76 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 77 |
+
dtype: Optional[torch.dtype] = torch.int32,
|
| 78 |
+
device: Optional[torch.device] = torch.device('cpu')
|
| 79 |
+
) -> torch.LongTensor:
|
| 80 |
+
if cu_seqlens is None:
|
| 81 |
+
total_tokens = batch_size * seq_len
|
| 82 |
+
cu_seqlens = list(range(0, total_tokens, seq_len)) + [total_tokens]
|
| 83 |
+
else:
|
| 84 |
+
cu_seqlens = cu_seqlens.tolist()
|
| 85 |
+
return torch.tensor(
|
| 86 |
+
[
|
| 87 |
+
i
|
| 88 |
+
for bos, eos in zip(cu_seqlens[:-1], cu_seqlens[1:])
|
| 89 |
+
for i in range(bos, eos, split_size)
|
| 90 |
+
] + [cu_seqlens[-1]],
|
| 91 |
+
dtype=dtype,
|
| 92 |
+
device=device
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@tensor_cache
|
| 97 |
+
def prepare_position_ids(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
| 98 |
+
return torch.cat([
|
| 99 |
+
torch.arange(n, dtype=cu_seqlens.dtype, device=cu_seqlens.device)
|
| 100 |
+
for n in prepare_lens(cu_seqlens).unbind()
|
| 101 |
+
])
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@tensor_cache
|
| 105 |
+
def prepare_sequence_ids(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
| 106 |
+
return prepare_position_ids(cu_seqlens).eq(0).cumsum(0) - 1
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@tensor_cache
|
| 110 |
+
def prepare_token_indices(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
| 111 |
+
position_ids = prepare_position_ids(cu_seqlens)
|
| 112 |
+
return torch.stack([prepare_sequence_ids(cu_seqlens), position_ids], 1).to(cu_seqlens)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@tensor_cache
|
| 116 |
+
def prepare_chunk_indices(
|
| 117 |
+
cu_seqlens: torch.LongTensor,
|
| 118 |
+
chunk_size: int
|
| 119 |
+
) -> torch.LongTensor:
|
| 120 |
+
indices = torch.cat([torch.arange(n) for n in triton.cdiv(prepare_lens(cu_seqlens), chunk_size).tolist()])
|
| 121 |
+
return torch.stack([indices.eq(0).cumsum(0) - 1, indices], 1).to(cu_seqlens)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@tensor_cache
|
| 125 |
+
def prepare_chunk_offsets(
|
| 126 |
+
cu_seqlens: torch.LongTensor,
|
| 127 |
+
chunk_size: int
|
| 128 |
+
) -> torch.LongTensor:
|
| 129 |
+
return torch.cat([cu_seqlens.new_tensor([0]), triton.cdiv(prepare_lens(cu_seqlens), chunk_size)]).cumsum(-1)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@tensor_cache
|
| 133 |
+
def get_max_num_splits(cu_seqlens: torch.LongTensor, chunk_size: int) -> int:
|
| 134 |
+
return triton.cdiv(int(max(prepare_lens(cu_seqlens))), chunk_size)
|
utils/pack.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# Code adapted from https://github.com/mayank31398/cute-kernels
|
| 5 |
+
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import triton
|
| 10 |
+
import triton.language as tl
|
| 11 |
+
|
| 12 |
+
from fla.ops.utils.index import prepare_lens
|
| 13 |
+
from fla.utils import autotune_cache_kwargs, input_guard
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@triton.autotune(
|
| 17 |
+
configs=[
|
| 18 |
+
triton.Config({}, num_warps=num_warps)
|
| 19 |
+
for num_warps in [4, 8, 16, 32]
|
| 20 |
+
],
|
| 21 |
+
key=['D', 'PADDING_SIDE', 'PACK'],
|
| 22 |
+
**autotune_cache_kwargs
|
| 23 |
+
)
|
| 24 |
+
@triton.jit
|
| 25 |
+
def packunpack_sequence_kernel(
|
| 26 |
+
x,
|
| 27 |
+
y,
|
| 28 |
+
cu_seqlens,
|
| 29 |
+
S,
|
| 30 |
+
D,
|
| 31 |
+
BD: tl.constexpr,
|
| 32 |
+
PADDING_SIDE: tl.constexpr,
|
| 33 |
+
PACK: tl.constexpr,
|
| 34 |
+
):
|
| 35 |
+
i_d, i_s, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 36 |
+
bos, eos = tl.load(cu_seqlens + i_b), tl.load(cu_seqlens + i_b + 1)
|
| 37 |
+
|
| 38 |
+
T = eos - bos
|
| 39 |
+
if PADDING_SIDE == 'left':
|
| 40 |
+
NP = S - T
|
| 41 |
+
if i_s < NP:
|
| 42 |
+
return
|
| 43 |
+
i_t = bos + (i_s - NP)
|
| 44 |
+
else:
|
| 45 |
+
if i_s >= T:
|
| 46 |
+
return
|
| 47 |
+
i_t = bos + i_s
|
| 48 |
+
|
| 49 |
+
o_d = i_d * BD + tl.arange(0, BD)
|
| 50 |
+
mask = o_d < D
|
| 51 |
+
|
| 52 |
+
if PACK:
|
| 53 |
+
b_x = tl.load(x + (i_b * S + i_s) * D + o_d, mask=mask)
|
| 54 |
+
tl.store(y + i_t * D + o_d, b_x, mask=mask)
|
| 55 |
+
else:
|
| 56 |
+
b_x = tl.load(x + i_t * D + o_d, mask=mask)
|
| 57 |
+
tl.store(y + (i_b * S + i_s) * D + o_d, b_x, mask=mask)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def pack_sequence_fwdbwd(
|
| 61 |
+
x: torch.Tensor,
|
| 62 |
+
cu_seqlens: torch.Tensor,
|
| 63 |
+
padding_side: str,
|
| 64 |
+
) -> torch.Tensor:
|
| 65 |
+
B, S = x.shape[:2]
|
| 66 |
+
D = x.numel() // (B * S)
|
| 67 |
+
BD = min(triton.next_power_of_2(D), 4096)
|
| 68 |
+
ND = triton.cdiv(D, BD)
|
| 69 |
+
|
| 70 |
+
y = torch.empty(cu_seqlens[-1].item(), *x.shape[2:], device=x.device, dtype=x.dtype)
|
| 71 |
+
packunpack_sequence_kernel[ND, S, B](
|
| 72 |
+
x=x,
|
| 73 |
+
y=y,
|
| 74 |
+
cu_seqlens=cu_seqlens,
|
| 75 |
+
S=S,
|
| 76 |
+
D=D,
|
| 77 |
+
BD=BD,
|
| 78 |
+
PADDING_SIDE=padding_side,
|
| 79 |
+
PACK=True,
|
| 80 |
+
)
|
| 81 |
+
return y
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def unpack_sequence_fwdbwd(
|
| 85 |
+
x: torch.Tensor,
|
| 86 |
+
cu_seqlens: torch.Tensor,
|
| 87 |
+
padding_side: str,
|
| 88 |
+
desired_shape: torch.Size,
|
| 89 |
+
) -> torch.Tensor:
|
| 90 |
+
if desired_shape is None:
|
| 91 |
+
desired_shape = (len(cu_seqlens) - 1, prepare_lens(cu_seqlens).max().item(), *x.shape[1:])
|
| 92 |
+
y = torch.zeros(desired_shape, device=x.device, dtype=x.dtype)
|
| 93 |
+
B, S = y.shape[:2]
|
| 94 |
+
D = y.numel() // (B * S)
|
| 95 |
+
BD = min(triton.next_power_of_2(D), 4096)
|
| 96 |
+
ND = triton.cdiv(D, BD)
|
| 97 |
+
|
| 98 |
+
packunpack_sequence_kernel[ND, S, B](
|
| 99 |
+
x=x,
|
| 100 |
+
y=y,
|
| 101 |
+
cu_seqlens=cu_seqlens,
|
| 102 |
+
S=S,
|
| 103 |
+
D=D,
|
| 104 |
+
BD=BD,
|
| 105 |
+
PADDING_SIDE=padding_side,
|
| 106 |
+
PACK=False,
|
| 107 |
+
)
|
| 108 |
+
return y
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class PackSequenceFunction(torch.autograd.Function):
|
| 112 |
+
|
| 113 |
+
@staticmethod
|
| 114 |
+
@input_guard
|
| 115 |
+
def forward(
|
| 116 |
+
ctx,
|
| 117 |
+
x: torch.Tensor,
|
| 118 |
+
cu_seqlens: torch.Tensor,
|
| 119 |
+
padding_side: str,
|
| 120 |
+
) -> torch.Tensor:
|
| 121 |
+
assert padding_side in ['left', 'right']
|
| 122 |
+
assert x.ndim >= 2
|
| 123 |
+
|
| 124 |
+
ctx.cu_seqlens = cu_seqlens
|
| 125 |
+
ctx.padding_side = padding_side
|
| 126 |
+
ctx.desired_shape = x.shape
|
| 127 |
+
|
| 128 |
+
y = pack_sequence_fwdbwd(
|
| 129 |
+
x=x,
|
| 130 |
+
cu_seqlens=cu_seqlens,
|
| 131 |
+
padding_side=padding_side,
|
| 132 |
+
)
|
| 133 |
+
return y
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
@input_guard
|
| 137 |
+
def backward(ctx, dy: torch.Tensor) -> tuple[torch.Tensor | None]:
|
| 138 |
+
dx = unpack_sequence_fwdbwd(
|
| 139 |
+
x=dy,
|
| 140 |
+
cu_seqlens=ctx.cu_seqlens,
|
| 141 |
+
padding_side=ctx.padding_side,
|
| 142 |
+
desired_shape=ctx.desired_shape,
|
| 143 |
+
)
|
| 144 |
+
return dx, *[None] * 10
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class UnpackSequenceFunction(torch.autograd.Function):
|
| 148 |
+
|
| 149 |
+
@staticmethod
|
| 150 |
+
@input_guard
|
| 151 |
+
def forward(
|
| 152 |
+
ctx,
|
| 153 |
+
x: torch.Tensor,
|
| 154 |
+
cu_seqlens: torch.Tensor,
|
| 155 |
+
padding_side: str,
|
| 156 |
+
desired_shape: Optional[torch.Size] = None,
|
| 157 |
+
) -> torch.Tensor:
|
| 158 |
+
assert padding_side in ['left', 'right']
|
| 159 |
+
assert x.ndim >= 2
|
| 160 |
+
if desired_shape is not None:
|
| 161 |
+
assert desired_shape[0] == cu_seqlens.shape[0] - 1
|
| 162 |
+
assert desired_shape[2:] == x.shape[1:]
|
| 163 |
+
|
| 164 |
+
ctx.cu_seqlens = cu_seqlens
|
| 165 |
+
ctx.padding_side = padding_side
|
| 166 |
+
|
| 167 |
+
y = unpack_sequence_fwdbwd(
|
| 168 |
+
x=x,
|
| 169 |
+
cu_seqlens=cu_seqlens,
|
| 170 |
+
padding_side=padding_side,
|
| 171 |
+
desired_shape=desired_shape,
|
| 172 |
+
)
|
| 173 |
+
return y
|
| 174 |
+
|
| 175 |
+
@staticmethod
|
| 176 |
+
@input_guard
|
| 177 |
+
def backward(ctx, dy: torch.Tensor) -> tuple[torch.Tensor | None]:
|
| 178 |
+
dx = pack_sequence_fwdbwd(
|
| 179 |
+
x=dy,
|
| 180 |
+
cu_seqlens=ctx.cu_seqlens,
|
| 181 |
+
padding_side=ctx.padding_side,
|
| 182 |
+
)
|
| 183 |
+
return dx, None, None, None
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def pack_sequence(
|
| 187 |
+
x: torch.Tensor,
|
| 188 |
+
cu_seqlens: torch.Tensor,
|
| 189 |
+
padding_side: str = 'left'
|
| 190 |
+
) -> torch.Tensor:
|
| 191 |
+
return PackSequenceFunction.apply(
|
| 192 |
+
x,
|
| 193 |
+
cu_seqlens,
|
| 194 |
+
padding_side,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def unpack_sequence(
|
| 199 |
+
x: torch.Tensor,
|
| 200 |
+
cu_seqlens: torch.Tensor,
|
| 201 |
+
padding_side: str = 'left',
|
| 202 |
+
desired_shape: Optional[torch.Size] = None,
|
| 203 |
+
) -> torch.Tensor:
|
| 204 |
+
return UnpackSequenceFunction.apply(
|
| 205 |
+
x,
|
| 206 |
+
cu_seqlens,
|
| 207 |
+
padding_side,
|
| 208 |
+
desired_shape,
|
| 209 |
+
)
|
utils/softmax.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2024, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import triton
|
| 8 |
+
import triton.language as tl
|
| 9 |
+
|
| 10 |
+
from fla.ops.utils.op import exp
|
| 11 |
+
from fla.utils import autotune_cache_kwargs, is_amd
|
| 12 |
+
|
| 13 |
+
NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@triton.autotune(
|
| 17 |
+
configs=[
|
| 18 |
+
triton.Config({}, num_warps=num_warps)
|
| 19 |
+
for num_warps in NUM_WARPS_AUTOTUNE
|
| 20 |
+
],
|
| 21 |
+
key=['D'],
|
| 22 |
+
**autotune_cache_kwargs
|
| 23 |
+
)
|
| 24 |
+
@triton.jit
|
| 25 |
+
def softmax_fwd_kernel(
|
| 26 |
+
x,
|
| 27 |
+
p,
|
| 28 |
+
D: tl.constexpr,
|
| 29 |
+
B: tl.constexpr
|
| 30 |
+
):
|
| 31 |
+
i_n = tl.program_id(0)
|
| 32 |
+
o_d = tl.arange(0, B)
|
| 33 |
+
m_d = o_d < D
|
| 34 |
+
|
| 35 |
+
b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=-float('inf'))
|
| 36 |
+
b_m = tl.max(b_x, 0)
|
| 37 |
+
b_x = exp(b_x - b_m)
|
| 38 |
+
b_p = b_x / tl.sum(b_x, 0)
|
| 39 |
+
|
| 40 |
+
tl.store(p + i_n * D + o_d, b_p.to(p.dtype.element_ty), mask=m_d)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@triton.autotune(
|
| 44 |
+
configs=[
|
| 45 |
+
triton.Config({}, num_warps=num_warps)
|
| 46 |
+
for num_warps in NUM_WARPS_AUTOTUNE
|
| 47 |
+
],
|
| 48 |
+
key=['D'],
|
| 49 |
+
**autotune_cache_kwargs
|
| 50 |
+
)
|
| 51 |
+
@triton.jit
|
| 52 |
+
def softmax_bwd_kernel(
|
| 53 |
+
p,
|
| 54 |
+
dp,
|
| 55 |
+
ds,
|
| 56 |
+
D: tl.constexpr,
|
| 57 |
+
B: tl.constexpr
|
| 58 |
+
):
|
| 59 |
+
i_n = tl.program_id(0)
|
| 60 |
+
o_d = tl.arange(0, B)
|
| 61 |
+
m_d = o_d < D
|
| 62 |
+
|
| 63 |
+
b_p = tl.load(p + i_n * D + o_d, mask=m_d, other=0.)
|
| 64 |
+
b_dp = tl.load(dp + i_n * D + o_d, mask=m_d, other=0.)
|
| 65 |
+
b_pp = tl.sum(b_p * b_dp, 0)
|
| 66 |
+
b_ds = b_p * b_dp - b_p * b_pp
|
| 67 |
+
tl.store(ds + i_n * D + o_d, b_ds.to(ds.dtype.element_ty), mask=m_d)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def softmax_fwd(
|
| 71 |
+
x: torch.Tensor,
|
| 72 |
+
dtype: Optional[torch.dtype] = torch.float
|
| 73 |
+
) -> torch.Tensor:
|
| 74 |
+
shape = x.shape
|
| 75 |
+
x = x.view(-1, x.shape[-1])
|
| 76 |
+
|
| 77 |
+
N, D = x.shape
|
| 78 |
+
B = triton.next_power_of_2(D)
|
| 79 |
+
|
| 80 |
+
p = torch.empty_like(x, dtype=dtype)
|
| 81 |
+
softmax_fwd_kernel[(N,)](
|
| 82 |
+
x=x,
|
| 83 |
+
p=p,
|
| 84 |
+
D=D,
|
| 85 |
+
B=B
|
| 86 |
+
)
|
| 87 |
+
return p.view(*shape)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def softmax_bwd(
|
| 91 |
+
p: torch.Tensor,
|
| 92 |
+
dp: torch.Tensor,
|
| 93 |
+
dtype: Optional[torch.dtype] = torch.float
|
| 94 |
+
) -> torch.Tensor:
|
| 95 |
+
shape = p.shape
|
| 96 |
+
p = p.view(-1, p.shape[-1])
|
| 97 |
+
ds = torch.empty_like(p, dtype=dtype)
|
| 98 |
+
|
| 99 |
+
N, D = p.shape
|
| 100 |
+
B = triton.next_power_of_2(D)
|
| 101 |
+
softmax_bwd_kernel[(N,)](
|
| 102 |
+
p=p,
|
| 103 |
+
dp=dp,
|
| 104 |
+
ds=ds,
|
| 105 |
+
D=D,
|
| 106 |
+
B=B
|
| 107 |
+
)
|
| 108 |
+
return ds.view(*shape)
|
utils/solve_tril.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import triton
|
| 9 |
+
import triton.language as tl
|
| 10 |
+
|
| 11 |
+
from fla.ops.utils.index import prepare_chunk_indices
|
| 12 |
+
from fla.ops.utils.op import make_tensor_descriptor
|
| 13 |
+
from fla.utils import autotune_cache_kwargs, input_guard, is_amd, is_tma_supported
|
| 14 |
+
|
| 15 |
+
FLA_TRIL_PRECISION = os.environ.get('FLA_TRIL_PRECISION', 'ieee')
|
| 16 |
+
ALLOWED_TRIL_PRECISIONS = ['ieee', 'tf32'] if is_amd else ['ieee', 'tf32', 'tf32x3']
|
| 17 |
+
assert FLA_TRIL_PRECISION in ALLOWED_TRIL_PRECISIONS, \
|
| 18 |
+
f'FLA_TRIL_PRECISION must be one of {ALLOWED_TRIL_PRECISIONS}, but got {FLA_TRIL_PRECISION}'
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@triton.heuristics({
|
| 22 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
| 23 |
+
})
|
| 24 |
+
@triton.autotune(
|
| 25 |
+
configs=[
|
| 26 |
+
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
| 27 |
+
for num_warps in [1, 2, 4, 8]
|
| 28 |
+
for num_stages in [2, 3, 4, 5]
|
| 29 |
+
],
|
| 30 |
+
key=['BT'],
|
| 31 |
+
**autotune_cache_kwargs
|
| 32 |
+
)
|
| 33 |
+
@triton.jit(do_not_specialize=['T'])
|
| 34 |
+
def solve_tril_16x16_kernel(
|
| 35 |
+
A,
|
| 36 |
+
Ai,
|
| 37 |
+
cu_seqlens,
|
| 38 |
+
chunk_indices,
|
| 39 |
+
T,
|
| 40 |
+
H: tl.constexpr,
|
| 41 |
+
BT: tl.constexpr,
|
| 42 |
+
USE_TMA: tl.constexpr,
|
| 43 |
+
IS_VARLEN: tl.constexpr,
|
| 44 |
+
DOT_PRECISION: tl.constexpr
|
| 45 |
+
):
|
| 46 |
+
i_t, i_bh = tl.program_id(0), tl.program_id(1)
|
| 47 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 48 |
+
if IS_VARLEN:
|
| 49 |
+
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
| 50 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 51 |
+
T = eos - bos
|
| 52 |
+
else:
|
| 53 |
+
bos, eos = i_b * T, i_b * T + T
|
| 54 |
+
o_i = tl.arange(0, 16)
|
| 55 |
+
m_A = o_i[:, None] > o_i[None, :]
|
| 56 |
+
m_I = o_i[:, None] == o_i[None, :]
|
| 57 |
+
|
| 58 |
+
A = A + (bos*H + i_h) * BT
|
| 59 |
+
Ai = Ai + (bos*H + i_h) * 16
|
| 60 |
+
|
| 61 |
+
offset = (i_t * 16) % BT
|
| 62 |
+
if not USE_TMA:
|
| 63 |
+
p_A = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * 16, offset), (16, 16), (1, 0))
|
| 64 |
+
# [16, 16]
|
| 65 |
+
b_A = tl.load(p_A, boundary_check=(0, 1)).to(tl.float32)
|
| 66 |
+
else:
|
| 67 |
+
desc = make_tensor_descriptor(A, [T, BT], [H*BT, 1], [16, 16])
|
| 68 |
+
desc_o = make_tensor_descriptor(Ai, [T, 16], [H*16, 1], [16, 16])
|
| 69 |
+
b_A = desc.load([i_t * 16, offset]).to(tl.float32)
|
| 70 |
+
b_A = -tl.where(m_A, b_A, 0)
|
| 71 |
+
|
| 72 |
+
for i in range(2, min(16, T - i_t * 16)):
|
| 73 |
+
# [16]
|
| 74 |
+
b_a = -tl.load(A + (i_t * 16 + i) * H*BT + o_i + offset)
|
| 75 |
+
b_a = b_a + tl.sum(b_a[:, None] * b_A, 0)
|
| 76 |
+
b_A = tl.where((o_i == i)[:, None], b_a, b_A)
|
| 77 |
+
b_A += m_I
|
| 78 |
+
if not USE_TMA:
|
| 79 |
+
p_Ai = tl.make_block_ptr(Ai, (T, 16), (H*16, 1), (i_t * 16, 0), (16, 16), (1, 0))
|
| 80 |
+
tl.store(p_Ai, b_A.to(p_Ai.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 81 |
+
else:
|
| 82 |
+
desc_o.store([i_t * 16, 0], b_A.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@triton.heuristics({
|
| 86 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
| 87 |
+
})
|
| 88 |
+
@triton.autotune(
|
| 89 |
+
configs=[
|
| 90 |
+
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
| 91 |
+
for num_warps in [1, 2, 4, 8]
|
| 92 |
+
for num_stages in [2, 3, 4, 5]
|
| 93 |
+
],
|
| 94 |
+
key=['H', 'BT', 'IS_VARLEN'],
|
| 95 |
+
**autotune_cache_kwargs
|
| 96 |
+
)
|
| 97 |
+
@triton.jit(do_not_specialize=['T'])
|
| 98 |
+
def merge_16x16_to_32x32_inverse_kernel(
|
| 99 |
+
A,
|
| 100 |
+
Ai,
|
| 101 |
+
cu_seqlens,
|
| 102 |
+
chunk_indices,
|
| 103 |
+
T,
|
| 104 |
+
H: tl.constexpr,
|
| 105 |
+
BT: tl.constexpr,
|
| 106 |
+
USE_TMA: tl.constexpr,
|
| 107 |
+
IS_VARLEN: tl.constexpr,
|
| 108 |
+
DOT_PRECISION: tl.constexpr
|
| 109 |
+
):
|
| 110 |
+
i_t, i_bh = tl.program_id(0), tl.program_id(1)
|
| 111 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 112 |
+
if IS_VARLEN:
|
| 113 |
+
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
| 114 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 115 |
+
T = eos - bos
|
| 116 |
+
else:
|
| 117 |
+
bos, eos = i_b * T, i_b * T + T
|
| 118 |
+
|
| 119 |
+
o_i = tl.arange(0, 16)
|
| 120 |
+
m_A = o_i[:, None] > o_i[None, :]
|
| 121 |
+
m_I = o_i[:, None] == o_i[None, :]
|
| 122 |
+
A += (bos * H + i_h) * BT
|
| 123 |
+
Ai += (bos * H + i_h) * BT
|
| 124 |
+
|
| 125 |
+
if not USE_TMA:
|
| 126 |
+
p_A_11 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT, 0), (16, 16), (1, 0))
|
| 127 |
+
p_A_22 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 16, 16), (16, 16), (1, 0))
|
| 128 |
+
b_Ai_11 = tl.load(p_A_11, boundary_check=(0, 1)).to(tl.float32)
|
| 129 |
+
b_Ai_22 = tl.load(p_A_22, boundary_check=(0, 1)).to(tl.float32)
|
| 130 |
+
else:
|
| 131 |
+
desc = make_tensor_descriptor(A, [T, BT], [H*BT, 1], [16, 16])
|
| 132 |
+
desc_o = make_tensor_descriptor(Ai, [T, BT], [H*BT, 1], [16, 16])
|
| 133 |
+
b_Ai_11 = desc.load([i_t * BT + 0, 0]).to(tl.float32)
|
| 134 |
+
b_Ai_22 = desc.load([i_t * BT + 16, 16]).to(tl.float32)
|
| 135 |
+
|
| 136 |
+
# [16, 16]
|
| 137 |
+
b_Ai_11 = -tl.where(m_A, b_Ai_11, 0)
|
| 138 |
+
b_Ai_22 = -tl.where(m_A, b_Ai_22, 0)
|
| 139 |
+
|
| 140 |
+
for i in range(2, min(16, T - i_t * BT)):
|
| 141 |
+
b_a_11 = -tl.load(A + (i_t * BT + i) * H*BT + o_i)
|
| 142 |
+
b_a_11 += tl.sum(b_a_11[:, None] * b_Ai_11, 0)
|
| 143 |
+
b_Ai_11 = tl.where((o_i == i)[:, None], b_a_11, b_Ai_11)
|
| 144 |
+
for i in range(16 + 2, min(32, T - i_t * BT)):
|
| 145 |
+
b_a_22 = -tl.load(A + (i_t * BT + i) * H*BT + o_i + 16)
|
| 146 |
+
b_a_22 += tl.sum(b_a_22[:, None] * b_Ai_22, 0)
|
| 147 |
+
b_Ai_22 = tl.where((o_i == i - 16)[:, None], b_a_22, b_Ai_22)
|
| 148 |
+
|
| 149 |
+
b_Ai_11 += m_I
|
| 150 |
+
b_Ai_22 += m_I
|
| 151 |
+
|
| 152 |
+
if not USE_TMA:
|
| 153 |
+
p_A_21 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 16, 0), (16, 16), (1, 0))
|
| 154 |
+
b_A_21 = tl.load(p_A_21, boundary_check=(0, 1)).to(tl.float32)
|
| 155 |
+
else:
|
| 156 |
+
b_A_21 = desc.load([i_t * BT + 16, 0]).to(tl.float32)
|
| 157 |
+
|
| 158 |
+
b_Ai_21 = -tl.dot(tl.dot(b_Ai_22, b_A_21, input_precision=DOT_PRECISION), b_Ai_11, input_precision=DOT_PRECISION)
|
| 159 |
+
|
| 160 |
+
if not USE_TMA:
|
| 161 |
+
p_Ai_11 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT, 0), (16, 16), (1, 0))
|
| 162 |
+
p_Ai_21 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 16, 0), (16, 16), (1, 0))
|
| 163 |
+
p_Ai_22 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 16, 16), (16, 16), (1, 0))
|
| 164 |
+
tl.store(p_Ai_11, b_Ai_11.to(p_Ai_11.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 165 |
+
tl.store(p_Ai_22, b_Ai_22.to(p_Ai_22.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 166 |
+
tl.store(p_Ai_21, b_Ai_21.to(p_Ai_21.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 167 |
+
else:
|
| 168 |
+
desc_o.store([i_t * BT + 0, 0], b_Ai_11.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 169 |
+
desc_o.store([i_t * BT + 16, 0], b_Ai_21.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 170 |
+
desc_o.store([i_t * BT + 16, 16], b_Ai_22.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@triton.heuristics({
|
| 174 |
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
| 175 |
+
})
|
| 176 |
+
@triton.autotune(
|
| 177 |
+
configs=[
|
| 178 |
+
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
| 179 |
+
for num_warps in [2, 4, 8]
|
| 180 |
+
for num_stages in [2, 3, 4, 5]
|
| 181 |
+
],
|
| 182 |
+
key=['H', 'BT', 'IS_VARLEN'],
|
| 183 |
+
**autotune_cache_kwargs
|
| 184 |
+
)
|
| 185 |
+
@triton.jit(do_not_specialize=['T'])
|
| 186 |
+
def merge_16x16_to_64x64_inverse_kernel(
|
| 187 |
+
A,
|
| 188 |
+
Ai,
|
| 189 |
+
cu_seqlens,
|
| 190 |
+
chunk_indices,
|
| 191 |
+
T,
|
| 192 |
+
H: tl.constexpr,
|
| 193 |
+
BT: tl.constexpr,
|
| 194 |
+
USE_TMA: tl.constexpr,
|
| 195 |
+
IS_VARLEN: tl.constexpr,
|
| 196 |
+
DOT_PRECISION: tl.constexpr
|
| 197 |
+
):
|
| 198 |
+
i_t, i_bh = tl.program_id(0), tl.program_id(1)
|
| 199 |
+
i_b, i_h = i_bh // H, i_bh % H
|
| 200 |
+
if IS_VARLEN:
|
| 201 |
+
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
| 202 |
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
| 203 |
+
T = eos - bos
|
| 204 |
+
else:
|
| 205 |
+
bos, eos = i_b * T, i_b * T + T
|
| 206 |
+
|
| 207 |
+
o_i = tl.arange(0, 16)
|
| 208 |
+
m_A = o_i[:, None] > o_i[None, :]
|
| 209 |
+
m_I = o_i[:, None] == o_i[None, :]
|
| 210 |
+
A += (bos * H + i_h) * BT
|
| 211 |
+
Ai += (bos * H + i_h) * BT
|
| 212 |
+
|
| 213 |
+
if not USE_TMA:
|
| 214 |
+
p_A_11 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT, 0), (16, 16), (1, 0))
|
| 215 |
+
p_A_22 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 16, 16), (16, 16), (1, 0))
|
| 216 |
+
p_A_33 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 32, 32), (16, 16), (1, 0))
|
| 217 |
+
p_A_44 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 48, 48), (16, 16), (1, 0))
|
| 218 |
+
b_Ai_11 = tl.load(p_A_11, boundary_check=(0, 1)).to(tl.float32)
|
| 219 |
+
b_Ai_22 = tl.load(p_A_22, boundary_check=(0, 1)).to(tl.float32)
|
| 220 |
+
b_Ai_33 = tl.load(p_A_33, boundary_check=(0, 1)).to(tl.float32)
|
| 221 |
+
b_Ai_44 = tl.load(p_A_44, boundary_check=(0, 1)).to(tl.float32)
|
| 222 |
+
else:
|
| 223 |
+
desc = make_tensor_descriptor(A, [T, BT], [H*BT, 1], [16, 16])
|
| 224 |
+
desc_o = make_tensor_descriptor(Ai, [T, BT], [H*BT, 1], [16, 16])
|
| 225 |
+
b_Ai_11 = desc.load([i_t * BT + 0, 0]).to(tl.float32)
|
| 226 |
+
b_Ai_22 = desc.load([i_t * BT + 16, 16]).to(tl.float32)
|
| 227 |
+
b_Ai_33 = desc.load([i_t * BT + 32, 32]).to(tl.float32)
|
| 228 |
+
b_Ai_44 = desc.load([i_t * BT + 48, 48]).to(tl.float32)
|
| 229 |
+
|
| 230 |
+
# [16, 16]
|
| 231 |
+
b_Ai_11 = -tl.where(m_A, b_Ai_11, 0)
|
| 232 |
+
b_Ai_22 = -tl.where(m_A, b_Ai_22, 0)
|
| 233 |
+
b_Ai_33 = -tl.where(m_A, b_Ai_33, 0)
|
| 234 |
+
b_Ai_44 = -tl.where(m_A, b_Ai_44, 0)
|
| 235 |
+
|
| 236 |
+
for i in range(2, min(16, T - i_t * BT)):
|
| 237 |
+
b_a_11 = -tl.load(A + (i_t * BT + i) * H*BT + o_i)
|
| 238 |
+
b_a_11 += tl.sum(b_a_11[:, None] * b_Ai_11, 0)
|
| 239 |
+
b_Ai_11 = tl.where((o_i == i)[:, None], b_a_11, b_Ai_11)
|
| 240 |
+
for i in range(16 + 2, min(32, T - i_t * BT)):
|
| 241 |
+
b_a_22 = -tl.load(A + (i_t * BT + i) * H*BT + o_i + 16)
|
| 242 |
+
b_a_22 += tl.sum(b_a_22[:, None] * b_Ai_22, 0)
|
| 243 |
+
b_Ai_22 = tl.where((o_i == i - 16)[:, None], b_a_22, b_Ai_22)
|
| 244 |
+
for i in range(32 + 2, min(48, T - i_t * BT)):
|
| 245 |
+
b_a_33 = -tl.load(A + (i_t * BT + i) * H*BT + o_i + 32)
|
| 246 |
+
b_a_33 += tl.sum(b_a_33[:, None] * b_Ai_33, 0)
|
| 247 |
+
b_Ai_33 = tl.where((o_i == i - 32)[:, None], b_a_33, b_Ai_33)
|
| 248 |
+
for i in range(48 + 2, min(64, T - i_t * BT)):
|
| 249 |
+
b_a_44 = -tl.load(A + (i_t * BT + i) * H*BT + o_i + 48)
|
| 250 |
+
b_a_44 += tl.sum(b_a_44[:, None] * b_Ai_44, 0)
|
| 251 |
+
b_Ai_44 = tl.where((o_i == i - 48)[:, None], b_a_44, b_Ai_44)
|
| 252 |
+
b_Ai_11 += m_I
|
| 253 |
+
b_Ai_22 += m_I
|
| 254 |
+
b_Ai_33 += m_I
|
| 255 |
+
b_Ai_44 += m_I
|
| 256 |
+
|
| 257 |
+
if not USE_TMA:
|
| 258 |
+
p_A_21 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 16, 0), (16, 16), (1, 0))
|
| 259 |
+
p_A_31 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 32, 0), (16, 16), (1, 0))
|
| 260 |
+
p_A_32 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 32, 16), (16, 16), (1, 0))
|
| 261 |
+
p_A_41 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 48, 0), (16, 16), (1, 0))
|
| 262 |
+
p_A_42 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 48, 16), (16, 16), (1, 0))
|
| 263 |
+
p_A_43 = tl.make_block_ptr(A, (T, BT), (H*BT, 1), (i_t * BT + 48, 32), (16, 16), (1, 0))
|
| 264 |
+
b_A_21 = tl.load(p_A_21, boundary_check=(0, 1)).to(tl.float32)
|
| 265 |
+
b_A_31 = tl.load(p_A_31, boundary_check=(0, 1)).to(tl.float32)
|
| 266 |
+
b_A_32 = tl.load(p_A_32, boundary_check=(0, 1)).to(tl.float32)
|
| 267 |
+
b_A_41 = tl.load(p_A_41, boundary_check=(0, 1)).to(tl.float32)
|
| 268 |
+
b_A_42 = tl.load(p_A_42, boundary_check=(0, 1)).to(tl.float32)
|
| 269 |
+
b_A_43 = tl.load(p_A_43, boundary_check=(0, 1)).to(tl.float32)
|
| 270 |
+
else:
|
| 271 |
+
b_A_21 = desc.load([i_t * BT + 16, 0]).to(tl.float32)
|
| 272 |
+
b_A_31 = desc.load([i_t * BT + 32, 0]).to(tl.float32)
|
| 273 |
+
b_A_32 = desc.load([i_t * BT + 32, 16]).to(tl.float32)
|
| 274 |
+
b_A_41 = desc.load([i_t * BT + 48, 0]).to(tl.float32)
|
| 275 |
+
b_A_42 = desc.load([i_t * BT + 48, 16]).to(tl.float32)
|
| 276 |
+
b_A_43 = desc.load([i_t * BT + 48, 32]).to(tl.float32)
|
| 277 |
+
|
| 278 |
+
b_Ai_21 = -tl.dot(tl.dot(b_Ai_22, b_A_21, input_precision=DOT_PRECISION), b_Ai_11, input_precision=DOT_PRECISION)
|
| 279 |
+
b_Ai_32 = -tl.dot(tl.dot(b_Ai_33, b_A_32, input_precision=DOT_PRECISION), b_Ai_22, input_precision=DOT_PRECISION)
|
| 280 |
+
b_Ai_43 = -tl.dot(tl.dot(b_Ai_44, b_A_43, input_precision=DOT_PRECISION), b_Ai_33, input_precision=DOT_PRECISION)
|
| 281 |
+
|
| 282 |
+
b_Ai_31 = -tl.dot(
|
| 283 |
+
b_Ai_33,
|
| 284 |
+
tl.dot(b_A_31, b_Ai_11, input_precision=DOT_PRECISION) +
|
| 285 |
+
tl.dot(b_A_32, b_Ai_21, input_precision=DOT_PRECISION),
|
| 286 |
+
input_precision=DOT_PRECISION
|
| 287 |
+
)
|
| 288 |
+
b_Ai_42 = -tl.dot(
|
| 289 |
+
b_Ai_44,
|
| 290 |
+
tl.dot(b_A_42, b_Ai_22, input_precision=DOT_PRECISION) +
|
| 291 |
+
tl.dot(b_A_43, b_Ai_32, input_precision=DOT_PRECISION),
|
| 292 |
+
input_precision=DOT_PRECISION
|
| 293 |
+
)
|
| 294 |
+
b_Ai_41 = -tl.dot(
|
| 295 |
+
b_Ai_44,
|
| 296 |
+
tl.dot(b_A_41, b_Ai_11, input_precision=DOT_PRECISION) +
|
| 297 |
+
tl.dot(b_A_42, b_Ai_21, input_precision=DOT_PRECISION) +
|
| 298 |
+
tl.dot(b_A_43, b_Ai_31, input_precision=DOT_PRECISION),
|
| 299 |
+
input_precision=DOT_PRECISION
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
if not USE_TMA:
|
| 303 |
+
p_Ai_11 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT, 0), (16, 16), (1, 0))
|
| 304 |
+
p_Ai_22 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 16, 16), (16, 16), (1, 0))
|
| 305 |
+
p_Ai_33 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 32, 32), (16, 16), (1, 0))
|
| 306 |
+
p_Ai_44 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 48, 48), (16, 16), (1, 0))
|
| 307 |
+
p_Ai_21 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 16, 0), (16, 16), (1, 0))
|
| 308 |
+
p_Ai_31 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 32, 0), (16, 16), (1, 0))
|
| 309 |
+
p_Ai_32 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 32, 16), (16, 16), (1, 0))
|
| 310 |
+
p_Ai_41 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 48, 0), (16, 16), (1, 0))
|
| 311 |
+
p_Ai_42 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 48, 16), (16, 16), (1, 0))
|
| 312 |
+
p_Ai_43 = tl.make_block_ptr(Ai, (T, BT), (H*BT, 1), (i_t * BT + 48, 32), (16, 16), (1, 0))
|
| 313 |
+
tl.store(p_Ai_11, b_Ai_11.to(p_Ai_11.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 314 |
+
tl.store(p_Ai_22, b_Ai_22.to(p_Ai_22.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 315 |
+
tl.store(p_Ai_33, b_Ai_33.to(p_Ai_33.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 316 |
+
tl.store(p_Ai_44, b_Ai_44.to(p_Ai_44.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 317 |
+
tl.store(p_Ai_21, b_Ai_21.to(p_Ai_21.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 318 |
+
tl.store(p_Ai_31, b_Ai_31.to(p_Ai_31.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 319 |
+
tl.store(p_Ai_32, b_Ai_32.to(p_Ai_32.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 320 |
+
tl.store(p_Ai_41, b_Ai_41.to(p_Ai_41.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 321 |
+
tl.store(p_Ai_42, b_Ai_42.to(p_Ai_42.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 322 |
+
tl.store(p_Ai_43, b_Ai_43.to(p_Ai_43.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
|
| 323 |
+
else:
|
| 324 |
+
desc_o.store([i_t * BT + 0, 0], b_Ai_11.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 325 |
+
desc_o.store([i_t * BT + 16, 16], b_Ai_22.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 326 |
+
desc_o.store([i_t * BT + 32, 32], b_Ai_33.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 327 |
+
desc_o.store([i_t * BT + 48, 48], b_Ai_44.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 328 |
+
desc_o.store([i_t * BT + 16, 0], b_Ai_21.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 329 |
+
desc_o.store([i_t * BT + 32, 0], b_Ai_31.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 330 |
+
desc_o.store([i_t * BT + 32, 16], b_Ai_32.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 331 |
+
desc_o.store([i_t * BT + 48, 0], b_Ai_41.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 332 |
+
desc_o.store([i_t * BT + 48, 16], b_Ai_42.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 333 |
+
desc_o.store([i_t * BT + 48, 32], b_Ai_43.to(desc_o.dtype, fp_downcast_rounding="rtne"))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@input_guard
|
| 337 |
+
def solve_tril(
|
| 338 |
+
A: torch.Tensor,
|
| 339 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 340 |
+
output_dtype: torch.dtype = torch.float
|
| 341 |
+
) -> torch.Tensor:
|
| 342 |
+
"""
|
| 343 |
+
Compute the inverse of the matrix I + A
|
| 344 |
+
A should be strictly lower triangular, i.e., A.triu() == 0.
|
| 345 |
+
|
| 346 |
+
Args:
|
| 347 |
+
A (torch.Tensor):
|
| 348 |
+
[B, T, H, BT], where BT should only be 16, 32, or 64.
|
| 349 |
+
cu_seqlens (torch.Tensor):
|
| 350 |
+
The cumulative sequence lengths of the input tensor. Default: `None`.
|
| 351 |
+
output_dtype (torch.dtype):
|
| 352 |
+
The dtype of the output tensor. Default: `torch.float`.
|
| 353 |
+
If `None`, the output dtype will be the same as the input dtype.
|
| 354 |
+
|
| 355 |
+
Returns:
|
| 356 |
+
(I + A)^-1 with the same shape as A
|
| 357 |
+
"""
|
| 358 |
+
assert A.shape[-1] in [16, 32, 64]
|
| 359 |
+
output_dtype = A.dtype if output_dtype is None else output_dtype
|
| 360 |
+
|
| 361 |
+
B, T, H, BT = A.shape
|
| 362 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
|
| 363 |
+
NT = len(chunk_indices) if cu_seqlens is not None else triton.cdiv(T, BT)
|
| 364 |
+
|
| 365 |
+
Ai = torch.zeros_like(A, dtype=output_dtype)
|
| 366 |
+
if BT == 16:
|
| 367 |
+
merge_fn = solve_tril_16x16_kernel
|
| 368 |
+
elif BT == 32:
|
| 369 |
+
merge_fn = merge_16x16_to_32x32_inverse_kernel
|
| 370 |
+
elif BT == 64:
|
| 371 |
+
merge_fn = merge_16x16_to_64x64_inverse_kernel
|
| 372 |
+
|
| 373 |
+
merge_fn[NT, B * H](
|
| 374 |
+
A=A,
|
| 375 |
+
Ai=Ai,
|
| 376 |
+
cu_seqlens=cu_seqlens,
|
| 377 |
+
chunk_indices=chunk_indices,
|
| 378 |
+
T=T,
|
| 379 |
+
H=H,
|
| 380 |
+
BT=BT,
|
| 381 |
+
USE_TMA=is_tma_supported,
|
| 382 |
+
DOT_PRECISION=FLA_TRIL_PRECISION,
|
| 383 |
+
)
|
| 384 |
+
return Ai
|