Token Classification
MLX
Safetensors
qwen3_5
AI-Detector-0.8B / gpu /worker.py
matthewagi's picture matt's picture
Initial model release
7acaf56
Raw History Blame Contribute Delete
13.3 kB
"""Dense 0.8B stateless Repeat2 prefill on Hopper using vLLM kernels."""
from types import SimpleNamespace
import numpy as np
import torch
from torch.nn import functional as F
from safetensors import safe_open
from vllm import _custom_ops as ops
from vllm.vllm_flash_attn import flash_attn_varlen_func
from flashinfer.gdn_prefill import chunk_gated_delta_rule
from conv_prep_fused import _conv_prep
from vllm.triton_utils import triton, tl
BF = torch.bfloat16
FP8 = torch.float8_e4m3fn
@triton.jit
def _norm_gate_quant(X, Z, W, Out, Scale, Z_STRIDE: tl.constexpr, EPS: tl.constexpr):
row = tl.program_id(0)
head = tl.arange(0, 16)
dim = tl.arange(0, 128)
idx = row * 2048 + head[:, None] * 128 + dim[None, :]
x = tl.load(X + idx).to(tl.float32)
z = tl.load(Z + row * Z_STRIDE + head[:, None] * 128 + dim[None, :]).to(tl.float32)
y = x * tl.rsqrt(tl.sum(x * x, axis=1) / 128 + EPS)[:, None]
y = (y.to(tl.bfloat16) * tl.load(W + dim)[None, :]).to(tl.bfloat16)
y = (y * (z * tl.sigmoid(z))).to(tl.bfloat16).to(tl.float32)
scale = tl.maximum(tl.max(tl.max(tl.abs(y), axis=1), axis=0), 1e-10) / 448
tl.store(Out + idx, y / scale)
tl.store(Scale + row, scale)
@triton.jit
def _pool_chunks(
states, scores, starts, ends, pooled, WIDTH: tl.constexpr, TILE: tl.constexpr
):
chunk = tl.program_id(0)
tokens = tl.load(starts + chunk) + tl.arange(0, 64)
valid = tokens <= tl.load(ends + chunk)
features = tl.program_id(1) * TILE + tl.arange(0, TILE)
logits = tl.load(scores + tokens, mask=valid, other=-float("inf")).to(tl.float32)
weights = tl.softmax(logits)
values = tl.load(
states + tokens[:, None] * WIDTH + features[None, :],
mask=valid[:, None] & (features[None, :] < WIDTH),
other=0,
).to(tl.float32)
result = tl.sum(values * weights[:, None], axis=0)
tl.store(pooled + chunk * WIDTH + features, result, mask=features < WIDTH)
def packed_attention_pool(states, score_weight, starts, ends):
scores = F.linear(states, score_weight)
width = states.shape[1]
pooled = states.new_empty((len(starts), width))
_pool_chunks[(len(starts), triton.cdiv(width, 64))](
states, scores, starts, ends, pooled, width, 64
)
return pooled
def gpu(values, dtype=torch.long):
return torch.as_tensor(values, device="cuda", dtype=dtype)
class Matrix:
def __init__(self, weights):
w = torch.cat(weights).float()
self.scale = (w.abs().amax(1, keepdim=True) / 448).clamp_min_(1e-12)
self.weight = (w / self.scale).clamp_(-448, 448).to(FP8).T
def __call__(self, x, norm=None):
if isinstance(x, tuple):
act, scale = x
elif norm is None:
act, scale = ops.scaled_fp8_quant(
x.contiguous(), use_per_token_if_dynamic=True
)
else:
act, scale = ops.rms_norm_dynamic_per_token_quant(x, norm, 1e-6, FP8)
return ops.cutlass_scaled_mm(act, self.weight, scale, self.scale, BF)
def norm(x, weight):
out = torch.empty_like(x, memory_format=torch.contiguous_format)
ops.rms_norm(out, x.contiguous(), weight, 1e-6)
return out
class Block:
def __init__(self, w, recurrent, cross=False, donor=False):
self.pre = (w["input_layernorm.weight"].float() + 1).to(BF)
self.recurrent = recurrent
if not donor:
self.post = (w["post_attention_layernorm.weight"].float() + 1).to(BF)
self.up = Matrix([w["mlp.gate_proj.weight"], w["mlp.up_proj.weight"]])
self.down = Matrix([w["mlp.down_proj.weight"]])
if recurrent:
prefix = "linear_attn."
self.project = Matrix(
[w[prefix + "in_proj_" + n + ".weight"] for n in ("qkv", "z", "b", "a")]
)
self.out = Matrix([w[prefix + "out_proj.weight"]])
self.conv = w[prefix + "conv1d.weight"].reshape(6144, 4).contiguous()
self.alog = w[prefix + "A_log"]
self.dt = w[prefix + "dt_bias"]
self.gnorm = w[prefix + "norm.weight"]
else:
names = ["q_proj"] if cross else ["q_proj", "k_proj", "v_proj"]
self.project = Matrix([w["self_attn." + n + ".weight"] for n in names])
self.qnorm = (w["self_attn.q_norm.weight"].float() + 1).to(BF)
if not cross or donor:
self.knorm = (w["self_attn.k_norm.weight"].float() + 1).to(BF)
if donor:
self.kv = Matrix(
[w["self_attn." + n + ".weight"] for n in ("k_proj", "v_proj")]
)
self.out = Matrix([w["self_attn.o_proj.weight"]])
def mlp(self, x):
both = self.up(x, self.post)
act = torch.empty((len(x), both.shape[-1] // 2), dtype=BF, device=x.device)
torch.ops._C.silu_and_mul(act, both)
return x + self.down(act)
def gdn(self, x, layout):
total = len(x)
joined = self.project(x, self.pre)
mixed, z, b, a = joined.split([6144, 2048, 16, 16], dim=-1)
q, k, v = [
torch.empty((total, 16, 128), device=x.device, dtype=BF) for _ in range(3)
]
gate, beta = [
torch.empty((total, 16), device=x.device, dtype=torch.float32)
for _ in range(2)
]
_conv_prep[(len(layout.chunks) * 4, 32)](
mixed,
self.conv,
mixed,
layout.cu,
layout.chunks,
a,
b,
self.alog,
self.dt,
q,
k,
v,
gate,
beta,
*mixed.stride(),
*self.conv.stride(),
a.stride(0),
b.stride(0),
16,
16,
128,
4,
False,
True,
16,
num_warps=4,
num_stages=2,
enable_fp_fusion=False,
)
out = torch.empty_like(v)
chunk_gated_delta_rule(
q=q,
k=k,
v=v,
g=gate,
beta=beta,
initial_state=None,
output_final_state=False,
cu_seqlens=layout.cu64,
use_qk_l2norm_in_kernel=False,
output=out,
)
quant = torch.empty((total, 2048), device=x.device, dtype=FP8)
scale = torch.empty((total, 1), device=x.device, dtype=torch.float32)
_norm_gate_quant[(total,)](out, z, self.gnorm, quant, scale, z.stride(0), 1e-6)
return x + self.out((quant, scale))
def attention(self, x, layout, cache, windows=None):
proj = self.project(x, self.pre)
q, gate = proj[:, :4096].reshape(-1, 8, 512).chunk(2, -1)
q = norm(q, self.qnorm)
if windows is None:
k, v = proj[:, 4096:].reshape(-1, 4, 256).split(2, dim=1)
k = norm(k, self.knorm)
ops.rotary_embedding(layout.positions, q, k, 256, cache, True)
qcu, kcu, qmax, kmax = layout.cu, layout.cu, layout.maximum, layout.maximum
else:
ops.rotary_embedding(layout.positions, q, None, 256, cache, True)
k, v, qcu, kcu, qmax, kmax = windows
h = flash_attn_varlen_func(
q, k, v, qmax, qcu, kmax, kcu, causal=windows is None, fa_version=3
)
return x + self.out((h * gate.sigmoid()).reshape(len(x), -1))
class Worker:
def __init__(self, checkpoint):
from token_head import TokenHead
with safe_open(checkpoint, framework="pt") as f:
def get(name):
return f.get_tensor(name).to(device="cuda", dtype=BF)
self.embedding = get("embed_tokens.weight")
self.final = (get("norm.weight").float() + 1).to(BF)
self.blocks = []
for i in range(24):
prefix = f"layers.{i}."
weights = {
k[len(prefix) :]: get(k) for k in f.keys() if k.startswith(prefix)
}
self.blocks.append(Block(weights, i % 4 != 3, cross=i >= 12))
state = {
k: get(k)
for k in f.keys()
if k.startswith(("head.", "donor.", "attention_pool."))
}
self.donor = Block(
{
k[6:]: v.cuda().to(BF)
for k, v in state.items()
if k.startswith("donor.")
},
False,
cross=True,
donor=True,
)
self.pool = state["attention_pool.score.weight"]
self.head = TokenHead(1024, 64).cuda().to(BF)
self.head.load_state_dict(
{k[5:]: v for k, v in state.items() if k.startswith("head.")}
)
theta = gpu(np.arange(0, 64, 2), torch.float32) / 64
freq = torch.outer(
torch.arange(131072, device="cuda", dtype=torch.float32),
1 / (10000000**theta),
)
self.cache = torch.cat((freq.cos(), freq.sin()), dim=1).to(BF)
def __call__(self, ids, sizes, copies=2):
lengths = np.asarray(sizes)
chunk_sizes = (lengths + 63) // 64
offsets = np.r_[0, np.cumsum(lengths)]
chunk_offsets = np.r_[0, np.cumsum(chunk_sizes)]
chunk_rows = np.repeat(np.arange(len(lengths)), chunk_sizes)
starts = (np.arange(chunk_offsets[-1]) - chunk_offsets[chunk_rows]) * 64
ends = np.minimum(starts + 63, lengths[chunk_rows] - 1)
groups = np.flatnonzero(starts % 256 == 0)
center = starts[groups]
rows = chunk_rows[groups]
lo = np.maximum(center - 128, 0)
hi = np.minimum(center + 384, lengths[rows])
key_cu = np.r_[0, np.cumsum(hi - lo)]
original = lengths // copies
out_offsets = np.r_[0, np.cumsum(original)]
source = np.arange(out_offsets[-1]) + np.repeat(
offsets[:-1] + (copies - 1) * original - out_offsets[:-1], original
)
local = source - np.repeat(offsets[:-1], original)
decoder_tiles = (chunk_sizes + 63) // 64
tile_rows = np.repeat(np.arange(len(lengths)), decoder_tiles)
tile_pos = np.arange(len(tile_rows)) - np.repeat(
np.r_[0, decoder_tiles.cumsum()[:-1]], decoder_tiles
)
# Copy offsets and index maps before enqueueing any layers. One transfer per
# dtype avoids implicit host synchronizations between GPU operations.
def transfer(arrays, dtype):
sizes = [a.size for a in arrays]
buffer = torch.as_tensor(
np.concatenate([a.ravel() for a in arrays]).astype(dtype), device="cuda"
)
return [
view.view(a.shape)
for a, view in zip(arrays, buffer.split(sizes), strict=True)
]
pos, anchors, first, last, gather, readout, token_chunks, cu64, ccu64 = (
transfer(
[
np.arange(offsets[-1]) - np.repeat(offsets[:-1], lengths),
ends,
starts + offsets[chunk_rows],
ends + offsets[chunk_rows],
np.arange(key_cu[-1])
+ np.repeat(offsets[rows] + lo - key_cu[:-1], hi - lo),
source,
np.repeat(chunk_offsets[:-1], original) + local // 64,
offsets,
chunk_offsets,
],
np.int64,
)
)
cu, ccu, tiles, ctiles, qcu, kcu = transfer(
[
offsets,
chunk_offsets,
np.column_stack((chunk_rows, starts // 64)),
np.column_stack((tile_rows, tile_pos)),
np.r_[groups, chunk_offsets[-1]],
key_cu,
],
np.int32,
)
layout = SimpleNamespace(
cu=cu, cu64=cu64, chunks=tiles, positions=pos, maximum=int(lengths.max())
)
chunks = SimpleNamespace(
cu=ccu,
cu64=ccu64,
chunks=ctiles,
positions=anchors,
maximum=int(chunk_sizes.max()),
)
x = self.embedding[ids]
for block in self.blocks[:12]:
x = block.mlp(
block.gdn(x, layout)
if block.recurrent
else block.attention(x, layout, self.cache)
)
seed = packed_attention_pool(x, self.pool, first, last)
k, v = self.donor.kv(x, self.donor.pre).reshape(-1, 4, 256).chunk(2, dim=1)
k = norm(k, self.donor.knorm)
ops.rotary_embedding(layout.positions, k, None, 256, self.cache, True)
windows = (k[gather], v[gather], qcu, kcu, 4, int(np.max(hi - lo)))
h = self.donor.attention(seed, chunks, self.cache, windows)
for block in self.blocks[12:]:
h = block.mlp(
block.gdn(h, chunks)
if block.recurrent
else block.attention(h, chunks, self.cache, windows)
)
# readout indexes the scored copy within each document.
token = self.head.token(norm(x[readout], self.final))
context = self.head.context(norm(h, self.final))
return self.head.readout(token + context[token_chunks]).float()