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 multi-session: HY4_MU_SYNC_DEBUG=1 syncs and logs every stage of the slots path (prefill chunk, draft chain, graph replay segments) and runs each new trunk graph once eagerly with a sync around every layer / op, so one rerun names the kernel of an asynchronous HSA fault; CPU test

YanissAmzfa41179b0fdf
diff --git a/exllamav3/loader/mu_debug.py b/exllamav3/loader/mu_debug.py
new file mode 100644
index 0000000..b51a321
--- /dev/null
+++ b/exllamav3/loader/mu_debug.py
@@ -0,0 +1,63 @@
+"""HY4_MU_SYNC_DEBUG=1: locate a device fault (HSA 0x1016 / hipErrorLaunchFailure) of the multi-session path.
+
+A GPU fault is asynchronous: it surfaces at the next host sync (a .tolist(), a .to(), a torch.tensor(..., device=...)), far from the kernel that caused it. With the env set,
+every stage of the slots path (prefill chunk, draft chain, each graph segment replay, the eager probe of a new graph, the draft catch-up steps) logs `mu-sync begin <stage>` and
+waits for the device when it ends. The LAST `begin` line before the crash is the stage that faulted (a Python-level fault is also logged as `mu-sync FAULT in <stage>`).
+A new (bucket, rows) trunk graph is first run once eagerly (`probe`) with a sync + log around every layer, indexer, K-row write, Engram stage, MLA core and FFN, so one rerun names the
+layer and the op. Off by default: `stage` is a null context and `probe_wrap` does nothing."""
+from __future__ import annotations
+
+import contextlib
+import os
+
+import torch
+
+
+def enabled() -> bool:
+ return os.environ.get("HY4_MU_SYNC_DEBUG", "0") not in ("", "0")
+
+
+def sync():
+ if torch.cuda.is_available():
+ torch.cuda.synchronize()
+
+
+def _stage(name):
+ print(f"mu-sync begin {name}", flush=True)
+ try:
+ yield
+ sync()
+ except BaseException as ex: # noqa: BLE001
+ print(f"mu-sync FAULT in {name}: {ex!r}", flush=True)
+ raise
+
+
+def stage(name):
+ return _stage(name) if enabled() else contextlib.nullcontext()
+
+
+_MISSING = object()
+
+
+def probe_wrap(targets):
+ """targets = [(obj, attr, label)]: while active, obj.attr(...) is a synced, logged stage `label` (the first int argument, the layer index, is appended). Restores on exit."""
+ saved = []
+ for obj, attr, label in targets:
+ fn = getattr(obj, attr)
+
+ def wrapped(*a, _fn=fn, _label=label, **k):
+ idx = next((x for x in a[:2] if isinstance(x, int)), None)
+ with _stage(_label if idx is None else f"{_label} L{idx}"):
+ return _fn(*a, **k)
+ saved.append((obj, attr, obj.__dict__.get(attr, _MISSING)))
+ setattr(obj, attr, wrapped)
+ try:
+ yield
+ finally:
+ for obj, attr, old in reversed(saved):
+ if old is _MISSING:
+ delattr(obj, attr)
+ else:
+ setattr(obj, attr, old)
diff --git a/exllamav3/loader/step_mu.py b/exllamav3/loader/step_mu.py
index a3bbf95..25c708d 100644
--- a/exllamav3/loader/step_mu.py
+++ b/exllamav3/loader/step_mu.py
@@ -13,6 +13,7 @@ import os
import torch
+from . import mu_debug as DBG
from . import mu_slots as MS
from . import step_graph as SG
from . import step_nosync as _ns
@@ -100,6 +101,10 @@ class MultiDecoder(SG.GraphDecoder):
# -- sessions
def new_session(self, slot):
+ with DBG.stage(f"new_session slot {slot}"):
+ return self._new_session(slot)
+
+ def _new_session(self, slot):
s = Session(slot)
c = self.cap
for b in self.gs.kvflat.values():
@@ -143,10 +148,31 @@ class MultiDecoder(SG.GraphDecoder):
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)
+ with DBG.stage(f"start_graph_state slot {s.slot} n {s.n}"):
+ self.bind(s)
+ for i in self.gs.slabs:
+ SG.indexer_static_init(fw._indexer_fused(i), self.cap)
+ self.save(s)
+
+ def _probe(self, Nb, T, rows):
+ """HY4_MU_SYNC_DEBUG: the first step of each (bucket, rows, slot set) runs ONE eager body (captured graph or not) with a device sync + log around every layer and op
+ (mu_debug.probe_wrap), on the static inputs of this very step: a fault that depends on the slot index is caught on the first step that uses it"""
+ key = (Nb, T, tuple(sorted({s.slot for s, _ in rows})))
+ seen = self.__dict__.setdefault("_probed", set())
+ if key in seen:
+ return
+ seen.add(key)
+ fw, gs = self.fw, self.gs
+ tg = [(fw, "layer", "layer"), (fw, "_ffn", "ffn"), (gs, "indexer", "indexer"), (gs, "append_kv", "append_kv"), (gs, "engram", "engram")]
+ tg += [(fw._layer(i).mla, "attend", f"L{i} mla.attend") for i in range(fw.n_layers)]
+ gs.Nb, gs.T = Nb, T
+ old = fw._gs
+ fw._gs = gs
+ try:
+ with DBG.probe_wrap(tg), DBG.stage(f"probe eager body Nb={Nb} T={T} slots={key[2]}"):
+ self.body(self.bounds())
+ finally:
+ fw._gs = old
# -- host side of the Engram rows of a multi-session step
def _stage_rows(self, rows):
@@ -186,16 +212,22 @@ class MultiDecoder(SG.GraphDecoder):
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)
- cgs, _out = self._graph(Nb, T) # the solo capture: a LIST of graph segments (Engram split), replayed in order like step_rows
+ what = f"step_slots T={T} Nb={Nb} rows={[(s.slot, s.n, len(t)) for s, t in rows]}"
+ with DBG.stage(what + " inputs + Engram rows"):
+ 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)
+ if DBG.enabled():
+ self._probe(Nb, T, rows)
+ with DBG.stage(what + " graph (capture if new)"):
+ cgs, _out = self._graph(Nb, T) # the solo capture: a LIST of graph segments (Engram split), replayed in order like step_rows
self.x_out = _out[2]
fw._h = _out[3]
- for cg in cgs: # every Engram row of the step is already staged by _stage_rows: no per-segment staging, only the order
- cg.replay()
+ for si, cg in enumerate(cgs): # every Engram row of the step is already staged by _stage_rows: no per-segment staging, only the order
+ with DBG.stage(f"{what} replay segment {si}/{len(cgs)}"):
+ cg.replay()
self.ev.record()
self.ev_set = True
for s, toks in rows:
diff --git a/tests/test_hy4_mu_sync_debug.py b/tests/test_hy4_mu_sync_debug.py
new file mode 100644
index 0000000..a6d4e1d
--- /dev/null
+++ b/tests/test_hy4_mu_sync_debug.py
@@ -0,0 +1,112 @@
+"""CPU check of the HY4_MU_SYNC_DEBUG instrumentation (loader/mu_debug.py): off = null context, on = begin line per stage + a FAULT line when a stage raises, probe_wrap
+logs / restores wrapped methods (instance attribute removed again, original untouched)."""
+import os
+import sys
+import types
+
+import pytest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+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_debug as D # noqa: E402
+
+
+def test_off_is_a_null_context(capsys, monkeypatch):
+ monkeypatch.delenv("HY4_MU_SYNC_DEBUG", raising=False)
+ with D.stage("x"):
+ pass
+ assert capsys.readouterr().out == ""
+
+
+def test_on_logs_begin_and_fault(capsys, monkeypatch):
+ monkeypatch.setenv("HY4_MU_SYNC_DEBUG", "1")
+ with D.stage("a"):
+ pass
+ with pytest.raises(RuntimeError):
+ with D.stage("b"):
+ raise RuntimeError("boom")
+ out = capsys.readouterr().out.splitlines()
+ assert out[0] == "mu-sync begin a" and out[1] == "mu-sync begin b" and out[2].startswith("mu-sync FAULT in b")
+
+
+def test_probe_wrap_logs_layer_index_and_restores(capsys, monkeypatch):
+ monkeypatch.setenv("HY4_MU_SYNC_DEBUG", "1")
+
+ class Fw:
+ def layer(self, i, x):
+ return x + i
+
+ fw = Fw()
+ with D.probe_wrap([(fw, "layer", "layer")]):
+ assert fw.layer(3, 10) == 13
+ assert "layer" not in fw.__dict__ and fw.layer(1, 1) == 2
+ assert capsys.readouterr().out.splitlines() == ["mu-sync begin layer L3"]
+
+
+def test_step_slots_probe_runs_once_per_slot_set_and_restores(capsys, monkeypatch):
+ monkeypatch.setenv("HY4_MU_SYNC_DEBUG", "1")
+ import torch
+ from types import SimpleNamespace
+ from exllamav3.loader import step_mu
+
+ log = []
+
+ class Mla:
+ def attend(self, *a):
+ return a[0]
+
+ class Fw:
+ n_layers = 2
+ _gs = None
+ _h = None
+
+ def __init__(self):
+ self.mlas = [Mla(), Mla()]
+
+ def _layer(self, i):
+ return SimpleNamespace(mla=self.mlas[i])
+
+ def layer(self, i, x, *a):
+ self.mlas[i].attend(i)
+ self._ffn(i, None, x)
+ log.append(("layer", i, self._gs is not None))
+ return x
+
+ def _ffn(self, i, L, x):
+ return x
+
+ class Gs(SimpleNamespace):
+ def indexer(self, fw, i, *a):
+ return None
+
+ def append_kv(self, i, kn):
+ return kn
+
+ def engram(self, fw, i, x):
+ return x
+
+ out = (torch.zeros(1), torch.zeros(1), torch.zeros(1), torch.zeros(1))
+ d = object.__new__(step_mu.MultiDecoder)
+ d.fw = Fw()
+ d.gs = Gs(inp=torch.zeros(3, step_mu.TM, dtype=torch.long), Nb=0, T=0)
+ d.hin = torch.zeros(3, step_mu.TM, dtype=torch.long)
+ d.cap, d.prepared, d.ev_set = 4096, True, False
+ d.stats = {"replays": 0}
+ d.ev = SimpleNamespace(record=lambda: None, synchronize=lambda: None)
+ d._stage_rows = lambda rows: None
+ d._graph = lambda Nb, T: ([SimpleNamespace(replay=lambda: None)], out)
+ d.bounds = lambda: [(0, 2)]
+ d.body = lambda bnds: [d.fw.layer(i, None) for i in range(2)]
+ s = lambda slot: SimpleNamespace(slot=slot, n=5, tokens=[1] * 5)
+ d.step_slots([(s(6), [1])])
+ d.step_slots([(s(6), [1])]) # same key: no second probe
+ d.step_slots([(s(7), [1])]) # new slot set: probed again
+ lines = capsys.readouterr().out.splitlines()
+ assert sum("probe eager body" in l for l in lines) == 2
+ assert "mu-sync begin layer L1" in lines and "mu-sync begin L0 mla.attend L0" in lines and "mu-sync begin ffn L1" in lines
+ assert [l for l in lines if "replay segment" in l] and len([1 for e in log if e[0] == "layer"]) == 4
+ assert not any(k in d.fw.__dict__ for k in ("layer", "_ffn")) and "attend" not in d.fw.mlas[0].__dict__ and "indexer" not in d.gs.__dict__
diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.py
index 61dbb98..4b09128 100644
--- a/tools/hy4/mu_engine.py
+++ b/tools/hy4/mu_engine.py
@@ -6,6 +6,7 @@
Greedy: a session's stream equals plain greedy decoding of the trunk (the verifier keeps only the rows the trunk agrees with)."""
from __future__ import annotations
+import contextlib
import os
import threading
import time
@@ -14,6 +15,14 @@ from collections import deque
from engine import Hy4Engine, PRIME_ROWS, warmup_clamp
+def _stage(name):
+ """HY4_MU_SYNC_DEBUG=1: log the stage and sync the device when it ends (loader/mu_debug.py); a null context otherwise"""
+ if os.environ.get("HY4_MU_SYNC_DEBUG", "0") in ("", "0"):
+ return contextlib.nullcontext()
+ from exllamav3.loader import mu_debug
+ return mu_debug.stage(name)
+
+
class MuEngine(Hy4Engine):
def __init__(self, *a, slots: int = 4, **kw):
for f in ("HY4_SWA_RING", "HY4_LC_SPARSE"): # long-context levers act on the single-session K / indexer buffers, not on the slot slabs
@@ -50,15 +59,17 @@ class MuEngine(Hy4Engine):
if a == 0:
M.prefetch_engram(s.ids, s.chunk) # the row prefetch list is global: one prefill is in flight at a time, it starts with its first chunk
s.tok_dev = torch.tensor(s.ids, dtype=torch.long, device=self.dev)
- lg = M.step(s.ids[a:b])
- hs = M.head_state(M._x)
+ with _stage(f"prefill trunk step slot {s.slot} rows {a}:{b} of {n}"):
+ lg = M.step(s.ids[a:b])
+ hs = M.head_state(M._x)
M._x = None
e_end = min(b, n - 1) # head pairs (token j + 1, trunk state h_j) for j = a .. min(b, n - 1) - 1
if e_end > a:
f16 = os.environ.get("HY4_PF_F16")
os.environ["HY4_PF_F16"] = "0" # the fp16 attention chain is tuned for the trunk's matrices; the draft layer takes the generic prefill path
try:
- MT.prime(s.tok_dev[a + 1:e_end + 1], hs[:e_end - a], MT.ar[a:e_end], ((e_end + 3) // 4) * 4)
+ with _stage(f"prefill draft prime slot {s.slot} rows {a}:{e_end}"):
+ MT.prime(s.tok_dev[a + 1:e_end + 1], hs[:e_end - a], MT.ar[a:e_end], ((e_end + 3) // 4) * 4)
finally:
if f16 is None:
os.environ.pop("HY4_PF_F16", None)
@@ -85,7 +96,8 @@ class MuEngine(Hy4Engine):
out = {}
for r, s in enumerate(sess):
s.y = amh[r]
- s.hcur = hv[r:r + 1].clone() # a later spec_round (fewer sessions decode) drafts from the trunk state of the last fed position and the n-gram history
+ with _stage(f"plain_round hcur clone slot {s.slot} row {r}"):
+ s.hcur = hv[r:r + 1].clone() # a later spec_round (fewer sessions decode) drafts from the trunk state of the last fed position and the n-gram history
if s.ng is not None:
s.ng.add([s.y])
out[s] = [s.y]
@@ -121,7 +133,8 @@ class MuEngine(Hy4Engine):
continue
GR.bind(s)
MG.slot = s.slot
- plan.append((s, None, False, j, MG.run(s.y, s.hcur, j))) # drafts launched; read below
+ with _stage(f"spec_round draft chain slot {s.slot} j {j}"):
+ plan.append((s, None, False, j, MG.run(s.y, s.hcur, j))) # drafts launched; read below
rows, meta = [], []
for s, toks, skip, j, h in plan:
if toks is None:
@@ -165,11 +178,13 @@ class MuEngine(Hy4Engine):
GR.bind(s)
N = ((j + acc + 1 + 3) // 4) * 4
sts = torch.cat([skip_h(plan, s), hs[:acc]]) if acc > 0 else skip_h(plan, s)
- MT.step(torch.tensor(toks[:acc + 1], dtype=torch.long, device=self.dev), sts, MT.ar[j:j + acc + 1], N)
+ with _stage(f"spec_round draft catch-up (skip) slot {s.slot} j {j} acc {acc} N {N}"):
+ MT.step(torch.tensor(toks[:acc + 1], dtype=torch.long, device=self.dev), sts, MT.ar[j:j + acc + 1], N)
elif self.ngram_fill and acc >= kk and kk > 0:
GR.bind(s)
N = ((j + acc + 1 + 3) // 4) * 4
- MT.step(torch.tensor(toks[kk:acc + 1], dtype=torch.long, device=self.dev), hs[kk - 1:acc], MT.ar[j + kk:j + acc + 1], N)
+ with _stage(f"spec_round draft catch-up (fill) slot {s.slot} j {j} acc {acc} N {N}"):
+ MT.step(torch.tensor(toks[kk:acc + 1], dtype=torch.long, device=self.dev), hs[kk - 1:acc], MT.ar[j + kk:j + acc + 1], N)
if s.ng is not None:
s.ng.add(new)
s.y, s.hcur = amh[acc], hs[acc:acc + 1].clone()