KLM-1.6-Chat / fast_decode.py
Eclipse-Senpai's picture
KLM 1.6-Chat
ec8e64b
Raw History Blame Contribute Delete
29.9 kB
"""Fast batched generation for KLM on NVIDIA GPUs (KLMForCausalLM.fast_generate).
Prompts prefill in batches through the model's own forward; replies then decode in fixed slots, eight tokens of every
slot per CUDA-graph replay with sampling on the GPU, and a slot is refilled as soon as its reply ends. The one-token
step is the model's math under bf16 autocast fused into the Triton kernels below: weights cast once, projections that
share an input as one GEMM, attention over each row's own cells (flash-decoding), and the Gated DeltaNet-2 recurrence,
norms and residual mixing in fp32. With flash-linear-attention installed, long prompts prefill through its chunked
GDN-2 kernel instead of the token-by-token recurrence.
"""
from __future__ import annotations
import math
import sys
import time
from contextlib import contextmanager
import torch
import torch.nn.functional as F
try:
import triton
import triton.language as tl
from triton.language.extra import libdevice
except ImportError as e:
raise ImportError("fast_generate needs Triton, which ships with PyTorch's CUDA builds on Linux") from e
try:
from fla.ops.gdn2 import chunk_gdn2
except ImportError:
chunk_gdn2 = None
VOCAB = 4100 # real tokenizer ids; the model's 4,160 rows are padded
@triton.jit
def mix_kernel(normed, values, query, partial, weight, out, n, cap, eps,
D: tl.constexpr, NP: tl.constexpr, PARTIAL: tl.constexpr, NORM: tl.constexpr):
"""Block AttnRes consumer: softmax(query . normed sources) over the first n sources (plus the current layer's
mixer output `partial`), weighted sum of the sources, then (NORM) RMSNorm with `weight`. One program per row."""
b = tl.program_id(0)
i = tl.arange(0, NP)
d = tl.arange(0, D)
rows = b * cap * D + i[:, None] * D + d[None, :]
live = i[:, None] < n
q = tl.load(query + d)
logit = tl.sum(tl.load(normed + rows, mask=live, other=0.0) * q[None, :], 1)
logit = tl.where(i < n, logit, float("-inf"))
top = tl.max(logit, 0)
p = tl.zeros([D], tl.float32)
p_logit = 0.0
e_p = 0.0
if PARTIAL:
p = tl.load(partial + b * D + d).to(tl.float32)
p_logit = tl.sum(p * tl.rsqrt(tl.sum(p * p, 0) / D + eps) * q, 0)
top = tl.maximum(top, p_logit)
e = tl.exp(logit - top)
total = tl.sum(e, 0)
if PARTIAL:
e_p = tl.exp(p_logit - top)
total += e_p
x = tl.sum(tl.load(values + rows, mask=live, other=0.0) * (e / total)[:, None], 0)
if PARTIAL:
x += (e_p / total) * p
if NORM:
x = x * tl.rsqrt(tl.sum(x * x, 0) / D + eps) * tl.load(weight + d)
tl.store(out + b * D + d, x.to(out.dtype.element_ty))
@triton.jit
def add_kernel(a, b_in, values, normed, slot, cap, eps, D: tl.constexpr, TWO: tl.constexpr, ROUND: tl.constexpr):
"""A new Block AttnRes source: a (+ b_in, rounded to a's dtype as the model adds them) stored and RMS-normalized."""
r = tl.program_id(0)
d = tl.arange(0, D)
x = tl.load(a + r * D + d).to(tl.float32)
if TWO:
x += tl.load(b_in + r * D + d).to(tl.float32)
if ROUND:
x = x.to(a.dtype.element_ty).to(tl.float32)
at = r * cap * D + slot * D + d
tl.store(values + at, x)
tl.store(normed + at, x * tl.rsqrt(tl.sum(x * x, 0) / D + eps))
@triton.jit
def _conv(proj, windows, conv_w, c, own, j: tl.constexpr, INNER: tl.constexpr):
"""Short conv + SiLU of projection j over its window (oldest first); the window then shifts in the new input."""
p = tl.load(proj + j * INNER + c)
w = windows + j * 3 * INNER + c
r0, r1, r2 = tl.load(w), tl.load(w + INNER), tl.load(w + 2 * INNER)
cw = conv_w + (j * INNER + c) * 4
x = (tl.where(own >= 3, r0.to(tl.float32) * tl.load(cw), 0.0)
+ tl.where(own >= 2, r1.to(tl.float32) * tl.load(cw + 1), 0.0)
+ tl.where(own >= 1, r2.to(tl.float32) * tl.load(cw + 2), 0.0) + p.to(tl.float32) * tl.load(cw + 3))
tl.debug_barrier()
tl.store(w, r1)
tl.store(w + INNER, r2)
tl.store(w + 2 * INNER, p)
return x * tl.sigmoid(x)
@triton.jit
def gdn_kernel(proj, pstride, fg, windows, conv_w, state, dt_bias, a_log, o_weight, out, pos, start,
floor, ceiling, o_eps, H: tl.constexpr, K: tl.constexpr, INNER: tl.constexpr):
"""One Gated DeltaNet-2 token for row b, head h: short convs (q, k, v; window update), SiLU, L2 norms, the
floored decay, erase/write gates, the fp32 state update S <- (I - k (b*k)^T) diag(exp g) S + k (w*v)^T, the
readout q^T S / sqrt(K), its RMSNorm and sigmoid output gate. proj holds [q | k | v | b | w | ...] pre-conv
projections, fg the decay input f and the output gate."""
b = tl.program_id(0)
h = tl.program_id(1)
own = tl.load(pos + b) - tl.load(start + b)
c = h * K + tl.arange(0, K)
q = _conv(proj + b * pstride, windows + b * 3 * 3 * INNER, conv_w, c, own, 0, INNER)
k = _conv(proj + b * pstride, windows + b * 3 * 3 * INNER, conv_w, c, own, 1, INNER)
v = _conv(proj + b * pstride, windows + b * 3 * 3 * INNER, conv_w, c, own, 2, INNER)
q = q * tl.rsqrt(tl.sum(q * q, 0) + 1e-6) * (K ** -0.5)
k = k * tl.rsqrt(tl.sum(k * k, 0) + 1e-6)
s = tl.load(fg + b * 2 * INNER + c).to(tl.float32) + tl.load(dt_bias + c)
soft = tl.where(s > 20.0, s, libdevice.log1p(tl.exp(tl.minimum(s, 20.0)))) # softplus, torch's threshold
log_act = tl.where(s < -20.0, s, tl.log(tl.where(s < -20.0, 1.0, soft)))
log_mag = tl.load(a_log + h) + log_act
g = tl.where(log_mag >= ceiling, floor, -tl.exp(tl.minimum(log_mag, ceiling)))
erase_gate = tl.sigmoid(tl.load(proj + b * pstride + 3 * INNER + c).to(tl.float32))
write_gate = tl.sigmoid(tl.load(proj + b * pstride + 4 * INNER + c).to(tl.float32))
kk = tl.arange(0, K)
tile = state + (b * H + h) * K * K + kk[:, None] * K + kk[None, :]
S = tl.load(tile) * tl.exp(g)[:, None]
erase = tl.sum((erase_gate * k)[:, None] * S, 0)
S += k[:, None] * (write_gate * v - erase)[None, :]
tl.store(tile, S)
o = tl.sum(q[:, None] * S, 0)
o = o * tl.rsqrt(tl.sum(o * o, 0) / K + o_eps) * tl.load(o_weight + kk)
gate = tl.load(fg + b * 2 * INNER + INNER + c).to(tl.float32)
tl.store(out + b * INNER + c, (o * tl.sigmoid(gate)).to(out.dtype.element_ty))
@triton.jit
def attn_prep_kernel(proj, pstride, q_w, k_w, freqs, rope_scale, value_mix, v_first, pos, keys, values, q_out,
ctx, eps, FIRST: tl.constexpr, H: tl.constexpr, KVH: tl.constexpr, HD: tl.constexpr):
"""QK RMSNorm, (YaRN) RoPE at the row's position, the value residual mix with the first attention layer's
values, and the new key and value written into the row's cache cell. proj holds [q | k | v | gate]."""
b = tl.program_id(0)
at = tl.load(pos + b)
half = tl.arange(0, HD // 2)
angle = at.to(tl.float32) * tl.load(freqs + half)
cos, sin = tl.cos(angle) * rope_scale, tl.sin(angle) * rope_scale
hq = tl.arange(0, H)
base = proj + b * pstride + hq[:, None] * HD + half[None, :]
x1, x2 = tl.load(base).to(tl.float32), tl.load(base + HD // 2).to(tl.float32)
r = tl.rsqrt((tl.sum(x1 * x1, 1) + tl.sum(x2 * x2, 1)) / HD + eps)[:, None]
x1, x2 = x1 * r * tl.load(q_w + half)[None, :], x2 * r * tl.load(q_w + HD // 2 + half)[None, :]
qo = q_out + b * H * HD + hq[:, None] * HD + half[None, :]
tl.store(qo, x1 * cos[None, :] - x2 * sin[None, :])
tl.store(qo + HD // 2, x2 * cos[None, :] + x1 * sin[None, :])
hk = tl.arange(0, KVH)
base = proj + b * pstride + H * HD + hk[:, None] * HD + half[None, :]
x1, x2 = tl.load(base).to(tl.float32), tl.load(base + HD // 2).to(tl.float32)
r = tl.rsqrt((tl.sum(x1 * x1, 1) + tl.sum(x2 * x2, 1)) / HD + eps)[:, None]
x1, x2 = x1 * r * tl.load(k_w + half)[None, :], x2 * r * tl.load(k_w + HD // 2 + half)[None, :]
cell = ((b * KVH + hk[:, None]) * ctx + at) * HD + half[None, :]
tl.store(keys + cell, (x1 * cos[None, :] - x2 * sin[None, :]).to(keys.dtype.element_ty))
tl.store(keys + cell + HD // 2, (x2 * cos[None, :] + x1 * sin[None, :]).to(keys.dtype.element_ty))
d = tl.arange(0, HD)
v = proj + b * pstride + (H + KVH) * HD + hk[:, None] * HD + d[None, :]
first = v_first + b * KVH * HD + hk[:, None] * HD + d[None, :]
raw = tl.load(v)
if FIRST:
tl.store(first, raw)
base_v = raw.to(tl.float32)
else:
base_v = tl.load(first).to(tl.float32)
mixed = tl.load(value_mix) * raw.to(tl.float32) + tl.load(value_mix + 1) * base_v
cell = ((b * KVH + hk[:, None]) * ctx + at) * HD + d[None, :]
tl.store(values + cell, mixed.to(values.dtype.element_ty))
@triton.jit
def attn_split_kernel(q, keys, values, start, pos, m_out, l_out, acc_out, ctx, nsplit, scale,
SPLIT: tl.constexpr, BLOCK: tl.constexpr, G: tl.constexpr, KVH: tl.constexpr,
HD: tl.constexpr):
"""Flash-decoding partials: one row's cells [start, pos] in SPLIT-cell pieces, the G query heads of a KV head
at once; a piece outside the row's range is left empty (m = -inf, l = 0)."""
row = tl.program_id(0)
s = tl.program_id(1)
b, kvh = row // KVH, row % KVH
lo = tl.maximum(tl.load(start + b), s * SPLIT)
hi = tl.minimum(tl.load(pos + b) + 1, (s + 1) * SPLIT)
g = tl.arange(0, G)
d = tl.arange(0, HD)
qv = tl.load(q + (b * KVH * G + kvh * G + g)[:, None] * HD + d[None, :])
m = tl.full([G], float("-inf"), tl.float32)
l = tl.zeros([G], tl.float32)
acc = tl.zeros([G, HD], tl.float32)
base = (b * KVH + kvh) * ctx * HD
for c0 in range(lo, hi, BLOCK):
cells = c0 + tl.arange(0, BLOCK)
live = cells < hi
at = base + cells[:, None] * HD + d[None, :]
k = tl.load(keys + at, mask=live[:, None], other=0.0).to(tl.float32)
sc = tl.sum(qv[:, None, :] * k[None, :, :], 2) * scale
sc = tl.where(live[None, :], sc, float("-inf"))
m_new = tl.maximum(m, tl.max(sc, 1))
p = tl.exp(sc - m_new[:, None])
alpha = tl.exp(m - m_new)
v = tl.load(values + at, mask=live[:, None], other=0.0).to(tl.float32)
acc = acc * alpha[:, None] + tl.sum(p[:, :, None] * v[None, :, :], 1)
l = l * alpha + tl.sum(p, 1)
m = m_new
at = (row * nsplit + s) * G + g
tl.store(m_out + at, m)
tl.store(l_out + at, l)
tl.store(acc_out + at[:, None] * HD + d[None, :], acc)
@triton.jit
def attn_combine_kernel(m_in, l_in, acc_in, proj, pstride, out, nsplit, GATE: tl.constexpr, G: tl.constexpr,
KVH: tl.constexpr, HD: tl.constexpr, NS: tl.constexpr):
"""Merge the partials of one row and query head, then apply the sigmoid output gate."""
b = tl.program_id(0)
h = tl.program_id(1)
sp = tl.arange(0, NS)
live = sp < nsplit
at = ((b * KVH + h // G) * nsplit + sp) * G + h % G
m = tl.load(m_in + at, mask=live, other=float("-inf"))
top = tl.max(m, 0)
w = tl.where(m > float("-inf"), tl.exp(m - top), 0.0)
total = tl.sum(tl.load(l_in + at, mask=live, other=0.0) * w, 0)
d = tl.arange(0, HD)
acc = tl.load(acc_in + at[:, None] * HD + d[None, :], mask=live[:, None], other=0.0)
o = tl.sum(acc * w[:, None], 0) / total
gate = tl.load(proj + b * pstride + GATE + h * HD + d).to(tl.float32)
tl.store(out + b * G * KVH * HD + h * HD + d, (o * tl.sigmoid(gate)).to(out.dtype.element_ty))
def chunked_recurrence(loop):
"""fla's chunk_gdn2 in place of the model's step-by-step GDN-2 recurrence for a prefill. Only what follows a row's
last document start matters (a left-padded prompt): before it the gates and decay are zeroed, which holds the
state at zero, exactly the reset the start would make. A cached state with a start inside keeps the loop."""
def recurrence(q, k, v, g, b, w, starts, state):
inner = starts[:, 1:].any()
if not q.is_cuda or (inner and state is not None):
return loop(q, k, v, g, b, w, starts, state)
if inner:
idx = torch.arange(starts.shape[1], device=starts.device)
last = torch.where(starts, idx, 0).max(1).values
keep = (idx[None] >= last[:, None]).to(g.dtype)[..., None, None]
g, b, w = g * keep, b * keep, w * keep
elif state is not None:
state = state * (~starts[:, 0]).float().view(-1, 1, 1, 1)
with torch.autocast(q.device.type, enabled=False):
return chunk_gdn2(q=q.contiguous(), k=k.contiguous(), v=v.contiguous(), g=g.contiguous(),
b=b.contiguous(), w=w.contiguous(), initial_state=state, output_final_state=True)
return recurrence
def fused_mix(model_mix, kern):
"""The fused Block AttnRes mix for CUDA prefills: the model's own mix materializes (tokens, sources, dim) products."""
def mix(self, query, partial=None):
if not self.values.is_cuda:
return model_mix(self, query, partial)
batch, seq_len, cap, dim = self.values.shape
out = torch.empty(batch, seq_len, dim, device=self.values.device, dtype=self.values.dtype)
part = partial.contiguous() if partial is not None else out
kern.mix_kernel[(batch * seq_len,)](self.normed, self.values, query.contiguous(), part, query, out, self.n, cap,
self.eps, D=dim, NP=1 << (cap - 1).bit_length(), PARTIAL=partial is not None,
NORM=False, num_warps=8)
return out
return mix
class FastDecoder:
def __init__(self, model, slots: int, dtype: torch.dtype = torch.bfloat16, chunk: int = 8, split: int = 256):
self.k = sys.modules[__name__]
self.model, self.m, self.cfg = model, model.model, model.config
self.mod = sys.modules[type(model.model).__module__]
cfg, m, dev = self.cfg, self.m, model.device
self.slots, self.dtype, self.chunk, self.split = slots, dtype, chunk, split
self.refill = max(1, slots // 8)
self.ctx, self.dim, self.eps = cfg.max_position_embeddings, cfg.hidden_size, cfg.rms_norm_eps
b, n, dim = slots, self.ctx, self.dim
self.cap = cfg.num_hidden_layers + 2
self.nsplit = -(-n // split)
cast = lambda *ws: torch.cat([w.detach() for w in ws]).to(dtype).contiguous() # noqa: E731
f32 = lambda w: w.detach().float().contiguous() # noqa: E731
self.layers = []
for block in m.blocks:
a, ffn = block.mixer, block.ffn
L = {"attn": block.is_attention, "mixer_norm": f32(block.mixer_norm.weight),
"ffn_norm": f32(block.ffn_norm.weight), "up": cast(ffn.gate.weight, ffn.up.weight),
"down": cast(ffn.down.weight), "o": cast(a.o_proj.weight)}
if block.is_attention:
self.heads, self.kv_heads, self.head_dim = a.n_heads, a.n_kv_heads, a.head_dim
L.update(proj=cast(a.q_proj.weight, a.k_proj.weight, a.v_proj.weight, a.gate_proj.weight),
q_norm=f32(a.q_norm.weight), k_norm=f32(a.k_norm.weight), mix=f32(a.value_mix),
keys=torch.zeros(b, a.n_kv_heads, n, a.head_dim, device=dev, dtype=dtype),
values=torch.zeros(b, a.n_kv_heads, n, a.head_dim, device=dev, dtype=dtype))
self.freqs, self.rope_scale = a.freqs.to(dev).float(), float(a.rope_scale)
else:
self.gdn_heads, self.gdn_dim, inner = a.heads, a.head_dim, a.heads * a.head_dim
f2, g2 = a.f_proj[1].weight, a.g_proj[1].weight
fg = torch.zeros(2 * inner, 2 * a.head_dim, device=dev)
fg[:inner, :a.head_dim], fg[inner:, a.head_dim:] = f2, g2
L.update(proj=cast(a.q_proj.weight, a.k_proj.weight, a.v_proj.weight, a.b_proj.weight, a.w_proj.weight,
a.f_proj[0].weight, a.g_proj[0].weight),
fg=fg.to(dtype), fg_bias=torch.cat([torch.zeros(inner, device=dev), a.g_proj[1].bias.detach()]).to(dtype),
conv=torch.stack([f32(c.weight.view(inner, -1)) for c in (a.q_conv1d, a.k_conv1d, a.v_conv1d)]),
dt_bias=f32(a.dt_bias), a_log=f32(a.A_log), o_norm=f32(a.o_norm.weight),
o_eps=a.o_norm.eps, floor=float(a.decay_floor), ceiling=math.log(-a.decay_floor),
state=torch.zeros(b, a.heads, a.head_dim, a.head_dim, device=dev),
windows=torch.zeros(b, 3, self.mod.CONV - 1, inner, device=dev, dtype=dtype))
self.layers.append(L)
mem = m.memory
self.queries = f32(m.attn_res_query * m.attn_res_norm)
self.final_norm = f32(m.norm.weight)
self.embed = f32(m.embed.weight)
self.head = m.embed.weight.detach().to(dtype).contiguous()
self.ngram_proj = torch.cat([mem.bigram_proj.weight, mem.trigram_proj.weight], 1).detach().to(dtype).contiguous()
self.values = torch.zeros(b, self.cap, dim, device=dev)
self.normed = torch.zeros(b, self.cap, dim, device=dev)
self.q = torch.zeros(b, self.heads, self.head_dim, device=dev)
self.v_first = torch.zeros(b, self.kv_heads, self.head_dim, device=dev, dtype=dtype)
self.part_m = torch.zeros(b * self.kv_heads * self.nsplit * 2, device=dev)
self.part_l = torch.zeros_like(self.part_m)
self.part_acc = torch.zeros(self.part_m.numel(), self.head_dim, device=dev)
self.history = torch.zeros(b, 2, dtype=torch.long, device=dev)
self.token = torch.zeros(b, dtype=torch.long, device=dev)
self.pos = torch.zeros(b, dtype=torch.long, device=dev)
self.start = torch.zeros(b, dtype=torch.long, device=dev) # a left-padded prompt's first real position
self.out = torch.zeros(b, chunk, dtype=torch.long, device=dev)
self.temperature = torch.ones((), device=dev)
self.top_p = torch.ones((), device=dev)
self.graphs: dict[bool, torch.cuda.CUDAGraph] = {}
def mix(self, i: int, n: int, weight, partial=None, out_dtype=None):
out = torch.empty(self.slots, self.dim, device=self.values.device, dtype=out_dtype or self.dtype)
self.k.mix_kernel[(self.slots,)](self.normed, self.values, self.queries[i], partial if partial is not None else out,
weight, out, n, self.cap, self.eps, D=self.dim, NP=32,
PARTIAL=partial is not None, NORM=True, num_warps=8)
return out
def add(self, slot: int, a, b=None, round_sum: bool = False):
self.k.add_kernel[(self.slots,)](a, b if b is not None else a, self.values, self.normed, slot, self.cap, self.eps,
D=self.dim, TWO=b is not None, ROUND=round_sum, num_warps=4)
def step(self, greedy: bool) -> torch.Tensor:
"""One token for every slot: write its KV and state, sample the next token, advance the position."""
k, b, mem = self.k, self.slots, self.m.memory
tok, v = self.token, self.cfg.vocab_size
own = self.pos - self.start
prev1 = torch.where(own >= 1, self.history[:, 1], 0)
prev2 = torch.where(own >= 2, self.history[:, 0], 0)
rows = torch.cat([mem.bigram.weight[self.mod.lookup(mem.bigram_keys, prev1 * v + tok)],
mem.trigram.weight[self.mod.lookup(mem.trigram_keys, (prev2 * v + prev1) * v + tok)]], 1)
self.add(0, self.embed[tok])
self.add(1, F.linear(rows.to(self.dtype), self.ngram_proj))
first = True
for i, L in enumerate(self.layers):
h = self.mix(2 * i, 2 + i, L["mixer_norm"])
proj = F.linear(h, L["proj"])
out = torch.empty(b, self.dim, device=h.device, dtype=self.dtype)
if L["attn"]:
k.attn_prep_kernel[(b,)](proj, proj.stride(0), L["q_norm"], L["k_norm"], self.freqs, self.rope_scale,
L["mix"], self.v_first, self.pos, L["keys"], L["values"], self.q, self.ctx,
self.eps, FIRST=first, H=self.heads, KVH=self.kv_heads, HD=self.head_dim)
first = False
k.attn_split_kernel[(b * self.kv_heads, self.nsplit)](
self.q, L["keys"], L["values"], self.start, self.pos, self.part_m, self.part_l, self.part_acc,
self.ctx, self.nsplit, self.head_dim ** -0.5, SPLIT=self.split, BLOCK=64,
G=self.heads // self.kv_heads, KVH=self.kv_heads, HD=self.head_dim, num_warps=2)
k.attn_combine_kernel[(b, self.heads)](
self.part_m, self.part_l, self.part_acc, proj, proj.stride(0), out, self.nsplit,
GATE=(self.heads + 2 * self.kv_heads) * self.head_dim, G=self.heads // self.kv_heads,
KVH=self.kv_heads, HD=self.head_dim, NS=max(2, 1 << (self.nsplit - 1).bit_length()))
else:
inner = self.gdn_heads * self.gdn_dim
fg = F.linear(proj[:, 5 * inner:], L["fg"], L["fg_bias"])
k.gdn_kernel[(b, self.gdn_heads)](
proj, proj.stride(0), fg, L["windows"], L["conv"], L["state"], L["dt_bias"], L["a_log"],
L["o_norm"], out, self.pos, self.start, L["floor"], L["ceiling"],
L["o_eps"], H=self.gdn_heads, K=self.gdn_dim, INNER=inner, num_warps=4)
mixed = F.linear(out, L["o"])
up = F.linear(self.mix(2 * i + 1, 2 + i, L["ffn_norm"], mixed), L["up"])
half = up.shape[1] // 2
self.add(2 + i, mixed, F.linear(F.silu(up[:, :half]) * up[:, half:], L["down"]), round_sum=True)
x = self.mix(len(self.queries) - 1, self.cap, self.final_norm)
logits = F.linear(x, self.head).float()
logits[:, VOCAB:] = -float("inf")
nxt = logits.argmax(-1) if greedy else self.sample(logits, self.temperature, self.top_p)
self.history.copy_(torch.stack([self.history[:, 1], tok], 1))
self.token.copy_(nxt)
self.pos.copy_((self.pos + 1).clamp_(max=self.ctx - 1))
return nxt
@staticmethod
def sample(logits: torch.Tensor, temperature, top_p) -> torch.Tensor:
"""Nucleus sampling by an exponential race over the kept probabilities (no host sync, graph-safe RNG)."""
probs = (logits / temperature).softmax(-1)
sorted_p, idx = probs.sort(-1, descending=True)
sorted_p = sorted_p.masked_fill((sorted_p.cumsum(-1) - sorted_p) > top_p, 0)
race = sorted_p / torch.empty_like(sorted_p).exponential_()
return idx.gather(1, race.argmax(-1, keepdim=True))[:, 0]
def graph(self, greedy: bool) -> torch.cuda.CUDAGraph:
"""The chunk graph, captured on first use; its warm-up steps overwrite every slot, so only between sessions."""
if greedy not in self.graphs:
stream = torch.cuda.Stream()
stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(stream), torch.no_grad():
for _ in range(2):
self.step(greedy)
torch.cuda.current_stream().wait_stream(stream)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph), torch.no_grad():
for j in range(self.chunk):
self.out[:, j] = self.step(greedy)
self.graphs[greedy] = graph
return self.graphs[greedy]
@contextmanager
def prefill_kernels(self):
"""For the prefill only: fla's chunk_gdn2 for the token-by-token recurrence (when installed) and the fused
Block AttnRes mix; the model's own forward is restored afterwards."""
mod = self.mod
saved = mod.recurrence, mod.AttnResSources.mix
if chunk_gdn2 is not None:
mod.recurrence = chunked_recurrence(saved[0])
mod.AttnResSources.mix = fused_mix(saved[1], self.k)
try:
yield
finally:
mod.recurrence, mod.AttnResSources.mix = saved
def load(self, slot: int, cache, row: int = 0, start: int = 0) -> None:
"""Copy row `row` of a KLMCache (a prefilled prompt, left-padded to its first real position `start`) into
`slot`; the padding stays outside the slot's visible cells."""
for i, L in enumerate(self.layers):
ca, cb = cache.layers[i]
if L["attn"]:
L["keys"][slot, :, :ca.shape[2]].copy_(ca[row])
L["values"][slot, :, :cb.shape[2]].copy_(cb[row])
else:
L["state"][slot].copy_(ca[row])
for j, w in enumerate(cb):
L["windows"][slot, j].copy_(w[row])
hist = cache.history[row, -2:]
self.history[slot].copy_(torch.cat([hist.new_zeros(2 - hist.numel()), hist]))
self.start[slot] = start
@torch.no_grad()
def generate(self, prompts: list[list[int]], max_new: int, stop: tuple[int, ...], temperature: float = 0.0,
top_p: float = 1.0, seed: int = 0, **prefill) -> list[list[int]]:
"""Each prompt's reply tokens, ending with the stop token when one came; prompt + reply never exceeds the
context. Greedy at temperature 0, else nucleus sampling with a seeded generator."""
self.reset(stop, temperature, top_p, seed, **prefill)
for i, p in enumerate(prompts):
self.submit(i, p, max_new)
out: list[list[int]] = [[] for _ in prompts]
while self.busy():
for i, ids in self.advance():
out[i] = ids
return out
def reset(self, stop: tuple[int, ...], temperature: float = 0.0, top_p: float = 1.0, seed: int = 0,
prefill_tokens: int = 1 << 16, prefill_cells: int = 1 << 28) -> None:
"""Start a decoding session: replies are submitted at any time and come back as each ends (`advance`), so a
long reply holds only its own slot (a multi-turn caller need not wait for its slowest conversation). At most
`prefill_tokens` tokens and `prefill_cells` attention cells per prefill batch: the prefill attention is dense."""
torch.cuda.manual_seed(seed)
self.timing = {"prefill_s": 0.0, "decode_s": 0.0, "steps": 0}
self.temperature.fill_(max(temperature, 1e-6))
self.top_p.fill_(top_p)
self.stop, self.greedy = stop, temperature == 0
self.graph(self.greedy)
self.prefill_tokens, self.prefill_cells = prefill_tokens, prefill_cells
self.pending: list[tuple] = []
self.ended: list[tuple] = []
self.owner: list = [None] * self.slots # (key, reply tokens, budget) per busy slot
def submit(self, key, prompt: list[int], max_new: int) -> None:
if len(prompt) >= self.ctx:
self.ended.append((key, []))
else:
self.pending.append((key, prompt, max_new))
def busy(self) -> bool:
return bool(self.pending or self.ended or any(o is not None for o in self.owner))
@torch.no_grad()
def advance(self) -> list[tuple]:
"""Fill free slots (shortest pending prompts first, prefilled together, left-padded with <eos>), run one
decode chunk; the (key, reply tokens) of every reply that ended."""
free = [s for s in range(self.slots) if self.owner[s] is None]
live = self.slots - len(free)
# a prefill costs about as much for one prompt as for many, so wait for a batch of free slots
if self.pending and len(free) >= min(self.refill, len(self.pending)) or not live and self.pending:
t0 = time.monotonic()
self.pending.sort(key=lambda p: len(p[1]))
group: list[tuple] = []
while self.pending and len(group) < len(free):
width = len(self.pending[0][1])
n = len(group) + 1
if group and (n * width > self.prefill_tokens or n * width * width > self.prefill_cells):
break
group.append(self.pending.pop(0))
width = len(group[-1][1])
x = torch.tensor([[2] * (width - len(p)) + p for _, p, _ in group], device="cuda")
with torch.autocast("cuda", dtype=self.dtype, enabled=self.dtype != torch.float32), self.prefill_kernels():
step = self.model(x, use_cache=True)
logits = step.logits[:, -1].float()
logits[:, VOCAB:] = -float("inf")
firsts = (logits.argmax(-1) if self.greedy else self.sample(logits, self.temperature, self.top_p)).tolist()
for row, (key, prompt, max_new) in enumerate(group):
budget = min(max_new, self.ctx - width)
if firsts[row] in self.stop or budget <= 1:
self.ended.append((key, [firsts[row]]))
continue
slot = free.pop(0)
self.load(slot, step.past_key_values, row, width - len(prompt))
self.token[slot], self.pos[slot] = firsts[row], width
self.owner[slot] = (key, [firsts[row]], budget)
del step
torch.cuda.synchronize()
self.timing["prefill_s"] += time.monotonic() - t0
if any(o is not None for o in self.owner):
t0 = time.monotonic()
self.graph(self.greedy).replay()
chunk = self.out.tolist()
self.timing["decode_s"] += time.monotonic() - t0
self.timing["steps"] += self.chunk
for s, o in enumerate(self.owner):
if o is None:
continue
key, out, budget = o
for t in chunk[s]:
out.append(t)
if t in self.stop or len(out) >= budget:
self.ended.append((key, out))
self.owner[s] = None
break
ended, self.ended = self.ended, []
return ended