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 prefill: collect only the head states the draft head reads
zaxbysauce170a2f21d79e
diff --git a/tests/test_hy4_prefill_head_states_cpu.py b/tests/test_hy4_prefill_head_states_cpu.pynew file mode 100644index 0000000..607ec42--- /dev/null+++ b/tests/test_hy4_prefill_head_states_cpu.py@@ -0,0 +1,106 @@+"""CPU tests of the Hy4 prefill head-state window (tools/hy4/engine.py).++The MTP draft head reads the trunk head states of prompt rows [lo, n-1] only. prefill() used to+build the state of every prompt row and torch.cat them, which costs 2 x n x 3072 x 4 B of peak+memory - 24.6 GiB at a 1M prompt - and OOMs long-context prefill. It now keeps only the rows the+draft head reads.++These tests pin the invariant that makes that safe: the rows the collector keeps are the rows+_prime_draft() reads, with the same values and the same order.++No GPU, no model. Run: PYTHONPATH=. pytest -q tests/test_hy4_prefill_head_states_cpu.py+"""+import os+import sys++import torch++HERE = os.path.dirname(os.path.abspath(__file__))+TREE = os.path.dirname(HERE)+sys.path.insert(0, os.path.join(TREE, "tools", "hy4"))++os.environ.setdefault("HY4_PRIME_ROWS", "7") # small, so the draft fill takes several slices+from engine import PRIME_ROWS, copy_head_state_rows, head_state_window # noqa: E402++EMB = 8 # fake n_embd+++def chunk_plan(total, chunk):+ """the chunk boundaries prefill walks (full chunks of `chunk` rows)"""+ out, s = [], 0+ while s < total:+ e = min(total, s + chunk)+ out.append((s, e))+ s = e+ return out+++def collect(plan, n, lo):+ """-> the buffer prefill builds: one row per prompt row in [lo, n-1]"""+ out = torch.full((n - lo, EMB), -1.0)+ for s, e in plan:+ st = torch.arange(s, e, dtype=torch.float32).unsqueeze(1).repeat(1, EMB)+ copy_head_state_rows(out, st, s, e, lo)+ return out+++def row(j):+ return torch.full((EMB,), float(j))+++def test_window_covers_the_whole_prompt_when_prime_rows_is_zero():+ # prime_rows = 0 means "fill the draft cache for the whole prompt": nothing may be dropped+ for n in (1, 100, 999983):+ assert head_state_window(n, 0) == (0, n)+++def test_window_is_the_draft_tail_when_prime_rows_is_set():+ n, prime_rows = 999983, 2048+ lo, count = head_state_window(n, prime_rows)+ assert lo == n - 1 - prime_rows+ assert count == prime_rows + 1 # rows [lo, n-1] inclusive+ # a prompt shorter than the window keeps everything+ assert head_state_window(100, 2048) == (0, 100)+ assert head_state_window(2049, 2048) == (0, 2049)+++def test_collected_rows_are_exactly_the_rows_the_draft_head_reads():+ n, chunk, prime_rows = 1000, 256, 64+ lo, count = head_state_window(n, prime_rows)+ H = collect(chunk_plan(n, chunk), n, lo)+ assert H.shape == (count, EMB)++ # every collected row carries the value of its prompt row+ for j in range(lo, n):+ assert torch.equal(H[j - lo], row(j))++ # the rows _prime_draft() reads are present, in order, with the right values+ read, s = [], lo+ while s < n - 1:+ e = min(n - 1, s + PRIME_ROWS)+ read.extend(range(s, e))+ s = e+ assert read == list(range(lo, n - 1))+ for r in read:+ assert torch.equal(H[r - lo], row(r))+++def test_a_chunk_that_starts_before_lo_is_truncated_not_dropped():+ # the chunk containing lo starts before lo: its head is kept from lo on, its prefix is dropped+ n, chunk, prime_rows = 1000, 256, 64+ lo, _ = head_state_window(n, prime_rows)+ plan = chunk_plan(n, chunk)+ s, e = next((s, e) for s, e in plan if e > lo)+ assert s < lo < e+ H = collect(plan, n, lo)+ for j in range(lo, n):+ assert torch.equal(H[j - lo], row(j))+++def test_rows_before_lo_are_never_copied():+ n, chunk, prime_rows = 1000, 256, 64+ lo, _ = head_state_window(n, prime_rows)+ out = torch.full((n - lo, EMB), -1.0)+ st = torch.arange(0, 100, dtype=torch.float32).unsqueeze(1).repeat(1, EMB)+ copy_head_state_rows(out, st, 0, 100, lo)+ assert torch.equal(out, torch.full((n - lo, EMB), -1.0))diff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex 2102a9c..b914caa 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -21,6 +21,26 @@ CHUNK_DEFAULT = 8192PRIME_ROWS = int(os.environ.get("HY4_PRIME_ROWS", "2048")) # rows per batched MTP draft-cache fill call+def head_state_window(n: int, prime_rows: int):+ """-> (lo, count): the prompt rows whose trunk head states the MTP draft head reads.++ The draft head consumes prompt rows [lo, n-1]; lo = n-1-prime_rows when prime_rows > 0, else 0.+ Rows before lo are never read, so prefill does not have to materialise them. prefill() and+ _prime_draft() both take lo from here, so the collector and the consumer cannot drift apart.+ """+ lo = 0 if prime_rows <= 0 else max(0, n - 1 - prime_rows)+ return lo, n - lo+++def copy_head_state_rows(out, st, s: int, e: int, lo: int):+ """Copy the part of the chunk head state `st` (prompt rows s..e-1) that lies at or after `lo`+ into `out`, whose row 0 is prompt row `lo`."""+ if e <= lo:+ return+ a = max(s, lo)+ out[a - lo:e - lo].copy_(st[a - s:e - s])++WARMUP_MIN = 256 # below this many prompt tokens a warm-up compiles nothing useful: skip itWARMUP_PAD = 16 # row alignment of the last prefill chunk (the static buffers also keep 64 spare rows, see serve.apply_env)@@ -258,15 +278,23 @@ class Hy4Engine:n = len(ids)self.phase("prefill")M.prefetch_engram(ids, self.chunk)- states, lg = [], None+ # The MTP draft head reads the head states of rows [lo, n-1] only (see head_state_window), so+ # prefill keeps just those rows. Collecting every row and torch.cat-ing them costs+ # 2 x n x 3072 x 4 B of peak memory - 22.9 GiB at a 1M prompt - and OOMs there.+ lo = head_state_window(n, self.prime_rows)[0]+ H, lg = None, Nonefor s, e in self.hf.chunk_plan(0, n, self.chunk):lg = M.step(ids[s:e])- states.append(M.head_state(M._x))+ st = M.head_state(M._x)M._x = None+ if e > lo: # rows before lo are never read by the draft head+ if H is None:+ H = torch.empty(n - lo, st.shape[1], dtype=st.dtype, device=st.device)+ copy_head_state_rows(H, st, s, e, lo)torch.cuda.synchronize()y = int(torch.argmax(lg))- H = torch.cat(states) if len(states) > 1 else states[0]- self._H = H+ if H is None:+ raise RuntimeError("prefill produced no head states")hcur = H[-1:].clone()t = time.perf_counter()self.last_stats["prefill_trunk_s"] = t - self._t0@@ -280,7 +308,7 @@ class Hy4Engine:bench harness does one position at a time with MT.chain(.., k=1))"""torch, MT = self.torch, self.MTn = len(ids)- lo = 0 if self.prime_rows <= 0 else max(0, n - 1 - self.prime_rows)+ lo = head_state_window(n, self.prime_rows)[0] # H starts at prompt row lotok = torch.tensor(ids, dtype=torch.long, device=self.dev)ar = MT.ars = lo@@ -289,15 +317,15 @@ class Hy4Engine:try:while s < n - 1:e = min(n - 1, s + PRIME_ROWS)- MT.prime(tok[s + 1:e + 1], H[s:e], ar[s:e], ((e + 3) // 4) * 4)+ MT.prime(tok[s + 1:e + 1], H[s - lo:e - lo], ar[s:e], ((e + 3) // 4) * 4)s = eself.last_stats["prime_mode"] = "batched" if lo == 0 else f"batched tail {n - 1 - lo}"except Exception as ex: # noqa: BLE001 - the draft only affects speed, never the output: fall back to the last 128 rows one by oneprint(f"draft cache fill failed ({type(ex).__name__}: {ex}); falling back to a short per-row fill", flush=True)torch.cuda.synchronize()MT.reset()- for j in range(max(0, n - 129), n - 1):- MT.chain(tok[j + 1:j + 2], H[j:j + 1], j, 1)+ for j in range(max(lo, n - 129), n - 1):+ MT.chain(tok[j + 1:j + 2], H[j - lo:j + 1 - lo], j, 1)self.last_stats["prime_mode"] = "per-row tail 128 (batched failed)"finally:if f16 is None: