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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Hy4 multi-session: slot slabs for K / indexer state, slot-aware MLA core and indexer ops, MultiDecoder step over rows of several sessions, CPU tests (batched == solo, isolation, sentinels, Triton interpreter)
YanissAmzc4fbc83cb0a0
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex 981a6ee..fae9894 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -773,7 +773,8 @@ class Hy4Forward:kbase = 0ring = getattr(mla, "kv_ring", 0) # HY4_SWA_RING: window layers keep a ring of `ring` K rows instead of the full contextmla.ring_call = ring if gs is not None else 0- if gs is not None and gs.T == 1 and _KVF.ENABLED and _AE.ENABLED: # HY4_KV_FUSED: rms + rope + K-row write in ONE kernel+ slots = gs is not None and getattr(gs, "slots", False) # multi-session step (step_mu): K rows / indexer / attention go through the slot slabs+ if gs is not None and gs.T == 1 and _KVF.ENABLED and _AE.ENABLED and not slots: # HY4_KV_FUSED: rms + rope + K-row write in ONE kernelkc = gs.kv_row_fused(i, mla, cur, pos)else:with tm.t("attn proj"):@@ -783,7 +784,7 @@ class Hy4Forward:mla.kpos_arange = T > 16 # short eager steps use the generic kpos path (absolute positions); prefill rows are relative to the scratchelse:kc = gs.append_kv(i, kn) if gs is not None else _ns.append_kv(self, i, kn, start) if _ns.active(self) else (torch.cat([self.kc[i], kn]) if self.kc[i] is not None else kn)- N = kc.shape[0]+ N = gs.Nb if slots else kc.shape[0]allow = Noneif L.ix:with tm.t("indexer / kpool"):@@ -802,6 +803,7 @@ class Hy4Forward:for t, r in enumerate(sel.rows):allow[t, r.long()] = Trueallow = allow.to(self.dev)+ mla.slot_base = gs.base if slots else Nonekqv, gated, out = mla.attend(cur, pos, kc, gs.ar[:N] if gs is not None else _ns.kpos(self, kbase + N)[kbase:] if _ns.active(self) else torch.arange(N, device=self.dev), allow)self.kc[i] = kcself._hk("attn_kqv", i, kqv)diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex 8e192cf..c81df05 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -149,6 +149,7 @@ class Hy4MLA:qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))return self._h(qlat, "q"), self._h(qp, "q")+ slot_base = None # [T] long device (slot * cap per row) during a multi-session step, else None_qr_n = None # normalised q_a of this call's rows (indexer branch, HY4_PF_FUSE=1), consumed by attend_ck_qa_pre = None # raw wq_a output of this call's rows, left by the indexer branch (same expression): reused instead of a second GEMM@@ -280,7 +281,10 @@ class Hy4MLA:with tm.t("attn proj"):qlat, qpe = self.q(cur, pos, qa)with tm.t("MLA core + sinks"):- if PF_ATTN and T > PF_ATTN_MIN and qlat.is_cuda and getattr(self, "kpos_arange", False):+ if self.slot_base is not None: # multi-session step: kcache = the flat K slabs, row t reads its own slab (mu_slots)+ from . import mu_slots as _mu+ o = _mu.mla_attend_slots(qlat, qpe, kcache, pos, self.slot_base, kpos.shape[0], self.scale, self.sinks, self.window, allow)+ elif PF_ATTN and T > PF_ATTN_MIN and qlat.is_cuda and getattr(self, "kpos_arange", False):from . import prefill_attn as _pa # prefill rows: flash-style kernel, keys visited only inside the window / causal rangeo = (_pa.mla_flash if PF_ATTN_FLASH else _pa.mla_banded)(qlat, qpe, kcache, kcache.shape[0] - T, self.scale, self.sinks, self.window, allow)elif allow.__class__.__name__ == "SparseSel": # HY4_LC_SPARSE: decode rows, exact selected groups + tail onlydiff --git a/exllamav3/loader/mu_slots.py b/exllamav3/loader/mu_slots.pynew file mode 100644index 0000000..590c289--- /dev/null+++ b/exllamav3/loader/mu_slots.py@@ -0,0 +1,198 @@+"""Multi-session (slot) variants of the three decode ops that touch per-session state: MLA core over the K cache, k-pool indexer update + scoring,+K-row write. Everything else of the Hy4 step is row-wise, so rows of different sessions share one batched step.++Layout: every per-session buffer is a SLAB of a flat tensor: K `[S * cap, W]`, indexer value|gate rows `[S * cap, 2d]`, pooled keys `[S * cap / k, d]`.+A row r carries `base[r] = slot * cap` (device long) and its position `pos[r]`; the flat row of its token is `base + pos`. Session s's own view is+`flat[s * cap:(s + 1) * cap]` (a contiguous view of the same storage), so the solo code paths run on a session unchanged.+Generic by shape: nothing is keyed on a model name. No kernel here reads a row outside [base, base + N) with N <= cap (bounds are tested in+tests/test_hy4_mu_slots.py with NaN canaries around every slab)."""+from __future__ import annotations++import math+import os++import torch++try:+ import triton+ import triton.language as tl+except Exception: # noqa: BLE001+ triton = None++MAX_T = 16+++def _usable(*ts):+ if triton is None:+ return False+ if os.environ.get("TRITON_INTERPRET", "0") == "1":+ return True+ return all(t.is_cuda for t in ts)+++# ---------------------------------------------------------------------------------------------------- MLA core over per-row K slabs+def mla_slots_ref(q_lat, q_pe, kflat, qpos, base, N, scale, sinks, window, allow):+ """torch reference: row t attends keys base[t] + 0 .. N - 1 of the flat K buffer (causal on its own position, optional window / allow / sink)"""+ R = q_lat.shape[-1]+ T = q_lat.shape[0]+ out = torch.empty(q_lat.shape, dtype=torch.float32, device=q_lat.device)+ for t in range(T):+ n = min(N, int(qpos[t]) + 1) # keys past the row's own position are never read (like the kernel)+ b = int(base[t])+ ck = kflat[b:b + n]+ ar = torch.arange(n, device=kflat.device)+ s = torch.einsum("hr,nr->hn", q_lat[t], ck[:, :R]) + torch.einsum("hp,np->hn", q_pe[t], ck[:, R:])+ s = s * scale+ vis = torch.ones(n, dtype=torch.bool, device=kflat.device)+ if window:+ vis = vis & ((qpos[t] - ar) < window)+ if allow is not None:+ vis = vis & allow[t, :n]+ s = s.masked_fill(~vis[None], float("-inf"))+ if sinks is not None:+ s = torch.cat([s, sinks.float()[:, None]], dim=-1)+ p = torch.softmax(s, dim=-1)+ if sinks is not None:+ p = p[:, :-1]+ out[t] = torch.einsum("hn,nr->hr", p, ck[:, :R])+ return out+++if triton is not None:+ @triton.jit+ def _mla_slots_kernel(QL, QP, CK, QPOS, KB, ALLOW, SINK, O, N, scale, window,+ s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_al, s_o_t, s_o_h,+ R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BP: tl.constexpr, BN: tl.constexpr,+ HAS_ALLOW: tl.constexpr, HAS_WIN: tl.constexpr):+ t = tl.program_id(0)+ h = tl.program_id(1)+ offr = tl.arange(0, BR)+ offp = tl.arange(0, BP)+ mr = offr < R+ mp = offp < P+ q = tl.load(QL + t * s_ql_t + h * s_ql_h + offr, mask=mr, other=0.0).to(tl.float32)+ qp = tl.load(QP + t * s_qp_t + h * s_qp_h + offp, mask=mp, other=0.0).to(tl.float32)+ qpos = tl.load(QPOS + t)+ kb = tl.load(KB + t)+ m = tl.load(SINK + h).to(tl.float32)+ l = tl.zeros([], dtype=tl.float32) + 1.0+ acc = tl.zeros([BR], dtype=tl.float32)+ lo = 0+ hi = tl.minimum(N, qpos + 1)+ if HAS_WIN:+ lo = tl.maximum(0, qpos - window + 1) // BN * BN+ for n0 in range(lo, hi, BN):+ offn = n0 + tl.arange(0, BN)+ inb = offn < N+ vis = inb & (offn <= qpos)+ if HAS_WIN:+ vis = vis & ((qpos - offn) < window)+ if HAS_ALLOW:+ vis = vis & (tl.load(ALLOW + t * s_al + offn, mask=inb, other=0) != 0)+ rows = (kb + offn) * s_ck+ ck = tl.load(CK + rows[:, None] + offr[None, :], mask=inb[:, None] & mr[None, :], other=0.0).to(tl.float32)+ kp = tl.load(CK + rows[:, None] + R + offp[None, :], mask=inb[:, None] & mp[None, :], other=0.0).to(tl.float32)+ s = (tl.sum(ck * q[None, :], axis=1) + tl.sum(kp * qp[None, :], axis=1)) * scale+ s = tl.where(vis, s, float("-inf"))+ mn = tl.maximum(m, tl.max(s, axis=0))+ mn_s = tl.where(mn == float("-inf"), 0.0, mn)+ alpha = tl.exp(m - mn_s)+ pr = tl.exp(s - mn_s)+ l = l * alpha + tl.sum(pr, axis=0)+ acc = acc * alpha + tl.sum(pr[:, None] * ck, axis=0)+ m = mn+ tl.store(O + t * s_o_t + h * s_o_h + offr, acc / l, mask=mr)+++def mla_attend_slots(q_lat, q_pe, kflat, qpos, base, N, scale, sinks, window=0, allow=None):+ """q_lat [T, H, R], q_pe [T, H, P] fp32, kflat [S*cap, R+P] fp32 (flat K slabs), qpos [T] long, base [T] long (slot * cap), N rows scanned per row+ (bucket, <= cap; rows past qpos are never read), sinks [H], allow [T, >= N] bool or None -> o_lat [T, H, R] fp32.+ Same online-softmax maths as ref_fused._mla_kernel (sink = a key with logit s and a zero value)."""+ T, H, R = q_lat.shape+ P = q_pe.shape[-1]+ if (not _usable(q_lat, kflat) or T > MAX_T or sinks is None or q_lat.dtype != torch.float32 or kflat.dtype != torch.float32+ or q_lat.stride(-1) != 1 or q_pe.stride(-1) != 1 or kflat.stride(-1) != 1):+ return mla_slots_ref(q_lat, q_pe, kflat, qpos, base, N, scale, sinks, window, allow)+ out = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)+ al = allow.view(torch.uint8) if allow is not None else qpos+ _mla_slots_kernel[(T, H)](q_lat, q_pe, kflat, qpos, base, al, sinks.float().contiguous(), out, int(N), float(scale), int(window),+ q_lat.stride(0), q_lat.stride(1), q_pe.stride(0), q_pe.stride(1), kflat.stride(0),+ allow.stride(0) if allow is not None else 0, out.stride(0), out.stride(1),+ R=R, P=P, BR=triton.next_power_of_2(R), BP=triton.next_power_of_2(P), BN=16,+ HAS_ALLOW=allow is not None, HAS_WIN=bool(window), num_warps=4)+ return out+++# ---------------------------------------------------------------------------------------------------- indexer over slabs+def _rms(x, w, eps):+ x = x.float()+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * w+++class IxSlabs:+ """flat state of one indexer layer for S sessions: vgb [S*cap, 2d] (per-position value | gate rows), pool [S*cap/k, d]; `view(s)` = the solo buffers of session s.+ pool_update's Triton kernel indexes the rope table by group start: the table is tiled S times so the FLAT group start is a valid index."""++ def __init__(self, ix, S, cap):+ k, d = ix.k, ix.d+ assert cap % k == 0+ self.S, self.cap, self.k, self.d = S, cap, k, d+ self.vgb = torch.zeros(S * cap, 2 * d, device=ix.dev)+ self.pool = torch.zeros(S * cap // k, d, device=ix.dev)+ self.tiles = None++ def view(self, s):+ c, k = self.cap, self.k+ return self.pool[s * c // k:(s + 1) * c // k], self.vgb[s * c:(s + 1) * c]++ def tiled_table(self, ix):+ if self.tiles is None:+ cs, sn = ix._table(self.cap)+ self.tiles = (cs[:self.cap].repeat(self.S, 1).contiguous(), sn[:self.cap].repeat(self.S, 1).contiguous())+ return self.tiles++[email protected]_grad()+def indexer_forward_slots(ix, sl, x, qr, pos, base, Nb, ar, poolk=False):+ """indexer_forward_static for rows of different sessions. x [T, E], qr [T, R], pos [T] long = position inside the row's own session, base [T] long = slot * cap.+ Each row writes its value | gate row at base + pos, updates the pooled group of its position, then (when Nb is past the all-causal bound) scores the pooled keys of ITS+ OWN slab and selects its top groups: the maths of one solo step per row. -> allow [T, Nb] bool or None."""+ k, d, H = ix.k, ix.d, ix.H+ 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)+ flat = base + pos+ sl.vgb.index_copy_(0, flat, vg_new)+ if poolk: # the one Triton kernel on flat positions; rope table tiled per slab+ from . import pool_fused as _pf+ cs, sn = sl.tiled_table(ix)+ _pf._pool_kernel[(pos.shape[0],)](sl.vgb, flat, ix.w["ape"], ix.w["pool_norm"], cs, sn, sl.pool, ix.eps, k=k, d=d, rd=ix.rope_dim)+ else:+ g0 = (flat // k) * k+ rows = sl.vgb[g0[:, None] + ar[:k][None, :]]+ v, g = rows[..., :d].reshape(-1, k, d), rows[..., d:].reshape(-1, k, d)+ p = (torch.softmax(g + ix.w["ape"][None], dim=1) * v).sum(1)+ pooled = ix._rope(_rms(p, ix.w["pool_norm"], ix.eps), (pos // k) * k)+ sl.pool.index_copy_(0, flat // k, pooled)+ if Nb <= (ix.n_top + 1) * k:+ 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)+ Pb = Nb // k+ pidx = (base // k)[:, None] + ar[:Pb][None, :]+ pg = sl.pool[pidx] # [T, Pb, d] pooled keys of each row's own session+ kq = torch.relu(torch.einsum("nhd,npd->nhp", iq, pg))+ sc = (kq * wt[:, :, None]).sum(1)+ gend = ar[:Pb] * k + (k - 1)+ vis = (gend[None] < pos[:, None]) if ix.tail else (gend[None] <= pos[:, None])+ sc = torch.where(vis, sc, torch.full_like(sc, -math.inf))+ idx = torch.topk(sc, min(ix.n_top, Pb), dim=1).indices+ gsel = torch.zeros(T, Pb, dtype=torch.bool, device=ix.dev)+ gsel.scatter_(1, idx, True)+ gsel &= vis+ allow = torch.zeros(T, Nb, dtype=torch.bool, device=ix.dev)+ allow[:, :Pb * k] = gsel.repeat_interleave(k, dim=1)+ lo = (pos - (pos % k)) if ix.tail else (pos - ((pos + 1) % k) + 1)+ j = ar[:Nb][None]+ allow |= (j >= lo[:, None]) & (j <= pos[:, None])+ return allowdiff --git a/exllamav3/loader/step_mu.py b/exllamav3/loader/step_mu.pynew file mode 100644index 0000000..9dc4279--- /dev/null+++ b/exllamav3/loader/step_mu.py@@ -0,0 +1,235 @@+"""Multi-session Hy4 decode: rows of S sessions in ONE graph replay (perf/hy4-strix-mu).++The solo graph step (step_graph.GraphDecoder) appends T consecutive tokens of ONE sequence. Here the T rows of a step may belong to different sessions: each row+carries (token, position, slab base) in the static input, every per-session buffer is a slab of a flat tensor (mu_slots), and the ops that read or write per-session+state (K row write, indexer update + scoring, MLA core, Engram row staging) address their own slab. Dense matrices, router, experts (union of the rows' experts), hyper+connections and the output head are row-wise already, so the rows share every weight read.++A session binds to the eager objects (Hy4Forward n / tokens, the indexers' pool / vgb / n / P / vg, the MTP head's K buffer) by `bind`: the solo code of prefill and of the draft+head runs on a session unchanged, on the slab views. Graphs are keyed (bucket, rows): the row -> session mapping is device data, so any mix of sessions reuses them."""+from __future__ import annotations++import os++import torch++from . import mu_slots as MS+from . import step_graph as SG+from . import step_nosync as _ns+from .engram_rows import QB # noqa: F401 (re-export for callers)++TM = SG.TM+++class _GSMU(SG._GS):+ """static context of a multi-session step: inp rows 0 token, 1 position, 2 slab base (slot * cap)"""+ slots = True++ def __init__(self, fw, cap):+ super().__init__(fw, cap)+ self.inp = torch.zeros(3, TM, dtype=torch.long, device=fw.dev)+ self.kvflat = {}+ self.slabs = {}++ @property+ def base(self):+ return self.inp[2, :self.T]++ def append_kv(self, i, kn):+ b = self.kvflat[i]+ b.index_copy_(0, self.base + self.pos, kn)+ return b++ def indexer(self, fw, i, cur, qr, N):+ from . import pool_fused as _PF+ return MS.indexer_forward_slots(fw._indexer_fused(i), self.slabs[i], cur, qr, self.pos, self.base, N, self.ar, poolk=_PF.ENABLED)+++class Session:+ """host state of one session; the device state lives in the slabs of the decoder"""++ def __init__(self, slot):+ self.slot = slot+ self.tokens: list[int] = []+ self.n = 0 # positions written (== len(tokens) between steps)+ self.ixs: dict = {} # trunk indexer layer -> (n, P, vg) eager state+ self.mt_ix = (0, 0, None) # MTP head indexer eager state (unused after the static init: kept for symmetry)+ self.y = None # next token to feed (host int)+ self.hcur = None # trunk state [1, D] of the last accepted position (device)+ self.ids: list[int] = []+ self.pf_pos = 0+ self.H: list = []+ self.ng = None+ self.extra: dict = {}+++class MultiDecoder(SG.GraphDecoder):+ def __init__(self, fw, nslots, cap=None):+ super().__init__(fw, cap)+ self.S = nslots+ self.gs = _GSMU(fw, self.cap)+ self.hin = torch.zeros(3, TM, dtype=torch.long).pin_memory()+ self.mt = None++ # -- one-time setup: flat slabs, then the solo prepare on slot 0's views+ def prepare(self):+ fw, st, gs, cap, S = self.fw, self.st, self.gs, self.cap, self.S+ st.ensure(cap)+ for i in range(fw.n_layers):+ mla = fw._layer(i).mla+ flat = torch.zeros(S * cap, mla.R + mla.rope_dim, dtype=torch.float32, device=fw.dev)+ gs.kvflat[i] = flat+ st.kv[i] = flat[:cap]+ for i in range(fw.n_layers):+ if fw._layer(i).ix:+ ix = fw._indexer_fused(i)+ sl = gs.slabs[i] = MS.IxSlabs(ix, S, cap)+ ix.pool, ix.vgb = sl.view(0)+ super().prepare()+ for ix in getattr(fw, "ixf", {}).values(): # slabs are zero: eager state of every session starts empty+ ix.n, ix.P, ix.vg = 0, 0, None++ def attach_mtp(self, mt):+ """per-session K buffer + indexer slabs of the MTP draft head"""+ self.mt = mt+ S, cap = self.S, self.cap+ mt.kflat = torch.zeros(S * cap, mt.mla.R + mt.mla.rope_dim, dtype=torch.float32, device=mt.dev)+ mt.sl = MS.IxSlabs(mt.ix, S, cap)+ mt.kbuf = mt.kflat[:cap]+ mt.ix.pool, mt.ix.vgb = mt.sl.view(0)++ # -- sessions+ def new_session(self, slot):+ s = Session(slot)+ c = self.cap+ for b in self.gs.kvflat.values():+ b[slot * c:(slot + 1) * c].zero_()+ for sl in self.gs.slabs.values():+ p, v = sl.view(slot)+ p.zero_()+ v.zero_()+ if self.mt is not None:+ self.mt.kflat[slot * c:(slot + 1) * c].zero_()+ p, v = self.mt.sl.view(slot)+ p.zero_()+ v.zero_()+ return s++ def bind(self, s):+ """make the eager objects (Hy4Forward, indexers, MTP head) work on session s"""+ fw, st, c = self.fw, self.st, self.cap+ for i, flat in self.gs.kvflat.items():+ st.kv[i] = flat[s.slot * c:(s.slot + 1) * c]+ for i, sl in self.gs.slabs.items():+ ix = fw._indexer_fused(i)+ ix.pool, ix.vgb = sl.view(s.slot)+ ix.n, ix.P, ix.vg = s.ixs.get(i, (0, 0, None))+ fw.n, fw.tokens, fw._x, fw._eng_pf = s.n, s.tokens, None, getattr(fw, "_eng_pf", {})+ if self.mt is not None:+ mt = self.mt+ mt.kbuf = mt.kflat[s.slot * c:(s.slot + 1) * c]+ mt.ix.pool, mt.ix.vgb = mt.sl.view(s.slot)+ mt.ix.n, mt.ix.P, mt.ix.vg = s.mt_ix++ def save(self, s):+ fw = self.fw+ s.n = fw.n+ for i in self.gs.slabs:+ ix = fw._indexer_fused(i)+ s.ixs[i] = (ix.n, ix.P, ix.vg)+ if self.mt is not None:+ s.mt_ix = (self.mt.ix.n, self.mt.ix.P, self.mt.ix.vg)++ def start_graph_state(self, s):+ """after the eager prefill of s: fold the open indexer group of each layer into the static vg rows (the solo `expect_n != start` branch)"""+ fw = self.fw+ self.bind(s)+ for i in self.gs.slabs:+ SG.indexer_static_init(fw._indexer_fused(i), self.cap)+ self.save(s)++ # -- host side of the Engram rows of a multi-session step+ def _stage_rows(self, rows):+ fw = self.fw+ jobs, r = [], 0+ for s, toks in rows:+ for t in range(len(toks)):+ p = s.n + t+ for i in sorted(fw.ple):+ e = fw.eng[i]+ ids, valid = SG.engram_row_ids(e, s.tokens, p)+ self.vpin[e.e, r] = torch.tensor(valid)+ jobs += [(e, r, c, rr) for c, rr in enumerate(ids)]+ r += 1+ for f in self._submit(jobs):+ f.result()+ self.gs.eng_raw.copy_(self.rpin, non_blocking=True)+ self.gs.eng_valid.copy_(self.vpin, non_blocking=True)++ def step_slots(self, rows):+ """rows = [(session, [tokens])]: append each token list at that session's next positions, ONE graph replay for all rows. Returns DEVICE (logits, argmax, x, h)+ with the rows concatenated in order (single row: logits [V], argmax scalar). session.n and session.tokens advance; a verifier that rejects rows calls `rewind`."""+ fw, gs = self.fw, self.gs+ T = sum(len(t) for _, t in rows)+ assert 1 <= T <= TM+ if not self.prepared:+ self.prepare()+ if self.ev_set:+ self.ev.synchronize()+ tk, ps, bs, top = [], [], [], 0+ for s, toks in rows:+ assert s.n + len(toks) <= self.cap, "context past the slab"+ s.tokens.extend(int(t) for t in toks)+ tk += [int(t) for t in toks]+ ps += list(range(s.n, s.n + len(toks)))+ bs += [s.slot * self.cap] * len(toks)+ top = max(top, s.n + len(toks))+ Nb = min(self.cap, ((top - 1) // SG.BUCKET + 1) * SG.BUCKET)+ gs.Nb = Nb+ self.hin[0, :T] = torch.tensor(tk)+ self.hin[1, :T] = torch.tensor(ps)+ self.hin[2, :T] = torch.tensor(bs)+ gs.inp.copy_(self.hin, non_blocking=True)+ self._stage_rows(rows)+ cg, _out = self._graph(Nb, T)+ self.x_out = _out[2]+ fw._h = _out[3]+ cg.replay()+ self.ev.record()+ self.ev_set = True+ for s, toks in rows:+ s.n += len(toks)+ self.stats["replays"] += 1+ return _out[0], _out[1], _out[2], _out[3]++ @staticmethod+ def rewind(s, n):+ """session s continues from position n (<= s.n): stale K / indexer rows past n are overwritten by position"""+ del s.tokens[n:]+ s.n = n+++from . import mtp_head as _MH+++class MTPGraphMU(_MH.MTPGraph):+ """the draft chain graph per (slot, bucket): the captured graph holds the addresses of the slot's K buffer / indexer slab views (set `slot` and bind the session first)"""+ slot = 0++ def _graph(self, N):+ key = (self.slot, N)+ g = self.graphs.get(key)+ if g is not None:+ return g+ s = torch.cuda.Stream()+ s.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(s):+ for _ in range(2):+ self.body(N)+ torch.cuda.current_stream().wait_stream(s)+ torch.cuda.synchronize()+ cg = torch.cuda.CUDAGraph()+ with torch.cuda.graph(cg, pool=self.pool):+ out = self.body(N)+ g = self.graphs[key] = (cg, out)+ return gdiff --git a/tests/test_hy4_mu_slots.py b/tests/test_hy4_mu_slots.pynew file mode 100644index 0000000..fe1e87c--- /dev/null+++ b/tests/test_hy4_mu_slots.py@@ -0,0 +1,203 @@+"""CPU tests of the multi-session slot ops (loader/mu_slots.py): batched rows of several sessions == each session stepped alone (solo ops of step_graph /+ref_fused), slab isolation (neighbour slots untouched, scrambled neighbours change nothing), bounds (slots outside the active ones keep a sentinel).+Tiny config: kpool 4, indexer head dim 16, top_k 16 (n_top 3: scoring starts past 16 positions), MLA R 8 + rope 4."""+import math+import os+import sys+import types+import importlib.util++import pytest+import torch++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def _load():+ for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):+ m = sys.modules.get(n) or types.ModuleType(n)+ m.__path__ = [os.path.join(ROOT, "exllamav3", s)]+ sys.modules[n] = m+ from exllamav3.loader import mu_slots, step_graph, indexer_fused, ref_fused+ return mu_slots, step_graph, indexer_fused, ref_fused+++MS, SG, IXF, RF = _load()+K, D, H, E, RQ = 4, 16, 2, 24, 12+CAP, S = 64, 4+++def make_ix(seed=0, cap=CAP):+ g = torch.Generator().manual_seed(seed)+ r = lambda *s: torch.randn(*s, generator=g) * 0.5+ w = {"attn_k": r(D, E), "q_b": r(H * D, RQ), "value": r(D, D), "gate": r(D, D), "k_norm": 1 + r(D) * 0.1, "proj": r(H, E), "ape": r(K, D) * 0.1,+ "pool_norm": 1 + r(D) * 0.1}+ return IXF.FusedKPoolIndexer(w, "cpu", n_head=H, head_dim=D, top_k=16, kpool=K, select_tail=True, rope_dim=8, rope_base=1e4, eps=1e-5, cap=cap)+++def solo_ix(w_from, cap=CAP):+ ix = make_ix(0, cap)+ ix.w = w_from.w+ SG.indexer_static_init(ix, cap)+ return ix+++def causal(pos, Nb):+ return torch.arange(Nb)[None] <= pos[:, None]+++def run_case(plan, scramble=False, poolk=False, seed=1):+ """plan: list of steps, each a list of (slot, T) rows; returns (ok flags) comparing the batched slab ops with solo ops per session"""+ g = torch.Generator().manual_seed(seed)+ ixb = make_ix(0)+ SG.indexer_static_init(ixb, CAP)+ sl = MS.IxSlabs(ixb, S, CAP)+ if scramble:+ sl.vgb.normal_(generator=g)+ sl.pool.normal_(generator=g)+ solo = {}+ ar = torch.arange(CAP)+ nxt = {}+ for step in plan:+ rows = []+ for slot, T in step:+ n0 = nxt.get(slot, 0)+ nxt[slot] = n0 + T+ rows.append((slot, n0, T))+ xs = {r: torch.randn(r[2], E, generator=g) for r in rows}+ qs = {r: torch.randn(r[2], RQ, generator=g) for r in rows}+ pos = torch.cat([torch.arange(n0, n0 + T) for _, n0, T in rows])+ base = torch.cat([torch.full((T,), slot * CAP) for slot, _, T in rows])+ x = torch.cat([xs[r] for r in rows])+ qr = torch.cat([qs[r] for r in rows])+ Nb = min(CAP, ((int((pos).max()) + 1 - 1) // 16 + 1) * 16)+ al_b = MS.indexer_forward_slots(ixb, sl, x, qr, pos, base, Nb, ar, poolk=poolk)+ if al_b is None:+ al_b = causal(pos, Nb)+ o = 0+ for slot, n0, T in rows:+ ixs = solo.get(slot)+ if ixs is None:+ ixs = solo[slot] = solo_ix(ixb)+ p = torch.arange(n0, n0 + T)+ Nbs = min(CAP, ((n0 + T - 1) // 16 + 1) * 16)+ al_s = SG.indexer_forward_static(ixs, xs[(slot, n0, T)], qs[(slot, n0, T)], p, Nbs, ar)+ if al_s is None:+ al_s = causal(p, Nbs)+ got = al_b[o:o + T]+ assert torch.equal(got[:, :Nbs], al_s), f"allow differs slot {slot} n0 {n0}"+ assert not got[:, Nbs:].any() or bool((got[:, Nbs:] <= causal(p, Nb)[:, Nbs:]).all())+ o += T+ for slot, ixs in solo.items():+ n = nxt[slot]+ pv, vv = sl.view(slot)+ assert torch.equal(vv[:n], ixs.vgb[:n]), f"vgb rows differ slot {slot}"+ ng = n // K # completed groups: pooled keys+ tol = dict(rtol=0, atol=0) if not poolk else dict(rtol=1e-5, atol=1e-6)+ torch.testing.assert_close(pv[:ng], ixs.pool[:ng], **tol)+ return sl, nxt+++PLAN = [[(1, 3), (2, 3)], [(1, 1), (2, 1)], [(1, 4), (2, 2)]] + [[(1, 1), (2, 1)]] * 25 + [[(2, 2)], [(1, 3)]] + [[(1, 1), (2, 4)]] * 6+++def test_indexer_batched_equals_solo_past_scoring_bound():+ run_case(PLAN)+++def test_indexer_staggered_sessions_unequal_positions():+ plan = [[(0, 5)], [(0, 5), (3, 2)], [(3, 3)]] + [[(0, 1), (3, 1)]] * 30 + [[(3, 1)]] * 7 + [[(0, 1), (3, 1)]] * 4+ run_case(plan)+++def test_indexer_neighbour_garbage_changes_nothing_and_idle_slots_untouched():+ sl, nxt = run_case(PLAN, scramble=False)+ k0 = None+ # scrambled slab content (finite garbage in every slot incl. the active ones beyond their position): same allow / same rows below the position+ sl2, _ = run_case(PLAN, scramble=True)+ for slot in (0, 3): # idle slots: never written+ assert not sl.vgb[slot * CAP:(slot + 1) * CAP].any() and not sl.pool[slot * CAP // K:(slot + 1) * CAP // K].any()+++def test_indexer_sentinel_slots_outside_the_batch_keep_their_values():+ ixb = make_ix(0)+ SG.indexer_static_init(ixb, CAP)+ sl = MS.IxSlabs(ixb, S, CAP)+ sl.vgb.fill_(7.0)+ sl.pool.fill_(7.0)+ ar = torch.arange(CAP)+ g = torch.Generator().manual_seed(5)+ T = 8+ for n0 in range(0, CAP, T): # slot S - 1 (the last slab) and slot 1 run to their last position+ pos = torch.cat([torch.arange(n0, n0 + T)] * 2)+ base = torch.cat([torch.full((T,), (S - 1) * CAP), torch.full((T,), CAP)])+ MS.indexer_forward_slots(ixb, sl, torch.randn(2 * T, E, generator=g), torch.randn(2 * T, RQ, generator=g), pos, base, min(CAP, n0 + T + 8), ar)+ for slot in (0, 2):+ assert bool((sl.vgb[slot * CAP:(slot + 1) * CAP] == 7.0).all()) and bool((sl.pool[slot * CAP // K:(slot + 1) * CAP // K] == 7.0).all())+ assert not bool((sl.vgb[S * CAP - 1] == 7.0).all()) and not bool((sl.pool[-1] == 7.0).all())+++def test_indexer_poolk_triton_interpreter_matches_torch_path():+ if os.environ.get("TRITON_INTERPRET") != "1":+ pytest.skip("needs TRITON_INTERPRET=1")+ run_case(PLAN[:12], poolk=True)+++# ------------------------------------------------------------------------------------------------ attention core+def attn_inputs(seed=3):+ g = torch.Generator().manual_seed(seed)+ R, P = 8, 4+ kflat = torch.randn(S * CAP, R + P, generator=g)+ return g, R, P, kflat++[email protected]("window", [0, 7])+def test_mla_slots_ref_equals_per_row_solo_reference(window):+ g, R, P, kflat = attn_inputs()+ rows = [(1, 40), (2, 3), (1, 41), (3, 63), (0, 0)]+ T = len(rows)+ ql, qp = torch.randn(T, 2, R, generator=g), torch.randn(T, 2, P, generator=g)+ sinks = torch.randn(2, generator=g)+ qpos = torch.tensor([p for _, p in rows])+ base = torch.tensor([s * CAP for s, _ in rows])+ N = 64+ allow = torch.rand(T, N, generator=g) > 0.3+ for al in (None, allow):+ got = MS.mla_slots_ref(ql, qp, kflat, qpos, base, N, 0.3, sinks, window, al)+ for t, (s, p) in enumerate(rows):+ kk = kflat[s * CAP:s * CAP + N]+ want = RF.mla_sink_attend_ref(ql[t:t + 1], qp[t:t + 1], kk[:, :R], kk[:, R:], qpos[t:t + 1], torch.arange(N), 0.3, sinks, window, None if al is None else al[t:t + 1])+ torch.testing.assert_close(got[t], want[0], rtol=1e-5, atol=1e-6)+++def test_mla_slots_other_slabs_and_future_rows_are_not_read():+ g, R, P, kflat = attn_inputs()+ T = 3+ ql, qp = torch.randn(T, 2, R, generator=g), torch.randn(T, 2, P, generator=g)+ sinks = torch.randn(2, generator=g)+ qpos = torch.tensor([30, 10, 63])+ base = torch.tensor([CAP, 2 * CAP, 3 * CAP])+ a = MS.mla_slots_ref(ql, qp, kflat, qpos, base, 64, 0.3, sinks, 0, None)+ k3 = kflat.clone()+ k3[:CAP] = float("nan")+ for s_, p_ in ((1, 30), (2, 10)):+ k3[s_ * CAP + p_ + 1:(s_ + 1) * CAP] = float("nan")+ b = MS.mla_slots_ref(ql, qp, k3, qpos, base, 64, 0.3, sinks, 0, None)+ assert torch.isfinite(b).all() and torch.equal(a, b)++[email protected](os.environ.get("TRITON_INTERPRET") != "1", reason="needs TRITON_INTERPRET=1")[email protected]("window", [0, 9])+def test_mla_slots_kernel_interpreter_equals_reference(window):+ g, R, P, kflat = attn_inputs()+ rows = [(1, 40), (2, 3), (3, 63), (0, 17)]+ T = len(rows)+ ql, qp = torch.randn(T, 2, R, generator=g), torch.randn(T, 2, P, generator=g)+ sinks = torch.randn(2, generator=g)+ qpos = torch.tensor([p for _, p in rows])+ base = torch.tensor([s * CAP for s, _ in rows])+ allow = torch.rand(T, 64, generator=g) > 0.3+ for al in (None, allow):+ want = MS.mla_slots_ref(ql, qp, kflat, qpos, base, 64, 0.3, sinks, window, al)+ got = MS.mla_attend_slots(ql, qp, kflat, qpos, base, 64, 0.3, sinks, window, al)+ torch.testing.assert_close(got, want, rtol=1e-4, atol=1e-5)diff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex 8937711..71570da 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -93,16 +93,22 @@ class Hy4Engine:torch.cuda.synchronize()self.M = Mprogress("graph decoder + draft head")- self.GR = SG.GraphDecoder(M)+ self.GR = self._decoder(M)self.GR.prepare() # static K / indexer / Engram buffers at the full context size: addresses never change after thisself.MT = MH.Hy4MTP(M)- self.MG = MH.MTPGraph(self.MT, self.k)+ self.MG = self._mtp_graph()MH._STAGE_OV[0] = os.environ.get("HY4_SERVE_STAGE_OV", "1") == "1" # Engram row 0 of the next verify staged during the draft chaintorch.cuda.synchronize()self.load_s = time.time() - t0self.ready = Trueprogress(f"ready: {M.n_layers} layers, {M.stats.get('resident_gib')} GiB resident experts, {self.load_s:.0f} s")+ def _decoder(self, M): # hooks of the multi-session engine (mu_engine.py)+ return self.SG.GraphDecoder(M)++ def _mtp_graph(self):+ return self.MH.MTPGraph(self.MT, self.k)+def _decode_flags(self):"""remember the decode-set switches the environment selected at import"""L = self.SG.__name__.rsplit(".", 1)[0]