[Model] add GLM-5.3-Flash support (#53906)
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rms_norm(x, w, eps, HIDDEN_SIZE: tl.constexpr):
|
||||
x = x.to(tl.float32)
|
||||
mean_sq = tl.sum(x * x, axis=0) / HIDDEN_SIZE
|
||||
rrms = tl.rsqrt(mean_sq + eps)
|
||||
w = w.to(tl.float32)
|
||||
return (x * rrms) * w
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fused_eh_norm_kernel(
|
||||
pos_ptr,
|
||||
embeds_ptr,
|
||||
embeds_stride,
|
||||
prev_ptr,
|
||||
prev_stride,
|
||||
enorm_w_ptr,
|
||||
hnorm_w_ptr,
|
||||
eps,
|
||||
out_ptr,
|
||||
out_stride,
|
||||
H: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
"""MTP input fusion: zero embeds at position 0, RMSNorm(embeds) with enorm
|
||||
and RMSNorm(prev_hidden) with hnorm, written side-by-side into ``out``
|
||||
([N, 2H]) ready for the eh_proj GEMM. Replaces where + 2x RMSNorm + cat."""
|
||||
tok = tl.program_id(0)
|
||||
off = tl.arange(0, BLOCK)
|
||||
mask = off < H
|
||||
|
||||
pos = tl.load(pos_ptr + tok)
|
||||
e = tl.load(embeds_ptr + tok * embeds_stride + off, mask=mask, other=0.0)
|
||||
e = tl.where(pos == 0, 0.0, e.to(tl.float32))
|
||||
ew = tl.load(enorm_w_ptr + off, mask=mask)
|
||||
e_normed = _rms_norm(e, ew, eps, H)
|
||||
tl.store(out_ptr + tok * out_stride + off, e_normed, mask=mask)
|
||||
|
||||
p = tl.load(prev_ptr + tok * prev_stride + off, mask=mask, other=0.0)
|
||||
hw = tl.load(hnorm_w_ptr + off, mask=mask)
|
||||
p_normed = _rms_norm(p, hw, eps, H)
|
||||
tl.store(out_ptr + tok * out_stride + H + off, p_normed, mask=mask)
|
||||
|
||||
|
||||
def fused_eh_norm(
|
||||
positions: torch.Tensor,
|
||||
inputs_embeds: torch.Tensor,
|
||||
previous_hidden: torch.Tensor,
|
||||
enorm_w: torch.Tensor,
|
||||
hnorm_w: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
"""Returns cat([enorm(masked embeds), hnorm(prev_hidden)]) -> [N, 2H]."""
|
||||
n, h = inputs_embeds.shape
|
||||
out = torch.empty(n, 2 * h, dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
||||
_fused_eh_norm_kernel[(n,)](
|
||||
positions,
|
||||
inputs_embeds,
|
||||
inputs_embeds.stride(0),
|
||||
previous_hidden,
|
||||
previous_hidden.stride(0),
|
||||
enorm_w,
|
||||
hnorm_w,
|
||||
eps,
|
||||
out,
|
||||
out.stride(0),
|
||||
h,
|
||||
triton.next_power_of_2(h),
|
||||
)
|
||||
return out
|
||||
@@ -0,0 +1,891 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""kpool (key-pooling) Triton kernels for the sparse-attention indexer.
|
||||
|
||||
The cache stores POOLS (1 entry per ``pool_size`` consecutive tokens) rather
|
||||
than individual tokens. ``compress_ratio == pool_size`` on the kv_cache_spec
|
||||
makes the metadata builder emit pool-granular slot_mapping / seq_lens /
|
||||
cu_seq_lens / page_table for free; this file supplies the compress-write
|
||||
kernel (replacing ``indexer_k_quant_and_cache``) and the pool-level topk
|
||||
helpers (select pools -> expand to tokens -> append tail).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
# The GLM-5.3-Flash indexer head dimension is fixed at 128.
|
||||
INDEX_HEAD_DIM = 128
|
||||
|
||||
|
||||
# Hadamard-128 rotation
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hadamard128_stage(x, GROUPS: tl.constexpr, STRIDE: tl.constexpr):
|
||||
x3 = tl.reshape(x, (GROUPS, 2, STRIDE))
|
||||
x3 = tl.trans(x3, 0, 2, 1)
|
||||
a, b = tl.split(x3)
|
||||
x3 = tl.join(a + b, a - b)
|
||||
x3 = tl.trans(x3, 0, 2, 1)
|
||||
return tl.reshape(x3, (128,))
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hadamard128(x):
|
||||
x = _hadamard128_stage(x, 64, 1)
|
||||
x = _hadamard128_stage(x, 32, 2)
|
||||
x = _hadamard128_stage(x, 16, 4)
|
||||
x = _hadamard128_stage(x, 8, 8)
|
||||
x = _hadamard128_stage(x, 4, 16)
|
||||
x = _hadamard128_stage(x, 2, 32)
|
||||
x = _hadamard128_stage(x, 1, 64)
|
||||
return x * 0.08838834764831845 # 1/sqrt(128)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fwht_stage(x, N: tl.constexpr, GROUPS: tl.constexpr, STRIDE: tl.constexpr):
|
||||
# One FWHT butterfly stage on a flat tensor of N = GROUPS*2*STRIDE elems;
|
||||
# same construction as _hadamard128_stage but with a parametric N so it can
|
||||
# process BLOCK_R rows at once.
|
||||
x3 = tl.reshape(x, (GROUPS, 2, STRIDE))
|
||||
x3 = tl.trans(x3, 0, 2, 1)
|
||||
a, b = tl.split(x3)
|
||||
x3 = tl.join(a + b, a - b)
|
||||
x3 = tl.trans(x3, 0, 2, 1)
|
||||
return tl.reshape(x3, (N,))
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fwht_quant_kernel(
|
||||
q_ptr,
|
||||
qout_ptr,
|
||||
sout_ptr,
|
||||
n_rows,
|
||||
BLOCK_R: tl.constexpr,
|
||||
):
|
||||
"""Fused Hadamard-128 rotation + per-row absmax FP8 (ue8m0) quant.
|
||||
|
||||
Each row uses fp32 butterflies and scaling, rounds to bf16, then applies
|
||||
absmax quantization with a power-of-two scale.
|
||||
"""
|
||||
pid = tl.program_id(0)
|
||||
rows = pid * BLOCK_R + tl.arange(0, BLOCK_R)
|
||||
rmask = rows < n_rows
|
||||
offs = tl.arange(0, 128)
|
||||
x = tl.load(
|
||||
q_ptr + rows[:, None] * 128 + offs[None, :], mask=rmask[:, None], other=0.0
|
||||
).to(tl.float32)
|
||||
|
||||
# Flatten so each row's 128 lanes stay contiguous: every stage's
|
||||
# (GROUPS, 2, STRIDE) tiling has 2*STRIDE dividing 128, so pairs never
|
||||
# straddle a row boundary. GROUPS of each stage scales by BLOCK_R.
|
||||
N: tl.constexpr = BLOCK_R * 128
|
||||
x = tl.reshape(x, (N,))
|
||||
x = _fwht_stage(x, N, BLOCK_R * 64, 1)
|
||||
x = _fwht_stage(x, N, BLOCK_R * 32, 2)
|
||||
x = _fwht_stage(x, N, BLOCK_R * 16, 4)
|
||||
x = _fwht_stage(x, N, BLOCK_R * 8, 8)
|
||||
x = _fwht_stage(x, N, BLOCK_R * 4, 16)
|
||||
x = _fwht_stage(x, N, BLOCK_R * 2, 32)
|
||||
x = _fwht_stage(x, N, BLOCK_R, 64)
|
||||
x = x * 0.08838834764831845 # 1/sqrt(128), exact in fp32
|
||||
|
||||
# Match the unfused path's bf16 materialization before quantizing.
|
||||
x = x.to(tl.bfloat16).to(tl.float32)
|
||||
x = tl.reshape(x, (BLOCK_R, 128))
|
||||
|
||||
absmax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-4)
|
||||
scale = tl.exp2(tl.ceil(tl.log2(absmax * (1.0 / 448.0))))
|
||||
y = tl.minimum(tl.maximum(x / scale[:, None], -448.0), 448.0)
|
||||
|
||||
tl.store(qout_ptr + rows[:, None] * 128 + offs[None, :], y, mask=rmask[:, None])
|
||||
tl.store(sout_ptr + rows, scale, mask=rmask)
|
||||
|
||||
|
||||
def fwht128_quant_fp8(q: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Rotate each 128-wide row by the Hadamard-128 transform, then FP8-quant.
|
||||
|
||||
The fused kernel avoids materializing the rotated tensor and uses an exact
|
||||
fp32 ``1 / sqrt(128)`` scale before block-128 ue8m0 quantization.
|
||||
|
||||
Args:
|
||||
q: ``[rows, 128]`` bf16 — one head vector per row.
|
||||
|
||||
Returns:
|
||||
(q_fp8 ``[rows, 128]`` float8_e4m3fn, scale ``[rows, 1]`` float32).
|
||||
"""
|
||||
assert q.ndim == 2 and q.shape[1] == 128, q.shape
|
||||
assert q.dtype == torch.bfloat16
|
||||
assert q.is_contiguous()
|
||||
n_rows = q.shape[0]
|
||||
q_fp8 = torch.empty((n_rows, 128), dtype=torch.float8_e4m3fn, device=q.device)
|
||||
q_scale = torch.empty((n_rows, 1), dtype=torch.float32, device=q.device)
|
||||
if n_rows == 0:
|
||||
return q_fp8, q_scale
|
||||
BLOCK_R = 32
|
||||
grid = (triton.cdiv(n_rows, BLOCK_R),)
|
||||
_fwht_quant_kernel[grid](q, q_fp8, q_scale, n_rows, BLOCK_R=BLOCK_R, num_warps=2)
|
||||
return q_fp8, q_scale
|
||||
|
||||
|
||||
# Fused pool compression and cache write.
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _kpool_softmax_rotate_write_cache_kernel(
|
||||
buf_fp8_ptr,
|
||||
buf_fp32_ptr,
|
||||
slot_k_ptr,
|
||||
slot_score_ptr,
|
||||
ape_ptr,
|
||||
loc_ptr,
|
||||
write_mask_ptr,
|
||||
compressed_k_ptr,
|
||||
compressed_scale_ptr,
|
||||
slot_k_stride_0,
|
||||
slot_k_stride_1,
|
||||
slot_score_stride_0,
|
||||
slot_score_stride_1,
|
||||
ape_stride_0,
|
||||
PAGE_SIZE: tl.constexpr,
|
||||
BUF_NUMEL_PER_PAGE: tl.constexpr,
|
||||
POOL_SIZE: tl.constexpr,
|
||||
HEAD_DIM: tl.constexpr,
|
||||
S_OFFSET_NBYTES_IN_PAGE: tl.constexpr,
|
||||
ROUND_SCALE: tl.constexpr,
|
||||
HAS_WRITE_MASK: tl.constexpr,
|
||||
RETURN_COMPRESSED: tl.constexpr,
|
||||
WRITE_CACHE: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
"""One program per pool. softmax(slot_score+ape)-weighted sum of slot_k ->
|
||||
Hadamard-128 -> per-vector fp8 absmax quant -> write to cache at ``loc``."""
|
||||
row = tl.program_id(0)
|
||||
do_write = True
|
||||
if HAS_WRITE_MASK:
|
||||
do_write = tl.load(write_mask_ptr + row)
|
||||
|
||||
offs = tl.arange(0, BLOCK_D)
|
||||
mask = (offs < HEAD_DIM) & do_write
|
||||
|
||||
# --- Pass 1: per-dim max over the pool (softmax numerical stability) ---
|
||||
max_score = tl.full((BLOCK_D,), -float("inf"), tl.float32)
|
||||
for slot in tl.static_range(0, POOL_SIZE):
|
||||
score = tl.load(
|
||||
slot_score_ptr
|
||||
+ row * slot_score_stride_0
|
||||
+ slot * slot_score_stride_1
|
||||
+ offs,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
score += tl.load(ape_ptr + slot * ape_stride_0 + offs, mask=mask, other=0.0).to(
|
||||
tl.float32
|
||||
)
|
||||
max_score = tl.maximum(max_score, score)
|
||||
|
||||
# --- Pass 2: softmax-weighted sum of K ---
|
||||
acc = tl.full((BLOCK_D,), 0.0, tl.float32)
|
||||
denom = tl.full((BLOCK_D,), 0.0, tl.float32)
|
||||
for slot in tl.static_range(0, POOL_SIZE):
|
||||
score = tl.load(
|
||||
slot_score_ptr
|
||||
+ row * slot_score_stride_0
|
||||
+ slot * slot_score_stride_1
|
||||
+ offs,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
score += tl.load(ape_ptr + slot * ape_stride_0 + offs, mask=mask, other=0.0).to(
|
||||
tl.float32
|
||||
)
|
||||
prob = tl.exp(score - max_score)
|
||||
denom += prob
|
||||
k = tl.load(
|
||||
slot_k_ptr + row * slot_k_stride_0 + slot * slot_k_stride_1 + offs,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
acc += k * prob
|
||||
|
||||
x = acc / denom
|
||||
x = tl.where(do_write, x, 0.0).to(tl.bfloat16).to(tl.float32)
|
||||
|
||||
# Match the unfused pooled-K path's bf16 precision before quantization.
|
||||
x = _hadamard128(x).to(tl.bfloat16).to(tl.float32)
|
||||
|
||||
# --- per-vector absmax fp8 quant ---
|
||||
fp8_max = 448.0
|
||||
fp8_max_inv = 1.0 / fp8_max
|
||||
absmax = tl.max(tl.abs(x), axis=0)
|
||||
absmax = tl.maximum(absmax, 1e-4)
|
||||
if ROUND_SCALE:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(absmax * fp8_max_inv)))
|
||||
else:
|
||||
scale = absmax * fp8_max_inv
|
||||
quantized = x / scale
|
||||
quantized = tl.minimum(tl.maximum(quantized, -fp8_max), fp8_max)
|
||||
|
||||
if WRITE_CACHE:
|
||||
loc = tl.load(loc_ptr + row, mask=do_write, other=0)
|
||||
loc_page_index = loc // PAGE_SIZE
|
||||
loc_token_offset_in_page = loc % PAGE_SIZE
|
||||
out_k_offsets = (
|
||||
loc_page_index * BUF_NUMEL_PER_PAGE
|
||||
+ loc_token_offset_in_page * HEAD_DIM
|
||||
+ offs
|
||||
)
|
||||
out_s_offset = (
|
||||
loc_page_index * BUF_NUMEL_PER_PAGE // 4
|
||||
+ S_OFFSET_NBYTES_IN_PAGE // 4
|
||||
+ loc_token_offset_in_page
|
||||
)
|
||||
tl.store(buf_fp8_ptr + out_k_offsets, quantized, mask=mask)
|
||||
tl.store(buf_fp32_ptr + out_s_offset, scale, mask=do_write)
|
||||
|
||||
if RETURN_COMPRESSED:
|
||||
tl.store(
|
||||
compressed_k_ptr + row * HEAD_DIM + offs,
|
||||
quantized,
|
||||
mask=offs < HEAD_DIM,
|
||||
)
|
||||
tl.store(compressed_scale_ptr + row, scale)
|
||||
|
||||
|
||||
def kpool_compress_and_write_cache(
|
||||
kv_cache: torch.Tensor,
|
||||
slot_k: torch.Tensor,
|
||||
slot_score: torch.Tensor,
|
||||
ape: torch.Tensor,
|
||||
loc: torch.Tensor,
|
||||
pool_size: int,
|
||||
head_dim: int = INDEX_HEAD_DIM,
|
||||
write_mask: torch.Tensor | None = None,
|
||||
round_scale: bool = True,
|
||||
return_compressed: bool = False,
|
||||
write_cache: bool = True,
|
||||
):
|
||||
"""Compress ``pool_size`` tokens into one fp8 K and write at ``loc``.
|
||||
|
||||
Args:
|
||||
kv_cache: indexer K cache ``[num_blocks, block_size, head_dim+4]`` uint8.
|
||||
slot_k: ``[n_pools, pool_size, head_dim]`` bf16 — raw per-token K.
|
||||
slot_score: ``[n_pools, pool_size, head_dim]`` — per-token gate score.
|
||||
ape: ``[pool_size, head_dim]`` fp32 — per-slot position bias.
|
||||
loc: ``[n_pools]`` int64 — flat physical slot per pool.
|
||||
"""
|
||||
assert slot_k.ndim == 3
|
||||
assert slot_score.shape == slot_k.shape
|
||||
assert ape.shape == slot_k.shape[1:]
|
||||
assert slot_k.shape[2] == head_dim
|
||||
assert slot_k.dtype == torch.bfloat16
|
||||
assert ape.dtype == torch.float32
|
||||
assert kv_cache.dtype == torch.uint8
|
||||
assert loc.dtype == torch.int64
|
||||
assert write_cache or return_compressed
|
||||
|
||||
page_size = kv_cache.shape[1]
|
||||
buf = kv_cache
|
||||
slot_k = slot_k.contiguous()
|
||||
slot_score = slot_score.contiguous()
|
||||
ape = ape.contiguous()
|
||||
loc = loc.contiguous()
|
||||
if write_mask is None:
|
||||
write_mask = torch.empty((1,), dtype=torch.bool, device=slot_k.device)
|
||||
has_write_mask = False
|
||||
else:
|
||||
assert write_mask.shape == (slot_k.shape[0],)
|
||||
write_mask = write_mask.contiguous()
|
||||
has_write_mask = True
|
||||
assert not return_compressed
|
||||
|
||||
if slot_k.shape[0] == 0:
|
||||
if return_compressed:
|
||||
return (
|
||||
torch.empty(
|
||||
(0, head_dim),
|
||||
dtype=torch.float8_e4m3fn,
|
||||
device=slot_k.device,
|
||||
),
|
||||
torch.empty((0,), dtype=torch.float32, device=slot_k.device),
|
||||
)
|
||||
return None
|
||||
|
||||
buf_fp8 = buf.view(torch.float8_e4m3fn)
|
||||
buf_fp32 = buf.view(torch.float32)
|
||||
# bytes per page (last dim of kv_cache) viewed as uint8
|
||||
buf_numel_per_page = buf.stride(0)
|
||||
s_offset_nbytes_in_page = page_size * head_dim
|
||||
|
||||
if return_compressed:
|
||||
compressed_k = torch.empty(
|
||||
(slot_k.shape[0], head_dim),
|
||||
dtype=torch.float8_e4m3fn,
|
||||
device=slot_k.device,
|
||||
)
|
||||
compressed_scale = torch.empty(
|
||||
(slot_k.shape[0],), dtype=torch.float32, device=slot_k.device
|
||||
)
|
||||
else:
|
||||
compressed_k = buf_fp8
|
||||
compressed_scale = buf_fp32
|
||||
|
||||
_kpool_softmax_rotate_write_cache_kernel[(slot_k.shape[0],)](
|
||||
buf_fp8,
|
||||
buf_fp32,
|
||||
slot_k,
|
||||
slot_score,
|
||||
ape,
|
||||
loc,
|
||||
write_mask,
|
||||
compressed_k,
|
||||
compressed_scale,
|
||||
slot_k.stride(0),
|
||||
slot_k.stride(1),
|
||||
slot_score.stride(0),
|
||||
slot_score.stride(1),
|
||||
ape.stride(0),
|
||||
PAGE_SIZE=page_size,
|
||||
BUF_NUMEL_PER_PAGE=buf_numel_per_page,
|
||||
POOL_SIZE=slot_k.shape[1],
|
||||
HEAD_DIM=head_dim,
|
||||
S_OFFSET_NBYTES_IN_PAGE=s_offset_nbytes_in_page,
|
||||
ROUND_SCALE=round_scale,
|
||||
HAS_WRITE_MASK=has_write_mask,
|
||||
RETURN_COMPRESSED=return_compressed,
|
||||
WRITE_CACHE=write_cache,
|
||||
BLOCK_D=triton.next_power_of_2(head_dim),
|
||||
)
|
||||
|
||||
if return_compressed:
|
||||
return compressed_k, compressed_scale
|
||||
return None
|
||||
|
||||
|
||||
# Seed each request's incomplete pool into its paged tail during prefill.
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _kpool_tail_seed_kernel(
|
||||
key_ptr,
|
||||
score_ptr,
|
||||
tslot_ptr,
|
||||
tail_ptr,
|
||||
n_tokens,
|
||||
HEAD_DIM: tl.constexpr,
|
||||
KPOOL: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
"""Copy token ``i``'s raw K + gate into its request's tail block.
|
||||
|
||||
Token ``i`` is among its request's last KPOOL tokens iff the token KPOOL
|
||||
ahead belongs to a different tail block (or is past the batch / padding,
|
||||
slot < 0). ``tslot = block * KPOOL + pos % KPOOL``; the destination is
|
||||
``tail[block, {0:K, 1:score}, pos % KPOOL, :]``.
|
||||
"""
|
||||
i = tl.program_id(0)
|
||||
t = tl.load(tslot_ptr + i).to(tl.int64)
|
||||
if t < 0:
|
||||
return
|
||||
blk = t // KPOOL # t >= 0 here, so trunc == floor
|
||||
ahead = tl.load(tslot_ptr + i + KPOOL, mask=i + KPOOL < n_tokens, other=-1).to(
|
||||
tl.int64
|
||||
)
|
||||
# Match the torch semantics exactly: a negative ahead slot floors to a
|
||||
# block id that differs from every real block -> token is in the tail.
|
||||
# Only divide non-negative slots (Triton int div truncates, torch floors).
|
||||
if ahead >= 0 and ahead // KPOOL == blk:
|
||||
return
|
||||
offs = tl.arange(0, BLOCK_D)
|
||||
m = offs < HEAD_DIM
|
||||
base = (blk * 2 * KPOOL + t % KPOOL) * HEAD_DIM
|
||||
k = tl.load(key_ptr + i * HEAD_DIM + offs, mask=m)
|
||||
s = tl.load(score_ptr + i * HEAD_DIM + offs, mask=m)
|
||||
tl.store(tail_ptr + base + offs, k, mask=m)
|
||||
tl.store(tail_ptr + base + KPOOL * HEAD_DIM + offs, s, mask=m)
|
||||
|
||||
|
||||
def kpool_seed_tail_cache(
|
||||
tail_kv_cache: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
gate_score: torch.Tensor,
|
||||
tslot: torch.Tensor,
|
||||
kpool: int,
|
||||
head_dim: int = INDEX_HEAD_DIM,
|
||||
) -> None:
|
||||
"""Seed the paged tail cache from a prefill batch (see the kernel)."""
|
||||
assert tail_kv_cache.dtype == torch.bfloat16
|
||||
assert key.dtype == torch.bfloat16
|
||||
n = tslot.shape[0]
|
||||
if n == 0:
|
||||
return
|
||||
_kpool_tail_seed_kernel[(n,)](
|
||||
key,
|
||||
gate_score,
|
||||
tslot,
|
||||
tail_kv_cache,
|
||||
n,
|
||||
HEAD_DIM=head_dim,
|
||||
KPOOL=kpool,
|
||||
BLOCK_D=triton.next_power_of_2(head_dim),
|
||||
)
|
||||
|
||||
|
||||
# Update each request's tail during decode and write completed pools.
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _kpool_decode_update_batched_kernel(
|
||||
buf_fp8_ptr,
|
||||
buf_fp32_ptr,
|
||||
tail_kv_ptr,
|
||||
tail_slot_mapping_ptr, # [B, NEXT_N] int32
|
||||
key_ptr, # [B, NEXT_N, HEAD_DIM] bf16
|
||||
key_stride_b,
|
||||
key_stride_t,
|
||||
slot_score_ptr, # [B, NEXT_N, HEAD_DIM] bf16
|
||||
ss_stride_b,
|
||||
ss_stride_t,
|
||||
ape_ptr,
|
||||
ape_stride_0,
|
||||
slot_mapping_ptr, # [B, NEXT_N] int32
|
||||
positions_ptr, # [B, NEXT_N] int32
|
||||
NEXT_N, # runtime token count per request (no .item() needed)
|
||||
PAGE_SIZE: tl.constexpr,
|
||||
BUF_NUMEL_PER_PAGE: tl.constexpr,
|
||||
POOL_SIZE: tl.constexpr,
|
||||
TAIL_BLOCK_ELEMS: tl.constexpr,
|
||||
KPOOL_HEAD: tl.constexpr,
|
||||
HEAD_DIM: tl.constexpr,
|
||||
S_OFFSET_NBYTES_IN_PAGE: tl.constexpr,
|
||||
ROUND_SCALE: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
"""One program per request; iterates its NEXT_N verify tokens in order.
|
||||
|
||||
Replaces the caller's per-token sequential launch loop. The intra-request
|
||||
iteration MUST stay in position order: a pool-completion at token t* reads
|
||||
the tail-ring slots that tokens t < t* (same request) just stashed in this
|
||||
same invocation. ``tl.range`` iterates sequentially within the program, so
|
||||
those stashes are visible to the later completion read. Cross-request
|
||||
programs are independent (distinct tail blocks). With NEXT_N < POOL_SIZE
|
||||
(the spec-verify case: NEXT_N ~= num_spec+1, POOL_SIZE=16) at most one
|
||||
completion can occur per request per call, but the ordered loop is correct
|
||||
for any NEXT_N.
|
||||
"""
|
||||
req = tl.program_id(0)
|
||||
offs = tl.arange(0, BLOCK_D)
|
||||
dim_mask = offs < HEAD_DIM
|
||||
|
||||
for t in tl.range(0, NEXT_N):
|
||||
idx = req * NEXT_N + t
|
||||
cache_loc = tl.load(slot_mapping_ptr + idx)
|
||||
pos = tl.load(positions_ptr + idx)
|
||||
safe_pos = tl.maximum(pos, 0)
|
||||
pos_valid = (cache_loc >= 0) & (pos >= 0)
|
||||
|
||||
slot = safe_pos % POOL_SIZE
|
||||
phys_slot = safe_pos % POOL_SIZE
|
||||
|
||||
# Derive the tail block from THIS token's tail_slot (the request's block
|
||||
# is constant across a pool, but a padded / invalid entry carries a
|
||||
# negative sentinel -- reading it from token 0 would poison every
|
||||
# token's base address). Clamp so an invalid entry can never form an
|
||||
# out-of-bounds base; the accesses below are gated on pos_valid anyway.
|
||||
tail_slot = tl.load(tail_slot_mapping_ptr + idx)
|
||||
block = tl.maximum(tail_slot, 0).to(tl.int64) // POOL_SIZE
|
||||
block_base = block * TAIL_BLOCK_ELEMS
|
||||
|
||||
# The tail-ring stash must run for EVERY real token, so it is gated on
|
||||
# the token-granular tail slot -- not on `pos_valid`, which keys off the
|
||||
# POOL-granular `slot_mapping` and is therefore only true on the pool's
|
||||
# last token. Gating the stash on pos_valid dropped every intra-pool
|
||||
# token, so a decode-built pool compressed 3 stale ring entries (the
|
||||
# prefill-seeded prompt tail, frozen forever) plus the current token.
|
||||
stash_valid = (pos >= 0) & (tail_slot >= 0)
|
||||
|
||||
key = tl.load(
|
||||
key_ptr + req * key_stride_b + t * key_stride_t + offs,
|
||||
mask=dim_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
score_current = tl.load(
|
||||
slot_score_ptr + req * ss_stride_b + t * ss_stride_t + offs,
|
||||
mask=dim_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
|
||||
if pos_valid & (slot == POOL_SIZE - 1):
|
||||
pool_logical_start = safe_pos - slot
|
||||
|
||||
max_score = tl.full((BLOCK_D,), -float("inf"), tl.float32)
|
||||
for pool_slot in tl.static_range(0, POOL_SIZE):
|
||||
is_current = pool_slot == slot
|
||||
phys = (pool_logical_start + pool_slot) % POOL_SIZE
|
||||
score_buf = tl.load(
|
||||
tail_kv_ptr + block_base + KPOOL_HEAD + phys * HEAD_DIM + offs,
|
||||
mask=dim_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
score = tl.where(is_current, score_current, score_buf)
|
||||
score += tl.load(
|
||||
ape_ptr + pool_slot * ape_stride_0 + offs,
|
||||
mask=dim_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
max_score = tl.maximum(max_score, score)
|
||||
|
||||
acc = tl.full((BLOCK_D,), 0.0, tl.float32)
|
||||
denom = tl.full((BLOCK_D,), 0.0, tl.float32)
|
||||
for pool_slot in tl.static_range(0, POOL_SIZE):
|
||||
is_current = pool_slot == slot
|
||||
phys = (pool_logical_start + pool_slot) % POOL_SIZE
|
||||
score_buf = tl.load(
|
||||
tail_kv_ptr + block_base + KPOOL_HEAD + phys * HEAD_DIM + offs,
|
||||
mask=dim_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
score = tl.where(is_current, score_current, score_buf)
|
||||
score += tl.load(
|
||||
ape_ptr + pool_slot * ape_stride_0 + offs,
|
||||
mask=dim_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
prob = tl.exp(score - max_score)
|
||||
denom += prob
|
||||
k_buf = tl.load(
|
||||
tail_kv_ptr + block_base + phys * HEAD_DIM + offs,
|
||||
mask=dim_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
k = tl.where(is_current, key, k_buf)
|
||||
acc += k * prob
|
||||
|
||||
x = (acc / denom).to(tl.bfloat16).to(tl.float32)
|
||||
x = _hadamard128(x).to(tl.bfloat16).to(tl.float32)
|
||||
|
||||
fp8_max = 448.0
|
||||
fp8_max_inv = 1.0 / fp8_max
|
||||
absmax = tl.maximum(tl.max(tl.abs(x), axis=0), 1e-4)
|
||||
if ROUND_SCALE:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(absmax * fp8_max_inv)))
|
||||
else:
|
||||
scale = absmax * fp8_max_inv
|
||||
quantized = tl.minimum(tl.maximum(x / scale, -fp8_max), fp8_max)
|
||||
|
||||
loc = cache_loc.to(tl.int64)
|
||||
loc_page_index = loc // PAGE_SIZE
|
||||
loc_token_offset_in_page = loc % PAGE_SIZE
|
||||
out_k_offsets = (
|
||||
loc_page_index * BUF_NUMEL_PER_PAGE
|
||||
+ loc_token_offset_in_page * HEAD_DIM
|
||||
+ offs
|
||||
)
|
||||
out_s_offset = (
|
||||
loc_page_index * BUF_NUMEL_PER_PAGE // 4
|
||||
+ S_OFFSET_NBYTES_IN_PAGE // 4
|
||||
+ loc_token_offset_in_page
|
||||
)
|
||||
tl.store(buf_fp8_ptr + out_k_offsets, quantized, mask=dim_mask)
|
||||
tl.store(buf_fp32_ptr + out_s_offset, scale)
|
||||
|
||||
# Stash the current token AFTER any completion read so the completion
|
||||
# uses prior stashes (and the current token's own key/score via
|
||||
# is_current), then leaves this token for future pools. Order matches
|
||||
# the per-token kernel: completion read first, stash second.
|
||||
update_mask = dim_mask & stash_valid
|
||||
tl.store(
|
||||
tail_kv_ptr + block_base + phys_slot * HEAD_DIM + offs,
|
||||
key,
|
||||
mask=update_mask,
|
||||
)
|
||||
tl.store(
|
||||
tail_kv_ptr + block_base + KPOOL_HEAD + phys_slot * HEAD_DIM + offs,
|
||||
score_current,
|
||||
mask=update_mask,
|
||||
)
|
||||
|
||||
|
||||
def kpool_decode_update_and_maybe_write_cache_batched(
|
||||
kv_cache: torch.Tensor,
|
||||
tail_kv_cache: torch.Tensor,
|
||||
tail_slot_mapping: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
slot_score: torch.Tensor,
|
||||
ape: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
pool_size: int,
|
||||
head_dim: int = INDEX_HEAD_DIM,
|
||||
round_scale: bool = True,
|
||||
) -> None:
|
||||
"""Batched decode-step kpool update for spec verify (``next_n > 1``).
|
||||
|
||||
One launch replaces the caller's per-token loop. Inputs are grouped per
|
||||
request: ``[num_requests, next_n, ...]``. Each program handles one
|
||||
request's ``next_n`` tokens in position order (see the kernel docstring for
|
||||
why ordering is required for pool-completion correctness).
|
||||
|
||||
Plain decode (``next_n == 1``) is handled here too — the kernel collapses
|
||||
to a single-iteration loop.
|
||||
|
||||
Args:
|
||||
kv_cache: indexer K cache ``[num_blocks, block_size, head_dim+4]`` uint8.
|
||||
tail_kv_cache: paged tail cache ``[num_blocks, 2, pool_size, head_dim]``
|
||||
bf16 (K at half 0, gate score at half 1).
|
||||
tail_slot_mapping: ``[num_requests, next_n]`` int32.
|
||||
key / slot_score: ``[num_requests, next_n, head_dim]`` bf16.
|
||||
ape: ``[pool_size, head_dim]`` fp32.
|
||||
slot_mapping / positions: ``[num_requests, next_n]`` int32.
|
||||
"""
|
||||
num_requests, next_n = key.shape[0], key.shape[1]
|
||||
if num_requests == 0 or next_n == 0:
|
||||
return
|
||||
assert tail_kv_cache.ndim == 4
|
||||
assert tail_kv_cache.shape[1] == 2
|
||||
assert tail_kv_cache.shape[2] == pool_size
|
||||
assert tail_kv_cache.shape[3] == head_dim
|
||||
assert tail_kv_cache.dtype == torch.bfloat16
|
||||
assert key.ndim == 3 and key.shape[2] == head_dim
|
||||
assert slot_score.shape == key.shape
|
||||
assert ape.shape == (pool_size, head_dim)
|
||||
assert tail_slot_mapping.shape == (num_requests, next_n)
|
||||
assert slot_mapping.shape == (num_requests, next_n)
|
||||
assert positions.shape == (num_requests, next_n)
|
||||
assert key.dtype == torch.bfloat16
|
||||
assert slot_score.dtype == torch.bfloat16
|
||||
assert ape.dtype == torch.float32
|
||||
assert kv_cache.dtype == torch.uint8
|
||||
|
||||
page_size = kv_cache.shape[1]
|
||||
buf = kv_cache
|
||||
buf_fp8 = buf.view(torch.float8_e4m3fn)
|
||||
buf_fp32 = buf.view(torch.float32)
|
||||
|
||||
# The kernel indexes the int tensors as ``req * next_n + t`` (row-major),
|
||||
# so they must be contiguous. Callers pass either a view of a contiguous
|
||||
# slice or a freshly scattered tensor, making these no-ops; the calls guard
|
||||
# against a future caller handing over a strided view.
|
||||
tail_slot_mapping = tail_slot_mapping.contiguous()
|
||||
slot_mapping = slot_mapping.contiguous()
|
||||
positions = positions.contiguous()
|
||||
|
||||
_kpool_decode_update_batched_kernel[(num_requests,)](
|
||||
buf_fp8,
|
||||
buf_fp32,
|
||||
tail_kv_cache,
|
||||
tail_slot_mapping,
|
||||
key,
|
||||
key.stride(0),
|
||||
key.stride(1),
|
||||
slot_score,
|
||||
slot_score.stride(0),
|
||||
slot_score.stride(1),
|
||||
ape,
|
||||
ape.stride(0),
|
||||
slot_mapping,
|
||||
positions,
|
||||
next_n,
|
||||
PAGE_SIZE=page_size,
|
||||
BUF_NUMEL_PER_PAGE=buf.stride(0),
|
||||
POOL_SIZE=pool_size,
|
||||
TAIL_BLOCK_ELEMS=tail_kv_cache.stride(0),
|
||||
KPOOL_HEAD=tail_kv_cache.stride(1),
|
||||
HEAD_DIM=head_dim,
|
||||
S_OFFSET_NBYTES_IN_PAGE=page_size * head_dim,
|
||||
ROUND_SCALE=round_scale,
|
||||
BLOCK_D=triton.next_power_of_2(head_dim),
|
||||
)
|
||||
|
||||
|
||||
# Pool-level top-k helpers.
|
||||
|
||||
|
||||
def history_group_budget_for_topk(topk: int, pool_size: int) -> int:
|
||||
"""Number of pools to select so that expanding yields ``topk`` tokens."""
|
||||
assert topk % pool_size == 0
|
||||
return topk // pool_size
|
||||
|
||||
|
||||
def expand_pools_to_tokens(
|
||||
group_ids: torch.Tensor,
|
||||
group_valid: torch.Tensor,
|
||||
topk: int,
|
||||
pool_size: int,
|
||||
page_table: torch.Tensor | None = None,
|
||||
topk_offsets: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Expand selected full-pool ids to a strict-width token topk tensor."""
|
||||
assert group_ids.ndim == 2
|
||||
assert group_valid.shape == group_ids.shape
|
||||
assert topk % pool_size == 0
|
||||
assert group_ids.shape[1] == history_group_budget_for_topk(topk, pool_size)
|
||||
assert page_table is None or topk_offsets is None
|
||||
|
||||
device = group_ids.device
|
||||
offsets = torch.arange(pool_size, device=device, dtype=torch.int64)
|
||||
token_ids = group_ids.to(torch.int64).unsqueeze(-1) * pool_size + offsets
|
||||
token_ids = token_ids.reshape(group_ids.shape[0], topk)
|
||||
valid = (
|
||||
group_valid.unsqueeze(-1)
|
||||
.expand(-1, -1, pool_size)
|
||||
.reshape(group_ids.shape[0], topk)
|
||||
)
|
||||
|
||||
if page_table is not None:
|
||||
assert page_table.ndim == 2
|
||||
safe_ids = token_ids.clamp(min=0, max=page_table.shape[1] - 1)
|
||||
output = torch.gather(page_table, dim=1, index=safe_ids).to(torch.int32)
|
||||
elif topk_offsets is not None:
|
||||
if topk_offsets.ndim == 2:
|
||||
assert topk_offsets.shape[1] == 1
|
||||
topk_offsets = topk_offsets.squeeze(1)
|
||||
output = (token_ids + topk_offsets.to(torch.int64).unsqueeze(1)).to(torch.int32)
|
||||
else:
|
||||
output = token_ids.to(torch.int32)
|
||||
|
||||
return torch.where(valid, output, torch.full_like(output, -1))
|
||||
|
||||
|
||||
def append_tail_to_topk(
|
||||
topk_result: torch.Tensor,
|
||||
seq_lens: torch.Tensor,
|
||||
pool_lens: torch.Tensor,
|
||||
pool_size: int,
|
||||
page_table: torch.Tensor | None = None,
|
||||
topk_offsets: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Append non-pooled tail tokens after expanded history tokens.
|
||||
|
||||
``index_kpool_always_select_tail`` keeps the (incomplete) trailing pool so
|
||||
the most recent tokens are always attended to.
|
||||
"""
|
||||
assert topk_result.dtype == torch.int32
|
||||
assert seq_lens.ndim == 1
|
||||
assert pool_lens.ndim == 1
|
||||
|
||||
tail_pool = pool_size - 1
|
||||
if tail_pool == 0:
|
||||
return topk_result
|
||||
|
||||
rows, n_cols = topk_result.shape
|
||||
out_cols = n_cols + tail_pool
|
||||
out = torch.empty(
|
||||
(rows, out_cols), dtype=topk_result.dtype, device=topk_result.device
|
||||
)
|
||||
|
||||
# tail tokens: [pool_len*pool_size, seq_len) for each row.
|
||||
pool_len = pool_lens.to(torch.int32)
|
||||
tail_start = pool_len * pool_size
|
||||
seq_len = seq_lens.to(torch.int32)
|
||||
tail_count = seq_len - tail_start # in [0, pool_size)
|
||||
|
||||
cols = torch.arange(out_cols, device=topk_result.device)[None, :]
|
||||
history_len = n_cols
|
||||
is_history = cols < history_len
|
||||
tail_off = cols - history_len
|
||||
is_tail = (tail_off >= 0) & (tail_off < tail_count[:, None])
|
||||
|
||||
# safe_hist must be per-row [rows, out_cols] so the gather reads each row's
|
||||
# OWN history. cols is [1, out_cols]; if used directly, gather (which does
|
||||
# NOT broadcast the index) would read only row 0 of topk_result, making every
|
||||
# query inherit row 0's history (empty for the first token) and lose all its
|
||||
# selected tokens — only the per-row tail would survive. This only manifests
|
||||
# for multi-row sparse PREFILL (decode has 1 row, so it reads its own row 0).
|
||||
safe_hist = torch.minimum(cols, torch.full_like(cols, n_cols - 1)).expand(
|
||||
rows, out_cols
|
||||
)
|
||||
history_val = torch.gather(topk_result, 1, safe_hist)
|
||||
|
||||
tail_raw = tail_start[:, None] + tail_off
|
||||
tail_val = tail_raw.to(torch.int32)
|
||||
if page_table is not None:
|
||||
safe_tail = tail_raw.clamp(min=0, max=page_table.shape[1] - 1)
|
||||
tail_val = torch.gather(page_table, 1, safe_tail).to(torch.int32)
|
||||
elif topk_offsets is not None:
|
||||
tail_val = (tail_raw + topk_offsets.to(torch.int64).unsqueeze(1)).to(
|
||||
torch.int32
|
||||
)
|
||||
|
||||
out = torch.where(is_history, history_val, -1)
|
||||
out = torch.where(is_tail, tail_val, out)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _expand_pools_and_append_tail_kernel(
|
||||
pool_ids_ptr, # [rows, n_groups], int (any int dtype)
|
||||
seq_lens_ptr, # [rows], int32 (token-granular seq_len)
|
||||
out_ptr, # [rows, out_cols], int32
|
||||
topk, # n_groups * pool_size
|
||||
out_cols, # topk + pool_size - 1
|
||||
POOL_SIZE: tl.constexpr,
|
||||
BLOCK_COLS: tl.constexpr,
|
||||
pid_s0,
|
||||
out_s0,
|
||||
):
|
||||
# Fuses expand_pools_to_tokens + append_tail_to_topk (identity path) into a
|
||||
# single kernel. Each program writes one (row, column-tile) of the output.
|
||||
row = tl.program_id(0)
|
||||
tile = tl.program_id(1)
|
||||
cols = tile * BLOCK_COLS + tl.arange(0, BLOCK_COLS)
|
||||
mask = cols < out_cols
|
||||
|
||||
seq_len = tl.load(seq_lens_ptr + row)
|
||||
pool_len = seq_len // POOL_SIZE
|
||||
tail_start = pool_len * POOL_SIZE
|
||||
tail_count = seq_len - tail_start # in [0, POOL_SIZE)
|
||||
|
||||
# History region [0, topk): expand selected pool g = cols // POOL_SIZE.
|
||||
is_history = cols < topk
|
||||
g = cols // POOL_SIZE
|
||||
o = cols % POOL_SIZE
|
||||
pid = tl.load(pool_ids_ptr + row * pid_s0 + g, mask=mask & is_history, other=-1)
|
||||
hist_val = (pid * POOL_SIZE + o).to(tl.int32)
|
||||
hist_out = tl.where(pid >= 0, hist_val, -1)
|
||||
|
||||
# Tail region [topk, out_cols): the request's trailing incomplete pool.
|
||||
tail_off = cols - topk
|
||||
is_tail = (tail_off >= 0) & (tail_off < tail_count)
|
||||
tail_val = (tail_start + tail_off).to(tl.int32)
|
||||
tail_out = tl.where(is_tail, tail_val, -1)
|
||||
|
||||
result = tl.where(is_history, hist_out, tail_out)
|
||||
tl.store(out_ptr + row * out_s0 + cols, result, mask=mask)
|
||||
|
||||
|
||||
def expand_pools_and_append_tail(
|
||||
pool_ids: torch.Tensor,
|
||||
seq_lens: torch.Tensor,
|
||||
pool_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Fuse ``expand_pools_to_tokens`` + ``append_tail_to_topk`` (identity path).
|
||||
|
||||
Produces the same ``[rows, topk + pool_size - 1]`` int32 output as calling
|
||||
the two functions in sequence when neither ``page_table`` nor
|
||||
``topk_offsets`` is passed — the only path used by the GLM-5.3-Flash indexer.
|
||||
The kernel derives ``pool_len = seq_len // pool_size`` internally, so the
|
||||
caller no longer needs to precompute it. Replaces ~25 elementwise kernels
|
||||
with one Triton launch.
|
||||
"""
|
||||
rows, n_groups = pool_ids.shape
|
||||
topk = n_groups * pool_size
|
||||
out_cols = topk + pool_size - 1
|
||||
out = torch.empty((rows, out_cols), dtype=torch.int32, device=pool_ids.device)
|
||||
BLOCK_COLS = 128
|
||||
n_tiles = triton.cdiv(out_cols, BLOCK_COLS)
|
||||
_expand_pools_and_append_tail_kernel[(rows, n_tiles)](
|
||||
pool_ids,
|
||||
seq_lens,
|
||||
out,
|
||||
topk,
|
||||
out_cols,
|
||||
POOL_SIZE=pool_size,
|
||||
BLOCK_COLS=BLOCK_COLS,
|
||||
pid_s0=pool_ids.stride(0),
|
||||
out_s0=out.stride(0),
|
||||
)
|
||||
return out
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from .kernels import chunk_kda_with_fused_gate, fused_recurrent_kda
|
||||
|
||||
__all__ = ["chunk_kda_with_fused_gate", "fused_recurrent_kda"]
|
||||
@@ -0,0 +1,656 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Songlin Yang, Yu Zhang
|
||||
# mypy: ignore-errors
|
||||
#
|
||||
# This file contains code copied from the flash-linear-attention project.
|
||||
# The original source code was licensed under the MIT license and included
|
||||
# the following copyright notice:
|
||||
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
||||
# ruff: noqa: E501
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.third_party.flash_linear_attention.ops.op import exp
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.heuristics(
|
||||
{
|
||||
"USE_INITIAL_STATE": lambda args: args["h0"] is not None,
|
||||
"IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
|
||||
"IS_CONTINUOUS_BATCHING": lambda args: args["ssm_state_indices"] is not None,
|
||||
"IS_SPEC_DECODING": lambda args: args["num_accepted_tokens"] is not None,
|
||||
}
|
||||
)
|
||||
@triton.jit(do_not_specialize=["N", "T"])
|
||||
def fused_recurrent_gated_delta_rule_fwd_kernel(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
g,
|
||||
beta,
|
||||
o,
|
||||
h0,
|
||||
ht,
|
||||
cu_seqlens,
|
||||
ssm_state_indices,
|
||||
num_accepted_tokens,
|
||||
a_log,
|
||||
g_bias,
|
||||
scale,
|
||||
N: tl.int64, # num of sequences
|
||||
T: tl.int64, # num of tokens
|
||||
B: tl.constexpr,
|
||||
H: tl.constexpr,
|
||||
HV: tl.constexpr,
|
||||
K: tl.constexpr,
|
||||
V: tl.constexpr,
|
||||
BK: tl.constexpr,
|
||||
BV: tl.constexpr,
|
||||
stride_init_state_token: tl.constexpr,
|
||||
stride_final_state_token: tl.constexpr,
|
||||
stride_indices_seq: tl.constexpr,
|
||||
stride_indices_tok: tl.constexpr,
|
||||
USE_INITIAL_STATE: tl.constexpr, # whether to use initial state
|
||||
INPLACE_FINAL_STATE: tl.constexpr, # whether to store final state inplace
|
||||
IS_BETA_HEADWISE: tl.constexpr, # whether beta is headwise vector or scalar,
|
||||
USE_QK_L2NORM_IN_KERNEL: tl.constexpr,
|
||||
IS_VARLEN: tl.constexpr,
|
||||
IS_CONTINUOUS_BATCHING: tl.constexpr,
|
||||
IS_SPEC_DECODING: tl.constexpr,
|
||||
IS_KDA: tl.constexpr,
|
||||
SIGMOID_BETA: tl.constexpr, # beta holds raw logits; sigmoid at fp32 load
|
||||
COMPUTE_GATE: tl.constexpr, # g holds raw logits; KDA gate computed in-kernel
|
||||
SAFE_GATE: tl.constexpr, # bounded gate variant (only branch implemented)
|
||||
LOWER_BOUND: tl.constexpr,
|
||||
):
|
||||
i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
||||
i_n, i_hv = i_nh // HV, i_nh % HV
|
||||
i_h = i_hv // (HV // H)
|
||||
if IS_VARLEN:
|
||||
bos, eos = (
|
||||
tl.load(cu_seqlens + i_n).to(tl.int64),
|
||||
tl.load(cu_seqlens + i_n + 1).to(tl.int64),
|
||||
)
|
||||
all = T
|
||||
T = eos - bos
|
||||
else:
|
||||
bos, eos = i_n * T, i_n * T + T
|
||||
all = B * T
|
||||
|
||||
if T == 0:
|
||||
# no tokens to process for this sequence
|
||||
return
|
||||
|
||||
o_k = i_k * BK + tl.arange(0, BK)
|
||||
o_v = i_v * BV + tl.arange(0, BV)
|
||||
|
||||
p_q = q + (bos * H + i_h) * K + o_k
|
||||
p_k = k + (bos * H + i_h) * K + o_k
|
||||
p_v = v + (bos * HV + i_hv) * V + o_v
|
||||
if IS_BETA_HEADWISE:
|
||||
p_beta = beta + (bos * HV + i_hv) * V + o_v
|
||||
else:
|
||||
p_beta = beta + bos * HV + i_hv
|
||||
|
||||
if not IS_KDA:
|
||||
p_g = g + bos * HV + i_hv
|
||||
else:
|
||||
p_gk = g + (bos * HV + i_hv) * K + o_k
|
||||
|
||||
# Per-head gate amplitude, hoisted out of the token loop (COMPUTE_GATE).
|
||||
if COMPUTE_GATE:
|
||||
b_a_log = tl.exp(tl.load(a_log + i_h).to(tl.float32))
|
||||
|
||||
p_o = o + ((i_k * all + bos) * HV + i_hv) * V + o_v
|
||||
|
||||
mask_k = o_k < K
|
||||
mask_v = o_v < V
|
||||
mask_h = mask_v[:, None] & mask_k[None, :]
|
||||
|
||||
b_h = tl.zeros([BV, BK], dtype=tl.float32)
|
||||
if USE_INITIAL_STATE:
|
||||
if IS_CONTINUOUS_BATCHING:
|
||||
if IS_SPEC_DECODING:
|
||||
i_t = tl.load(num_accepted_tokens + i_n).to(tl.int64) - 1
|
||||
else:
|
||||
i_t = 0
|
||||
# Load state index and check for invalid entries
|
||||
state_idx = tl.load(ssm_state_indices + i_n * stride_indices_seq + i_t).to(
|
||||
tl.int64
|
||||
)
|
||||
# Skip if state index is invalid (NULL_BLOCK_ID=0)
|
||||
if state_idx <= 0:
|
||||
return
|
||||
p_h0 = h0 + state_idx * stride_init_state_token
|
||||
else:
|
||||
p_h0 = h0 + bos * HV * V * K
|
||||
p_h0 = p_h0 + i_hv * V * K + o_v[:, None] * K + o_k[None, :]
|
||||
b_h += tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
|
||||
|
||||
for i_t in range(0, T):
|
||||
b_q = tl.load(p_q, mask=mask_k, other=0).to(tl.float32)
|
||||
b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
|
||||
b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
|
||||
|
||||
if USE_QK_L2NORM_IN_KERNEL:
|
||||
b_q = b_q / tl.sqrt(tl.sum(b_q * b_q) + 1e-6)
|
||||
b_k = b_k / tl.sqrt(tl.sum(b_k * b_k) + 1e-6)
|
||||
b_q = b_q * scale
|
||||
# [BV, BK]
|
||||
if not IS_KDA:
|
||||
b_g = tl.load(p_g).to(tl.float32)
|
||||
b_h *= exp(b_g)
|
||||
else:
|
||||
b_gk = tl.load(p_gk).to(tl.float32)
|
||||
if COMPUTE_GATE:
|
||||
# Replicates kda_gate_fwd_kernel's SAFE_GATE branch
|
||||
# bit-for-bit (same tl.exp, same fp32 math; the intermediate
|
||||
# gate value this replaces was stored/reloaded as fp32,
|
||||
# which is lossless): y = lb / (1 + exp(-exp(A)*(g+bias))).
|
||||
b_gk += tl.load(g_bias + i_h * K + o_k, mask=mask_k, other=0.0).to(
|
||||
tl.float32
|
||||
)
|
||||
b_gk = LOWER_BOUND / (1.0 + tl.exp(-(b_a_log * b_gk)))
|
||||
b_h *= exp(b_gk[None, :])
|
||||
# [BV]
|
||||
b_v -= tl.sum(b_h * b_k[None, :], 1)
|
||||
if IS_BETA_HEADWISE:
|
||||
b_beta = tl.load(p_beta, mask=mask_v, other=0).to(tl.float32)
|
||||
else:
|
||||
b_beta = tl.load(p_beta).to(tl.float32)
|
||||
# Matches torch's `x.float().sigmoid()` pre-computation bit-for-bit
|
||||
# on the input side (bf16->fp32 is exact); only the sigmoid impl itself
|
||||
# can differ by <=1 ULP.
|
||||
if SIGMOID_BETA:
|
||||
b_beta = tl.sigmoid(b_beta)
|
||||
b_v *= b_beta
|
||||
# [BV, BK]
|
||||
b_h += b_v[:, None] * b_k[None, :]
|
||||
# [BV]
|
||||
b_o = tl.sum(b_h * b_q[None, :], 1)
|
||||
tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
|
||||
|
||||
# keep the states for multi-query tokens
|
||||
if INPLACE_FINAL_STATE:
|
||||
# Load state index and check for invalid entries
|
||||
final_state_idx = tl.load(
|
||||
ssm_state_indices + i_n * stride_indices_seq + i_t
|
||||
).to(tl.int64)
|
||||
# Only store if state index is valid (not NULL_BLOCK_ID=0)
|
||||
if final_state_idx > 0:
|
||||
p_ht = ht + final_state_idx * stride_final_state_token
|
||||
p_ht = p_ht + i_hv * V * K + o_v[:, None] * K + o_k[None, :]
|
||||
tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
|
||||
else:
|
||||
p_ht = ht + (bos + i_t) * stride_final_state_token
|
||||
p_ht = p_ht + i_hv * V * K + o_v[:, None] * K + o_k[None, :]
|
||||
tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
|
||||
|
||||
p_q += H * K
|
||||
p_k += H * K
|
||||
p_o += HV * V
|
||||
p_v += HV * V
|
||||
if not IS_KDA:
|
||||
p_g += HV
|
||||
else:
|
||||
p_gk += HV * K
|
||||
p_beta += HV * (V if IS_BETA_HEADWISE else 1)
|
||||
|
||||
|
||||
def fused_recurrent_gated_delta_rule_fwd(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
beta: torch.Tensor,
|
||||
scale: float,
|
||||
initial_state: torch.Tensor,
|
||||
inplace_final_state: bool = True,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
ssm_state_indices: torch.Tensor | None = None,
|
||||
num_accepted_tokens: torch.Tensor | None = None,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
B, T, H, K, V = *k.shape, v.shape[-1]
|
||||
HV = v.shape[2]
|
||||
N = B if cu_seqlens is None else len(cu_seqlens) - 1
|
||||
BK, BV = triton.next_power_of_2(K), min(triton.next_power_of_2(V), 32)
|
||||
NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
|
||||
assert NK == 1, "NK > 1 is not supported yet"
|
||||
num_stages = 3
|
||||
num_warps = 1
|
||||
|
||||
o = q.new_empty(NK, *v.shape)
|
||||
if inplace_final_state:
|
||||
final_state = initial_state
|
||||
else:
|
||||
final_state = q.new_empty(T, HV, V, K, dtype=initial_state.dtype)
|
||||
|
||||
stride_init_state_token = initial_state.stride(0)
|
||||
stride_final_state_token = final_state.stride(0)
|
||||
|
||||
if ssm_state_indices is None:
|
||||
stride_indices_seq, stride_indices_tok = 1, 1
|
||||
elif ssm_state_indices.ndim == 1:
|
||||
stride_indices_seq, stride_indices_tok = ssm_state_indices.stride(0), 1
|
||||
else:
|
||||
stride_indices_seq, stride_indices_tok = ssm_state_indices.stride()
|
||||
|
||||
grid = (NK, NV, N * HV)
|
||||
fused_recurrent_gated_delta_rule_fwd_kernel[grid](
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
g=g,
|
||||
beta=beta,
|
||||
o=o,
|
||||
h0=initial_state,
|
||||
ht=final_state,
|
||||
cu_seqlens=cu_seqlens,
|
||||
ssm_state_indices=ssm_state_indices,
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
scale=scale,
|
||||
N=N,
|
||||
T=T,
|
||||
B=B,
|
||||
H=H,
|
||||
HV=HV,
|
||||
K=K,
|
||||
V=V,
|
||||
BK=BK,
|
||||
BV=BV,
|
||||
stride_init_state_token=stride_init_state_token,
|
||||
stride_final_state_token=stride_final_state_token,
|
||||
stride_indices_seq=stride_indices_seq,
|
||||
stride_indices_tok=stride_indices_tok,
|
||||
IS_BETA_HEADWISE=beta.ndim == v.ndim,
|
||||
USE_QK_L2NORM_IN_KERNEL=use_qk_l2norm_in_kernel,
|
||||
INPLACE_FINAL_STATE=inplace_final_state,
|
||||
IS_KDA=False,
|
||||
SIGMOID_BETA=False,
|
||||
a_log=None,
|
||||
g_bias=None,
|
||||
COMPUTE_GATE=False,
|
||||
SAFE_GATE=True,
|
||||
LOWER_BOUND=-5.0,
|
||||
num_warps=num_warps,
|
||||
num_stages=num_stages,
|
||||
)
|
||||
o = o.squeeze(0)
|
||||
return o, final_state
|
||||
|
||||
|
||||
@triton.jit
|
||||
def fused_recurrent_gated_delta_rule_packed_decode_kernel(
|
||||
mixed_qkv,
|
||||
a,
|
||||
b,
|
||||
A_log,
|
||||
dt_bias,
|
||||
o,
|
||||
h0,
|
||||
ht,
|
||||
ssm_state_indices,
|
||||
scale,
|
||||
stride_mixed_qkv_tok: tl.constexpr,
|
||||
stride_a_tok: tl.constexpr,
|
||||
stride_b_tok: tl.constexpr,
|
||||
stride_init_state_token: tl.constexpr,
|
||||
stride_final_state_token: tl.constexpr,
|
||||
stride_indices_seq: tl.constexpr,
|
||||
H: tl.constexpr,
|
||||
HV: tl.constexpr,
|
||||
K: tl.constexpr,
|
||||
V: tl.constexpr,
|
||||
BK: tl.constexpr,
|
||||
BV: tl.constexpr,
|
||||
SOFTPLUS_THRESHOLD: tl.constexpr,
|
||||
USE_QK_L2NORM_IN_KERNEL: tl.constexpr,
|
||||
SPLIT_BATCH_HEAD_GRID: tl.constexpr,
|
||||
):
|
||||
if SPLIT_BATCH_HEAD_GRID:
|
||||
i_v, i_hv, i_n = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
||||
else:
|
||||
i_v, i_nh = tl.program_id(0), tl.program_id(1)
|
||||
i_n, i_hv = i_nh // HV, i_nh % HV
|
||||
i_h = i_hv // (HV // H)
|
||||
|
||||
o_k = tl.arange(0, BK)
|
||||
o_v = i_v * BV + tl.arange(0, BV)
|
||||
mask_k = o_k < K
|
||||
mask_v = o_v < V
|
||||
mask_h = mask_v[:, None] & mask_k[None, :]
|
||||
|
||||
state_idx = tl.load(ssm_state_indices + i_n * stride_indices_seq).to(tl.int64)
|
||||
p_o = o + (i_n * HV + i_hv) * V + o_v
|
||||
|
||||
# Skip if state index is invalid (NULL_BLOCK_ID=0)
|
||||
if state_idx <= 0:
|
||||
zero = tl.zeros([BV], dtype=tl.float32).to(p_o.dtype.element_ty)
|
||||
tl.store(p_o, zero, mask=mask_v)
|
||||
return
|
||||
|
||||
p_h0 = h0 + state_idx * stride_init_state_token
|
||||
p_h0 = p_h0 + i_hv * V * K + o_v[:, None] * K + o_k[None, :]
|
||||
b_h = tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
|
||||
|
||||
p_mixed = mixed_qkv + i_n * stride_mixed_qkv_tok
|
||||
q_off = i_h * K + o_k
|
||||
k_off = (H * K) + i_h * K + o_k
|
||||
v_off = (2 * H * K) + i_hv * V + o_v
|
||||
b_q = tl.load(p_mixed + q_off, mask=mask_k, other=0).to(tl.float32)
|
||||
b_k = tl.load(p_mixed + k_off, mask=mask_k, other=0).to(tl.float32)
|
||||
b_v = tl.load(p_mixed + v_off, mask=mask_v, other=0).to(tl.float32)
|
||||
|
||||
if USE_QK_L2NORM_IN_KERNEL:
|
||||
b_q = b_q / tl.sqrt(tl.sum(b_q * b_q) + 1e-6)
|
||||
b_k = b_k / tl.sqrt(tl.sum(b_k * b_k) + 1e-6)
|
||||
b_q = b_q * scale
|
||||
|
||||
a_val = tl.load(a + i_n * stride_a_tok + i_hv).to(tl.float32)
|
||||
b_val = tl.load(b + i_n * stride_b_tok + i_hv).to(tl.float32)
|
||||
A_log_val = tl.load(A_log + i_hv).to(tl.float32)
|
||||
dt_bias_val = tl.load(dt_bias + i_hv).to(tl.float32)
|
||||
x = a_val + dt_bias_val
|
||||
softplus_x = tl.where(x <= SOFTPLUS_THRESHOLD, tl.log(1.0 + tl.exp(x)), x)
|
||||
g_val = -tl.exp(A_log_val) * softplus_x
|
||||
beta_val = tl.sigmoid(b_val)
|
||||
|
||||
b_h *= exp(g_val)
|
||||
b_v -= tl.sum(b_h * b_k[None, :], 1)
|
||||
b_v *= beta_val
|
||||
b_h += b_v[:, None] * b_k[None, :]
|
||||
b_o = tl.sum(b_h * b_q[None, :], 1)
|
||||
tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
|
||||
|
||||
p_ht = ht + state_idx * stride_final_state_token
|
||||
p_ht = p_ht + i_hv * V * K + o_v[:, None] * K + o_k[None, :]
|
||||
tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
|
||||
|
||||
|
||||
def fused_recurrent_gated_delta_rule_packed_decode(
|
||||
mixed_qkv: torch.Tensor,
|
||||
a: torch.Tensor,
|
||||
b: torch.Tensor,
|
||||
A_log: torch.Tensor,
|
||||
dt_bias: torch.Tensor,
|
||||
scale: float,
|
||||
initial_state: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
ssm_state_indices: torch.Tensor,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if mixed_qkv.ndim != 2:
|
||||
raise ValueError(
|
||||
f"`mixed_qkv` must be a 2D tensor (got ndim={mixed_qkv.ndim})."
|
||||
)
|
||||
if mixed_qkv.stride(-1) != 1:
|
||||
raise ValueError("`mixed_qkv` must be contiguous in the last dim.")
|
||||
if a.ndim != 2 or b.ndim != 2:
|
||||
raise ValueError(
|
||||
f"`a` and `b` must be 2D tensors (got a.ndim={a.ndim}, b.ndim={b.ndim})."
|
||||
)
|
||||
if a.stride(-1) != 1 or b.stride(-1) != 1:
|
||||
raise ValueError("`a`/`b` must be contiguous in the last dim.")
|
||||
if A_log.ndim != 1 or dt_bias.ndim != 1:
|
||||
raise ValueError("`A_log`/`dt_bias` must be 1D tensors.")
|
||||
if A_log.stride(0) != 1 or dt_bias.stride(0) != 1:
|
||||
raise ValueError("`A_log`/`dt_bias` must be contiguous.")
|
||||
if ssm_state_indices.ndim != 1:
|
||||
raise ValueError(
|
||||
f"`ssm_state_indices` must be 1D for packed decode (got ndim={ssm_state_indices.ndim})."
|
||||
)
|
||||
if not out.is_contiguous():
|
||||
raise ValueError("`out` must be contiguous.")
|
||||
|
||||
dev = mixed_qkv.device
|
||||
if (
|
||||
a.device != dev
|
||||
or b.device != dev
|
||||
or A_log.device != dev
|
||||
or dt_bias.device != dev
|
||||
or initial_state.device != dev
|
||||
or out.device != dev
|
||||
or ssm_state_indices.device != dev
|
||||
):
|
||||
raise ValueError("All inputs must be on the same device.")
|
||||
|
||||
B = mixed_qkv.shape[0]
|
||||
if a.shape[0] != B or b.shape[0] != B:
|
||||
raise ValueError(
|
||||
"Mismatched batch sizes: "
|
||||
f"mixed_qkv.shape[0]={B}, a.shape[0]={a.shape[0]}, b.shape[0]={b.shape[0]}."
|
||||
)
|
||||
if ssm_state_indices.shape[0] != B:
|
||||
raise ValueError(
|
||||
f"`ssm_state_indices` must have shape [B] (got {tuple(ssm_state_indices.shape)}; expected ({B},))."
|
||||
)
|
||||
|
||||
if initial_state.ndim != 4:
|
||||
raise ValueError(
|
||||
f"`initial_state` must be a 4D tensor (got ndim={initial_state.ndim})."
|
||||
)
|
||||
if initial_state.stride(-1) != 1:
|
||||
raise ValueError("`initial_state` must be contiguous in the last dim.")
|
||||
HV, V, K = initial_state.shape[-3:]
|
||||
if a.shape[1] != HV or b.shape[1] != HV:
|
||||
raise ValueError(
|
||||
f"`a`/`b` must have shape [B, HV] with HV={HV} (got a.shape={tuple(a.shape)}, b.shape={tuple(b.shape)})."
|
||||
)
|
||||
if A_log.numel() != HV or dt_bias.numel() != HV:
|
||||
raise ValueError(
|
||||
f"`A_log` and `dt_bias` must have {HV} elements (got A_log.numel()={A_log.numel()}, dt_bias.numel()={dt_bias.numel()})."
|
||||
)
|
||||
if out.shape != (B, 1, HV, V):
|
||||
raise ValueError(
|
||||
f"`out` must have shape {(B, 1, HV, V)} (got out.shape={tuple(out.shape)})."
|
||||
)
|
||||
|
||||
qkv_dim = mixed_qkv.shape[1]
|
||||
qk_dim = qkv_dim - HV * V
|
||||
if qk_dim <= 0 or qk_dim % 2 != 0:
|
||||
raise ValueError(
|
||||
f"Invalid packed `mixed_qkv` last dim={qkv_dim} for HV={HV}, V={V}."
|
||||
)
|
||||
q_dim = qk_dim // 2
|
||||
if q_dim % K != 0:
|
||||
raise ValueError(f"Invalid packed Q size {q_dim}: must be divisible by K={K}.")
|
||||
H = q_dim // K
|
||||
if H <= 0 or HV % H != 0:
|
||||
raise ValueError(
|
||||
f"Invalid head config inferred from mixed_qkv: H={H}, HV={HV}."
|
||||
)
|
||||
|
||||
BK = triton.next_power_of_2(K)
|
||||
if triton.cdiv(K, BK) != 1:
|
||||
raise ValueError(
|
||||
f"Packed decode kernel only supports NK=1 (got K={K}, BK={BK})."
|
||||
)
|
||||
BV = min(triton.next_power_of_2(V), 32)
|
||||
num_stages = 3
|
||||
num_warps = 1
|
||||
|
||||
stride_mixed_qkv_tok = mixed_qkv.stride(0)
|
||||
stride_a_tok = a.stride(0)
|
||||
stride_b_tok = b.stride(0)
|
||||
stride_init_state_token = initial_state.stride(0)
|
||||
stride_final_state_token = initial_state.stride(0)
|
||||
stride_indices_seq = ssm_state_indices.stride(0)
|
||||
|
||||
NV = triton.cdiv(V, BV)
|
||||
# CUDA limits grid Y/Z dimensions to 65535.
|
||||
split_batch_head_grid = B * HV > 65535
|
||||
grid = (NV, HV, B) if split_batch_head_grid else (NV, B * HV)
|
||||
fused_recurrent_gated_delta_rule_packed_decode_kernel[grid](
|
||||
mixed_qkv=mixed_qkv,
|
||||
a=a,
|
||||
b=b,
|
||||
A_log=A_log,
|
||||
dt_bias=dt_bias,
|
||||
o=out,
|
||||
h0=initial_state,
|
||||
ht=initial_state,
|
||||
ssm_state_indices=ssm_state_indices,
|
||||
scale=scale,
|
||||
stride_mixed_qkv_tok=stride_mixed_qkv_tok,
|
||||
stride_a_tok=stride_a_tok,
|
||||
stride_b_tok=stride_b_tok,
|
||||
stride_init_state_token=stride_init_state_token,
|
||||
stride_final_state_token=stride_final_state_token,
|
||||
stride_indices_seq=stride_indices_seq,
|
||||
H=H,
|
||||
HV=HV,
|
||||
K=K,
|
||||
V=V,
|
||||
BK=BK,
|
||||
BV=BV,
|
||||
SOFTPLUS_THRESHOLD=20.0,
|
||||
USE_QK_L2NORM_IN_KERNEL=use_qk_l2norm_in_kernel,
|
||||
SPLIT_BATCH_HEAD_GRID=split_batch_head_grid,
|
||||
num_warps=num_warps,
|
||||
num_stages=num_stages,
|
||||
)
|
||||
return out, initial_state
|
||||
|
||||
|
||||
class FusedRecurrentFunction(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
beta: torch.Tensor,
|
||||
scale: float,
|
||||
initial_state: torch.Tensor,
|
||||
inplace_final_state: bool = True,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
ssm_state_indices: torch.Tensor | None = None,
|
||||
num_accepted_tokens: torch.Tensor | None = None,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
):
|
||||
o, final_state = fused_recurrent_gated_delta_rule_fwd(
|
||||
q=q.contiguous(),
|
||||
k=k.contiguous(),
|
||||
v=v.contiguous(),
|
||||
g=g.contiguous(),
|
||||
beta=beta.contiguous(),
|
||||
scale=scale,
|
||||
initial_state=initial_state,
|
||||
inplace_final_state=inplace_final_state,
|
||||
cu_seqlens=cu_seqlens,
|
||||
ssm_state_indices=ssm_state_indices,
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
|
||||
)
|
||||
|
||||
return o, final_state
|
||||
|
||||
|
||||
def fused_recurrent_gated_delta_rule(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
beta: torch.Tensor = None,
|
||||
scale: float = None,
|
||||
initial_state: torch.Tensor = None,
|
||||
inplace_final_state: bool = True,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
ssm_state_indices: torch.Tensor | None = None,
|
||||
num_accepted_tokens: torch.Tensor | None = None,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
r"""
|
||||
Args:
|
||||
q (torch.Tensor):
|
||||
queries of shape `[B, T, H, K]`.
|
||||
k (torch.Tensor):
|
||||
keys of shape `[B, T, H, K]`.
|
||||
v (torch.Tensor):
|
||||
values of shape `[B, T, HV, V]`.
|
||||
GVA is applied if `HV > H`.
|
||||
g (torch.Tensor):
|
||||
g (decays) of shape `[B, T, HV]`.
|
||||
beta (torch.Tensor):
|
||||
betas of shape `[B, T, HV]`.
|
||||
scale (Optional[int]):
|
||||
Scale factor for the RetNet attention scores.
|
||||
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
||||
initial_state (Optional[torch.Tensor]):
|
||||
Initial state of shape `[N, HV, V, K]` for `N` input sequences.
|
||||
For equal-length input sequences, `N` equals the batch size `B`.
|
||||
Default: `None`.
|
||||
inplace_final_state: bool:
|
||||
Whether to store the final state in-place to save memory.
|
||||
Default: `True`.
|
||||
cu_seqlens (torch.Tensor):
|
||||
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
||||
consistent with the FlashAttention API.
|
||||
ssm_state_indices (Optional[torch.Tensor]):
|
||||
Indices to map the input sequences to the initial/final states.
|
||||
num_accepted_tokens (Optional[torch.Tensor]):
|
||||
Number of accepted tokens for each sequence during decoding.
|
||||
|
||||
Returns:
|
||||
o (torch.Tensor):
|
||||
Outputs of shape `[B, T, HV, V]`.
|
||||
final_state (torch.Tensor):
|
||||
Final state of shape `[N, HV, V, K]`.
|
||||
|
||||
Examples::
|
||||
>>> import torch
|
||||
>>> import torch.nn.functional as F
|
||||
>>> from einops import rearrange
|
||||
>>> from fla.ops.gated_delta_rule import fused_recurrent_gated_delta_rule
|
||||
# inputs with equal lengths
|
||||
>>> B, T, H, HV, K, V = 4, 2048, 4, 8, 512, 512
|
||||
>>> q = torch.randn(B, T, H, K, device='cuda')
|
||||
>>> k = F.normalize(torch.randn(B, T, H, K, device='cuda'), p=2, dim=-1)
|
||||
>>> v = torch.randn(B, T, HV, V, device='cuda')
|
||||
>>> g = F.logsigmoid(torch.rand(B, T, HV, device='cuda'))
|
||||
>>> beta = torch.rand(B, T, HV, device='cuda').sigmoid()
|
||||
>>> h0 = torch.randn(B, HV, V, K, device='cuda')
|
||||
>>> o, ht = fused_gated_recurrent_delta_rule(
|
||||
q, k, v, g, beta,
|
||||
initial_state=h0,
|
||||
)
|
||||
# for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
|
||||
>>> q, k, v, g, beta = map(lambda x: rearrange(x, 'b t ... -> 1 (b t) ...'), (q, k, v, g, beta))
|
||||
# for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
|
||||
>>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.int32)
|
||||
>>> o_var, ht_var = fused_gated_recurrent_delta_rule(
|
||||
q, k, v, g, beta,
|
||||
initial_state=h0,
|
||||
cu_seqlens=cu_seqlens
|
||||
)
|
||||
"""
|
||||
if cu_seqlens is not None and q.shape[0] != 1:
|
||||
raise ValueError(
|
||||
f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
|
||||
f"Please flatten variable-length inputs before processing."
|
||||
)
|
||||
if scale is None:
|
||||
scale = k.shape[-1] ** -0.5
|
||||
else:
|
||||
assert scale > 0, "scale must be positive"
|
||||
if beta is None:
|
||||
beta = torch.ones_like(q[..., 0])
|
||||
o, final_state = FusedRecurrentFunction.apply(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
g,
|
||||
beta,
|
||||
scale,
|
||||
initial_state,
|
||||
inplace_final_state,
|
||||
cu_seqlens,
|
||||
ssm_state_indices,
|
||||
num_accepted_tokens,
|
||||
use_qk_l2norm_in_kernel,
|
||||
)
|
||||
return o, final_state
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user