Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Hy4 draft MTP layer: itemised cost, int8 expert tile retune, Q8 absorb matrices and indexer mat-vec for the draft layer (HY4_DRAFT_MOE_TILES / HY4_DRAFT_MLA_BG / HY4_DRAFT_IX_GV, default off), model-free micros

YanissAmz6e044c367e8a
diff --git a/docs/STRIX_MTP_LAYER.md b/docs/STRIX_MTP_LAYER.md
new file mode 100644
index 0000000..731fae2
--- /dev/null
+++ b/docs/STRIX_MTP_LAYER.md
@@ -0,0 +1,21 @@
+# STRIX_MTP_LAYER: draft MTP layer, itemised (Strix box, 20/11, branch perf/hy4-strix-mtp off dv 7ecdfcc9a)
+FINDING: the draft experts are NOT the Q3_K single-row mmvq (105 GB/s). They are int8 + per-row scale (moe_i8.py, Triton `_k_gu` / `_k_down`, 16 experts, N = K = 1536) and already read 202 GB/s (84 % of the 240 roof). Routing them through the grouped kernel was not needed.
+Measured with real blk.42 tensors (64 of 512 experts, 16 distinct per step), HIP graph replay, k = 3 steps, NO head. Raw: ~/scratch/n1119/out/{mtp_micro1,mtp_prof1,mtp_arms1}.log. Tools: tools/hy4/step/{mtp_micro,mtp_items}.py, mtp_arms.sh.
+| part (per step, ctx 4096, rocprofv3) | us | bytes | GB/s | note |
+|---|---|---|---|---|
+| fp32 rocBLAS SGEMM (7 launches: wk_b, wv_b + 5 indexer mats) | 587 | ~58 MB | 12-130 | skinny M = 1 tiles; floor ~240 us. FIXED below |
+| dense Q8_0 gemv (12: eh_proj, wq_a/b, wkv_a, wo, wgate, rdown/rup, shexp x3) | 501 | 113 MB | ~225 | at roof |
+| MLA attend: _sparse_mla_kernel (fp32 K cache, one head per program, 32 programs) | 391 | 9 MB | 23 | selection active at 4K (not at 1K); at 1K the head-blocked Triton kernel runs (107 us). OPEN |
+| experts gate+up `_k_gu` | 366 | 76 MB | 196 | tiles retuned: 328 us / 230 GB/s |
+| experts down `_k_down` | 172 | 38 MB | 219 | tiles retuned: 163 us / 232 GB/s |
+| router mat-vec `_k_rg` | 47 | 6.3 MB | 134 | OPEN (fp16 router: HY4_RG_F16) |
+| ~60 small kernels (rms, rope, index_copy, cat, quant) + gaps 2.5 us each | ~260 | | | OPEN: glue fusion |
+| step window / round (no head) | 2448 / 7414 | 262 MB | | floor 1.09 ms / 3.3 ms; head Q5_K adds 3.3 per round (dv worker) |
+Round, no head, ms (A shipped -> E all three flags): ctx 1K 5.45 -> 4.34 (-20 %), ctx 4K 7.08 -> 5.60 (-21 %).
+| flag (default OFF, draft only) | 1K | 4K | step-1 rel err vs A |
+|---|---|---|---|
+| HY4_DRAFT_MOE_TILES=1 (expert tiles) | 5.27 | 6.90 | 4e-4 (sum order) |
+| HY4_DRAFT_MLA_BG=1 (wk_b / wv_b as int8 + fp16 block scales on the trunk batched mat-vec, +7.8 MB) | 4.94 | 6.55 | 1.5e-2 (Q8 re-quant of bf16) |
+| HY4_DRAFT_IX_GV=1 (draft indexer fp32 mats on the router mat-vec) | 5.05 | 6.30 | 0 |
+Not applicable: HY4_LC_HB (mla branch) is the fp8-cache kernel; the draft K cache is fp32 [cap, 576]. A head-blocked kernel for the fp32 sparse attend is the next lever (-0.85 ms per round at 4K+).
+Served ABBA (tau per class, draft ms, round ms): job 84_2f_mtp_ab, queued, not run yet.
diff --git a/exllamav3/loader/mla_bgemv.py b/exllamav3/loader/mla_bgemv.py
index 017d8c5..08be83a 100644
--- a/exllamav3/loader/mla_bgemv.py
+++ b/exllamav3/loader/mla_bgemv.py
@@ -144,6 +144,17 @@ class Q8Batched:
self.q = b[:, :, 2:].contiguous().view(torch.int8).reshape(H, N, K).contiguous()
self.H, self.N, self.K = H, N, K
+ @classmethod
+ def from_float(cls, w):
+ """[H, N, K] float tensor (K % 32 == 0) -> Q8_0-style int8 + fp16 block scales (the draft layer's GGUF tensors are bf16: no stored Q8_0 bytes to read)"""
+ H, N, K = w.shape
+ blk = w.float().reshape(H * N, K // 32, 32)
+ d = (blk.abs().amax(-1) / 127.0).clamp_min(1e-30).half()
+ q = torch.round(blk / d.float()[..., None]).clamp(-127, 127).to(torch.int8)
+ o = cls.__new__(cls)
+ o.d, o.q, o.H, o.N, o.K = d.reshape(H, N, K // 32).contiguous(), q.reshape(H, N, K).contiguous(), H, N, K
+ return o
+
def mv(self, x):
"""x [T, H, K] fp32 -> [T, H, N] fp32 (T == 1: the single-row kernel; T > 1: one kernel, weights read once)"""
if x.dim() == 3 and x.shape[0] > 1 and x.stride(-1) == 1:
diff --git a/exllamav3/loader/moe_i8.py b/exllamav3/loader/moe_i8.py
index dc7e838..8d53e45 100644
--- a/exllamav3/loader/moe_i8.py
+++ b/exllamav3/loader/moe_i8.py
@@ -6,6 +6,7 @@ verifies every token), so the stacks are quantised on load: w ~ q * s, q int8, s
gate_up(z [K], sel [S]) -> h [S, N] h[s] = silu(min(Wg[e] z, lim)) * clamp(Wu[e] z, -lim, lim) e = sel[s]
down(h [S, N], sel, w [S]) -> lat [N] lat = sum_s w[s] * (Wd[e_s] h[s])
Weights are [E, N, K] row-major (ggml ne0 = K fastest), K = N = 1536 here; generic in (E, N, K)."""
+import os
import numpy as np
import torch
import triton
@@ -76,13 +77,19 @@ def _k_down(wd_ptr, sd_ptr, sel_ptr, h_ptr, w_ptr, o_ptr, N, K, S: tl.constexpr,
tl.store(o_ptr + rows, out, mask=rm)
+# tiles (BN, BK, num_warps): HY4_DRAFT_MOE_TILES=1 = the box sweep of 20/11 (mtp_micro.py, int8 [512, 1536, 1536] x 3, 16 experts): gate/up 385 -> 328 us, down 173 -> 163 us (196 -> 231 GB/s of the 240 roof)
+TILES = os.environ.get("HY4_DRAFT_MOE_TILES", "0") == "1"
+GU_T = (8, 512, 8) if TILES else (16, 128, 4)
+DN_T = (16, 512, 4) if TILES else (8, 128, 4)
+
+
def experts_forward(gate, up, down, z, sel, w, lim):
"""z [K] fp32, sel [S] int64 device, w [S] fp32 -> lat [N] fp32 (K = gate/up K, N = gate/up N = down K, down N = latent)"""
S = sel.numel()
h = torch.empty(S, gate.N, dtype=torch.float32, device=z.device)
- _k_gu[(S, triton.cdiv(gate.N, 16))](gate.q, up.q, gate.s, up.s, sel, z, h, gate.N, gate.K, lim, BN=16, BK=128, num_warps=4)
+ _k_gu[(S, triton.cdiv(gate.N, GU_T[0]))](gate.q, up.q, gate.s, up.s, sel, z, h, gate.N, gate.K, lim, BN=GU_T[0], BK=GU_T[1], num_warps=GU_T[2])
out = torch.empty(down.N, dtype=torch.float32, device=z.device)
- _k_down[(triton.cdiv(down.N, 8),)](down.q, down.s, sel, h, w, out, down.N, down.K, S=S, BN=8, BK=128, num_warps=4)
+ _k_down[(triton.cdiv(down.N, DN_T[0]),)](down.q, down.s, sel, h, w, out, down.N, down.K, S=S, BN=DN_T[0], BK=DN_T[1], num_warps=DN_T[2])
return out
diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.py
index 3e6041a..c78dbe1 100644
--- a/exllamav3/loader/mtp_head.py
+++ b/exllamav3/loader/mtp_head.py
@@ -61,6 +61,9 @@ class Hy4MTP:
mla = Hy4MLA(g, il, lin=(lambda n: dl(n)) if self.fast else (lambda n: load_dense(g, n)))
_mv(mla, dev, torch.float32)
mla.post_norm, mla.sinks = mla.post_norm.to(dev), mla.sinks.to(dev)
+ if self.fast and os.environ.get("HY4_DRAFT_MLA_BG", "0") == "1": # absorb matrices wk_b / wv_b (fp32 einsum = rocBLAS SGEMM at 80-135 us each) as int8 + fp16 block scales on the trunk's batched mat-vec
+ from . import mla_bgemv as _BGM
+ mla.bg_kb, mla.bg_vb = _BGM.Q8Batched.from_float(mla.wk_b), _BGM.Q8Batched.from_float(mla.wv_b)
mla.kpos_arange = True
mla.tm = fw.tm
self.mla = mla
@@ -99,6 +102,7 @@ class Hy4MTP:
self.ar = st.ar if st.ar.shape[0] >= self.cap else torch.arange(self.cap, device=dev)
self.kbuf = torch.zeros(self.cap, mla.R + mla.rope_dim, device=dev)
SG.indexer_static_init(self.ix, self.cap)
+ self.ix.gv = self.fast and os.environ.get("HY4_DRAFT_IX_GV", "0") == "1" # indexer fp32 matrices on the mat-vec
try:
from . import attn_eager as _AE
_AE.ensure(self.cap)
diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.py
index bc07495..e57d9ee 100644
--- a/exllamav3/loader/step_graph.py
+++ b/exllamav3/loader/step_graph.py
@@ -23,6 +23,7 @@ import torch
from . import step_nosync as _ns
from .engram_rows import QB, E4M3, E8M0
from . import attn_eager as _ae
+from . import router_gemv as _RG
from .engram_stage import EngramStager
BUCKET = int(os.environ.get("HY4_GRAPH_BUCKET", "512"))
@@ -73,11 +74,17 @@ def indexer_static_init(ix, cap):
@torch.no_grad()
+def _mmw(ix, a, name):
+ """a @ ix.w[name].T; the draft layer's indexer (ix.gv, HY4_DRAFT_IX_GV=1) runs its small fp32 matrices through the router mat-vec (rocBLAS SGEMM at M = 1 runs these at 12-60 GB/s)"""
+ w = ix.w[name]
+ return _RG.logits(a, w) if (getattr(ix, "gv", False) and _RG.usable(a, w)) else a @ w.T
+
+
def indexer_keys_static(ix, x, pos, ar):
"""key side of indexer_forward_static: the per-position (value | gate) rows and the pool groups they complete (x [T, E], pos [T] long device, ascending). Needs no query and no selection."""
k, d = ix.k, ix.d
- ik = _rms(x @ ix.w["attn_k"].T, ix.w["k_norm"], ix.eps)
- vg_new = torch.cat([ik @ ix.w["value"].T, ik @ ix.w["gate"].T], -1)
+ ik = _rms(_mmw(ix, x, "attn_k"), ix.w["k_norm"], ix.eps)
+ vg_new = torch.cat([_mmw(ix, ik, "value"), _mmw(ix, ik, "gate")], -1)
vr = getattr(ix, "vg_ring", 0)
assert not vr or x.shape[0] + k <= vr, "vg ring smaller than one call"
ix.vgb.index_copy_(0, pos % vr if vr else pos, vg_new)
@@ -103,8 +110,8 @@ def indexer_forward_static(ix, x, qr, pos, Nb, ar):
if Nb <= (ix.n_top + 1) * k: # every position of this bucket sees <= n_top groups: the selection is all-causal (the eager path returns None)
return None
T = x.shape[0]
- iq = ix._rope((qr @ ix.w["q_b"].T).reshape(T, H, d), pos)
- wt = (x.float() @ ix.w["proj"].T) / math.sqrt(d * H)
+ iq = ix._rope(_mmw(ix, qr, "q_b").reshape(T, H, d), pos)
+ wt = _mmw(ix, x.float(), "proj") / math.sqrt(d * H)
Pb = Nb // k
if PRIME_IX and T > 16 and ix.tail and iq.is_cuda: # draft-cache fill of a long prompt (T up to 2048 rows): fused fp16 scorer + exact select instead of the fp32 [T, 16, Pb] einsum
off = (pos.data_ptr() - ar.data_ptr()) // ar.element_size()
diff --git a/tools/hy4/step/mtp_arms.sh b/tools/hy4/step/mtp_arms.sh
new file mode 100644
index 0000000..44fd853
--- /dev/null
+++ b/tools/hy4/step/mtp_arms.sh
@@ -0,0 +1,10 @@
+#!/bin/bash
+# arms.sh "ARMNAME:K=V,K=V" ...: one mtp_items round timing per arm (same process env otherwise), step-1 output checked against arm A
+cd ~/hermes-work/relay1114/hy4s/wt_mtp
+REF=/tmp/mtp_ref_$$.pt
+for arm in "$@"; do
+ n=${arm%%:*}; kv=${arm#*:}; envs=""; [ -n "$kv" ] && envs=$(echo $kv | tr ',' ' ')
+ echo "=== ARM $n ($kv)"
+ if [ "$n" = "A" ]; then env $envs python -u tools/hy4/step/mtp_items.py --save $REF 2>&1 | grep -E "MTP_ROUND|Error|error" ; else env $envs python -u tools/hy4/step/mtp_items.py --ref $REF 2>&1 | grep -E "MTP_ROUND|Error|error"; fi
+done
+rm -f $REF
diff --git a/tools/hy4/step/mtp_items.py b/tools/hy4/step/mtp_items.py
new file mode 100644
index 0000000..f398f6a
--- /dev/null
+++ b/tools/hy4/step/mtp_items.py
@@ -0,0 +1,76 @@
+"""mtp_items.py: itemise ONE draft step (Hy4MTP.step, shipped HY4_MTP_FAST=1, no head) by torch.profiler (record_shapes) on the real blk.<n_trunk> tensors (64 of 512 experts loaded, as opbench draft_mtp_layer).
+ mtp_items.py [--ctx 1024,4096] (run under both GPU locks: runmicro_mtp.sh)"""
+import os, sys, time, argparse
+HERE = os.path.dirname(os.path.abspath(__file__))
+TREE = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
+import ast
+src = open(os.path.join(TREE, "tools", "hy4", "serve.py")).read()
+for n in ast.walk(ast.parse(src)):
+ if isinstance(n, ast.Assign) and any(getattr(t, "id", "") == "SHIPPED_ENV" for t in n.targets):
+ for k, v in ast.literal_eval(n.value).items():
+ os.environ.setdefault(k, v)
+sys.path.insert(0, os.path.join(TREE, "tools", "hy4"))
+os.environ["HY4_MTP_HEAD"] = "" # no output head here (draft_head op)
+import numpy as np, torch
+import engine as _eng
+_eng._stub_package(TREE)
+from types import SimpleNamespace
+from exllamav3.loader import hy4_forward as HF, mtp_head as MT, attn_eager as AE
+from exllamav3.loader.gguf_collection import GGUFCollection
+ap = argparse.ArgumentParser(); ap.add_argument("--ctx", default="1024,4096"); ap.add_argument("--reps", type=int, default=20); a = ap.parse_known_args()[0]
+dev = torch.device("cuda")
+g = GGUFCollection(os.environ["GGUF"]); m = g.meta; p = m["general.architecture"] + "."
+il = m[p + "block_count"] - m.get(p + "nextn_predict_layers", 0); b = f"blk.{il}."
+ctxs = [int(x) for x in a.ctx.split(",")]; cap = (max(ctxs) + 1024 + 511) // 512 * 512
+NE = 64
+ixc = dict(n_head=m[p + "attention.indexer.head_count"], head_dim=m[p + "attention.indexer.key_length"], top_k=m[p + "attention.indexer.top_k"], kpool=m[p + "attention.indexer.kpool"],
+ select_tail=bool(m[p + "attention.indexer.kpool_select_tail"]), rope_dim=m[p + "rope.dimension_count"], rope_base=float(m[p + "rope.freq_base"]), eps=float(m[p + "attention.layer_norm_rms_epsilon"]))
+ty, dims, off = g.infos["token_embd.weight"]; rb = dims[0] // 32 * 34
+table = torch.from_numpy(np.array(g._pread(off, 8 * rb))).reshape(8, rb).to(dev)
+fw = SimpleNamespace(g=g, dev=dev, n_trunk=il, eps=ixc["eps"], clamp=list(m[p + "swiglu_clamp_exp"]), tm=HF._Tm(), ixc=ixc, topk=m[p + "expert_used_count"], w_scale=float(m[p + "expert_weights_scale"]),
+ D=int(m[p + "embedding_length"]), _ns=SimpleNamespace(cap=cap, ar=torch.arange(cap, device=dev), table=table))
+saved = {}
+for n_ in ("ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight"):
+ t_, d_, o_ = g.infos[b + n_]; saved[b + n_] = g.infos[b + n_]; g.infos[b + n_] = (t_, (d_[0], d_[1], NE), o_)
+try:
+ mt = MT.Hy4MTP(fw, cap=cap)
+finally:
+ g.infos.update(saved)
+mt.rbias[NE:] = -1e9; mt.logits = lambda y: y[0, :1]; AE.ensure(cap)
+D = fw.D
+import statistics
+ap2 = argparse.ArgumentParser(); ap2.add_argument("--ctx", default="1024,4096"); ap2.add_argument("--reps", type=int, default=20); ap2.add_argument("--prof", action="store_true"); ap2.add_argument("--save", default=""); ap2.add_argument("--ref", default="")
+a = ap2.parse_args()
+FL = {k: os.environ.get(k) for k in os.environ if k.startswith("HY4_DRAFT_")}
+for ctx in ctxs:
+ torch.manual_seed(0)
+ mt.kbuf.copy_(torch.randn_like(mt.kbuf) * 1.5)
+ j = ctx - 8; N = min(cap, ((j + 3) // 512 + 1) * 512); k = 3
+ tok = torch.tensor([1], device=dev); h0 = torch.randn(1, D, device=dev); pos0 = mt.ar[j:j + 1]
+ def rnd():
+ y, lg = mt.step(tok, h0, pos0, N)
+ t = torch.zeros(1, dtype=torch.long, device=dev); h = y[-1:]
+ for i in range(1, k):
+ y, lg = mt.step(t, h, mt.ar[j + i:j + i + 1], N); h = y
+ return y
+ y1 = mt.step(tok, h0, pos0, N)[0].clone()
+ for _ in range(3): rnd()
+ torch.cuda.synchronize()
+ s_ = torch.cuda.Stream(); s_.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s_): rnd()
+ torch.cuda.current_stream().wait_stream(s_); torch.cuda.synchronize()
+ gr = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(gr): rnd()
+ for _ in range(5): gr.replay()
+ torch.cuda.synchronize()
+ ts = []
+ e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ for _ in range(100):
+ e0.record(); gr.replay(); e1.record(); e1.synchronize(); ts.append(e0.elapsed_time(e1))
+ err = ""
+ if a.ref:
+ r = torch.load(a.ref)[ctx]; err = f" step1 rel err vs ref {((y1 - r).norm() / r.norm()).item():.2e}"
+ if a.save:
+ d = torch.load(a.save) if os.path.exists(a.save) else {}
+ d[ctx] = y1.cpu() if False else y1; torch.save(d, a.save)
+ print(f"MTP_ROUND ctx {ctx} N {N}: {statistics.median(ts):.3f} ms per round (3 steps, no head) p10 {sorted(ts)[10]:.3f} p90 {sorted(ts)[90]:.3f} flags {FL}{err}", flush=True)
diff --git a/tools/hy4/step/mtp_micro.py b/tools/hy4/step/mtp_micro.py
new file mode 100644
index 0000000..57b399f
--- /dev/null
+++ b/tools/hy4/step/mtp_micro.py
@@ -0,0 +1,128 @@
+"""mtp_micro.py: model-free micro of the draft MoE experts (int8 per-row Triton kernels of moe_i8.py) on SYNTHETIC int8 stacks at the real shapes.
+Reads only the GGUF header (topk, dims). Cycles >= 12 random expert selections over 512 experts (far above the 32 MB MALL), HIP-graph replay.
+ mtp_micro.py [--sweep] [--out F] run under both GPU locks (runmicro_mtp.sh), <= 180 s
+Reports ms / GB/s for _k_gu, _k_down (shipped tiles) and a tile sweep, plus the split-S down and fused variants of moe_i8 when present."""
+import os, sys, json, time, argparse, statistics
+HERE = os.path.dirname(os.path.abspath(__file__))
+TREE = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
+sys.path.insert(0, os.path.join(TREE, "tools", "hy4"))
+import torch
+import triton
+import engine as _eng
+_eng._stub_package(TREE)
+from exllamav3.loader import moe_i8 as MI
+from exllamav3.loader.gguf_collection import GGUFCollection
+
+ap = argparse.ArgumentParser()
+ap.add_argument("--sweep", action="store_true")
+ap.add_argument("--out", default="")
+ap.add_argument("--variants", type=int, default=12)
+a = ap.parse_args()
+dev = torch.device("cuda")
+g = GGUFCollection(os.environ["GGUF"])
+m = g.meta
+p = m["general.architecture"] + "."
+S = int(m[p + "expert_used_count"])
+il = m[p + "block_count"] - m.get(p + "nextn_predict_layers", 0)
+(K, N, E) = g.infos[f"blk.{il}.ffn_gate_exps.weight"][1]
+lim = float(m[p + "swiglu_clamp_exp"][il])
+print(f"MTP experts: E {E} N {N} K {K} topk {S} lim {lim}", flush=True)
+
+
+class St:
+ pass
+
+
+def stack():
+ s = St()
+ s.E, s.N, s.K = E, N, K
+ s.q = torch.randint(-127, 128, (E, N, K), dtype=torch.int8, device=dev)
+ s.s = torch.rand(E, N, device=dev) * 1e-3 + 1e-4
+ return s
+
+
+gate, up, down = stack(), stack(), stack()
+z = (torch.randn(K, device=dev) * 0.5).float()
+sels = [torch.randperm(E, device=dev)[:S].contiguous() for _ in range(a.variants)]
+ws = [torch.rand(S, device=dev) + 0.1 for _ in sels]
+h = torch.randn(S, N, device=dev)
+
+
+def bench(fns, nrep=150, budget=4.0):
+ for f in fns:
+ f()
+ torch.cuda.synchronize()
+ s_ = torch.cuda.Stream()
+ s_.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s_):
+ for f in fns:
+ f()
+ torch.cuda.current_stream().wait_stream(s_)
+ torch.cuda.synchronize()
+ gr = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(gr):
+ for f in fns:
+ f()
+ for _ in range(5):
+ gr.replay()
+ torch.cuda.synchronize()
+ ev0, ev1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ ts, t0 = [], time.time()
+ while len(ts) < nrep and (time.time() - t0 < budget or len(ts) < 20):
+ ev0.record(); gr.replay(); ev1.record(); ev1.synchronize()
+ ts.append(ev0.elapsed_time(ev1))
+ return statistics.median(ts) / len(fns)
+
+
+res = []
+
+
+def rep(name, ms, nbytes, ref=None):
+ gbs = nbytes / (ms * 1e-3) / 1e9
+ r = dict(name=name, us=round(ms * 1e3, 1), gbs=round(gbs, 1), pct240=round(100 * gbs / 240, 0))
+ if ref is not None:
+ r["err_rel"] = float(((ref[0] - ref[1]).norm() / ref[1].norm()).item())
+ res.append(r)
+ print(json.dumps(r), flush=True)
+
+
+b_gu = S * 2 * N * K + S * 2 * N * 4
+b_dn = S * N * K + S * N * 4
+out_gu = torch.empty(S, N, device=dev)
+out_dn = torch.empty(N, device=dev)
+
+
+def gu(sel, BN=16, BK=128, nw=4):
+ MI._k_gu[(S, triton.cdiv(N, BN))](gate.q, up.q, gate.s, up.s, sel, z, out_gu, N, K, lim, BN=BN, BK=BK, num_warps=nw)
+
+
+def dn(sel, w, BN=8, BK=128, nw=4):
+ MI._k_down[(triton.cdiv(N, BN),)](down.q, down.s, sel, h, w, out_dn, N, K, S=S, BN=BN, BK=BK, num_warps=nw)
+
+
+rep("shipped_gu BN16 BK128 w4", bench([lambda s=s: gu(s) for s in sels]), b_gu)
+rep("shipped_down BN8 BK128 w4", bench([lambda s=s, w=w: dn(s, w) for s, w in zip(sels, ws)]), b_dn)
+rep("shipped_total (experts_forward)", bench([lambda s=s, w=w: MI.experts_forward(gate, up, down, z, s, w, lim) for s, w in zip(sels, ws)]), b_gu + b_dn)
+if a.sweep:
+ for BN in (4, 8, 16, 32):
+ for BK in (64, 128, 256, 512):
+ for nw in (1, 2, 4, 8):
+ try:
+ rep(f"gu BN{BN} BK{BK} w{nw}", bench([lambda s=s: gu(s, BN, BK, nw) for s in sels], 40, 0.6), b_gu)
+ except Exception as e: # noqa: BLE001
+ print("gu fail", BN, BK, nw, str(e)[:60], flush=True)
+ for BN in (2, 4, 8, 16):
+ for BK in (64, 128, 256, 512):
+ for nw in (1, 2, 4, 8):
+ try:
+ rep(f"down BN{BN} BK{BK} w{nw}", bench([lambda s=s, w=w: dn(s, w, BN, BK, nw) for s, w in zip(sels, ws)], 40, 0.6), b_dn)
+ except Exception as e: # noqa: BLE001
+ print("down fail", BN, BK, nw, str(e)[:60], flush=True)
+# new variants live in moe_i8 (experts_forward_v2 and friends), added by the fix
+if hasattr(MI, "experts_forward_v2"):
+ ref = MI.experts_forward(gate, up, down, z, sels[0], ws[0], lim)
+ new = MI.experts_forward_v2(gate, up, down, z, sels[0], ws[0], lim)
+ rep("v2_total", bench([lambda s=s, w=w: MI.experts_forward_v2(gate, up, down, z, s, w, lim) for s, w in zip(sels, ws)]), b_gu + b_dn, (new, ref))
+if a.out:
+ json.dump(res, open(a.out, "w"))
+print("MTP_MICRO_DONE", flush=True)