KernelBench mega · RTX PRO 6000
Kimi-Linear Decode Composer 2.5 Fast
cleandid not score
manually audited: clean
H100 Composer-2.5-fast cell (1.76x). solution.py imports the actual compute from a sidecar `w4_kernels.py` (archived under scratch/) which IS a real Triton fused int4 dequant-GEMV (`(wq>>4)&0xF` / `wq&0xF` unpack + per-group dequant). Forbidden-scan passed; template_mutated=False; correctness clean (S=1.0, cache~1.0).
harnesscursor
Kernel source (redacted)
"""Fused W4A16 Kimi-Linear decode unit — int4 dequant fused into GEMV/GEMM."""
from __future__ import annotations
from dataclasses import dataclass, field
import torch
import torch.nn as nn
import torch.nn.functional as F
from w4_kernels import batch_gemv_rows_w4a16, batch_gemv_w4a16, gemm_w4a16, gemv_w4a16
EPS = 1.0e-6
GROUP_SIZE = 128
@dataclass(frozen=True)
class Config:
hidden: int = 2304
kda_heads: int = 32
kda_head_dim: int = 128
short_conv: int = 4
mla_heads: int = 32
kv_lora: int = 512
qk_nope: int = 128
qk_rope: int = 64
v_head: int = 128
rope_theta: float = 10000.0
n_experts: int = 64
n_active: int = 8
n_shared: int = 1
moe_inter: int = 1024
routed_scaling: float = 2.446
group: int = 128
pattern: tuple = ("K", "K", "K", "M")
dtype: torch.dtype = field(default=torch.bfloat16)
def build_config(shape: dict) -> Config:
return Config(n_experts=int(shape.get("n_experts", 64)))
class QuantLinear(nn.Module):
def __init__(self, in_f: int, out_f: int, group: int = GROUP_SIZE):
super().__init__()
assert in_f % group == 0 and in_f % 2 == 0
self.in_f, self.out_f, self.group = in_f, out_f, group
ng = in_f // group
self.register_buffer("w_q", torch.zeros(in_f // 2, out_f, dtype=torch.uint8))
self.register_buffer("scales", torch.zeros(ng, out_f, dtype=torch.bfloat16))
self.register_buffer("zeros", torch.zeros(ng, out_f, dtype=torch.bfloat16))
def forward(self, x: torch.Tensor) -> torch.Tensor:
if x.ndim == 1:
return gemv_w4a16(x, self.w_q, self.scales, self.zeros, self.in_f)
return gemm_w4a16(x, self.w_q, self.scales, self.zeros, self.in_f)
class QuantExperts(nn.Module):
def __init__(self, n: int, in_f: int, out_f: int, group: int = GROUP_SIZE):
super().__init__()
self.n, self.in_f, self.out_f, self.group = n, in_f, out_f, group
ng = in_f // group
self.register_buffer("w_q", torch.zeros(n, in_f // 2, out_f, dtype=torch.uint8))
self.register_buffer("scales", torch.zeros(n, ng, out_f, dtype=torch.bfloat16))
self.register_buffer("zeros", torch.zeros(n, ng, out_f, dtype=torch.bfloat16))
def gather(self, idx: torch.Tensor):
return (
self.w_q[idx],
self.scales[idx],
self.zeros[idx],
)
def gemv_batch(self, x: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
w_q, scales, zeros = self.gather(idx)
return batch_gemv_w4a16(x, w_q, scales, zeros, self.in_f)
def _rmsnorm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
xf = x.float()
xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + EPS)
return (xf * w.float()).to(x.dtype)
def _rope_cossin(pos: int, dim: int, theta: float, device):
inv = 1.0 / (theta ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim))
ang = pos * inv
return torch.cos(ang), torch.sin(ang)
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
xf = x.float()
even, odd = xf[..., 0::2], xf[..., 1::2]
out = torch.empty_like(xf)
out[..., 0::2] = even * cos - odd * sin
out[..., 1::2] = odd * cos + even * sin
return out.to(x.dtype)
class KDA(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.cfg = cfg
H, Dk, d = cfg.kda_heads, cfg.kda_head_dim, cfg.hidden
self.q_proj = QuantLinear(d, H * Dk, cfg.group)
self.k_proj = QuantLinear(d, H * Dk, cfg.group)
self.v_proj = QuantLinear(d, H * Dk, cfg.group)
self.g_proj = QuantLinear(d, H * Dk, cfg.group)
self.beta_proj = nn.Linear(d, H, bias=False, dtype=cfg.dtype)
self.conv_w = nn.Parameter(torch.empty(3, H * Dk, cfg.short_conv, dtype=cfg.dtype))
self.o_proj = QuantLinear(H * Dk, d, cfg.group)
self.scale = Dk ** -0.5
def _short_conv(self, val, prev, idx):
win = torch.cat([prev, val[None]], dim=0)
w = self.conv_w[idx].float().transpose(0, 1)
out = (win.float() * w).sum(0)
return F.silu(out).to(val.dtype), win[1:]
def step(self, x, st):
H, Dk = self.cfg.kda_heads, self.cfg.kda_head_dim
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
q, st["cq"] = self._short_conv(q, st["cq"], 0)
k, st["ck"] = self._short_conv(k, st["ck"], 1)
v, st["cv"] = self._short_conv(v, st["cv"], 2)
q = q.view(H, Dk).float() * self.scale
k = k.view(H, Dk).float()
v = v.view(H, Dk).float()
g = (-F.softplus(self.g_proj(x).float())).view(H, Dk)
beta = torch.sigmoid(self.beta_proj(x).float())
S = st["S"] * g.exp()[:, :, None]
pred = (S * k[:, :, None]).sum(1)
S = S + beta[:, None, None] * k[:, :, None] * (v - pred)[:, None, :]
o = (S * q[:, :, None]).sum(1)
st["S"] = S
return self.o_proj(o.reshape(H * Dk).to(torch.bfloat16))
class MLA(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.cfg = cfg
H, d = cfg.mla_heads, cfg.hidden
self.q_proj = QuantLinear(d, H * (cfg.qk_nope + cfg.qk_rope), cfg.group)
self.kv_a = QuantLinear(d, cfg.kv_lora + cfg.qk_rope, cfg.group)
self.kv_b = QuantLinear(cfg.kv_lora, H * (cfg.qk_nope + cfg.v_head), cfg.group)
self.o_proj = QuantLinear(H * cfg.v_head, d, cfg.group)
self.scale = (cfg.qk_nope + cfg.qk_rope) ** -0.5
def step(self, x, st):
cfg = self.cfg
H = cfg.mla_heads
pos = st["c_kv"].shape[0]
q = self.q_proj(x).view(H, cfg.qk_nope + cfg.qk_rope)
q_nope = q[:, : cfg.qk_nope]
q_rope = q[:, cfg.qk_nope :]
kv = self.kv_a(x)
c_kv = kv[: cfg.kv_lora]
k_rope = kv[cfg.kv_lora :]
cos, sin = _rope_cossin(pos, cfg.qk_rope, cfg.rope_theta, x.device)
q_rope = _apply_rope(q_rope, cos, sin)
k_rope = _apply_rope(k_rope, cos, sin)
st["c_kv"] = torch.cat([st["c_kv"], c_kv[None]], 0)
st["k_rope"] = torch.cat([st["k_rope"], k_rope[None]], 0)
if "kvb" in st:
kvb = torch.cat([st["kvb"], self.kv_b(c_kv)[None]], 0)
else:
kvb = self.kv_b(st["c_kv"])
st["kvb"] = kvb
kvb = kvb.view(-1, H, cfg.qk_nope + cfg.v_head)
k_nope = kvb[..., : cfg.qk_nope]
v = kvb[..., cfg.qk_nope :]
scores = (
torch.einsum("hd,lhd->lh", q_nope.float(), k_nope.float())
+ torch.einsum("hd,ld->lh", q_rope.float(), st["k_rope"].float())
) * self.scale
p = torch.softmax(scores, dim=0).to(x.dtype)
o = torch.einsum("lh,lhd->hd", p, v)
return self.o_proj(o.reshape(H * cfg.v_head))
class MoE(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.cfg = cfg
d, m, E = cfg.hidden, cfg.moe_inter, cfg.n_experts
self.router = nn.Linear(d, E, bias=False, dtype=cfg.dtype)
self.gate = QuantExperts(E, d, m, cfg.group)
self.up = QuantExperts(E, d, m, cfg.group)
self.down = QuantExperts(E, m, d, cfg.group)
self.s_gate = QuantExperts(cfg.n_shared, d, m, cfg.group)
self.s_up = QuantExperts(cfg.n_shared, d, m, cfg.group)
self.s_down = QuantExperts(cfg.n_shared, m, d, cfg.group)
def step(self, x):
cfg = self.cfg
probs = torch.softmax(self.router(x).float(), dim=-1)
w, idx = torch.topk(probs, cfg.n_active)
w = (w / (w.sum() + 1e-9) * cfg.routed_scaling).to(x.dtype)
g = torch.cat([self.gate.gather(idx)[0], self.s_gate.w_q], dim=0)
gs = torch.cat([self.gate.gather(idx)[1], self.s_gate.scales], dim=0)
gz = torch.cat([self.gate.gather(idx)[2], self.s_gate.zeros], dim=0)
u = torch.cat([self.up.gather(idx)[0], self.s_up.w_q], dim=0)
us = torch.cat([self.up.gather(idx)[1], self.s_up.scales], dim=0)
uz = torch.cat([self.up.gather(idx)[2], self.s_up.zeros], dim=0)
d = torch.cat([self.down.gather(idx)[0], self.s_down.w_q], dim=0)
ds = torch.cat([self.down.gather(idx)[1], self.s_down.scales], dim=0)
dz = torch.cat([self.down.gather(idx)[2], self.s_down.zeros], dim=0)
gate_out = batch_gemv_w4a16(x, g, gs, gz, cfg.hidden)
up_out = batch_gemv_w4a16(x, u, us, uz, cfg.hidden)
h = (F.silu(gate_out.float()) * up_out.float()).to(torch.bfloat16)
down_out = batch_gemv_rows_w4a16(h, d, ds, dz, cfg.moe_inter)
routed = (w[:, None] * down_out[: cfg.n_active]).sum(0)
shared = down_out[cfg.n_active :].sum(0)
return (routed + shared).to(torch.bfloat16)
class Block(nn.Module):
def __init__(self, cfg: Config, kind: str):
super().__init__()
self.kind = kind
self.attn_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype))
self.moe_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype))
self.attn = KDA(cfg) if kind == "K" else MLA(cfg)
self.moe = MoE(cfg)
def step(self, x, st):
h = x + self.attn.step(_rmsnorm(x, self.attn_norm), st)
return h + self.moe.step(_rmsnorm(h, self.moe_norm))
class Model(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.cfg = cfg
self.blocks = nn.ModuleList(Block(cfg, k) for k in cfg.pattern)
def step(self, hidden, state):
for i, blk in enumerate(self.blocks):
hidden = blk.step(hidden, state[i])
return hidden, state
def init_state(cfg: Config, context_len: int, seed: int) -> list:
dev = torch.device("cuda:0")
g = torch.Generator(device=dev).manual_seed(seed)
H, Dk = cfg.kda_heads, cfg.kda_head_dim
C = H * Dk
state = []
for kind in cfg.pattern:
if kind == "K":
state.append({
"S": torch.randn(H, Dk, Dk, device=dev, generator=g) * 0.05,
"cq": torch.randn(cfg.short_conv - 1, C, device=dev, generator=g, dtype=cfg.dtype) * 0.1,
"ck": torch.randn(cfg.short_conv - 1, C, device=dev, generator=g, dtype=cfg.dtype) * 0.1,
"cv": torch.randn(cfg.short_conv - 1, C, device=dev, generator=g, dtype=cfg.dtype) * 0.1,
})
else:
state.append({
"c_kv": torch.randn(context_len, cfg.kv_lora, device=dev, generator=g, dtype=cfg.dtype) * 0.1,
"k_rope": torch.randn(context_len, cfg.qk_rope, device=dev, generator=g, dtype=cfg.dtype) * 0.1,
})
return state
def init_token(cfg: Config, seed: int) -> torch.Tensor:
dev = torch.device("cuda:0")
g = torch.Generator(device=dev).manual_seed(seed + 1)
return torch.randn(cfg.hidden, device=dev, generator=g, dtype=cfg.dtype) * 0.25
# ==================================================================
# ===== sidecar: w4_kernels.py (11110 bytes, loaded by solution.py) =====
# ==================================================================
"""Fused W4A16 dequant + GEMV/GEMM (no materialized bf16 weights)."""
from __future__ import annotations
import torch
import triton
import triton.language as tl
GROUP_SIZE = 128
@triton.jit
def _gemv_kernel(
x_ptr,
w_q_ptr,
scales_ptr,
zeros_ptr,
y_ptr,
K,
N,
stride_x,
stride_wq_k,
stride_wq_n,
stride_s_g,
stride_s_n,
stride_z_g,
stride_z_n,
stride_y,
GROUP_SIZE: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
):
pid_n = tl.program_id(0)
n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
n_mask = n_offs < N
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
for k0 in range(0, K, BLOCK_K):
k_offs = k0 + tl.arange(0, BLOCK_K)
k_mask = k_offs < K
x = tl.load(x_ptr + k_offs * stride_x, mask=k_mask, other=0.0).to(tl.float32)
packed_row = k_offs // 2
is_hi = (k_offs & 1) == 1
wq = tl.load(
w_q_ptr + packed_row[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0,
)
w_int = tl.where(is_hi[:, None], (wq >> 4) & 0xF, wq & 0xF).to(tl.float32)
g_idx = k_offs // GROUP_SIZE
sc = tl.load(
scales_ptr + g_idx[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0.0,
).to(tl.float32)
zr = tl.load(
zeros_ptr + g_idx[:, None] * stride_z_g + n_offs[None, :] * stride_z_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0.0,
).to(tl.float32)
w = (w_int - zr) * sc
acc += tl.sum(x[:, None] * w, axis=0)
tl.store(y_ptr + n_offs * stride_y, acc, mask=n_mask)
@triton.jit
def _gemm_kernel(
x_ptr,
w_q_ptr,
scales_ptr,
zeros_ptr,
y_ptr,
M,
N,
K,
stride_xm,
stride_xk,
stride_wq_k,
stride_wq_n,
stride_s_g,
stride_s_n,
stride_z_g,
stride_z_n,
stride_ym,
stride_yn,
GROUP_SIZE: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
m_offs = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
m_mask = m_offs < M
n_mask = n_offs < N
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
for k0 in range(0, K, BLOCK_K):
k_offs = k0 + tl.arange(0, BLOCK_K)
k_mask = k_offs < K
x = tl.load(
x_ptr + m_offs[:, None] * stride_xm + k_offs[None, :] * stride_xk,
mask=m_mask[:, None] & k_mask[None, :],
other=0.0,
).to(tl.float32)
packed_row = k_offs // 2
is_hi = (k_offs & 1) == 1
wq = tl.load(
w_q_ptr + packed_row[None, :] * stride_wq_k + n_offs[:, None] * stride_wq_n,
mask=k_mask[None, :] & n_mask[:, None],
other=0,
)
w_int = tl.where(is_hi[None, :], (wq >> 4) & 0xF, wq & 0xF).to(tl.float32)
g_idx = k_offs // GROUP_SIZE
sc = tl.load(
scales_ptr + g_idx[None, :] * stride_s_g + n_offs[:, None] * stride_s_n,
mask=k_mask[None, :] & n_mask[:, None],
other=0.0,
).to(tl.float32)
zr = tl.load(
zeros_ptr + g_idx[None, :] * stride_z_g + n_offs[:, None] * stride_z_n,
mask=k_mask[None, :] & n_mask[:, None],
other=0.0,
).to(tl.float32)
w = (w_int - zr) * sc
acc += tl.dot(x, tl.trans(w))
tl.store(
y_ptr + m_offs[:, None] * stride_ym + n_offs[None, :] * stride_yn,
acc,
mask=m_mask[:, None] & n_mask[None, :],
)
@triton.jit
def _batch_gemv_kernel(
x_ptr,
w_q_ptr,
scales_ptr,
zeros_ptr,
y_ptr,
E,
K,
N,
stride_x,
stride_wqe,
stride_wq_k,
stride_wq_n,
stride_se,
stride_s_g,
stride_s_n,
stride_ze,
stride_z_g,
stride_z_n,
stride_ye,
stride_yn,
GROUP_SIZE: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
):
pid_e = tl.program_id(0)
pid_n = tl.program_id(1)
if pid_e >= E:
return
n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
n_mask = n_offs < N
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
for k0 in range(0, K, BLOCK_K):
k_offs = k0 + tl.arange(0, BLOCK_K)
k_mask = k_offs < K
x = tl.load(x_ptr + k_offs * stride_x, mask=k_mask, other=0.0).to(tl.float32)
packed_row = k_offs // 2
is_hi = (k_offs & 1) == 1
wq = tl.load(
w_q_ptr
+ pid_e * stride_wqe
+ packed_row[:, None] * stride_wq_k
+ n_offs[None, :] * stride_wq_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0,
)
w_int = tl.where(is_hi[:, None], (wq >> 4) & 0xF, wq & 0xF).to(tl.float32)
g_idx = k_offs // GROUP_SIZE
sc = tl.load(
scales_ptr
+ pid_e * stride_se
+ g_idx[:, None] * stride_s_g
+ n_offs[None, :] * stride_s_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0.0,
).to(tl.float32)
zr = tl.load(
zeros_ptr
+ pid_e * stride_ze
+ g_idx[:, None] * stride_z_g
+ n_offs[None, :] * stride_z_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0.0,
).to(tl.float32)
w = (w_int - zr) * sc
acc += tl.sum(x[:, None] * w, axis=0)
tl.store(y_ptr + pid_e * stride_ye + n_offs * stride_yn, acc, mask=n_mask)
@triton.jit
def _batch_gemv_rows_kernel(
x_ptr,
w_q_ptr,
scales_ptr,
zeros_ptr,
y_ptr,
E,
K,
N,
stride_xe,
stride_xk,
stride_wqe,
stride_wq_k,
stride_wq_n,
stride_se,
stride_s_g,
stride_s_n,
stride_ze,
stride_z_g,
stride_z_n,
stride_ye,
stride_yn,
GROUP_SIZE: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
):
pid_e = tl.program_id(0)
pid_n = tl.program_id(1)
if pid_e >= E:
return
n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
n_mask = n_offs < N
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
for k0 in range(0, K, BLOCK_K):
k_offs = k0 + tl.arange(0, BLOCK_K)
k_mask = k_offs < K
x = tl.load(
x_ptr + pid_e * stride_xe + k_offs * stride_xk,
mask=k_mask,
other=0.0,
).to(tl.float32)
packed_row = k_offs // 2
is_hi = (k_offs & 1) == 1
wq = tl.load(
w_q_ptr
+ pid_e * stride_wqe
+ packed_row[:, None] * stride_wq_k
+ n_offs[None, :] * stride_wq_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0,
)
w_int = tl.where(is_hi[:, None], (wq >> 4) & 0xF, wq & 0xF).to(tl.float32)
g_idx = k_offs // GROUP_SIZE
sc = tl.load(
scales_ptr
+ pid_e * stride_se
+ g_idx[:, None] * stride_s_g
+ n_offs[None, :] * stride_s_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0.0,
).to(tl.float32)
zr = tl.load(
zeros_ptr
+ pid_e * stride_ze
+ g_idx[:, None] * stride_z_g
+ n_offs[None, :] * stride_z_n,
mask=k_mask[:, None] & n_mask[None, :],
other=0.0,
).to(tl.float32)
w = (w_int - zr) * sc
acc += tl.sum(x[:, None] * w, axis=0)
tl.store(y_ptr + pid_e * stride_ye + n_offs * stride_yn, acc, mask=n_mask)
_GEMV_BLOCK_N = 128
_GEMV_BLOCK_K = 128
_GEMM_BLOCK_M = 32
_GEMM_BLOCK_N = 64
_GEMM_BLOCK_K = 128
def gemv_w4a16(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor, k_in: int) -> torch.Tensor:
assert x.ndim == 1 and x.is_contiguous()
kh, n = w_q.shape
assert kh * 2 == k_in
y = torch.empty(n, device=x.device, dtype=torch.bfloat16)
grid = (triton.cdiv(n, _GEMV_BLOCK_N),)
_gemv_kernel[grid](
x, w_q, scales, zeros, y,
k_in, n,
x.stride(0), w_q.stride(0), w_q.stride(1),
scales.stride(0), scales.stride(1),
zeros.stride(0), zeros.stride(1),
y.stride(0),
GROUP_SIZE=GROUP_SIZE,
BLOCK_N=_GEMV_BLOCK_N,
BLOCK_K=_GEMV_BLOCK_K,
num_warps=4,
)
return y
def gemm_w4a16(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor, k_in: int) -> torch.Tensor:
assert x.ndim == 2 and x.is_contiguous()
m, k = x.shape
kh, n = w_q.shape
assert k == k_in and kh * 2 == k_in
y = torch.empty(m, n, device=x.device, dtype=torch.bfloat16)
grid = (triton.cdiv(m, _GEMM_BLOCK_M), triton.cdiv(n, _GEMM_BLOCK_N))
_gemm_kernel[grid](
x, w_q, scales, zeros, y,
m, n, k_in,
x.stride(0), x.stride(1),
w_q.stride(0), w_q.stride(1),
scales.stride(0), scales.stride(1),
zeros.stride(0), zeros.stride(1),
y.stride(0), y.stride(1),
GROUP_SIZE=GROUP_SIZE,
BLOCK_M=_GEMM_BLOCK_M,
BLOCK_N=_GEMM_BLOCK_N,
BLOCK_K=_GEMM_BLOCK_K,
num_warps=4,
)
return y
def batch_gemv_w4a16(
x: torch.Tensor,
w_q: torch.Tensor,
scales: torch.Tensor,
zeros: torch.Tensor,
k_in: int,
) -> torch.Tensor:
assert x.ndim == 1 and x.is_contiguous()
e, kh, n = w_q.shape
assert kh * 2 == k_in
y = torch.empty(e, n, device=x.device, dtype=torch.bfloat16)
grid = (e, triton.cdiv(n, _GEMV_BLOCK_N))
_batch_gemv_kernel[grid](
x, w_q, scales, zeros, y,
e, k_in, n,
x.stride(0),
w_q.stride(0), w_q.stride(1), w_q.stride(2),
scales.stride(0), scales.stride(1), scales.stride(2),
zeros.stride(0), zeros.stride(1), zeros.stride(2),
y.stride(0), y.stride(1),
GROUP_SIZE=GROUP_SIZE,
BLOCK_N=_GEMV_BLOCK_N,
BLOCK_K=_GEMV_BLOCK_K,
num_warps=4,
)
return y
def batch_gemv_rows_w4a16(
x: torch.Tensor,
w_q: torch.Tensor,
scales: torch.Tensor,
zeros: torch.Tensor,
k_in: int,
) -> torch.Tensor:
"""x: (E, K) bf16; expert weights (E, K//2, N) -> y: (E, N) bf16."""
assert x.ndim == 2 and x.is_contiguous()
e, k = x.shape
assert w_q.shape[0] == e and w_q.shape[1] * 2 == k_in and k == k_in
n = w_q.shape[2]
y = torch.empty(e, n, device=x.device, dtype=torch.bfloat16)
grid = (e, triton.cdiv(n, _GEMV_BLOCK_N))
_batch_gemv_rows_kernel[grid](
x, w_q, scales, zeros, y,
e, k_in, n,
x.stride(0), x.stride(1),
w_q.stride(0), w_q.stride(1), w_q.stride(2),
scales.stride(0), scales.stride(1), scales.stride(2),
zeros.stride(0), zeros.stride(1), zeros.stride(2),
y.stride(0), y.stride(1),
GROUP_SIZE=GROUP_SIZE,
BLOCK_N=_GEMV_BLOCK_N,
BLOCK_K=_GEMV_BLOCK_K,
num_warps=4,
)
return y
20260619_062205_cursor_composer-2.5-fast_02_kimi_linear_decode