Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

docs: publish GLM-5.2 inference research closeout

ZacharyZcR56c03a1ee3e6
diff --git a/c/tests/fixtures/glm52_replay_python.json b/c/tests/fixtures/glm52_replay_python.json
new file mode 100644
index 00000000..d8a47710
--- /dev/null
+++ b/c/tests/fixtures/glm52_replay_python.json
@@ -0,0 +1,14 @@
+{
+ "source": "GLM-5.2 greedy continuation captured on 2026-07-28",
+ "prompt_ids": [576, 729, 1265, 537, 990, 279, 5798, 3419],
+ "full_ids": [
+ 576, 729, 1265, 537, 990, 279, 5798, 3419,
+ 1565, 6860, 53896, 1714, 476, 1565, 28200, 53896,
+ 729, 13, 12084, 11, 4211, 279, 10875, 3019,
+ 315, 279, 10875, 3378, 12105, 13, 1654, 1184,
+ 311, 3270, 264, 13020, 729, 429, 80296, 1378,
+ 10610, 11464, 1119, 825, 10610, 1140, 13, 576,
+ 729, 1265, 537, 990, 5798, 3419, 3378, 368,
+ 476, 10610, 1005, 1084, 1265, 4211, 279, 10875
+ ]
+}
diff --git a/c/tests/fixtures/glm52_replay_smoke.json b/c/tests/fixtures/glm52_replay_smoke.json
new file mode 100644
index 00000000..7fc1febd
--- /dev/null
+++ b/c/tests/fixtures/glm52_replay_smoke.json
@@ -0,0 +1,5 @@
+{
+ "source": "Short prefix of glm52_replay_python.json for CUDA smoke tests",
+ "prompt_ids": [576, 729, 1265, 537, 990, 279, 5798, 3419],
+ "full_ids": [576, 729, 1265, 537, 990, 279, 5798, 3419, 1565]
+}
diff --git a/c/tests/test_placement_balance.py b/c/tests/test_placement_balance.py
new file mode 100644
index 00000000..50960c2d
--- /dev/null
+++ b/c/tests/test_placement_balance.py
@@ -0,0 +1,44 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from tools.placement_balance import read_counts, solve
+
+
+class PlacementBalanceTest(unittest.TestCase):
+ def test_reads_unique_counts_in_descending_order(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "stats"
+ path.write_text("3 0 4\n3 1 8\n3 0 6\n")
+ self.assertEqual(read_counts(path), [8, 6])
+
+ def test_aggregates_independent_stats_files(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ (path / "a.txt").write_text("3 0 4\n3 1 8\n")
+ (path / "b.txt").write_text("3 0 6\n3 1 1\n")
+ self.assertEqual(read_counts(path), [10, 9])
+
+ def test_balances_critical_tier_instead_of_filling(self):
+ plan = solve([40, 30, 20, 10], 4, 2.0, 1.0)
+ self.assertEqual(plan.slots, 2)
+ self.assertEqual(plan.gpu_share, 0.7)
+ self.assertEqual(plan.cpu_seconds, 60.0)
+ self.assertEqual(plan.gpu_seconds, 70.0)
+
+ def test_capacity_floor_prevents_nonresident_plan(self):
+ plan = solve([40, 30, 20, 10], 4, 2.0, 1.0, min_slots=3)
+ self.assertEqual(plan.slots, 3)
+ self.assertEqual(plan.gpu_share, 0.9)
+
+ def test_rejects_capacity_floor_above_gpu_limit(self):
+ with self.assertRaises(ValueError):
+ solve([1, 1], 1, 2.0, 1.0, min_slots=2)
+
+ def test_rejects_invalid_cost(self):
+ with self.assertRaises(ValueError):
+ solve([1], 1, 0.0, 1.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_placement_crossval.py b/c/tests/test_placement_crossval.py
new file mode 100644
index 00000000..09a49886
--- /dev/null
+++ b/c/tests/test_placement_crossval.py
@@ -0,0 +1,52 @@
+import importlib.util
+import tempfile
+import unittest
+from pathlib import Path
+
+
+MODULE_PATH = Path(__file__).parents[1] / "tools" / "placement_crossval.py"
+SPEC = importlib.util.spec_from_file_location("placement_crossval", MODULE_PATH)
+MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(MODULE)
+
+
+class PlacementCrossvalTest(unittest.TestCase):
+ def test_category_holdout_and_rank_file(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ fixtures = {
+ "alpha_0.txt": "0 0 9\n0 1 1\n",
+ "alpha_1.txt": "0 0 8\n0 1 2\n",
+ "beta_0.txt": "0 0 7\n0 2 3\n",
+ "beta_1.txt": "0 0 6\n0 2 4\n",
+ "gamma_0.txt": "0 0 5\n0 3 5\n",
+ "gamma_1.txt": "0 0 6\n0 3 4\n",
+ }
+ for name, body in fixtures.items():
+ (root / name).write_text(body)
+
+ categories = MODULE.read_categories(root)
+ pooled_mean, pooled_worst, _ = MODULE.cross_validate(
+ categories, slots=1, penalty=None
+ )
+ mean, worst, detail = MODULE.cross_validate(categories, slots=1, penalty=0)
+ self.assertEqual([name for name, _ in detail], ["alpha", "beta", "gamma"])
+ self.assertGreaterEqual(pooled_mean, pooled_worst)
+ self.assertGreaterEqual(mean, worst)
+ self.assertAlmostEqual(worst, 0.55)
+
+ ranked = MODULE.rank_experts(categories, penalty=0)
+ output = root / "ranked.stats"
+ MODULE.write_ranked(output, ranked)
+ self.assertTrue(output.read_text().startswith("0 0 "))
+
+ def test_rejects_empty_stats(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "alpha_0.txt"
+ path.write_text("")
+ with self.assertRaises(ValueError):
+ MODULE.read_run(path)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tools/analyze_split_entropy.py b/c/tools/analyze_split_entropy.py
new file mode 100644
index 00000000..25856a92
--- /dev/null
+++ b/c/tools/analyze_split_entropy.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python3
+"""Measure whether packed INT4 experts can be split losslessly across VRAM/RAM.
+
+VRAM stores a fixed-width group id ("base"). RAM stores the exact symbol's
+local index inside that group ("residual"). The practical estimate uses a
+global codebook and fixed-width local indices, so it is GPU-decodable without
+pretending that an entropy lower bound is an implementation.
+"""
+
+import argparse
+import glob
+import json
+import math
+import os
+import re
+
+import numpy as np
+from safetensors import safe_open
+
+
+EXPERT = re.compile(
+ r"^model\.layers\.(\d+)\.mlp\.experts\.(\d+)\."
+ r"(gate|up|down)_proj\.weight$")
+DTYPE_BYTES = {
+ "BOOL": 1, "U8": 1, "I8": 1, "I16": 2, "U16": 2,
+ "F16": 2, "BF16": 2, "I32": 4, "U32": 4, "F32": 4,
+ "I64": 8, "U64": 8, "F64": 8,
+}
+
+
+def compositions(total, parts, minimum=1):
+ if parts == 1:
+ if total >= minimum:
+ yield (total,)
+ return
+ for first in range(minimum, total - minimum * (parts - 1) + 1):
+ for tail in compositions(total - first, parts - 1, minimum):
+ yield (first,) + tail
+
+
+def best_fixed_width_groups(prob, base_bits):
+ """Best global unequal groups under fixed-width local indices.
+
+ For a given group-size tuple, the most probable symbols are assigned to
+ slots with the cheapest local-index width. This is exact because the
+ objective is linear in symbol probability.
+ """
+ groups = 1 << base_bits
+ sorted_prob = np.sort(prob)[::-1]
+ best = None
+ for sizes in compositions(16, groups):
+ ordered_sizes = tuple(sorted(sizes,
+ key=lambda n: (math.ceil(math.log2(n)), n)))
+ widths = [
+ math.ceil(math.log2(size))
+ for size in ordered_sizes
+ for _ in range(size)
+ ]
+ residual = float(np.dot(sorted_prob, np.asarray(widths)))
+ candidate = (residual, ordered_sizes)
+ if best is None or candidate < best:
+ best = candidate
+ ranked_symbols = np.argsort(prob)[::-1].tolist()
+ symbol_to_group = [0] * 16
+ symbol_to_local = [0] * 16
+ cursor = 0
+ for group, size in enumerate(best[1]):
+ for local, symbol in enumerate(ranked_symbols[cursor:cursor + size]):
+ symbol_to_group[symbol] = group
+ symbol_to_local[symbol] = local
+ cursor += size
+ return {
+ "base_bits": base_bits,
+ "residual_bits": best[0],
+ "total_bits": base_bits + best[0],
+ "group_sizes": best[1],
+ "group_widths": [math.ceil(math.log2(n)) for n in best[1]],
+ "symbol_to_group": symbol_to_group,
+ "symbol_to_local": symbol_to_local,
+ }
+
+
+def tensor_nbytes(tensor_slice):
+ shape = tensor_slice.get_shape()
+ count = math.prod(shape)
+ return count * DTYPE_BYTES[str(tensor_slice.get_dtype())]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("model_dir")
+ ap.add_argument("--layers", default="3,10,30,50,76",
+ help="comma-separated layers sampled for the histogram")
+ ap.add_argument("--expert-vram-gb", type=float, default=176.57)
+ ap.add_argument("--offset-weights", type=int, default=4096,
+ help="one 32-bit residual offset per this many weights")
+ ap.add_argument("--json-out")
+ args = ap.parse_args()
+
+ wanted = {int(v) for v in args.layers.split(",") if v}
+ paths = sorted(glob.glob(os.path.join(args.model_dir, "*.safetensors")))
+ if not paths:
+ raise SystemExit(f"no safetensors found under {args.model_dir}")
+
+ total_weight_bytes = 0
+ total_scale_bytes = 0
+ selected = []
+ tensor_sizes = {}
+ for path in paths:
+ with safe_open(path, framework="numpy") as sf:
+ for name in sf.keys():
+ tensor_sizes[name] = tensor_nbytes(sf.get_slice(name))
+
+ expert_names = []
+ for path in paths:
+ with safe_open(path, framework="numpy") as sf:
+ for name in sf.keys():
+ match = EXPERT.match(name)
+ if not match or str(sf.get_slice(name).get_dtype()) != "U8":
+ continue
+ expert_names.append(name)
+ total_weight_bytes += tensor_sizes[name]
+ if int(match.group(1)) in wanted:
+ selected.append((path, name))
+ total_scale_bytes = sum(
+ tensor_sizes.get(name + ".qs", 0) for name in expert_names)
+
+ hist = np.zeros(16, dtype=np.int64)
+ sampled_bytes = 0
+ by_layer = {}
+ for index, (path, name) in enumerate(selected, 1):
+ with safe_open(path, framework="numpy") as sf:
+ packed = np.asarray(sf.get_tensor(name), dtype=np.uint8).reshape(-1)
+ local = (np.bincount(packed & 15, minlength=16) +
+ np.bincount(packed >> 4, minlength=16))
+ hist += local
+ sampled_bytes += packed.nbytes
+ layer = int(EXPERT.match(name).group(1))
+ by_layer.setdefault(layer, np.zeros(16, dtype=np.int64))
+ by_layer[layer] += local
+ if index % 256 == 0:
+ print(f"sampled {index}/{len(selected)} tensors "
+ f"({sampled_bytes / 1e9:.1f} GB)", flush=True)
+
+ count = int(hist.sum())
+ prob = hist / count
+ nz = prob[prob > 0]
+ entropy = float(-np.sum(nz * np.log2(nz)))
+ modes = {bits: best_fixed_width_groups(prob, bits) for bits in (1, 2)}
+
+ weight_count = total_weight_bytes * 2
+ offset_bytes = math.ceil(weight_count / args.offset_weights) * 4
+ budget = args.expert_vram_gb * 1e9
+ max_base = 8 * max(
+ 0, budget - total_scale_bytes - offset_bytes) / weight_count
+ base2_fraction = min(1.0, max(0.0, max_base - 1.0))
+ practical_residual = (
+ (1 - base2_fraction) * modes[1]["residual_bits"] +
+ base2_fraction * modes[2]["residual_bits"])
+ ideal_residual = max(0.0, entropy - max_base)
+
+ result = {
+ "model_dir": os.path.abspath(args.model_dir),
+ "sample_layers": sorted(wanted),
+ "sample_tensors": len(selected),
+ "sample_packed_gb": sampled_bytes / 1e9,
+ "expert_weight_gb": total_weight_bytes / 1e9,
+ "expert_scale_gb": total_scale_bytes / 1e9,
+ "symbol_histogram": hist.tolist(),
+ "entropy_bits_per_weight": entropy,
+ "rans_ideal_ratio_to_int4": entropy / 4,
+ "fixed_width_modes": modes,
+ "split_at_budget": {
+ "expert_vram_budget_gb": args.expert_vram_gb,
+ "offset_metadata_gb": offset_bytes / 1e9,
+ "max_average_base_bits": max_base,
+ "base2_weight_fraction": base2_fraction,
+ "ideal_residual_bits": ideal_residual,
+ "ideal_residual_gb": weight_count * ideal_residual / 8e9,
+ "practical_residual_bits": practical_residual,
+ "practical_residual_gb": weight_count * practical_residual / 8e9,
+ "practical_total_bits": max_base + practical_residual,
+ },
+ "layer_entropy": {
+ str(layer): float(-np.sum(
+ (h[h > 0] / h.sum()) * np.log2(h[h > 0] / h.sum())))
+ for layer, h in sorted(by_layer.items())
+ },
+ }
+ print(json.dumps(result, indent=2))
+ if args.json_out:
+ with open(args.json_out, "w", encoding="utf-8") as fh:
+ json.dump(result, fh, indent=2)
+ fh.write("\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/c/tools/benchmark_continuous_batch.py b/c/tools/benchmark_continuous_batch.py
new file mode 100644
index 00000000..6373903b
--- /dev/null
+++ b/c/tools/benchmark_continuous_batch.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+"""Measure pure mux decode throughput as the number of active slots grows."""
+
+import argparse
+import json
+import os
+import statistics
+import subprocess
+import sys
+import threading
+import time
+
+
+def frame(request_id, slot, prompt, max_tokens):
+ body = prompt.encode()
+ return (
+ f"SUBMIT {request_id} {slot} {len(body)} {max_tokens} 0 1\n".encode()
+ + body
+ + b"\n"
+ )
+
+
+def drain_stderr(pipe, lines):
+ for raw in iter(pipe.readline, b""):
+ line = raw.decode("utf-8", "replace").rstrip()
+ lines.append(line)
+ print(line, file=sys.stderr)
+
+
+def percentile(values, fraction):
+ ordered = sorted(values)
+ return ordered[round((len(ordered) - 1) * fraction)]
+
+
+def run_phase(proc, batch, tokens, phase_id):
+ prompts = [
+ f"Request {slot}: explain one practical property of hash tables. "
+ f"Use complete sentences. Measurement phase {phase_id}."
+ for slot in range(batch)
+ ]
+ base = phase_id * 1000
+ for slot, prompt in enumerate(prompts):
+ proc.stdin.write(frame(base + slot + 1, slot, prompt, tokens))
+ proc.stdin.flush()
+
+ data = {base + slot + 1: [] for slot in range(batch)}
+ done = {}
+ start = None
+ while len(done) < batch:
+ raw = proc.stdout.readline()
+ if not raw:
+ raise RuntimeError("engine exited during batch phase")
+ now = time.perf_counter()
+ line = raw.decode("utf-8", "replace").rstrip()
+ if line.startswith("DATA "):
+ _, sid, size = line.split()
+ request_id = int(sid)
+ proc.stdout.read(int(size))
+ proc.stdout.read(1)
+ if request_id in data:
+ data[request_id].append(now)
+ # SUBMIT is serial. The last request's first token marks the
+ # point after every prompt has completed prefill.
+ if request_id == base + batch and len(data[request_id]) == 1:
+ start = now
+ elif line.startswith("DONE "):
+ request_id = int(line.split()[1])
+ if request_id in data:
+ done[request_id] = (now, line)
+ elif line.startswith("ERROR "):
+ raise RuntimeError(line)
+
+ if start is None:
+ raise RuntimeError("last request produced no token")
+ end = max(item[0] for item in done.values())
+ measured_tokens = sum(
+ sum(timestamp >= start for timestamp in timestamps)
+ for timestamps in data.values()
+ )
+ gaps = []
+ for timestamps in data.values():
+ measured = [timestamp for timestamp in timestamps if timestamp >= start]
+ gaps.extend(b - a for a, b in zip(measured, measured[1:]))
+ wall = end - start
+ return {
+ "batch": batch,
+ "requested_tokens": tokens,
+ "measured_tokens": measured_tokens,
+ "decode_wall_s": wall,
+ "aggregate_tok_s": measured_tokens / wall,
+ "per_session_tok_s": measured_tokens / wall / batch,
+ "median_tbt_s": statistics.median(gaps) if gaps else None,
+ "p95_tbt_s": percentile(gaps, 0.95) if gaps else None,
+ "done": [done[key][1] for key in sorted(done)],
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--engine", required=True)
+ parser.add_argument("--model", required=True)
+ parser.add_argument("--batches", default="1,2,4,8,4,2,1")
+ parser.add_argument("--tokens", type=int, default=32)
+ parser.add_argument("--kv-slots", type=int, default=8)
+ args = parser.parse_args()
+ batches = [int(value) for value in args.batches.split(",")]
+ if not batches or min(batches) < 1 or max(batches) > args.kv_slots:
+ parser.error("batches must be between 1 and --kv-slots")
+
+ env = os.environ.copy()
+ env.update(
+ SNAP=args.model,
+ SERVE="1",
+ SERVE_BATCH="1",
+ KV_SLOTS=str(args.kv_slots),
+ COLI_KV_SHARE="0",
+ DRAFT="0",
+ COLI_TEMP="0",
+ )
+ proc = subprocess.Popen(
+ [args.engine, "8", "4", "4"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env,
+ )
+ stderr_lines = []
+ thread = threading.Thread(
+ target=drain_stderr, args=(proc.stderr, stderr_lines), daemon=True
+ )
+ thread.start()
+ results = []
+ try:
+ while True:
+ line = proc.stdout.readline()
+ if not line:
+ raise RuntimeError("engine exited before READY")
+ if b"READY" in line:
+ break
+ for phase_id, batch in enumerate(batches, 1):
+ results.append(run_phase(proc, batch, args.tokens, phase_id))
+ finally:
+ if proc.stdin:
+ proc.stdin.close()
+ proc.wait(timeout=60)
+ thread.join(timeout=1)
+
+ grouped = {}
+ for result in results:
+ grouped.setdefault(result["batch"], []).append(result["aggregate_tok_s"])
+ summary = {
+ "runs": results,
+ "median_aggregate_tok_s": {
+ str(batch): statistics.median(values)
+ for batch, values in sorted(grouped.items())
+ },
+ "stderr_tail": stderr_lines[-40:],
+ }
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/c/tools/benchmark_kv_prefix.py b/c/tools/benchmark_kv_prefix.py
new file mode 100644
index 00000000..a44440e3
--- /dev/null
+++ b/c/tools/benchmark_kv_prefix.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""Measure cross-slot KV prefix adoption through Colibri's mux protocol."""
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+import threading
+import time
+
+
+def stderr_drain(pipe, lines):
+ for raw in iter(pipe.readline, b""):
+ line = raw.decode("utf-8", "replace").rstrip()
+ lines.append(line)
+ print(line, file=sys.stderr)
+
+
+def wait_ready(pipe):
+ while True:
+ raw = pipe.readline()
+ if not raw:
+ raise RuntimeError("engine exited before READY")
+ if b"READY" in raw:
+ print("[bench] READY", file=sys.stderr, flush=True)
+ return
+
+
+def request(proc, request_id, slot, payload):
+ body = payload.encode()
+ frame = (
+ f"SUBMIT {request_id} {slot} {len(body)} 1 0 1\n".encode()
+ + body
+ + b"\n"
+ )
+ started = time.perf_counter()
+ proc.stdin.write(frame)
+ proc.stdin.flush()
+ print(f"[bench] submitted id={request_id} slot={slot} bytes={len(body)}", file=sys.stderr, flush=True)
+ accepted = first_data = done = None
+ done_fields = None
+ data = bytearray()
+ while done is None:
+ raw = proc.stdout.readline()
+ if not raw:
+ raise RuntimeError(f"engine exited during request {request_id}")
+ line = raw.decode("utf-8", "replace").rstrip()
+ if line.startswith(f"ACCEPT {request_id} "):
+ accepted = time.perf_counter()
+ print(f"[bench] accepted id={request_id}", file=sys.stderr, flush=True)
+ elif line.startswith(f"DATA {request_id} "):
+ if first_data is None:
+ first_data = time.perf_counter()
+ print(f"[bench] first data id={request_id}", file=sys.stderr, flush=True)
+ size = int(line.rsplit(" ", 1)[1])
+ data.extend(proc.stdout.read(size))
+ proc.stdout.read(1)
+ elif line.startswith(f"DONE {request_id} "):
+ done = time.perf_counter()
+ done_fields = line
+ print(f"[bench] done id={request_id}", file=sys.stderr, flush=True)
+ elif line.startswith("ERROR "):
+ raise RuntimeError(line)
+ return {
+ "submit_to_accept_s": accepted - started if accepted else None,
+ "ttft_s": first_data - started if first_data else None,
+ "total_s": done - started,
+ "done": done_fields,
+ "data_hex": data.hex(),
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--engine", required=True)
+ ap.add_argument("--model", required=True)
+ ap.add_argument("--share", type=int, choices=(0, 1), required=True)
+ ap.add_argument("--repeat", type=int, default=80)
+ ap.add_argument("--rounds", type=int, default=1)
+ args = ap.parse_args()
+
+ env = os.environ.copy()
+ env.update(
+ SNAP=args.model,
+ SERVE="1",
+ SERVE_BATCH="1",
+ KV_SLOTS="2",
+ COLI_KV_SHARE=str(args.share),
+ DRAFT="0",
+ COLI_TEMP="0",
+ )
+ proc = subprocess.Popen(
+ [args.engine, "8", "4", "4"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env,
+ )
+ stderr_lines = []
+ thread = threading.Thread(target=stderr_drain, args=(proc.stderr, stderr_lines), daemon=True)
+ thread.start()
+ results = []
+ try:
+ wait_ready(proc.stdout)
+ for round_id in range(args.rounds):
+ base = (
+ f"Experiment round {round_id}: "
+ + (
+ "A hummingbird can hover by reversing lift through each wingbeat. "
+ "Its diet combines flower nectar with small insects for protein. "
+ )
+ * args.repeat
+ )
+ prompts = (
+ base + "\nQuestion A: Summarize the passage.",
+ base + "\nQuestion B: State the main facts.",
+ )
+ first = request(proc, round_id * 2 + 1, 0, prompts[0])
+ print(json.dumps({"event": "first", "round": round_id, **first}), flush=True)
+ second = request(proc, round_id * 2 + 2, 1, prompts[1])
+ print(json.dumps({"event": "second", "round": round_id, **second}), flush=True)
+ results.append(
+ {
+ "round": round_id,
+ "payload_bytes": [len(p.encode()) for p in prompts],
+ "first": first,
+ "second": second,
+ }
+ )
+ finally:
+ proc.stdin.close()
+ proc.wait(timeout=30)
+ thread.join(timeout=1)
+
+ prefix_lines = [line for line in stderr_lines if "[API] KV " in line]
+ print(
+ json.dumps(
+ {
+ "share": args.share,
+ "repeat": args.repeat,
+ "rounds": results,
+ "kv_events": prefix_lines,
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/c/tools/benchmark_serving_interference.py b/c/tools/benchmark_serving_interference.py
new file mode 100644
index 00000000..c96d542a
--- /dev/null
+++ b/c/tools/benchmark_serving_interference.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+"""Measure decode stalls caused by serial prefill in Colibri's mux scheduler."""
+
+import argparse
+import json
+import os
+import statistics
+import subprocess
+import sys
+import threading
+import time
+
+
+def submit(proc, request_id, slot, prompt, max_tokens):
+ body = prompt.encode()
+ frame = (
+ f"SUBMIT {request_id} {slot} {len(body)} {max_tokens} 0 1\n".encode()
+ + body
+ + b"\n"
+ )
+ proc.stdin.write(frame)
+ proc.stdin.flush()
+ return time.perf_counter()
+
+
+def drain_stderr(pipe, lines):
+ for raw in iter(pipe.readline, b""):
+ line = raw.decode("utf-8", "replace").rstrip()
+ lines.append(line)
+ print(line, file=sys.stderr)
+
+
+def gaps(times):
+ return [b - a for a, b in zip(times, times[1:])]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--engine", required=True)
+ ap.add_argument("--model", required=True)
+ ap.add_argument("--long-repeat", type=int, default=20)
+ ap.add_argument("--decode-tokens", type=int, default=32)
+ args = ap.parse_args()
+
+ env = os.environ.copy()
+ env.update(
+ SNAP=args.model,
+ SERVE="1",
+ SERVE_BATCH="1",
+ KV_SLOTS="2",
+ COLI_KV_SHARE="0",
+ DRAFT="0",
+ COLI_TEMP="0",
+ )
+ proc = subprocess.Popen(
+ [args.engine, "8", "4", "4"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env,
+ )
+ stderr_lines = []
+ thread = threading.Thread(
+ target=drain_stderr, args=(proc.stderr, stderr_lines), daemon=True
+ )
+ thread.start()
+ requests = {}
+ phase = "ready"
+ long_submitted = False
+ try:
+ while True:
+ raw = proc.stdout.readline()
+ if not raw:
+ raise RuntimeError("engine exited before experiment completed")
+ now = time.perf_counter()
+ line = raw.decode("utf-8", "replace").rstrip()
+ if "READY" in line and phase == "ready":
+ requests[1] = {
+ "submitted": submit(
+ proc,
+ 1,
+ 0,
+ "Explain why a Python dictionary lookup is usually fast, "
+ "then give several implementation details.",
+ args.decode_tokens,
+ ),
+ "data": [],
+ }
+ phase = "control"
+ elif line.startswith("DATA "):
+ _, sid, size = line.split()
+ request_id = int(sid)
+ proc.stdout.read(int(size))
+ proc.stdout.read(1)
+ requests[request_id]["data"].append(now)
+ if phase == "treatment" and request_id == 2 and not long_submitted:
+ long_prompt = (
+ "A hummingbird can hover by reversing lift through each wingbeat. "
+ "Its diet combines flower nectar with small insects for protein. "
+ ) * args.long_repeat
+ requests[3] = {
+ "submitted": submit(proc, 3, 1, long_prompt, 1),
+ "data": [],
+ }
+ long_submitted = True
+ elif line.startswith("ACCEPT "):
+ request_id = int(line.split()[1])
+ if request_id in requests:
+ requests[request_id]["accepted"] = now
+ elif line.startswith("DONE "):
+ request_id = int(line.split()[1])
+ if request_id not in requests:
+ continue
+ requests[request_id]["done"] = now
+ requests[request_id]["done_line"] = line
+ if request_id == 1:
+ requests[2] = {
+ "submitted": submit(
+ proc,
+ 2,
+ 0,
+ "Explain how virtual memory works in a modern operating "
+ "system, including page faults and replacement.",
+ args.decode_tokens,
+ ),
+ "data": [],
+ }
+ phase = "treatment"
+ elif request_id == 2 and 3 in requests and "done" in requests[3]:
+ break
+ elif request_id == 3 and 2 in requests and "done" in requests[2]:
+ break
+ elif line.startswith("ERROR "):
+ raise RuntimeError(line)
+ finally:
+ if proc.stdin:
+ proc.stdin.close()
+ proc.wait(timeout=30)
+ thread.join(timeout=1)
+
+ control_gaps = gaps(requests[1]["data"])
+ treatment_gaps = gaps(requests[2]["data"])
+ summary = {
+ "control": {
+ "tokens": len(requests[1]["data"]),
+ "median_tbt_s": statistics.median(control_gaps),
+ "max_tbt_s": max(control_gaps),
+ "total_s": requests[1]["done"] - requests[1]["submitted"],
+ },
+ "treatment": {
+ "tokens": len(requests[2]["data"]),
+ "median_tbt_s": statistics.median(treatment_gaps),
+ "max_tbt_s": max(treatment_gaps),
+ "total_s": requests[2]["done"] - requests[2]["submitted"],
+ },
+ "interfering_prefill": {
+ "submit_to_accept_s": requests[3]["accepted"] - requests[3]["submitted"],
+ "ttft_s": requests[3]["data"][0] - requests[3]["submitted"],
+ "total_s": requests[3]["done"] - requests[3]["submitted"],
+ },
+ "prefill_events": [
+ line for line in stderr_lines if "[API] KV slot" in line
+ ],
+ }
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/c/tools/benchmark_split_entropy.cu b/c/tools/benchmark_split_entropy.cu
new file mode 100644
index 00000000..bd91ea21
--- /dev/null
+++ b/c/tools/benchmark_split_entropy.cu
@@ -0,0 +1,224 @@
+// GPU decode microbenchmark for analyze_split_entropy.py's practical codec.
+// Build: nvcc -O3 -arch=native -o /tmp/bench_split benchmark_split_entropy.cu
+#include <cuda_runtime.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+#include <vector>
+
+#define CUDA_OK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { \
+ fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, cudaGetErrorString(e)); \
+ exit(1); }} while (0)
+
+static constexpr int TILE = 4096;
+static constexpr int THREADS = 256;
+
+__device__ __forceinline__ unsigned get_bits(
+ const uint8_t *p, unsigned bit, unsigned width) {
+ if (!width) return 0;
+ uint64_t word = 0;
+ memcpy(&word, p + (bit >> 3), sizeof(word));
+ return (word >> (bit & 7)) & ((1u << width) - 1);
+}
+
+template<int BASE_BITS>
+__global__ void decode(const uint8_t *__restrict__ base,
+ const uint8_t *__restrict__ residual,
+ const uint32_t *__restrict__ residual_offsets,
+ uint8_t *__restrict__ out, size_t weights,
+ const uint8_t *__restrict__ group_width,
+ const uint8_t *__restrict__ group_symbol) {
+ __shared__ uint16_t prefix[TILE];
+ const size_t tile = blockIdx.x;
+ const size_t begin = tile * TILE;
+ if (begin >= weights) return;
+
+ for (int i = threadIdx.x; i < TILE; i += blockDim.x) {
+ size_t index = begin + i;
+ unsigned group = 0;
+ if (index < weights)
+ group = get_bits(base + tile * (TILE * BASE_BITS / 8),
+ i * BASE_BITS, BASE_BITS);
+ prefix[i] = index < weights ? group_width[group] : 0;
+ }
+ __syncthreads();
+
+ // Blelloch exclusive scan; max tile residual is 16384 bits.
+ for (int stride = 1; stride < TILE; stride <<= 1) {
+ int i = (threadIdx.x + 1) * stride * 2 - 1;
+ for (; i < TILE; i += blockDim.x * stride * 2)
+ prefix[i] += prefix[i - stride];
+ __syncthreads();
+ }
+ if (threadIdx.x == 0) prefix[TILE - 1] = 0;
+ __syncthreads();
+ for (int stride = TILE >> 1; stride; stride >>= 1) {
+ int i = (threadIdx.x + 1) * stride * 2 - 1;
+ for (; i < TILE; i += blockDim.x * stride * 2) {
+ uint16_t left = prefix[i - stride];
+ prefix[i - stride] = prefix[i];
+ prefix[i] += left;
+ }
+ __syncthreads();
+ }
+
+ const uint8_t *tile_residual = residual + residual_offsets[tile];
+ for (int i = threadIdx.x; i < TILE; i += blockDim.x) {
+ size_t index = begin + i;
+ if (index >= weights) continue;
+ unsigned group = get_bits(base + tile * (TILE * BASE_BITS / 8),
+ i * BASE_BITS, BASE_BITS);
+ unsigned local = get_bits(tile_residual, prefix[i],
+ group_width[group]);
+ out[index] = group_symbol[group * 16 + local];
+ }
+}
+
+static void put_bits(std::vector<uint8_t>& dst, size_t bit,
+ unsigned width, unsigned value) {
+ for (unsigned i = 0; i < width; ++i)
+ if (value & (1u << i))
+ dst[(bit + i) >> 3] |= 1u << ((bit + i) & 7);
+}
+
+template<int BASE_BITS>
+static void run(const std::vector<uint8_t>& symbols,
+ const uint8_t *symbol_group, const uint8_t *symbol_local,
+ const std::vector<uint8_t>& widths,
+ const std::vector<uint8_t>& group_symbols) {
+ const size_t weights = symbols.size();
+ const size_t tiles = (weights + TILE - 1) / TILE;
+ std::vector<uint8_t> base(tiles * TILE * BASE_BITS / 8);
+ std::vector<uint8_t> residual;
+ std::vector<uint32_t> offsets(tiles + 1);
+ residual.reserve(weights / 2);
+ for (size_t tile = 0; tile < tiles; ++tile) {
+ offsets[tile] = residual.size();
+ size_t residual_bit = 0;
+ std::vector<uint8_t> chunk(TILE / 2 + 8);
+ for (int i = 0; i < TILE; ++i) {
+ size_t index = tile * TILE + i;
+ uint8_t symbol = index < weights ? symbols[index] : 0;
+ unsigned group = symbol_group[symbol];
+ put_bits(base, tile * TILE * BASE_BITS + i * BASE_BITS,
+ BASE_BITS, group);
+ if (index < weights) {
+ put_bits(chunk, residual_bit, widths[group],
+ symbol_local[symbol]);
+ residual_bit += widths[group];
+ }
+ }
+ size_t bytes = (residual_bit + 7) / 8;
+ residual.insert(residual.end(), chunk.begin(), chunk.begin() + bytes);
+ }
+ offsets[tiles] = residual.size();
+ residual.resize(residual.size() + 8);
+
+ uint8_t *d_base, *d_residual, *d_out, *d_width, *d_symbols;
+ uint32_t *d_offsets;
+ CUDA_OK(cudaMalloc(&d_base, base.size()));
+ CUDA_OK(cudaMalloc(&d_residual, residual.size()));
+ CUDA_OK(cudaMalloc(&d_offsets, offsets.size() * sizeof(uint32_t)));
+ CUDA_OK(cudaMalloc(&d_out, weights));
+ CUDA_OK(cudaMalloc(&d_width, widths.size()));
+ CUDA_OK(cudaMalloc(&d_symbols, group_symbols.size()));
+ CUDA_OK(cudaMemcpy(d_base, base.data(), base.size(), cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(d_residual, residual.data(), residual.size(),
+ cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(d_offsets, offsets.data(),
+ offsets.size() * sizeof(uint32_t), cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(d_width, widths.data(), widths.size(),
+ cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(d_symbols, group_symbols.data(), group_symbols.size(),
+ cudaMemcpyHostToDevice));
+
+ decode<BASE_BITS><<<tiles, THREADS>>>(d_base, d_residual, d_offsets, d_out,
+ weights, d_width, d_symbols);
+ CUDA_OK(cudaDeviceSynchronize());
+ std::vector<uint8_t> output(weights);
+ CUDA_OK(cudaMemcpy(output.data(), d_out, weights, cudaMemcpyDeviceToHost));
+ if (output != symbols) {
+ fprintf(stderr, "base%d roundtrip mismatch\n", BASE_BITS);
+ exit(2);
+ }
+
+ cudaEvent_t start, stop;
+ CUDA_OK(cudaEventCreate(&start));
+ CUDA_OK(cudaEventCreate(&stop));
+ constexpr int rounds = 100;
+ CUDA_OK(cudaEventRecord(start));
+ for (int i = 0; i < rounds; ++i)
+ decode<BASE_BITS><<<tiles, THREADS>>>(d_base, d_residual, d_offsets,
+ d_out, weights, d_width, d_symbols);
+ CUDA_OK(cudaEventRecord(stop));
+ CUDA_OK(cudaEventSynchronize(stop));
+ float ms;
+ CUDA_OK(cudaEventElapsedTime(&ms, start, stop));
+ double seconds = ms / 1e3 / rounds;
+ printf("base%d: base %.3f bits + residual %.3f bits = %.3f bits/weight"
+ " | exact roundtrip | decode %.1f Gweight/s"
+ " | raw-INT4 equivalent %.1f GB/s",
+ BASE_BITS, double(BASE_BITS),
+ residual.size() * 8.0 / weights,
+ BASE_BITS + residual.size() * 8.0 / weights,
+ weights / seconds / 1e9, weights / 2.0 / seconds / 1e9);
+
+ CUDA_OK(cudaHostRegister(residual.data(), residual.size(),
+ cudaHostRegisterDefault));
+ CUDA_OK(cudaEventRecord(start));
+ for (int i = 0; i < rounds; ++i) {
+ CUDA_OK(cudaMemcpyAsync(d_residual, residual.data(), residual.size(),
+ cudaMemcpyHostToDevice));
+ decode<BASE_BITS><<<tiles, THREADS>>>(d_base, d_residual, d_offsets,
+ d_out, weights, d_width, d_symbols);
+ }
+ CUDA_OK(cudaEventRecord(stop));
+ CUDA_OK(cudaEventSynchronize(stop));
+ CUDA_OK(cudaEventElapsedTime(&ms, start, stop));
+ seconds = ms / 1e3 / rounds;
+ printf(" | H2D+decode %.1f Gweight/s (residual %.1f GB/s,"
+ " raw-equivalent %.1f GB/s)\n",
+ weights / seconds / 1e9,
+ (residual.size() - 8) / seconds / 1e9,
+ weights / 2.0 / seconds / 1e9);
+ CUDA_OK(cudaHostUnregister(residual.data()));
+
+ cudaFree(d_base); cudaFree(d_residual); cudaFree(d_offsets);
+ cudaFree(d_out); cudaFree(d_width); cudaFree(d_symbols);
+}
+
+int main() {
+ const size_t weights = 1ull << 26;
+ const double p[16] = {
+ 0, .0003231, .001374, .005613, .02026, .05401, .1164, .1861,
+ .2314, .1861, .1164, .05399, .02025, .005611, .001373, .0003231};
+ std::discrete_distribution<int> distribution(p, p + 16);
+ std::mt19937 rng(52);
+ std::vector<uint8_t> symbols(weights);
+ for (auto& symbol : symbols) symbol = distribution(rng);
+
+ // Descending-probability order: 8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,0.
+ const uint8_t order[16] = {8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,0};
+ for (int bits = 1; bits <= 2; ++bits) {
+ const std::vector<int> sizes = bits == 1
+ ? std::vector<int>{4, 12} : std::vector<int>{1, 2, 2, 11};
+ std::vector<uint8_t> widths, table(sizes.size() * 16);
+ uint8_t group[16] = {}, local[16] = {};
+ int cursor = 0;
+ for (int g = 0; g < (int)sizes.size(); ++g) {
+ widths.push_back(sizes[g] == 1 ? 0 :
+ sizes[g] <= 2 ? 1 :
+ sizes[g] <= 4 ? 2 : 4);
+ for (int i = 0; i < sizes[g]; ++i) {
+ uint8_t symbol = order[cursor++];
+ group[symbol] = g; local[symbol] = i;
+ table[g * 16 + i] = symbol;
+ }
+ }
+ if (bits == 1) run<1>(symbols, group, local, widths, table);
+ else run<2>(symbols, group, local, widths, table);
+ }
+}
diff --git a/c/tools/benchmark_split_matvec.cu b/c/tools/benchmark_split_matvec.cu
new file mode 100644
index 00000000..7cab7dca
--- /dev/null
+++ b/c/tools/benchmark_split_matvec.cu
@@ -0,0 +1,269 @@
+// Fused row-wise base/residual decode + GLM-sized W4A32 matvec benchmark.
+// Build: nvcc -O3 -std=c++17 -arch=sm_120 -o /tmp/bench_split_matvec $0
+#include <cuda_runtime.h>
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <random>
+#include <vector>
+
+#define CUDA_OK(x) do { cudaError_t e=(x); if(e!=cudaSuccess){ \
+ fprintf(stderr,"%s:%d: %s\n",__FILE__,__LINE__,cudaGetErrorString(e));exit(1);} \
+} while(0)
+
+static constexpr int THREADS=256;
+static constexpr int SCAN=8192; // next power of two above GLM hidden 6144
+
+__device__ __forceinline__ unsigned bits(const uint8_t *p,unsigned bit,unsigned n){
+ if(!n)return 0; uint64_t v=0; memcpy(&v,p+(bit>>3),sizeof(v));
+ return (v>>(bit&7))&((1u<<n)-1);
+}
+
+__global__ void raw_w4(float *y,const float *x,const uint8_t *w,int I,int O){
+ int o=blockIdx.x;if(o>=O)return;const uint8_t *row=w+(size_t)o*((I+1)/2);
+ float sum=0;for(int i=threadIdx.x;i<I;i+=blockDim.x){
+ uint8_t q=row[i>>1];int v=(i&1)?q>>4:q&15;sum+=x[i]*(float)(v-8);
+ }
+ __shared__ float partial[THREADS];partial[threadIdx.x]=sum;__syncthreads();
+ for(int n=THREADS/2;n;n>>=1){if(threadIdx.x<n)partial[threadIdx.x]+=partial[threadIdx.x+n];__syncthreads();}
+ if(!threadIdx.x)y[o]=partial[0];
+}
+
+template<int BASE_BITS>
+__global__ void split_w4(float *y,const float *x,const uint8_t *base,
+ const uint8_t *residual,const uint32_t *offsets,int I,int O,
+ const uint8_t *width,const uint8_t *symbol){
+ int o=blockIdx.x;if(o>=O)return;
+ extern __shared__ uint8_t storage[];
+ uint16_t *prefix=(uint16_t*)storage;
+ float *partial=(float*)(storage+SCAN*sizeof(uint16_t));
+ size_t base_row=(size_t)o*((I*BASE_BITS+7)/8);
+ for(int i=threadIdx.x;i<SCAN;i+=blockDim.x){
+ unsigned group=i<I?bits(base+base_row,i*BASE_BITS,BASE_BITS):0;
+ prefix[i]=i<I?width[group]:0;
+ }
+ __syncthreads();
+ for(int stride=1;stride<SCAN;stride<<=1){
+ int i=(threadIdx.x+1)*stride*2-1;
+ for(;i<SCAN;i+=blockDim.x*stride*2)prefix[i]+=prefix[i-stride];
+ __syncthreads();
+ }
+ if(!threadIdx.x)prefix[SCAN-1]=0;__syncthreads();
+ for(int stride=SCAN>>1;stride;stride>>=1){
+ int i=(threadIdx.x+1)*stride*2-1;
+ for(;i<SCAN;i+=blockDim.x*stride*2){
+ uint16_t left=prefix[i-stride];prefix[i-stride]=prefix[i];prefix[i]+=left;
+ }
+ __syncthreads();
+ }
+ const uint8_t *rr=residual+offsets[o];float sum=0;
+ for(int i=threadIdx.x;i<I;i+=blockDim.x){
+ unsigned group=bits(base+base_row,i*BASE_BITS,BASE_BITS);
+ unsigned local=bits(rr,prefix[i],width[group]);
+ int value=(int)symbol[group*16+local]-8;
+ sum+=x[i]*(float)value;
+ }
+ partial[threadIdx.x]=sum;__syncthreads();
+ for(int n=THREADS/2;n;n>>=1){if(threadIdx.x<n)partial[threadIdx.x]+=partial[threadIdx.x+n];__syncthreads();}
+ if(!threadIdx.x)y[o]=partial[0];
+}
+
+template<int BASE_BITS>
+__global__ void split_w4_segmented(float *y,const float *x,const uint8_t *base,
+ const uint8_t *residual,const uint32_t *offsets,int I,int O,
+ const uint8_t *width,const uint8_t *symbol){
+ int o=blockIdx.x;if(o>=O)return;int lane=threadIdx.x&31,warp=threadIdx.x>>5;
+ size_t base_row=(size_t)o*((I*BASE_BITS+7)/8);
+ int span=(I+blockDim.x-1)/blockDim.x,begin=threadIdx.x*span,end=min(I,begin+span);
+ unsigned count=0;
+ for(int i=begin;i<end;i++){
+ unsigned group=bits(base+base_row,i*BASE_BITS,BASE_BITS);
+ count+=width[group];
+ }
+ unsigned scan=count;
+ for(int d=1;d<32;d<<=1){unsigned v=__shfl_up_sync(0xffffffff,scan,d);
+ if(lane>=d)scan+=v;}
+ __shared__ unsigned warp_sum[8],warp_prefix[8];
+ if(lane==31)warp_sum[warp]=scan;__syncthreads();
+ if(warp==0){unsigned v=lane<8?warp_sum[lane]:0,ws=v;
+ for(int d=1;d<32;d<<=1){unsigned z=__shfl_up_sync(0xffffffff,ws,d);
+ if(lane>=d)ws+=z;}
+ if(lane<8)warp_prefix[lane]=ws-v;}
+ __syncthreads();
+ unsigned bit=warp_prefix[warp]+scan-count;
+ const uint8_t *rr=residual+offsets[o];float sum=0;
+ for(int i=begin;i<end;i++){
+ unsigned group=bits(base+base_row,i*BASE_BITS,BASE_BITS),n=width[group];
+ unsigned local=bits(rr,bit,n);bit+=n;
+ sum+=x[i]*(float)((int)symbol[group*16+local]-8);
+ }
+ __shared__ float partial[THREADS];partial[threadIdx.x]=sum;__syncthreads();
+ for(int n=THREADS/2;n;n>>=1){if(threadIdx.x<n)partial[threadIdx.x]+=partial[threadIdx.x+n];__syncthreads();}
+ if(!threadIdx.x)y[o]=partial[0];
+}
+
+/* Random-access variant for the dominant 2-bit mode. One residual bit is
+ * directly addressable for every weight. Only group 3 needs three more bits;
+ * each warp owns a separate exception stream, so no global rank/prefix scan is
+ * needed. */
+__global__ void split_w4_direct2(float *y,const float *x,const uint8_t *base,
+ const uint8_t *low,const uint8_t *extra,const uint32_t *row_offset,
+ const uint16_t *warp_offset,int I,int O,const uint8_t *symbol){
+ int o=blockIdx.x;if(o>=O)return;int lane=threadIdx.x&31,warp=threadIdx.x>>5;
+ size_t base_row=(size_t)o*((I*2+7)/8),low_row=(size_t)o*((I+7)/8);
+ const uint8_t *rr=extra+row_offset[o];unsigned ebit=warp_offset[(size_t)o*8+warp];
+ float sum=0;
+ for(int chunk=warp*32;chunk<I;chunk+=8*32){
+ int i=chunk+lane;unsigned group=i<I?bits(base+base_row,i*2,2):0;
+ unsigned local=i<I?bits(low+low_row,i,1):0;
+ unsigned mask=__ballot_sync(0xffffffff,i<I&&group==3);
+ if(i<I&&group==3)local|=bits(rr,ebit+3*__popc(mask&((1u<<lane)-1)),3)<<1;
+ if(i<I)sum+=x[i]*(float)((int)symbol[group*16+local]-8);
+ ebit+=3*__popc(mask);
+ }
+ for(int d=16;d;d>>=1)sum+=__shfl_down_sync(0xffffffff,sum,d);
+ __shared__ float wp[8];if(!lane)wp[warp]=sum;__syncthreads();
+ if(threadIdx.x<8){float v=wp[threadIdx.x];for(int d=4;d;d>>=1)
+ v+=__shfl_down_sync(0xff,v,d);if(!threadIdx.x)y[o]=v;}
+}
+
+static void put(std::vector<uint8_t>& dst,size_t bit,unsigned n,unsigned value){
+ for(unsigned i=0;i<n;i++)if(value&(1u<<i))dst[(bit+i)>>3]|=1u<<((bit+i)&7);
+}
+
+template<int BASE_BITS>
+static void bench(int I,int O,const std::vector<uint8_t>& q,const std::vector<float>& x,
+ const uint8_t *map_group,const uint8_t *map_local,
+ const std::vector<uint8_t>& widths,const std::vector<uint8_t>& table){
+ size_t base_rb=(I*BASE_BITS+7)/8;
+ std::vector<uint8_t> base((size_t)O*base_rb);
+ std::vector<uint8_t> residual;std::vector<uint32_t> offsets(O+1);
+ residual.reserve(q.size()/2);
+ for(int o=0;o<O;o++){
+ offsets[o]=residual.size();size_t bit=0;std::vector<uint8_t> row((size_t)I/2+8);
+ for(int i=0;i<I;i++){
+ uint8_t v=q[(size_t)o*I+i],g=map_group[v];
+ put(base,(size_t)o*base_rb*8+(size_t)i*BASE_BITS,BASE_BITS,g);
+ put(row,bit,widths[g],map_local[v]);bit+=widths[g];
+ }
+ residual.insert(residual.end(),row.begin(),row.begin()+(bit+7)/8);
+ }
+ offsets[O]=residual.size();residual.resize(residual.size()+8);
+
+ uint8_t *dq,*db,*dr,*dw,*dt;float *dx,*yr,*ys,*yf;uint32_t *dof;
+ CUDA_OK(cudaMalloc(&dq,q.size()/2));CUDA_OK(cudaMalloc(&db,base.size()));
+ CUDA_OK(cudaMalloc(&dr,residual.size()));CUDA_OK(cudaMalloc(&dof,offsets.size()*4));
+ CUDA_OK(cudaMalloc(&dw,widths.size()));CUDA_OK(cudaMalloc(&dt,table.size()));
+ CUDA_OK(cudaMalloc(&dx,x.size()*4));CUDA_OK(cudaMalloc(&yr,O*4));CUDA_OK(cudaMalloc(&ys,O*4));CUDA_OK(cudaMalloc(&yf,O*4));
+ std::vector<uint8_t> packed(q.size()/2);
+ for(size_t i=0;i<q.size();i+=2)packed[i/2]=q[i]|(q[i+1]<<4);
+ CUDA_OK(cudaMemcpy(dq,packed.data(),packed.size(),cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(db,base.data(),base.size(),cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dr,residual.data(),residual.size(),cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dof,offsets.data(),offsets.size()*4,cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dw,widths.data(),widths.size(),cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dt,table.data(),table.size(),cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dx,x.data(),x.size()*4,cudaMemcpyHostToDevice));
+ size_t smem=SCAN*sizeof(uint16_t)+THREADS*sizeof(float);
+ raw_w4<<<O,THREADS>>>(yr,dx,dq,I,O);
+ split_w4<BASE_BITS><<<O,THREADS,smem>>>(ys,dx,db,dr,dof,I,O,dw,dt);
+ split_w4_segmented<BASE_BITS><<<O,THREADS>>>(yf,dx,db,dr,dof,I,O,dw,dt);
+ CUDA_OK(cudaDeviceSynchronize());
+ std::vector<float> a(O),b(O),f(O);CUDA_OK(cudaMemcpy(a.data(),yr,O*4,cudaMemcpyDeviceToHost));
+ CUDA_OK(cudaMemcpy(b.data(),ys,O*4,cudaMemcpyDeviceToHost));
+ CUDA_OK(cudaMemcpy(f.data(),yf,O*4,cudaMemcpyDeviceToHost));
+ float max_abs=0,max_rel=0,fast_abs=0,fast_rel=0;for(int i=0;i<O;i++){float d=fabsf(a[i]-b[i]),z=fabsf(a[i]-f[i]);
+ max_abs=fmaxf(max_abs,d);max_rel=fmaxf(max_rel,d/fmaxf(1.f,fabsf(a[i])));
+ fast_abs=fmaxf(fast_abs,z);fast_rel=fmaxf(fast_rel,z/fmaxf(1.f,fabsf(a[i])));}
+
+ cudaEvent_t start,stop;CUDA_OK(cudaEventCreate(&start));CUDA_OK(cudaEventCreate(&stop));
+ constexpr int R=200;float raw_ms,split_ms,fast_ms,pipe_ms;
+ CUDA_OK(cudaEventRecord(start));for(int r=0;r<R;r++)raw_w4<<<O,THREADS>>>(yr,dx,dq,I,O);
+ CUDA_OK(cudaEventRecord(stop));CUDA_OK(cudaEventSynchronize(stop));CUDA_OK(cudaEventElapsedTime(&raw_ms,start,stop));
+ CUDA_OK(cudaEventRecord(start));for(int r=0;r<R;r++)split_w4<BASE_BITS><<<O,THREADS,smem>>>(ys,dx,db,dr,dof,I,O,dw,dt);
+ CUDA_OK(cudaEventRecord(stop));CUDA_OK(cudaEventSynchronize(stop));CUDA_OK(cudaEventElapsedTime(&split_ms,start,stop));
+ CUDA_OK(cudaEventRecord(start));for(int r=0;r<R;r++)split_w4_segmented<BASE_BITS><<<O,THREADS>>>(yf,dx,db,dr,dof,I,O,dw,dt);
+ CUDA_OK(cudaEventRecord(stop));CUDA_OK(cudaEventSynchronize(stop));CUDA_OK(cudaEventElapsedTime(&fast_ms,start,stop));
+ CUDA_OK(cudaHostRegister(residual.data(),residual.size(),cudaHostRegisterDefault));
+ CUDA_OK(cudaEventRecord(start));for(int r=0;r<R;r++){CUDA_OK(cudaMemcpyAsync(dr,residual.data(),residual.size(),cudaMemcpyHostToDevice));
+ split_w4_segmented<BASE_BITS><<<O,THREADS>>>(yf,dx,db,dr,dof,I,O,dw,dt);}
+ CUDA_OK(cudaEventRecord(stop));CUDA_OK(cudaEventSynchronize(stop));CUDA_OK(cudaEventElapsedTime(&pipe_ms,start,stop));
+ CUDA_OK(cudaHostUnregister(residual.data()));
+ printf("%dx%d base%d: residual %.3f bits/w | scan exact abs %.3g rel %.3g"
+ " | segmented abs %.3g rel %.3g | raw %.3f ms | scan %.3f ms (%.2fx)"
+ " | segmented %.3f ms (%.2fx) | H2D+segmented %.3f ms (%.2fx)\n",
+ O,I,BASE_BITS,(residual.size()-8)*8.0/q.size(),max_abs,max_rel,fast_abs,fast_rel,
+ raw_ms/R,split_ms/R,raw_ms/split_ms,fast_ms/R,raw_ms/fast_ms,pipe_ms/R,raw_ms/pipe_ms);
+ cudaFree(dq);cudaFree(db);cudaFree(dr);cudaFree(dof);cudaFree(dw);cudaFree(dt);
+ cudaFree(dx);cudaFree(yr);cudaFree(ys);cudaFree(yf);
+}
+
+static void bench_direct2(int I,int O,const std::vector<uint8_t>& q,
+ const std::vector<float>& x,const uint8_t *group,const uint8_t *local,
+ const std::vector<uint8_t>& table){
+ size_t br=(I*2+7)/8,lr=(I+7)/8;std::vector<uint8_t>base((size_t)O*br),low((size_t)O*lr);
+ std::vector<uint8_t>extra;std::vector<uint32_t>row(O+1);std::vector<uint16_t>wo((size_t)O*8);
+ for(int o=0;o<O;o++){
+ row[o]=extra.size();std::vector<std::vector<uint8_t>> streams(8);
+ std::vector<size_t> stream_bits(8);
+ for(int warp=0;warp<8;warp++)for(int chunk=warp*32;chunk<I;chunk+=256)
+ for(int lane=0;lane<32&&chunk+lane<I;lane++){
+ int i=chunk+lane;uint8_t v=q[(size_t)o*I+i],g=group[v],l=local[v];
+ put(base,(size_t)o*br*8+(size_t)i*2,2,g);
+ put(low,(size_t)o*lr*8+i,1,l&1);
+ if(g==3){if(streams[warp].size()<(stream_bits[warp]+10)/8)streams[warp].resize((stream_bits[warp]+10)/8);
+ put(streams[warp],stream_bits[warp],3,l>>1);stream_bits[warp]+=3;}
+ }
+ size_t bit=0;for(int warp=0;warp<8;warp++){wo[(size_t)o*8+warp]=bit;
+ for(size_t j=0;j<stream_bits[warp];j++)if(streams[warp][j>>3]&(1u<<(j&7))){
+ if(extra.size()<row[o]+(bit+j+8)/8)extra.resize(row[o]+(bit+j+8)/8);
+ extra[row[o]+((bit+j)>>3)]|=1u<<((bit+j)&7);}
+ bit+=stream_bits[warp];}
+ extra.resize(row[o]+(bit+7)/8);
+ }
+ row[O]=extra.size();extra.resize(extra.size()+8);
+ uint8_t *dq,*db,*dl,*de,*dt;uint32_t*drow;uint16_t*dwo;float*dx,*yr,*yd;
+ std::vector<uint8_t>packed(q.size()/2);for(size_t i=0;i<q.size();i+=2)packed[i/2]=q[i]|(q[i+1]<<4);
+ CUDA_OK(cudaMalloc(&dq,packed.size()));CUDA_OK(cudaMalloc(&db,base.size()));CUDA_OK(cudaMalloc(&dl,low.size()));
+ CUDA_OK(cudaMalloc(&de,extra.size()));CUDA_OK(cudaMalloc(&dt,table.size()));CUDA_OK(cudaMalloc(&drow,row.size()*4));
+ CUDA_OK(cudaMalloc(&dwo,wo.size()*2));CUDA_OK(cudaMalloc(&dx,x.size()*4));CUDA_OK(cudaMalloc(&yr,O*4));CUDA_OK(cudaMalloc(&yd,O*4));
+ CUDA_OK(cudaMemcpy(dq,packed.data(),packed.size(),cudaMemcpyHostToDevice));CUDA_OK(cudaMemcpy(db,base.data(),base.size(),cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dl,low.data(),low.size(),cudaMemcpyHostToDevice));CUDA_OK(cudaMemcpy(de,extra.data(),extra.size(),cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dt,table.data(),table.size(),cudaMemcpyHostToDevice));CUDA_OK(cudaMemcpy(drow,row.data(),row.size()*4,cudaMemcpyHostToDevice));
+ CUDA_OK(cudaMemcpy(dwo,wo.data(),wo.size()*2,cudaMemcpyHostToDevice));CUDA_OK(cudaMemcpy(dx,x.data(),x.size()*4,cudaMemcpyHostToDevice));
+ raw_w4<<<O,THREADS>>>(yr,dx,dq,I,O);split_w4_direct2<<<O,THREADS>>>(yd,dx,db,dl,de,drow,dwo,I,O,dt);CUDA_OK(cudaDeviceSynchronize());
+ std::vector<float>a(O),b(O);CUDA_OK(cudaMemcpy(a.data(),yr,O*4,cudaMemcpyDeviceToHost));CUDA_OK(cudaMemcpy(b.data(),yd,O*4,cudaMemcpyDeviceToHost));
+ float ma=0,mr=0;for(int i=0;i<O;i++){float d=fabsf(a[i]-b[i]);ma=fmaxf(ma,d);mr=fmaxf(mr,d/fmaxf(1.f,fabsf(a[i])));}
+ cudaEvent_t s,t;cudaEventCreate(&s);cudaEventCreate(&t);constexpr int R=200;float rm,dm,pm;
+ cudaEventRecord(s);for(int r=0;r<R;r++)raw_w4<<<O,THREADS>>>(yr,dx,dq,I,O);cudaEventRecord(t);cudaEventSynchronize(t);cudaEventElapsedTime(&rm,s,t);
+ cudaEventRecord(s);for(int r=0;r<R;r++)split_w4_direct2<<<O,THREADS>>>(yd,dx,db,dl,de,drow,dwo,I,O,dt);cudaEventRecord(t);cudaEventSynchronize(t);cudaEventElapsedTime(&dm,s,t);
+ CUDA_OK(cudaHostRegister(low.data(),low.size(),cudaHostRegisterDefault));CUDA_OK(cudaHostRegister(extra.data(),extra.size(),cudaHostRegisterDefault));
+ cudaEventRecord(s);for(int r=0;r<R;r++){cudaMemcpyAsync(dl,low.data(),low.size(),cudaMemcpyHostToDevice);cudaMemcpyAsync(de,extra.data(),extra.size(),cudaMemcpyHostToDevice);
+ split_w4_direct2<<<O,THREADS>>>(yd,dx,db,dl,de,drow,dwo,I,O,dt);}cudaEventRecord(t);cudaEventSynchronize(t);cudaEventElapsedTime(&pm,s,t);
+ cudaHostUnregister(low.data());cudaHostUnregister(extra.data());
+ printf("%dx%d base2-direct: residual %.3f bits/w + metadata %.3f bits/w | abs %.3g rel %.3g | raw %.3f ms | fused %.3f ms (%.2fx) | H2D+fused %.3f ms (%.2fx)\n",
+ O,I,(low.size()*8.0+(extra.size()-8)*8.0)/q.size(),(row.size()*4.0+wo.size()*2.0)*8/q.size(),ma,mr,rm/R,dm/R,rm/dm,pm/R,rm/pm);
+ cudaFree(dq);cudaFree(db);cudaFree(dl);cudaFree(de);cudaFree(dt);cudaFree(drow);cudaFree(dwo);cudaFree(dx);cudaFree(yr);cudaFree(yd);
+}
+
+int main(){
+ const double p[16]={0,.0003231,.001374,.005613,.02026,.05401,.1164,.1861,
+ .2314,.1861,.1164,.05399,.02025,.005611,.001373,.0003231};
+ const uint8_t order[16]={8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,0};
+ std::mt19937 rng(52);std::discrete_distribution<int> dist(p,p+16);
+ std::uniform_real_distribution<float> xf(-1,1);
+ for(auto shape: {std::pair<int,int>{6144,2048}, {2048,6144}}){
+ int I=shape.first,O=shape.second;std::vector<uint8_t> q((size_t)I*O);
+ std::vector<float>x(I);for(auto&v:q)v=dist(rng);for(auto&v:x)v=xf(rng);
+ for(int bits_n=1;bits_n<=2;bits_n++){
+ std::vector<int> sizes=bits_n==1?std::vector<int>{4,12}:std::vector<int>{1,2,2,11};
+ std::vector<uint8_t>w,table(sizes.size()*16);uint8_t group[16]={},local[16]={};int cur=0;
+ for(int g=0;g<(int)sizes.size();g++){w.push_back(sizes[g]==1?0:sizes[g]<=2?1:sizes[g]<=4?2:4);
+ for(int j=0;j<sizes[g];j++){uint8_t s=order[cur++];group[s]=g;local[s]=j;table[g*16+j]=s;}}
+ if(bits_n==1)bench<1>(I,O,q,x,group,local,w,table);else bench<2>(I,O,q,x,group,local,w,table);
+ if(bits_n==2)bench_direct2(I,O,q,x,group,local,table);
+ }
+ }
+}
diff --git a/c/tools/disaggregation_break_even.py b/c/tools/disaggregation_break_even.py
new file mode 100644
index 00000000..c69feeb5
--- /dev/null
+++ b/c/tools/disaggregation_break_even.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Calibrated KV-transfer model for layer streaming and phase splitting."""
+
+import argparse
+import json
+
+
+def transfer_finish(prefill_s, layers, bytes_per_layer, bandwidth_Bps):
+ network_done = 0.0
+ transfer_s = bytes_per_layer / bandwidth_Bps
+ for layer in range(1, layers + 1):
+ produced = prefill_s * layer / layers
+ network_done = max(network_done, produced) + transfer_s
+ return network_done
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--tokens", type=int, default=501)
+ ap.add_argument("--layers", type=int, default=79)
+ ap.add_argument("--kv-latent", type=int, default=512)
+ ap.add_argument("--kv-rope", type=int, default=64)
+ ap.add_argument("--index-dim", type=int, default=128)
+ ap.add_argument("--prefill-s", type=float, default=44.198862534)
+ ap.add_argument(
+ "--bandwidth-gbps",
+ type=float,
+ nargs="+",
+ default=(1, 10, 25, 50, 100, 200),
+ help="Decimal link rates in gigabits/s.",
+ )
+ args = ap.parse_args()
+
+ row_bytes = (args.kv_latent + args.kv_rope + args.index_dim) * 4
+ bytes_per_layer = args.tokens * row_bytes
+ total_bytes = args.layers * bytes_per_layer
+ rows = []
+ for gbps in args.bandwidth_gbps:
+ bandwidth = gbps * 1e9 / 8
+ whole_s = total_bytes / bandwidth
+ streamed_done = transfer_finish(
+ args.prefill_s, args.layers, bytes_per_layer, bandwidth
+ )
+ visible_s = max(0.0, streamed_done - args.prefill_s)
+ rows.append(
+ {
+ "bandwidth_gbps": gbps,
+ "whole_kv_transfer_ms": whole_s * 1000,
+ "layer_stream_visible_ms": visible_s * 1000,
+ "hidden_fraction": 1 - visible_s / whole_s,
+ "minimum_phase_specialization_gain_ms": visible_s * 1000,
+ }
+ )
+ print(
+ json.dumps(
+ {
+ "inputs": vars(args),
+ "row_bytes_per_layer_token": row_bytes,
+ "total_kv_bytes": total_bytes,
+ "results": rows,
+ "model_scope": (
+ "Uniform per-layer production and one serialized transfer link; "
+ "excludes RPC, queueing, serialization, and remote allocation."
+ ),
+ },
+ indent=2,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/c/tools/placement_balance.py b/c/tools/placement_balance.py
new file mode 100644
index 00000000..1c5be03a
--- /dev/null
+++ b/c/tools/placement_balance.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""Choose a frequency-ranked GPU prefix that balances CPU and GPU tier time."""
+
+import argparse
+from dataclasses import dataclass
+from pathlib import Path
+
+
+@dataclass(frozen=True)
+class Plan:
+ slots: int
+ gpu_share: float
+ cpu_seconds: float
+ gpu_seconds: float
+
+ @property
+ def critical_seconds(self) -> float:
+ return max(self.cpu_seconds, self.gpu_seconds)
+
+
+def read_usage(path: Path) -> dict[tuple[int, int], int]:
+ counts: dict[tuple[int, int], int] = {}
+ paths = sorted(path.glob("*.txt")) if path.is_dir() else [path]
+ if not paths:
+ raise ValueError(f"{path}: no stats files")
+ for stats in paths:
+ run: dict[tuple[int, int], int] = {}
+ for lineno, line in enumerate(stats.read_text().splitlines(), 1):
+ fields = line.split()
+ if len(fields) != 3:
+ raise ValueError(f"{stats}:{lineno}: expected layer expert count")
+ layer, expert, count = map(int, fields)
+ key = (layer, expert)
+ run[key] = max(run.get(key, 0), count)
+ for key, count in run.items():
+ counts[key] = counts.get(key, 0) + count
+ return counts
+
+
+def read_counts(path: Path) -> list[int]:
+ return sorted(read_usage(path).values(), reverse=True)
+
+
+def solve(
+ counts: list[int],
+ max_slots: int,
+ cpu_seconds_per_selection: float,
+ gpu_seconds_per_selection: float,
+ min_slots: int = 0,
+) -> Plan:
+ if not counts or max_slots < 0 or min_slots < 0 or min_slots > max_slots:
+ raise ValueError("counts must be non-empty and max_slots non-negative")
+ if cpu_seconds_per_selection <= 0 or gpu_seconds_per_selection <= 0:
+ raise ValueError("tier costs must be positive")
+ total = sum(counts)
+ gpu_count = 0
+ best = None
+ if min_slots == 0:
+ best = Plan(0, 0.0, total * cpu_seconds_per_selection, 0.0)
+ for slots, count in enumerate(counts[:max_slots], 1):
+ gpu_count += count
+ if slots < min_slots:
+ continue
+ plan = Plan(
+ slots,
+ gpu_count / total,
+ (total - gpu_count) * cpu_seconds_per_selection,
+ gpu_count * gpu_seconds_per_selection,
+ )
+ if best is None or plan.critical_seconds < best.critical_seconds:
+ best = plan
+ if best is None:
+ raise ValueError("min_slots exceeds observed experts")
+ return best
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("stats", type=Path)
+ parser.add_argument("--max-gpu-slots", type=int, required=True)
+ parser.add_argument("--observed-cpu-seconds", type=float, required=True)
+ parser.add_argument("--observed-cpu-selections", type=int, required=True)
+ parser.add_argument("--observed-gpu-seconds", type=float, required=True)
+ parser.add_argument("--observed-gpu-selections", type=int, required=True)
+ parser.add_argument("--total-experts", type=int)
+ parser.add_argument("--max-ram-slots", type=int)
+ parser.add_argument("--write-ranked", type=Path)
+ args = parser.parse_args()
+
+ cpu_cost = args.observed_cpu_seconds / args.observed_cpu_selections
+ gpu_cost = args.observed_gpu_seconds / args.observed_gpu_selections
+ usage = read_usage(args.stats)
+ counts = sorted(usage.values(), reverse=True)
+ if (args.total_experts is None) != (args.max_ram_slots is None):
+ parser.error("--total-experts and --max-ram-slots must be used together")
+ min_slots = 0
+ if args.total_experts is not None:
+ min_slots = max(0, args.total_experts - args.max_ram_slots)
+ if min_slots > args.max_gpu_slots:
+ parser.error("GPU+RAM capacity cannot hold all experts")
+ plan = solve(counts, args.max_gpu_slots, cpu_cost, gpu_cost, min_slots)
+ full = Plan(
+ args.max_gpu_slots,
+ sum(counts[: args.max_gpu_slots]) / sum(counts),
+ (sum(counts) - sum(counts[: args.max_gpu_slots])) * cpu_cost,
+ sum(counts[: args.max_gpu_slots]) * gpu_cost,
+ )
+
+ print(f"experts={len(counts)} selections={sum(counts)}")
+ if args.total_experts is not None:
+ print(
+ f"capacity total_experts={args.total_experts} ram_slots={args.max_ram_slots} "
+ f"min_gpu_slots={min_slots}"
+ )
+ print(f"cost cpu={cpu_cost * 1e6:.3f} us/selection gpu={gpu_cost * 1e6:.3f} us/selection")
+ print(
+ f"fill slots={full.slots} gpu_share={full.gpu_share:.4%} "
+ f"cpu={full.cpu_seconds:.3f}s gpu={full.gpu_seconds:.3f}s "
+ f"critical={full.critical_seconds:.3f}s"
+ )
+ print(
+ f"balance slots={plan.slots} gpu_share={plan.gpu_share:.4%} "
+ f"cpu={plan.cpu_seconds:.3f}s gpu={plan.gpu_seconds:.3f}s "
+ f"critical={plan.critical_seconds:.3f}s"
+ )
+ print(f"predicted_speedup={full.critical_seconds / plan.critical_seconds:.4f}x")
+ if args.write_ranked:
+ ranked = sorted(usage.items(), key=lambda item: (-item[1], item[0]))
+ args.write_ranked.write_text(
+ "".join(f"{layer} {expert} {count}\n" for (layer, expert), count in ranked)
+ )
+ print(f"ranked_stats={args.write_ranked}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/c/tools/placement_crossval.py b/c/tools/placement_crossval.py
new file mode 100644
index 00000000..a10823ce
--- /dev/null
+++ b/c/tools/placement_crossval.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+"""Evaluate expert-placement rankings with category-held-out routing traces."""
+
+import argparse
+import math
+import re
+import statistics
+from collections import defaultdict
+from pathlib import Path
+
+
+PROMPT_RE = re.compile(r"^(?P<category>.+)_(?P<replicate>\d+)\.txt$")
+
+
+def read_run(path: Path) -> dict[tuple[int, int], int]:
+ counts: dict[tuple[int, int], int] = {}
+ for lineno, line in enumerate(path.read_text().splitlines(), 1):
+ fields = line.split()
+ if len(fields) != 3:
+ raise ValueError(f"{path}:{lineno}: expected layer expert count")
+ layer, expert, count = map(int, fields)
+ counts[layer, expert] = count
+ if not counts:
+ raise ValueError(f"{path}: empty stats")
+ return counts
+
+
+def read_categories(stats_dir: Path) -> dict[str, list[dict[tuple[int, int], int]]]:
+ categories: dict[str, list[dict[tuple[int, int], int]]] = defaultdict(list)
+ for path in sorted(stats_dir.glob("*.txt")):
+ match = PROMPT_RE.match(path.name)
+ if match:
+ categories[match.group("category")].append(read_run(path))
+ if len(categories) < 2:
+ raise ValueError(f"{stats_dir}: need at least two categories")
+ return dict(categories)
+
+
+def category_shares(
+ runs: list[dict[tuple[int, int], int]],
+) -> dict[tuple[int, int], float]:
+ shares: dict[tuple[int, int], float] = defaultdict(float)
+ for run in runs:
+ total = sum(run.values())
+ for expert, count in run.items():
+ shares[expert] += count / total
+ return {expert: share / len(runs) for expert, share in shares.items()}
+
+
+def rank_experts(
+ categories: dict[str, list[dict[tuple[int, int], int]]],
+ penalty: float,
+) -> list[tuple[int, int]]:
+ per_category = [category_shares(runs) for runs in categories.values()]
+ experts = set().union(*(shares.keys() for shares in per_category))
+ ranked = []
+ for expert in experts:
+ values = [shares.get(expert, 0.0) for shares in per_category]
+ mean = statistics.fmean(values)
+ deviation = statistics.pstdev(values)
+ score = mean - penalty * deviation
+ ranked.append((score, mean, expert))
+ ranked.sort(key=lambda row: (-row[0], -row[1], row[2]))
+ return [expert for _, _, expert in ranked]
+
+
+def rank_pooled(
+ categories: dict[str, list[dict[tuple[int, int], int]]],
+) -> list[tuple[int, int]]:
+ counts: dict[tuple[int, int], int] = defaultdict(int)
+ for runs in categories.values():
+ for run in runs:
+ for expert, count in run.items():
+ counts[expert] += count
+ return [expert for expert, _ in sorted(counts.items(), key=lambda item: (-item[1], item[0]))]
+
+
+def covered_share(run: dict[tuple[int, int], int], selected: set[tuple[int, int]]) -> float:
+ return sum(count for expert, count in run.items() if expert in selected) / sum(run.values())
+
+
+def cross_validate(
+ categories: dict[str, list[dict[tuple[int, int], int]]],
+ slots: int,
+ penalty: float | None,
+) -> tuple[float, float, list[tuple[str, float]]]:
+ results = []
+ for held_out in sorted(categories):
+ train = {name: runs for name, runs in categories.items() if name != held_out}
+ ranked = rank_pooled(train) if penalty is None else rank_experts(train, penalty)
+ selected = set(ranked[:slots])
+ shares = [covered_share(run, selected) for run in categories[held_out]]
+ results.append((held_out, statistics.fmean(shares)))
+ values = [share for _, share in results]
+ return statistics.fmean(values), min(values), results
+
+
+def write_ranked(path: Path, ranked: list[tuple[int, int]]) -> None:
+ # pin_load only needs a deterministic descending integer score.
+ size = len(ranked)
+ path.write_text(
+ "".join(f"{layer} {expert} {size - rank}\n" for rank, (layer, expert) in enumerate(ranked))
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("stats_dir", type=Path)
+ parser.add_argument("--gpu-slots", type=int, default=9335)
+ parser.add_argument("--penalties", default="0,0.25,0.5,1,2")
+ parser.add_argument("--write-ranked", type=Path)
+ parser.add_argument("--selected-penalty", type=float)
+ args = parser.parse_args()
+
+ if args.gpu_slots < 1:
+ parser.error("--gpu-slots must be positive")
+ penalties = [float(value) for value in args.penalties.split(",")]
+ if any(not math.isfinite(value) or value < 0 for value in penalties):
+ parser.error("--penalties must be finite and non-negative")
+
+ categories = read_categories(args.stats_dir)
+ print(
+ f"categories={len(categories)} prompts={sum(map(len, categories.values()))} "
+ f"gpu_slots={args.gpu_slots}"
+ )
+ pooled_mean, pooled_worst, pooled_detail = cross_validate(categories, args.gpu_slots, None)
+ print(
+ f"pooled heldout_mean={pooled_mean:.4%} heldout_worst={pooled_worst:.4%} "
+ + " ".join(f"{name}={share:.2%}" for name, share in pooled_detail)
+ )
+ best = None
+ for penalty in penalties:
+ mean, worst, detail = cross_validate(categories, args.gpu_slots, penalty)
+ print(
+ f"penalty={penalty:g} heldout_mean={mean:.4%} heldout_worst={worst:.4%} "
+ + " ".join(f"{name}={share:.2%}" for name, share in detail)
+ )
+ candidate = (worst, mean, -penalty)
+ if best is None or candidate > best[0]:
+ best = (candidate, penalty)
+
+ selected = args.selected_penalty if args.selected_penalty is not None else best[1]
+ print(f"selected_penalty={selected:g}")
+ if args.write_ranked:
+ ranked = rank_experts(categories, selected)
+ write_ranked(args.write_ranked, ranked)
+ print(f"ranked_experts={len(ranked)} ranked_stats={args.write_ranked}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/experiments/glm52-continuous-batching-2026-07-31.md b/docs/experiments/glm52-continuous-batching-2026-07-31.md
new file mode 100644
index 00000000..e50f00df
--- /dev/null
+++ b/docs/experiments/glm52-continuous-batching-2026-07-31.md
@@ -0,0 +1,99 @@
+# GLM-5.2 continuous batching experiment
+
+Date: 2026-07-31
+
+## Question
+
+Can Colibri's existing mux scheduler raise aggregate GLM-5.2 decode throughput
+by evaluating one token from several independent KV slots in the same forward?
+
+## Method
+
+- Host: 6 x RTX 5090, dual Xeon Silver 4510, 251 GiB RAM.
+- Model: `/data/models/GLM-5.2-colibri-int4`.
+- Greedy decode: `DRAFT=0`, temperature 0.
+- CUDA dense tensors, attention, routed experts, and async expert groups enabled.
+- Frozen placement:
+ `/data/test/colibri-simroute-20260726/prune/frozen-general.stats`.
+- Full residency: 9,335 VRAM experts + 10,121 RAM experts, zero disk reads.
+- Eight KV slots with `CTX=256`; this is sufficient for the 21-token prompts
+ and 32-token completions without wasting the RAM needed by expert residency.
+- One engine process, batch order `1,2,4,8,4,2,1`.
+- Timing starts when the last request emits its first token. This excludes all
+ serial prompt prefill and measures only the interval in which every submitted
+ request is eligible for batched decode.
+
+The harness is `c/tools/benchmark_continuous_batch.py`.
+
+## Result
+
+| Active sessions | Aggregate tok/s, runs | Median aggregate tok/s | Median per-session tok/s |
+|---:|---:|---:|---:|
+| 1 | 4.29, 5.39 | **4.84** | **4.84** |
+| 2 | 7.19, 5.47 | **6.33** | **3.16** |
+| 4 | 8.22, 8.07 | **8.14** | **2.04** |
+| 8 | 8.30 | **8.30** | **1.04** |
+
+The experiment does **not** show an aggregate throughput breakthrough.
+Throughput rises relative to the mux single-slot path, but saturates at roughly
+8-9 tok/s by four sessions. That is approximately the existing non-mux
+single-stream baseline (8.90 tok/s on the same frozen placement), not a
+multiple of it.
+
+The 8-session median TBT was 0.852 s and p95 TBT was 1.306 s. Batching trades
+away individual-session latency without increasing total work completed enough
+to justify the trade at this point.
+
+## Profile
+
+A shorter `1,4,8` run with `PROF=1` reproduced the same shape:
+
+| Active sessions | Aggregate tok/s | Forward p50 | CPU expert bandwidth |
+|---:|---:|---:|---:|
+| 1 | 3.74 | 267 ms | 26.57 GB/s |
+| 4 | 7.35 | 522 ms | about 31-35 GB/s |
+| 8 | 9.05 | 813 ms | about 33-35 GB/s |
+
+Expert matmul consumed 69-72% of the measured time. At eight sessions the CPU
+expert side was 5.6-11.1 times slower than the overlapping GPU critical path.
+The ordinary 8.90 tok/s single-stream run reached 66.88 GB/s on CPU experts.
+
+The current multi-row CPU expert path therefore loses roughly half of the
+effective RAM bandwidth. It groups rows that select the same expert, but its
+multi-row quantized matmul does not turn that grouping into enough weight reuse
+or parallel memory bandwidth. Attention was only 15-17% and is not the primary
+bottleneck.
+
+## Memory trap found during the experiment
+
+With eight default `CTX=4096` slots and automatic live-history placement, only
+9,335 VRAM + 5,321 RAM experts were pinned. The first pass then measured
+96.6-99.8% hits and aggregate medians of only 3.64/3.51/5.48/6.00 tok/s for
+1/2/4/8 sessions. Those numbers mix batching with disk/LRU warm-up and are
+invalid as a compute comparison.
+
+Serving configuration must reserve KV memory before claiming full expert
+residency. `KV_SLOTS`, `CTX`, and expert placement are one capacity decision,
+not independent tuning knobs.
+
+## Verdict
+
+Continuous batching is already functionally implemented, but **the present
+CPU+GPU execution path does not increase aggregate GLM-5.2 decode throughput
+beyond the existing single-stream ceiling**. It must not be advertised as a
+throughput multiplier yet.
+
+The next bounded experiment is a dedicated multi-row INT4 CPU expert kernel:
+decode each expert's weights once into vector registers/cache and accumulate
+all rows before advancing through the weight stream. It is worth integrating
+only if it restores at least the single-row 60+ GB/s effective bandwidth and
+raises the full-resident 4/8-session aggregate above 8.9 tok/s.
+
+## Artifacts
+
+- `/data/test/colibri-contbatch-20260731-IucO7Z/continuous-batch-fullresident-abba.json`
+- `/data/test/colibri-contbatch-20260731-IucO7Z/continuous-batch-fullresident-abba.stderr`
+- `/data/test/colibri-contbatch-20260731-IucO7Z/continuous-batch-profile.json`
+- `/data/test/colibri-contbatch-20260731-IucO7Z/continuous-batch-profile.stderr`
+- Invalid memory-pressure control:
+ `/data/test/colibri-contbatch-20260731-IucO7Z/continuous-batch-abba.json`
diff --git a/docs/experiments/glm52-decode-failure-ledger-2026-07-31.md b/docs/experiments/glm52-decode-failure-ledger-2026-07-31.md
new file mode 100644
index 00000000..5fbcffdd
--- /dev/null
+++ b/docs/experiments/glm52-decode-failure-ledger-2026-07-31.md
@@ -0,0 +1,117 @@
+# GLM-5.2 decode failure ledger
+
+Date: 2026-07-31
+
+This is the stop-doing list for GLM-5.2 744B decode work. It records ideas
+that looked plausible but failed under controlled measurements, why they
+failed, and the evidence required before anybody spends time on them again.
+
+The default reference is the 6 x RTX 5090 host with dual-socket DDR5 RAM,
+Colibri INT4 weights, greedy decode (`COLI_TEMP=0 DRAFT=0`), and the model
+fully resident across VRAM and RAM unless stated otherwise.
+
+## Rules
+
+- Do not reopen a rejected direction because a microbenchmark is faster.
+- Do not compare separate processes without an interleaved ABBA control.
+- A compute experiment must report residency, disk reads, CPU expert
+ bandwidth, output equality or quality, and the exact generated token count.
+- “Conditional” means the feature may help a narrow workload; it is not a
+ safe default.
+- A new name, paper, or implementation does not invalidate the measurements
+ below. The stated reopen gate must change.
+
+## Rejected or quarantined directions
+
+| Direction | Controlled evidence | Why it failed | Status and reopen gate |
+|---|---|---|---|
+| Whole-expert NUMA ownership | Interleaved controls: 8.84/8.92 tok/s and 64.74/64.89 GB/s CPU expert bandwidth. Node-local ownership: 6.16 tok/s and 30.97 GB/s, at 100% hit and zero disk. | With roughly 80% of routes on GPU, only 1-2 RAM experts remain per layer. Assigning each whole expert to one socket idles the other memory controller; interleaving lets one expert consume both. | **Rejected on this topology.** Reopen only when many CPU experts execute concurrently per layer, or when the memory topology changes. |
+| One CPU task per expert / expert-parallel OpenMP | Earlier trials regressed about 23%; each expert obtained only about 2.5 GB/s. Row batching and persistent-team variants were neutral or negative. | There are too few CPU experts per layer. Splitting workers across experts sacrifices row-parallel bandwidth and NUMA/cache locality. | **Rejected.** Reopen only if CPU expert concurrency becomes materially larger. |
+| Impact/cost-aware placement without a hard residency constraint | Fixed replay fell from a 7.46 tok/s frequency-fill median to 4.01 tok/s (-46.2%). It caused about 490-491 disk loads, 9.28 GB fetched, and 4.29-4.46 s of wait. A capacity-preserving variant measured 6.88 versus 7.26 tok/s; a held-out learned layout also produced a zero-disk regression of about 38%. | Optimizing an estimated CPU/GPU compute balance evicted useful resident weights and did not transfer across prompt classes. When full capacity is enforced, the policy largely collapses back to frequency fill. | **Rejected as implemented.** Reopen only with hard full-residency constraints, actual tier-latency costs, and category-held-out validation. |
+| Cross-layer expert prefetch (`PREFETCH`, `PILOT`, learned coupling) | `PREFETCH=1` reduced median replay from 4.01 to 3.91 tok/s (-2.5%), while service/wait changed by less than 1%. Learned coupling produced only six nonresident hints and worsened misses and wait. | The predictable experts were already resident. Staging contended with PCIe/attention, so routing recall did not translate into avoided cold misses. | **Rejected for resident decode.** Reopen only on a genuine disk-miss workload and optimize measured cold-miss recall, not routing recall. |
+| WarpDecode low-row CUDA kernel | Bit-exact isolated GLM-sized eight-expert group: block kernel 0.248 ms, WarpDecode 0.326 ms (about 31% slower). Earlier end-to-end wins tracked CPU bandwidth and machine-state drift. | The specialized mapping did not offset its scheduling and reduction costs on RTX 5090. | **Rejected on sm_120.** Reopen on a materially different GPU only after an isolated kernel win plus interleaved end-to-end controls with stable CPU bandwidth. |
+| Fused ANS decompress + expert matvec | Same-process ABBA: materialize path 6.505 tok/s, fused path 5.285 tok/s (-18.8%), with identical predictions. The earlier cross-process +7.1% result was drift. | Per-row decode/control overhead cost more than the eliminated scratch materialization. | **Rejected.** Reopen only with a decode-native, vector-aligned encoding whose isolated fused kernel first beats materialization. ANS residency itself remains valid. |
+| GPU shared-expert microkernels and GPU routed scatter-add in isolation | Shared-expert end-to-end run was 110.08 s versus a 94.05 s control; routed scatter-add was 135.27 s versus 94.05 s, despite faster isolated arithmetic. | Launches, synchronization, transfers, and reductions dominated the saved matrix time. | **Rejected in the current split layer.** Reopen only as a genuinely persistent/fused whole-layer path that removes the round trips. |
+| GPU-resident residual ownership across a PCIe star | Parallel device dispatch helped (6.82 to 7.44 tok/s, +9.1%), but extending ownership across the layer did not. | Moving the roughly 95 MB layer state among peers serializes on the no-NVLink PCIe topology; host traffic was not the dominant cost. | **Reject residual/P2P expansion; keep parallel dispatch.** Reopen with NVLink or whole-layer fusion that eliminates transfers. |
+| GPU zero-copy reads of RAM-resident experts | The preserved dual-lane prototype measured 4.24 tok/s for CPU-direct, but only 1.71 tok/s when a GPU kernel demand-read mapped host weights. Effective PCIe zero-copy bandwidth was about 2.8 GB/s, versus 56 GB/s for bulk pinned DMA. Later double-buffered DMA reached only parity (8.16 versus 8.25 tok/s); registration consumed roughly 0.57 extra RSS bytes per registered byte, while `cudaHostAlloc` broke NUMA interleave and reduced the CPU leg to 38 GB/s. | Fine-grained PCIe reads are latency-bound. Bulk DMA needs a large pinned store, but this 251 GiB host cannot register enough of the 191 GiB warm tier without losing memory capacity or NUMA placement; the offload fraction is too small to beat CPU contention. | **Rejected on this host.** Reopen only with 384-512 GiB RAM headroom, a driver/IOMMU configuration that removes registration inflation, or a coherent high-bandwidth CPU-GPU interconnect. |
+| Static expert pruning / `EXPERT_BUDGET` as a lossless speed path | Every tested budget was either no faster or incoherent; the control is quarantined behind `EXPERT_BUDGET_EXPERIMENTAL`. | It reduces model computation by changing the model, not by removing redundant engine work; quality and routing behavior fail before a dependable speed win appears. | **Rejected as a lossless/default feature.** Reopen only as an explicitly lossy model-compression study with full quality evaluation and measured byte reduction. |
+| Direct cross-expert common-basis extraction | Real weights from layers 3/10/30/50/77 and all 256 experts showed only 0.38%-0.69% shared mean energy, near the random baseline of 1/256. Pairwise cosine means were near zero; 90% energy needed roughly 192-224 of 256 bases. A 35% storage cut caused about 18%-30% sampled reconstruction error. | Independently trained experts do not contain a large aligned linear component that can be losslessly factored after training. | **Rejected for engine-only transformation.** Reopen only with training/distillation; that produces a derivative model. |
+| Permutation-based expert neuron alignment | Across layers 3/30/77, nearest matched cosine was 0.246-0.253 versus a random nearest baseline near 0.245. | Apparent matches are the expected nearest-neighbour statistic, not reusable neurons. | **Rejected.** Reopen only if a new method beats a matched random control by a substantial margin and reconstructs held-out activations. |
+| SERE-style functional expert substitution | Five diverse prompts, real hidden states, layers 3/30/77, all 256 experts, and 489,600 comparisons: mean nearest similarity was 0.08457/0.02133/0.07281; maximum pair similarity was 0.30321/0.06062/0.28433; no pair reached 0.5. | GLM-5.2 did not exhibit the strong functional expert redundancy required by SERE. Substitution here is lossy skipping with no redundancy signal. | **Rejected for runtime integration.** Reopen only if a much broader activation corpus yields stable cross-prompt clusters above 0.5. |
+| MTP/speculative draft as a global default | Latest full-resident retest: `DRAFT=0` 8.90 tok/s; `DRAFT=1` 7.51 (-15.6%, 60% acceptance, +30.4% CPU rows); `DRAFT=3` 3.95 (-55.6%, 23% acceptance, +145% CPU rows). A predictable prompt previously gave D1 +9.2% at 91% acceptance. | Rejected drafts widen the expert union. Acceptance alone does not guarantee that saved forwards exceed added expert work. | **Conditional, never default.** Keep opt-in/guarded. Reopen for a stronger trained draft only when acceptance is near 90% and expert-union growth is bounded across prompt classes. |
+| Adding GPUs without fixing placement/execution | vLLM-Moet TP4 measured 2.6 tok/s; TP2 x PP3 using all six GPUs measured 1.78 tok/s. | Extra aggregate VRAM did not compensate for per-rank residency, communication, replay, and serial pipeline latency. | **Rejected as a standalone remedy.** Reopen only with a materially different placement and parallel execution path under matched quality. |
+| Repin/promotion policy sweeps | `REPIN=8`, `REPIN=32`, 64 swaps/round, and 8 swaps/round all regressed. A second prefill correction pass measured 5.86 tok/s; lazy demotion 4.77; GPU-to-RAM recovery 6.15. | More frequent movement pays synchronization overhead; less frequent movement leaves stale expert sets. Recovery costs approximately as much as page-cache rereads. | **Rejected around the tested operating point.** Current local optimum is 16 tokens and 16 swaps/round. Reopen only after the movement mechanism or workload changes. |
+| CPU/GPU expert overlap through extra pthreads | 6.09-6.30 tok/s with no stable gain. | Extra workers compete with the 24 CPU workers while the GPU expert group is too small to hide enough wall time. | **Rejected implementation.** Do not confuse this with the existing async device dispatch; reopen only with an execution graph that removes worker contention. |
+| Generic CPU/JIT tuning as the main breakthrough | Global NUMA interleave, huge pages, 12-core restriction, smaller VRAM reserve, normalized profiles, VNNI int4 x int8, and OpenMP restructuring were neutral or negative. AVX-512 showed 5.12 to 5.89 tok/s in a greedy A/B but changed accumulation order and eventually diverged; row blocking collapsed from a short benchmark win to 6.84 versus 6.83 tok/s over sustained decode. | The remaining path is memory-bound and sensitive to cache/turbo state; arithmetic microbench wins do not reliably preserve output or end-to-end throughput. | **Rejected as a blanket direction.** Reopen a specific kernel only with sustained ABBA, numeric-error/quality tests, and end-to-end gain. |
+| Existing continuous batching as a throughput multiplier | Full-resident mux ABBA medians for 1/2/4/8 active sessions were 4.84/6.33/8.14/8.30 aggregate tok/s. A profiled eight-session run reached 9.05 tok/s, but CPU expert bandwidth was only about 33-35 GB/s versus 66.88 GB/s in the ordinary 8.90 tok/s single-stream baseline; the CPU side was 5.6-11.1x the GPU critical path. | The current multi-row INT4 CPU expert path does not convert shared expert weights into enough reuse and loses roughly half the effective RAM bandwidth. Batching raises throughput relative to its own slow mux S=1 path, then saturates at the existing single-stream ceiling. | **Current implementation rejected as a speed claim; serving mechanism retained.** Reopen after a dedicated multi-row expert kernel restores 60+ GB/s and pushes full-resident 4/8-session aggregate throughput beyond 8.9 tok/s. |
+
+## Keep these results
+
+These are not failures and must not be discarded while avoiding the directions
+above:
+
+- Keep the model fully resident whenever possible; disk avoidance dominates.
+- Keep frequency/hotness-based expert placement as the current robust default.
+- Keep selective NUMA interleaving for the small number of RAM experts.
+- Keep parallel per-device dispatch and the existing CPU/GPU asynchronous path.
+- Keep the ANS compressed resident tier; only fused consumption was rejected.
+- Keep the continuous-batching scheduler and paged/ragged KV machinery as
+ functional serving infrastructure, but do not claim a throughput gain until
+ its multi-row CPU expert path passes the gate above. Keep prefix reuse and
+ prefill acceleration for TTFT.
+- Keep MTP available as an opt-in workload-specific feature, not an automatic
+ speed claim.
+
+## Remote evidence index
+
+- `/data/test/glm52-cross-expert-structure-20260731.json`
+- `/data/test/glm52-neuron-alignment-20260731.json`
+- `/data/test/sere-calib-output/aggregate-5-summary.json`
+- `/data/test/sere-calib-output/layer-003-aggregate-5.csv`
+- `/data/test/sere-calib-output/layer-030-aggregate-5.csv`
+- `/data/test/sere-calib-output/layer-077-aggregate-5.csv`
+- `/data/test/mtp-retest-20260731/`
+
+The temporary SERE calibration code lives at
+`/data/test/colibri-sere-calib`. The latest-dev MTP retest source lives at
+`/data/test/colibri-mtp-retest`. Neither is a production implementation.
+
+## Remaining honest directions
+
+1. A persistent or whole-layer expert kernel that removes launches, host
+ round-trips, and reductions together, validated on the target GPU.
+2. A stronger trained draft model whose acceptance and expert-union cost are
+ jointly controlled.
+3. A retrained/distilled derivative MoE designed for shared structure or
+ locality; this is model research, not a post-training lossless rewrite.
+4. Hardware that raises resident capacity and memory bandwidth without adding
+ a worse communication topology.
+
+The detailed experimental context remains in
+`inference-paper-test-matrix-2026-07-28.md` and
+`glm52-6x5090-2026-07-12.md`.
+
+## Final software-ceiling conclusion
+
+For the original GLM-5.2 744B architecture, lossless greedy single-stream
+decode, and this 6 x RTX 5090 + dual Xeon Silver 4510 + 251 GiB DDR5 host, the
+best current full-resident result is 8.90 tok/s:
+
+- 9,335 experts in VRAM and 10,121 in RAM;
+- 100% expert hit rate and zero disk traffic;
+- CPU expert bandwidth 66.88 GB/s;
+- approximately 44% expert matmul, 34% attention, and 22% remaining work.
+
+The controlled failures in this ledger remove every identified path to a
+general 1.5-2x engine-only improvement without changing the model, quality
+policy, workload, or hardware. The remaining realistic engineering headroom is
+incremental: roughly 10-25% in aggregate, with a practical stable target around
+9.5-10.5 tok/s and an exceptional upper target around 11-12 tok/s. These are
+planning bounds, not measured benchmark claims.
+
+Material gains beyond that require changing a boundary condition: more VRAM,
+substantially higher memory bandwidth/coherent memory, a trained route-aware
+draft, or a retrained locality-aware MoE derivative. Future engine work should
+therefore prioritize stability, automatic hardware planning, and cross-machine
+performance portability unless a proposal demonstrates that it reduces bytes
+per token or removes a measured whole-layer critical-path cost.
diff --git a/docs/experiments/glm52-split-entropy-2026-07-31.md b/docs/experiments/glm52-split-entropy-2026-07-31.md
new file mode 100644
index 00000000..5797795f
--- /dev/null
+++ b/docs/experiments/glm52-split-entropy-2026-07-31.md
@@ -0,0 +1,110 @@
+# GLM-5.2 lossless VRAM-base / RAM-residual feasibility
+
+Date: 2026-07-31
+
+## Question
+
+Can every routed-expert INT4 weight be represented by a small base kept in
+VRAM, with an exact residual fetched from RAM only after routing, then restored
+on the GPU without changing model output?
+
+## Real-weight capacity result
+
+`c/tools/analyze_split_entropy.py` scanned 3,840 routed projection tensors
+(24.16 GB packed weights) from layers 3, 10, 30, 50, and 76 of
+`/data/models/GLM-5.2-colibri-int4`. It also read all shard headers to obtain
+the corpus size:
+
+- routed packed weights: 372.052 GB;
+- routed F32 scale sidecars: 0.797 GB;
+- measured symbol entropy: 2.9147 bits/weight (72.87% of raw INT4);
+- per-layer entropy: 2.7698, 2.9433, 2.9495, 2.9505, and 2.9386 bits/weight.
+
+At the measured 176.57 GB expert-VRAM budget, after scales and one 32-bit tile
+offset per 4,096 weights, the base may average 1.882 bits/weight. An ideal
+entropy residual would be 96.06 GB, but that is not a practical random-access
+codec.
+
+The tested GPU-decodable representation uses a global unequal-group codebook:
+
+- 1-bit base: groups of 4/12 symbols, 2.559 residual bits/weight;
+- 2-bit base: groups of 1/2/2/11 symbols, 1.258 residual bits/weight;
+- 11.8% 1-bit tiles plus 88.2% 2-bit tiles fit the VRAM budget;
+- practical RAM residual: **131.31 GB**;
+- total representation: 3.294 bits/weight, or 82.34% of raw INT4.
+
+This is lossless symbol coding. It does not claim that 744B model information
+has been reduced to the VRAM base alone; the missing information remains in
+RAM.
+
+## RTX 5090 decode and transfer microbenchmark
+
+`c/tools/benchmark_split_entropy.cu` generated symbols with the measured GLM
+histogram, packed both formats, reconstructed every symbol on one RTX 5090,
+and compared the complete output before timing.
+
+| Format | GPU decode only | Pinned H2D + decode | Result |
+|---|---:|---:|---|
+| 1-bit base + 2.560-bit residual | 184.0 Gweight/s (92.0 raw-INT4 GB/s) | 65.8 Gweight/s (32.9 raw-INT4 GB/s) | exact |
+| 2-bit base + 1.259-bit residual | 184.3 Gweight/s (92.1 raw-INT4 GB/s) | 97.8 Gweight/s (48.9 raw-INT4 GB/s) | exact |
+
+The capacity-weighted H2D-plus-decode rate is about 91.9 Gweight/s, equivalent
+to 46.0 GB/s of original packed INT4 per GPU. With about 607 routed experts per
+token and 19.12 MB of packed weight per expert, a perfectly balanced six-GPU
+transfer/decode-only ceiling is roughly **23.8 tok/s**. This is an upper bound,
+not model throughput: expert matmul, routing, attention, synchronization, and
+contention are excluded.
+
+## Conclusion
+
+The representation is technically feasible. The standalone decoder initially
+looked fast enough to continue, but the decisive fused-matvec test rejected the
+current representation as a decode-speed path.
+
+The important negative constraint is that all routed experts now require RAM
+traffic and GPU compute. The current 8.90 tok/s engine already overlaps hot
+GPU experts with cold CPU experts; replacing that path can lose the existing
+parallelism. A real claim requires a fused residual-decode + INT4 matvec path,
+six-GPU placement, a 131 GB pinned/registered residual store, and an ABBA
+end-to-end replay against the 8.90 tok/s baseline. Until then, 23.8 tok/s is
+only a transfer/decode roof and must not be reported as achieved throughput.
+
+## Fused matvec follow-up
+
+`c/tools/benchmark_split_matvec.cu` tested the two real GLM projection
+geometries (`2048 x 6144` and `6144 x 2048`) against a resident raw-INT4
+W4A32 kernel. All paths reconstructed the same weights; the exact global-scan
+variant produced bit-identical FP32 outputs. A faster segmented reduction only
+changed FP32 accumulation order (maximum relative error below 3.1e-5).
+
+| Geometry | Codec | Raw resident | Fused decode+matvec | Pinned H2D+fused |
+|---|---|---:|---:|---:|
+| 2048 x 6144 | 1-bit variable | 0.013 ms | 0.054 ms | 0.186 ms |
+| 2048 x 6144 | 2-bit variable | 0.013 ms | 0.055 ms | 0.120 ms |
+| 2048 x 6144 | 2-bit direct+exceptions | 0.013 ms | 0.049 ms | 0.124 ms |
+| 6144 x 2048 | 1-bit variable | 0.014 ms | 0.056 ms | 0.172 ms |
+| 6144 x 2048 | 2-bit variable | 0.014 ms | 0.055 ms | 0.098 ms |
+| 6144 x 2048 | 2-bit direct+exceptions | 0.014 ms | 0.047 ms | 0.107 ms |
+
+The first address scheme scanned all variable residual widths per row and was
+7-10x slower than raw. A segmented warp-prefix implementation reduced that to
+about 4x slower. The final direct-bitplane plus per-warp exception-stream
+format removed the global prefix dependency at the cost of increasing the
+2-bit residual from 1.259 to 1.491 bits/weight; it was still 3.4-3.8x slower
+before transfer and 7.6-9.5x slower with transfer.
+
+This is worse than the engine baseline in two additional ways not represented
+by the table: Colibri already fuses gate/up projection work, and its CPU and
+GPU expert lanes overlap. Therefore full-engine integration is not justified.
+The capacity result remains useful, but the proposed lossless split exchanges
+RAM capacity for an address-dependent codec that destroys the cheap raw-INT4
+inner loop.
+
+Artifacts on `rs-yuesheng-gpu`:
+
+- `/tmp/glm52-split-entropy.json`
+- `/tmp/analyze_split_entropy.py`
+- `/tmp/benchmark_split_entropy`
+- `/tmp/benchmark_split_entropy.cu`
+- `/tmp/benchmark_split_matvec`
+- `/tmp/benchmark_split_matvec.cu`
diff --git a/docs/experiments/inference-paper-test-matrix-2026-07-28.md b/docs/experiments/inference-paper-test-matrix-2026-07-28.md
new file mode 100644
index 00000000..025a2ef2
--- /dev/null
+++ b/docs/experiments/inference-paper-test-matrix-2026-07-28.md
@@ -0,0 +1,954 @@
+# Inference-paper claim test matrix
+
+Date: 2026-07-28
+
+This is an experimental ledger, not a literature summary. A paper claim is
+counted as tested only when the relevant implementation is compared against a
+controlled baseline on the same hardware, model, prompt/replay, token count,
+and precision policy. Paper-reported numbers are context, never local proof.
+
+## Scope and verdicts
+
+The initial corpus covers the inference mechanisms raised by Kimi K3, Kimi
+Linear, Mooncake, HybriMoE, SparseSpec, PagedAttention, Splitwise, and
+HCAttention. References are listed at the end.
+
+Verdicts:
+
+- **confirmed**: reproduced locally on the intended real workload;
+- **conditional**: reproduced, but only under a measured prerequisite;
+- **rejected**: controlled local A/B contradicts the useful form of the claim;
+- **pending-runtime**: applicable, but the runtime mechanism is missing;
+- **pending-model**: requires weights trained for a different architecture;
+- **not-applicable**: the claim targets a materially different serving regime.
+
+## Measurement contract
+
+- Primary hardware: 6x RTX 5090 (32 GiB each), dual Xeon Silver 4510, 251 GiB
+ host RAM.
+- Primary model: GLM-5.2 int4, unless a claim requires another architecture.
+- Decode comparisons: greedy, `COLI_TEMP=0 DRAFT=0`, fixed prompt and output
+ length, warm-up first, ABBA or rotated order, at least three measured runs.
+- Speculation comparisons explicitly vary `DRAFT`; their control remains
+ `DRAFT=0`.
+- Report median tok/s and the execution breakdown, not the best run.
+- Correctness gate: identical replay tokens where the mechanism claims
+ losslessness; otherwise an explicit quality suite and error bound.
+- A throughput claim fails if it merely moves time into startup, prefill,
+ transfer, or an unreported CPU path.
+- Serving claims require concurrent request traces and TTFT/TBT/goodput; a
+ batch-1 decode run cannot validate them.
+
+## Claim matrix
+
+| ID | Paper mechanism and testable claim | Colibri experiment | Status / current evidence |
+|---|---|---|---|
+| M1 | HybriMoE: CPU and GPU intra-layer work can overlap instead of serializing | Compare synchronous expert groups with `COLI_GROUP_ASYNC=1`; record CPU time, GPU critical path, overlap window, and tok/s | **confirmed, conditional** on current `dev`: +7.1% without NUMA but only +2.0% after NUMA makes the GPU tier the straggler |
+| M2 | HybriMoE: impact-aware placement beats frequency-only placement | Use measured CPU/GPU cost to choose the prefix that minimizes `max(T_cpu, T_gpu)`; compare with filling VRAM from the same hot-count ranking | **rejected on this host**: fixed-token replay median fell 7.46 -> 4.01 tok/s; compute-only balancing reduced RAM/LRU residency and exposed about 4.3-4.5 s of disk wait |
+| M3 | HybriMoE: inter-layer prefetch hides expert movement | Sweep prefetch distance and queue depth; compare service time versus visible wait time | **rejected for the available policies**: `PREFETCH=1` lowered replay throughput 2.5%; a cross-domain coupling table predicted almost exclusively resident experts, and bounded non-resident/real-load variants did not reduce misses or felt wait |
+| M4 | Kimi K3 LatentMoE: narrowing the routed branch reduces expert weight and communication traffic while allowing larger top-k | Train or obtain matched full-width and latent-routed checkpoints; compare quality, bytes/token, expert compute, and collective traffic | **pending-model**; cannot be inferred from GLM-5.2 |
+| M5 | Kimi K3 sparse MoE benefits from a low-row warp-specialized decode kernel | Compare block kernel and WarpDecode with identical weights, routing, and output | **rejected on current dev/RTX 5090**: a bit-exact isolated 8-expert GLM-sized group measured block 0.248 ms versus warp 0.326 ms; noisy end-to-end wins were CPU-bandwidth drift |
+| M6 | Kimi K3 deployment-aware FP4 expert quantization reduces serving memory without unacceptable quality loss | Compare the same checkpoint before/after QAT MXFP4; measure quality and real kernel throughput | **pending-model**; post-training quantization is not equivalent to the paper's QAT claim |
+| A1 | Kimi Linear/K3: 3:1 KDA-MLA hybrid reduces long-context KV traffic while retaining periodic global attention | Matched trained hybrid/full-attention checkpoints; sweep context length and report KV bytes, TTFT, TBT, and quality | **pending-model** |
+| A2 | Kimi Linear: KDA's specialized chunkwise/DPLR algorithm is required for hardware-efficient prefill | Kernel A/B against a mathematically equivalent unfused implementation on a KDA checkpoint | **pending-model** |
+| A3 | Kimi K3: unified paging of fixed KDA state and growing MLA KV simplifies allocation and transfer without losing reuse | Implement typed pages in one allocator; stress allocation, eviction, transfer, and restore across mixed state types | **pending-runtime**, after A1 support exists |
+| A4 | Kimi K3: decoupling physical-page, prefix-hash, and recurrent-checkpoint granularities improves prefix reuse | Trace replay over several block/hash/checkpoint sizes; measure hit rate, retained bytes, restore cost, and TTFT | **partly supported, model-limited**: physical pages are independently tunable and 64 tokens is the measured allocation/fragmentation Pareto point; prefix adoption remains exact token-granular; GLM-5.2 has no KDA recurrent checkpoint to test |
+| K1 | PagedAttention: paged KV removes fragmentation and enables flexible sharing | Compare contiguous KV and paged KV under changing sequence lengths and slots; measure waste, maximum concurrency, and latency | **partly confirmed by prototype**: ragged KV now uses real 64-token physical pages with no grow-copy; cross-page correctness is exact and a length-skew trace reserves 76.4% less than fixed-slot allocation, but page alias/refcount sharing and an end-to-end concurrency curve remain absent |
+| K2 | Prefix reuse substantially reduces repeated-prefix TTFT | Compare cold second request against cross-slot prefix adoption on an identical long prefix | **confirmed on current `dev`**: three-round median second-request TTFT fell 17.689 -> 0.569 s (31.1x); each reused 257/264 prompt tokens and prefilling only 7 |
+| K3 | HCAttention: key quantization, value offload, and eviction can retain quality at 25% (and remain competitive at 12.5%) KV | Implement each component separately, then combined; LongBench-style quality plus latency/traffic at 100/25/12.5% | **pending-runtime**; requires an accuracy experiment, not only a memory benchmark |
+| S1 | MTP/speculative decoding accelerates decode when accepted tokens amortize target work | Sweep draft depth and prompt on full residency; report acceptance, tok/forward, draft cost, verify cost, expert union, and tok/s | **confirmed, strongly conditional**: DRAFT=1 was +9.2% on predictable text but -17.7% on explanatory text; a 24-proposal/70% guard cuts the measured negative case to -7.8% without disabling a 100%-acceptance case |
+| S2 | The S1 result reverses when grouped GPU verification makes multi-position expert work sublinear | Compare S=1/2/4 expert time with grouped kernels and near-full GPU residency, then repeat draft sweep | **partly confirmed**: current grouped/async/full-resident runtime makes DRAFT=1 and DRAFT=3 positive, but deeper verification still grows expert work and is prompt-sensitive |
+| S3 | Kimi K3/EAGLE-3: a target-feature draft trained for acceptance improves lossless speculation | Compare current MTP head with an EAGLE-3-style feature-fusion draft on the same target | **pending-model** |
+| S4 | SparseSpec: delayed verification can overlap CPU draft work with GPU target work | Timeline CPU draft, target verify, and KV mutations; compare serial versus delayed schedule | **pending-runtime**, dependent on a useful S2/S3 draft |
+| C1 | Losslessly compressed resident experts increase effective VRAM capacity enough to offset decode cost | Raw expert tier versus ANS tier on identical placement budget and output | **confirmed**: capacity +13.9%; 32-token decode 6.19 -> 7.12 tok/s; 128-token 6.75 -> 7.31 tok/s; controlled output byte-identical |
+| C2 | Pipelined/aligned direct sidecar loading hides or reduces compressed-weight placement cost | Buffered, pinned-staging, and aligned direct-read sidecar placement | **confirmed**: about 197 s buffered, 157 s pinned, 80-103 s direct; full 110 GB archive read 18.94-19.15 s |
+| C3 | Compression decode can be fused with expert matvec to eliminate materialization traffic | Compare current decode-to-scratch against row-aligned fused decode/matvec on fixed-token replay | **rejected after integrated ABBA**: predictions remained identical, but same-process materialize 6.505 versus fused 5.285 tok/s (-18.8%); the earlier cross-process +7.1% was machine drift |
+| P1 | More aggregate GPUs do not help when expert placement remains per-rank and the execution is serial | Compare TP4 with TP2xPP3 under equal model/quality conditions | **confirmed**: TP4 median 2.6 tok/s; all-six TP2xPP3 1.78 tok/s |
+| P2 | Residual broadcast + parallel per-device expert compute beats serial layer ownership on PCIe-only GPUs | Compare existing concurrent per-device groups with a forced global serialization control; verify overlap with Nsight | **parallel dispatch confirmed; GPU-resident residual rejected for this architecture**: multi-device execution raises fixed-replay median 6.82 -> 7.44 tok/s (+9.1%), while the remaining host transfer is not the critical path |
+| P3 | NUMA-aware placement raises effective CPU expert bandwidth on a dual-socket host | Interleaved on/off, same binary and prompts, ABBA order | **confirmed** on current `dev`: 5.67 -> 7.89 tok/s without async and 6.07 -> 8.05 with async in the first controlled replicate |
+| D1 | Splitwise/Mooncake: separating prefill and decode improves goodput under mixed concurrent traffic | Replay a concurrent long/short request trace against mixed scheduling; measure TTFT/TBT SLO goodput and KV transfer | **interference confirmed; split benefit pending**: inserting a 501-token prefill raised an active decode's maximum TBT from 0.188 s to 44.205 s, but Colibri has no disaggregated execution path for the treatment |
+| D2 | Mooncake: layer-wise KV transfer hides most prefill/decode transfer latency | Serialized whole-KV transfer versus per-layer streaming on the same interconnect | **supported only by calibrated model**: for the measured 111.5 MB KV, ideal layer streaming hides 98.7% of link time; no transfer runtime exists |
+| D3 | Mooncake: prefix-affinity scheduling and hot-prefix replication improve effective throughput | Trace-driven multi-instance comparison against round-robin/LRU | **mechanism confirmed, scheduler pending**: K2 shows a prefix hit cuts TTFT 17.689 -> 0.569 s, but no multi-instance affinity/replication scheduler was exercised |
+| D4 | Splitwise is useful only when phase specialization outweighs KV transfer | Sweep prompt/output distributions and interconnect bandwidth; locate the break-even boundary | **calibrated boundary only**: under ideal layer streaming the measured 501-token request exposes 11.29 ms at 1 Gb/s and 0.11 ms at 100 Gb/s; RPC, queueing, and remote allocation remain unmeasured |
+
+## Immediate experiment batches
+
+### Batch 1: rerun mechanisms that already exist
+
+1. CPU/GPU group overlap (M1), with synchronous control.
+2. Selective NUMA (P3), crossed with M1 to expose interaction.
+3. Raw versus ANS residency (C1), retaining token/routing identity.
+4. Block versus WarpDecode (M5), on the same ANS archive.
+5. MTP S=1/2/4 cost curve (S1/S2 gate), with expert-union counters.
+
+This is a factorial experiment where practical, not five unrelated "best"
+runs. The important interactions are NUMA x overlap and ANS x WarpDecode.
+
+### Batch 2: small runtime additions
+
+1. Cost-weighted expert placement (M2).
+2. Fused ANS decode/matvec prototype (C3).
+3. Parallel multi-device expert dispatch/gather (P2).
+4. End-to-end paged/prefix KV experiments (K1/K2).
+
+### Batch 3: model-dependent work
+
+KDA/MLA, LatentMoE, MXFP4 QAT, EAGLE-3, and HCAttention quality claims require
+appropriate checkpoints or training. Microbenchmarks may validate kernels,
+but cannot validate model-quality claims.
+
+## Results added on 2026-07-28
+
+### M5: ANS-resident block kernel versus WarpDecode
+
+Hardware and workload:
+
+- 6x RTX 5090, 24 physical CPU threads spread across cores;
+- `COLI_NUMA=1`;
+- 10,628 VRAM experts through the same 2,500-raw + ANS sidecar;
+- remaining 8,828 experts resident in RAM;
+- 100% expert hit rate;
+- identical 20-token prompt, 64-token greedy decode, routing counts, and output;
+- async CPU/GPU expert-group path enabled in both runs.
+
+| mode | decode | expert matmul | CPU expert rows | effective CPU BW |
+|---|---:|---:|---:|---:|
+| block control | 7.65 tok/s | 3.836 s | 9,207 | 55.76 GB/s |
+| WarpDecode | 7.76 tok/s | 3.637 s | 9,207 | 60.48 GB/s |
+| change | **+1.4%** | **-5.2%** | identical | +8.5% |
+
+This confirms the direction but not the earlier +9.2% magnitude. The
+end-to-end gain is small in this routing because CPU rows remain on the
+critical path and attention is already about 35% of decode. More rotated
+repeats and prompts are required before replacing the earlier estimate.
+
+An earlier pair in the same session is deliberately invalidated: without
+fixed physical-thread binding and explicit NUMA placement, the control
+measured 4.89 tok/s and the WarpDecode run 2.16 tok/s, while CPU expert
+bandwidth independently collapsed from 26.96 to 10.16 GB/s and prefill also
+regressed. That pair measures a NUMA/thread-placement confound, not the GPU
+kernel. It is retained here because silently selecting the favorable run
+would violate the measurement contract.
+
+The original async profiler reported `routed GPU critical 0.000s` during
+decode despite thousands of GPU-served calls. The instrumentation fix used in
+the next experiment records successful issue-to-take windows without changing
+execution. It is a critical window (and therefore includes useful CPU overlap),
+not a sum of isolated CUDA kernel durations.
+
+#### Current-dev revalidation
+
+The two WarpDecode commits were replayed cleanly onto current `dev`, without
+the ANS materialization/fusion experiment. A same-process balanced sequence
+(`A-B-B-A-B-A-A-B`, where A is the existing block kernel) did not reproduce a
+stable end-to-end gain: block phases ranged from 6.80 to 8.61 tok/s and warp
+from 6.76 to 8.55 tok/s while CPU expert bandwidth independently moved between
+55 and 78 GB/s. The balanced medians actually favored block, 8.41 versus
+7.56 tok/s.
+
+An isolated CUDA benchmark then removed the CPU tier. It used eight GLM-sized
+W4 experts (`D=7168`, `I=2048`, one row each), alternated call order for 40
+pairs, and checked every output bit. Five fresh processes gave:
+
+| process | block | WarpDecode | block / warp |
+|---:|---:|---:|---:|
+| 1 | 0.239 ms | 0.312 ms | 0.766x |
+| 2 | 0.248 ms | 0.340 ms | 0.728x |
+| 3 | 0.267 ms | 0.316 ms | 0.846x |
+| 4 | 0.252 ms | 0.326 ms | 0.773x |
+| 5 | 0.241 ms | 0.344 ms | 0.701x |
+| median | **0.248 ms** | **0.326 ms** | **0.761x** |
+
+`maxerr=0` in every process, but the warp mapping increased median kernel-call
+latency by 31.5%. The apparent end-to-end gains were therefore not caused by
+this kernel. WarpDecode remains experimental and is not merged into current
+`dev`.
+
+Artifacts:
+
+- `/data/test/paper-m5-warp-current-balanced8.log`
+- `/data/test/paper-m5-warp-micro.log`
+
+### CPU thread-count control
+
+Because CPU expert bandwidth repeatedly confounded GPU-kernel comparisons, the
+full-resident fixed replay swept 12/16/20/24/32/48 OpenMP threads in one
+process, using a mirrored order so every thread count had equal average phase
+position. The first sweep suggested 20 threads (7.89 tok/s paired mean) over
+24 (7.25), but a focused balanced-eight revalidation reversed the result:
+
+| threads | median decode | median expert matmul |
+|---:|---:|---:|
+| 20 | 8.09 tok/s | 3.485 s |
+| 24 | **8.35 tok/s** | **3.370 s** |
+
+Twenty threads was 3.1% slower; 48-thread SMT was also clearly poor in the
+broad sweep (6.19 tok/s paired mean). The existing 24-physical-thread setting
+is retained. The broad-sweep win was machine-state drift, not a tuning result.
+
+Artifacts:
+
+- `/data/test/paper-cpu-omp-sweep.log`
+- `/data/test/paper-cpu-omp20-vs24-balanced8.log`
+
+The other existing CPU fork, disabling the fused FP32 gate/up pair so S=1
+experts use separate AVX-512 VNNI IDOT calls, also failed a balanced-eight
+same-process gate:
+
+| CPU expert path | median decode | median expert matmul | CPU rows |
+|---|---:|---:|---:|
+| fused pair | 7.25 tok/s | **4.035 s** | 11,210 |
+| separate IDOT | 7.36 tok/s | 4.242 s | 11,321 |
+
+The 1.5% decode difference is below the observed run noise, expert time is
+5.1% worse, and the changed accumulation path alters downstream routing. It is
+therefore neither a useful performance result nor a lossless substitution.
+The fused-pair default remains.
+
+Artifact:
+
+- `/data/test/paper-cpu-pair-vs-idot-balanced8.log`
+
+### M1/P3: CPU-GPU overlap crossed with NUMA placement
+
+This experiment used current `upstream/dev` plus a profiling-only fix that
+records successful async issue-to-take windows. It used the raw resident tier
+(9,335 VRAM + 10,121 RAM experts), the same fixed placement, 24 physical
+threads, 64 greedy tokens, identical routing/output, and 100% expert hits.
+
+| NUMA interleave | async groups | decode | expert matmul | CPU expert | GPU critical window |
+|---|---|---:|---:|---:|---:|
+| off | off | 5.67 tok/s | 6.276 s | 5.557 s / 34.86 GB/s | 0.450 s |
+| off | on | 6.07 tok/s | 5.538 s | 4.888 s / 39.63 GB/s | 5.362 s |
+| on | off | 7.89 tok/s | 3.432 s | 2.889 s / 67.06 GB/s | 0.444 s |
+| on | on | 8.05 tok/s | 3.305 s | 2.839 s / 68.23 GB/s | 3.290 s |
+
+Effects in this first controlled replicate:
+
+- async overlap with NUMA off: **+7.1%** throughput, **-11.8%** expert time;
+- NUMA with async off: **+39.2%** throughput, **-45.3%** expert time;
+- async overlap after NUMA: **+2.0%** throughput, **-3.7%** expert time;
+- NUMA with async on: **+32.6%** throughput, **-40.3%** expert time.
+
+The mechanisms interact rather than add. When CPU expert bandwidth is poor,
+overlap hides a useful fraction of serialized GPU work. Once interleaving
+raises CPU bandwidth to about 67-68 GB/s, the async GPU window is slightly
+longer than the CPU row window (3.290 versus 2.839 seconds), so the GPU tier
+becomes the straggler and overlap has only a 2% end-to-end remainder.
+
+Verdicts:
+
+- M1 (HybriMoE-style intra-layer CPU/GPU overlap): **confirmed, conditional**;
+ useful, but its gain depends on the CPU/GPU tier balance.
+- P3 (NUMA-aware expert placement): **confirmed** and substantially larger
+ than overlap on this dual-socket host.
+- The next placement experiment must minimize `max(T_cpu, T_gpu)`, not assign
+ experts by hit count alone. This result supplies the measured cost signal
+ needed by M2.
+
+Raw logs:
+
+- `/data/test/paper-m1-numa0-async0-r1.log`
+- `/data/test/paper-m1-numa0-async1-r1.log`
+- `/data/test/paper-m1-numa1-async0-r1.log`
+- `/data/test/paper-m1-numa1-async1-r1.log`
+
+### M2: impact-aware capacity versus frequency-only fill
+
+GLM-5.2 uses equal-sized experts and the same CPU/GPU kernels for every
+expert, so HybriMoE's per-expert impact ordering reduces to frequency ordering
+on this model. The locally testable distinction is therefore capacity policy:
+fill all available VRAM with that ordering, or stop at the prefix that
+minimizes the measured `max(T_cpu, T_gpu)`.
+
+`tools/placement_balance.py` aggregated the existing 30-prompt Expert Atlas
+trace (1,421,400 selections across 18,943 observed experts). Using the measured
+M1/P3 costs, its static model predicted:
+
+| policy | GPU experts | routed GPU share | predicted critical path |
+|---|---:|---:|---:|
+| frequency fill | 9,335 | 81.16% | 137.708 s |
+| impact balance | 6,848 | 69.90% | 118.615 s |
+
+That is a predicted **1.161x** speedup. The first real A/B used an Atlas Python
+prompt, 24 physical threads, NUMA interleave, async groups, greedy 64-token
+decode, and the same aggregate ranking:
+
+| policy | decode | CPU rows/time | GPU critical | disk wait | hit rate |
+|---|---:|---:|---:|---:|---:|
+| frequency fill (9,335) | 7.36 tok/s | 8,955 / 3.278 s | 3.806 s | 0.000 s | 100.0% |
+| impact balance (6,846 actual) | 5.54 tok/s | 14,588 / 4.229 s | 4.656 s | 2.568 s | 99.5% |
+
+The measured result is **-24.7%**, opposite to the analytic prediction. The
+model assumed constant per-selection cost and ignored capacity effects:
+moving 2,489 experts out of VRAM increased the RAM resident set, reduced the
+per-layer LRU cap from 10 to 1, and exposed 189 disk loads. It also
+underpredicted the prompt-specific CPU routing share. On this constrained
+host, compute-only impact balancing is not sufficient; residency, cache
+capacity, and miss cost must be part of the objective.
+
+An additional Chinese-category prompt showed the same direction: 7.72 versus
+5.26 tok/s (**-31.9%**), with 2.058 seconds of visible disk wait in the
+balanced configuration. Its generated token stream diverged between tiers,
+however, so it is supporting systems evidence rather than a controlled replay
+replicate. The final M2 verdict requires fixed-token `REPLAY` inputs.
+
+A fixed-token replay then removed that caveat. A 64-token continuation captured
+from GLM-5.2 was split into an 8-token prompt and 56 identical decode inputs.
+The order was fill, balance, balance, fill, balance, fill:
+
+| policy | runs | median | median change |
+|---|---|---:|---:|
+| frequency fill | 6.16, 7.53, 7.46 tok/s | **7.46 tok/s** | control |
+| impact balance | 3.87, 4.06, 4.01 tok/s | **4.01 tok/s** | **-46.2%** |
+
+Every replay traversed exactly 56 fixed tokens. The balance runs consistently
+made 490-491 disk loads, fetched about 9.28 GB, and waited 4.29-4.46 seconds;
+fill made no decode-time loads and retained a 100% hit rate. Thus M2 is
+**rejected on this host in its compute-only form**. A capacity-aware objective
+could still recover the paper's direction on a host with enough RAM, but that
+is a different policy and remains to be tested rather than assumed.
+
+The follow-up capacity-aware solver adds the missing hard residency bound:
+`min_gpu_slots = total_experts - max_ram_slots`. For this host that is
+`19,456 - 10,121 = 9,335` GPU experts. Applying the bound to the same Atlas
+trace and measured tier costs clamps the compute-only 6,848-expert proposal
+back to 9,335, exactly the frequency-fill placement. Predicted speedup is
+therefore 1.000x: the useful result is preventing the measured 46.2%
+regression and 490-491 disk loads, not inventing a speedup.
+`tools/placement_balance.py` now accepts `--total-experts` and
+`--max-ram-slots`, rejects infeasible GPU+RAM capacities, and has unit coverage
+for the capacity floor.
+
+A final capacity-preserving check raised the explicit RAM budget to 230 GB,
+then compared the normal 176.6 GB GPU expert tier with a 171 GB tier. Both
+placements kept all 19,456 experts resident and fetched 0.000 GB during
+decode, so this isolates tier balance rather than cache misses:
+
+| GPU budget | GPU/RAM experts | decode runs | median | CPU rows | median CPU / GPU critical |
+|---|---:|---|---:|---:|---:|
+| 176.6 GB | 9,335 / 10,121 | 6.55, 7.64, 7.26 | **7.26 tok/s** | 9,560 | 3.240 / 3.716 s |
+| 171 GB | 9,040 / 10,416 | 7.44, 6.68, 6.88 | **6.88 tok/s** | 10,085 | 3.625 / 4.120 s |
+
+The smaller tier moves 525 routed rows from GPU to CPU, but does not reduce
+the measured critical path. Its median decode is 5.2% lower (mean 2.1% lower),
+while run-to-run variance is large enough to reverse individual pairs. This
+rejects capacity-only tier shrinking: expert count is not a sufficient load
+signal, even when residency is held constant. A future placement policy must
+optimize from per-expert routed work and observed tier time; the default keeps
+the full 176.6 GB GPU tier.
+
+The next experiment measured the most optimistic possible upper bound:
+`ROUTE_TRACE` captured the exact fixed replay, and its 8,989 observed experts
+were ranked ahead of the cold tail for a fresh run of that same replay. This is
+deliberately an in-sample oracle, not a deployable policy:
+
+| placement | decode | CPU rows | GPU rows | CPU / GPU critical |
+|---|---:|---:|---:|---:|
+| Atlas baseline during trace capture | 8.74 tok/s | 9,560 | 24,040 | 2.670 / 3.067 s |
+| replay oracle, run 1 | 13.38 tok/s | 457 | 33,143 | 0.161 / 0.774 s |
+| replay oracle, run 2 | 12.64 tok/s | 457 | 33,143 | 0.180 / 0.786 s |
+
+The repeated oracle median is 13.01 tok/s, 48.9% above its trace-capture
+baseline. This falsifies the linear per-selection cost model: concentrating
+reused experts can improve CUDA grouping enough that 98.6% of routed rows on
+GPU is faster, not slower.
+
+It does **not** validate the policy. On a separate fixed 11-to-18-token replay,
+the same placement failed to transfer:
+
+| held-out placement | decode | CPU rows | GPU rows | CPU / GPU critical |
+|---|---:|---:|---:|---:|
+| Atlas baseline | **8.93 tok/s** | 1,110 | 3,090 | 0.328 / 0.380 s |
+| replay oracle | 5.54 tok/s | 1,404 | 2,796 | 0.699 / 0.760 s |
+
+That is a 38.0% held-out regression with zero disk I/O in both runs. The large
+in-sample gain is real but workload-specific; it is exactly the kind of oracle
+result that becomes misleading when a paper does not separate placement
+training from evaluation. The production default remains the broader Atlas
+ranking. Any learned placement follow-up must use category-held-out traces and
+report both transfer gain and worst-case regression.
+
+`tools/placement_crossval.py` then evaluated the original 10-category,
+30-prompt Atlas with each category held out in turn. A score based on
+category-normalized mean frequency minus `lambda * population_stddev` selected
+`lambda=0.25` by worst held-out coverage:
+
+| ranking | held-out mean GPU coverage | worst category |
+|---|---:|---:|
+| raw pooled Atlas | 73.29% | 68.04% |
+| category mean (`lambda=0`) | 73.23% | 68.51% |
+| robust (`lambda=0.25`) | **73.70%** | **69.32%** |
+| robust (`lambda=0.5`) | 73.02% | 67.14% |
+| robust (`lambda=1`) | 68.56% | 63.69% |
+
+The modest offline improvement did not survive real execution. Adjacent,
+reverse-order A/B runs held the GPU capacity, RAM budget, replay tokens,
+resident set, and zero-I/O condition constant:
+
+| replay | pooled Atlas | robust `lambda=0.25` | change |
+|---|---:|---:|---:|
+| 56-token main | **7.48 tok/s** | 6.63 tok/s | **-11.4%** |
+| independent 7-token decode | **8.84 tok/s** | 6.53 tok/s | **-26.1%** |
+
+On the short replay, robust ranking even increased GPU-routed rows from 3,090
+to 3,144 while GPU critical time worsened from 0.377 to 0.517 seconds. Routing
+coverage is therefore not an adequate optimization target: expert identity,
+per-device packing, grouping shape, and NUMA locality change the cost of the
+same number of rows. The robust-frequency candidate is rejected and the pooled
+Atlas placement remains the default.
+
+To expose that missing cost, CUDA group telemetry was split by device without
+changing execution. The pooled Atlas baseline showed 4,037-4,751 routed rows
+per GPU (17.7% max/min spread) and 2,472-2,830 group calls (14.5% spread).
+An opt-in LPT prototype kept the same 9,335-expert GPU prefix but assigned its
+frequency-ranked experts to the device with the lowest accumulated Atlas
+weight instead of the fewest placed bytes.
+
+The assignment was deterministic across three fresh processes. It reduced the
+observed row spread only to 4,332-4,982 (15.0%) because Atlas aggregate
+frequency does not exactly predict this replay; device 2 became the new
+straggler. End-to-end paired results were nevertheless positive:
+
+| run | byte-balanced control | frequency-load assignment | paired change |
+|---|---:|---:|---:|
+| 1 | 7.83 tok/s | 7.86 tok/s | +0.4% |
+| 2 | 7.64 tok/s | 8.27 tok/s | +8.2% |
+| 3 (reverse order) | 6.57 tok/s | 7.49 tok/s | +14.0% |
+| median | **7.64 tok/s** | **7.86 tok/s** | **+2.9%** |
+
+All runs retained 19,456 resident experts, 100% hits, and zero decode I/O.
+The direction repeated, but CPU-frequency variance is too large and only one
+56-token workload has been tested. `CUDA_EXPERT_LOAD_BALANCE=1` is therefore
+retained as an experimental opt-in, not enabled by default. Per-device group
+telemetry is retained unconditionally because it is measurement-only and
+identifies a real placement objective missed by aggregate counters.
+
+Raw logs:
+
+- `/data/test/paper-m2-fill-code.log`
+- `/data/test/paper-m2-balance-code.log`
+- `/data/test/paper-m2-fill-chinese.log`
+- `/data/test/paper-m2-balance-chinese.log`
+- `/data/test/paper-m2-replay-fill-r1.log`
+- `/data/test/paper-m2-replay-fill-r2.log`
+- `/data/test/paper-m2-replay-fill-r3.log`
+- `/data/test/paper-m2-replay-balance-r1.log`
+- `/data/test/paper-m2-replay-balance-r2.log`
+- `/data/test/paper-m2-replay-balance-r3.log`
+- `/data/test/paper-tier-171-r1.log`
+- `/data/test/paper-tier-171-r2.log`
+- `/data/test/paper-tier-171-r3.log`
+- `/data/test/paper-tier-1766-r1.log`
+- `/data/test/paper-tier-1766-r2.log`
+- `/data/test/paper-tier-1766-r3.log`
+- `/data/test/paper-m2-oracle-train.log`
+- `/data/test/paper-m2-oracle-hot-r1.log`
+- `/data/test/paper-m2-oracle-hot-r2.log`
+- `/data/test/paper-m2-heldout-atlas-r1.log`
+- `/data/test/paper-m2-heldout-oracle-r1.log`
+- `/data/test/paper-m2-robust-main-r1.log`
+- `/data/test/paper-m2-atlas-main-adj-r1.log`
+- `/data/test/paper-m2-atlas-heldout-adj-r1.log`
+- `/data/test/paper-m2-robust-heldout-r1.log`
+- `/data/test/paper-m2-device-groups-atlas-r1.log`
+- `/data/test/paper-m2-device-groups-atlas-r2.log`
+- `/data/test/paper-m2-device-groups-atlas-r3.log`
+- `/data/test/paper-m2-device-load-balance-r1.log`
+- `/data/test/paper-m2-device-load-balance-r2.log`
+- `/data/test/paper-m2-device-load-balance-r3.log`
+
+### M3: existing cross-layer prefetch
+
+The balance placement from M2 supplies a real I/O-bound control: each 56-token
+fixed replay fetches about 9.3 GB and feels more than four seconds of disk
+stall. The treatment enables Colibri's existing previous-token cross-layer
+hint (`PREFETCH=1`) with every other setting unchanged.
+
+| mode | tok/s runs | median tok/s | median disk service | median felt wait |
+|---|---|---:|---:|---:|
+| no prefetch | 3.87, 4.06, 4.01 | **4.01** | 4.902 s | 4.342 s |
+| `PREFETCH=1` | 3.91, 3.94, 3.84 | **3.91** | 4.858 s | 4.302 s |
+
+The hint reduced both service and visible wait by less than 1%, while median
+throughput fell 2.5%. The profiler moved time from `expert-matmul` into
+unclassified orchestration/overlap, but the end-to-end clock did not improve.
+Verdict: **rejected for this heuristic and workload**. This does not reject
+HybriMoE's learned or deeper lookahead policy; Colibri does not implement that
+policy, so substituting the current one-token route hint is only a test of the
+mechanism already available here.
+
+Treatment logs:
+
+- `/data/test/paper-m3-prefetch1-r1.log`
+- `/data/test/paper-m3-prefetch1-r2.log`
+- `/data/test/paper-m3-prefetch1-r3.log`
+
+#### Learned cross-layer coupling follow-up
+
+The stronger existing `COUPLE` mechanism was tested without leaking the fixed
+replay into training. A coupling table with 31,152 conditioning entries was
+built from 267 routed positions across ten Atlas prompt categories, then
+evaluated on the independent 56-token replay.
+
+The original K1/K4 implementation enqueued zero hints: its highest-scored
+candidates were already in the 17,789-expert resident tier, and it stopped
+instead of searching for a non-resident candidate. An experimental bounded
+search through the top 16 scores found only six non-resident candidates over
+the whole replay. Neither advisory nor real-load variants helped:
+
+| coupling mode | tok/s | hints | misses | fetched | felt wait |
+|---|---:|---:|---:|---:|---:|
+| no prefetch median | 4.01 | - | 500 | 9.458 GB | 4.342 s |
+| K1 advisory, non-resident search | 4.14 | 6 | 510 | 9.647 GB | 4.448 s |
+| K4 real load, non-resident search | 4.13 | 6 | 510 | 9.666 GB | 4.458 s |
+
+The apparent throughput increase is not attributed to prefetch: miss count and
+visible I/O both worsened, while the changing term was expert-matmul time. The
+non-resident search and real-load prototypes were therefore removed. This
+rejects the present small-table policy on this placement; useful learning must
+target cold-miss probability directly rather than overall next-layer routing,
+whose most predictable experts are already resident.
+
+Artifacts:
+
+- `/data/test/paper-m3-couple-train.trace`
+- `/data/test/paper-m3-couple-train.coli_pairs`
+- `/data/test/paper-m3-couple-k1-nonresident-r1.log`
+- `/data/test/paper-m3-couple-real-k4-r1.log`
+
+### C3: fused ANS decode and expert matvec
+
+Two implementations were tested rather than treating a compiling CUDA kernel
+as evidence:
+
+1. A block-partial prototype decoded each ANS block independently and reduced
+ cross-block row fragments afterward. It passed an illegal-access smoke test
+ but failed the numerical gate: fixed replay predictions diverged at step 13,
+ and throughput fell from 7.67 to 6.33 tok/s.
+2. A row-aligned tile prototype decodes eight complete matrix rows into shared
+ memory and performs the matvec before the tile is discarded. Its 256-thread
+ reduction matches the materialized kernel's arithmetic order closely enough
+ to retain all 56 fixed-replay argmax predictions.
+
+The aligned prototype was also connected to the asynchronous issue/take path.
+The controlled setup used 2,500 raw plus 8,128 ANS experts (10,628 total in
+VRAM), 8,828 RAM experts, 100% hit rate, the same 56 replay tokens, NUMA
+interleave, and 24 physical threads.
+
+| mode | tok/s runs | median tok/s | expert-time runs | median expert time |
+|---|---|---:|---|---:|
+| materialize control | 7.48, 6.71, 6.88 | **6.88** | 3.492, 4.241, 4.120 s | **4.120 s** |
+| row-aligned fused | 7.67, 7.09, 7.37 | **7.37** | 3.396, 3.921, 3.653 s | **3.653 s** |
+| change | | **+7.1%** | | **-11.3%** |
+
+Verdict: **confirmed by prototype**. Fusion removes global raw-weight
+materialization for eligible one-row ANS groups and improves the strongest
+async path without changing fixed-replay predictions. The effect is useful but
+not enormous because only compressed, single-row, homogeneous groups take the
+new path; raw and mixed groups retain the existing kernels.
+
+The experiment also exposed a placement hygiene requirement: layer 78 MTP
+experts are int8 and must not be fed into the fmt2-only ANS sidecar. The
+controlled ranking therefore excludes that layer rather than silently
+misaligning sidecar records.
+
+Prototype worktree:
+
+- `/home/Kei/colibri-wt-ans-tile` (`exp/ans-tile-pipeline`)
+
+#### Integrated revalidation
+
+The prototype result above did not survive a stricter integration audit.
+After replaying the ANS base commits and fused kernel onto the current `dev`,
+separate-process runs varied enough to reverse direction. A same-process
+A-B-B-A replay then loaded the model and all resident experts once and changed
+only `COLI_ANS_ALIGNED_MV`:
+
+| mode | tok/s | median | expert time | median |
+|---|---|---:|---|---:|
+| materialize | 6.58, 6.43 | **6.505** | 4.897, 4.946 s | **4.922 s** |
+| row-aligned fused | 5.57, 5.00 | **5.285** | 5.885, 6.988 s | **6.437 s** |
+
+All four phases produced identical argmax predictions. Materialize recovered
+to 6.43 tok/s after both fused phases, ruling out monotonic thermal throttling
+as the explanation. The integrated fused path reduced throughput by 18.8%
+and increased expert time by 30.8%. The earlier cross-process +7.1% result was
+a machine-state false positive. The fused kernel is therefore **rejected** and
+was not merged into `dev`.
+
+Raw logs:
+
+- `/data/test/paper-c3-async-control-r1.log`
+- `/data/test/paper-c3-async-control-r2.log`
+- `/data/test/paper-c3-async-control-r3.log`
+- `/data/test/paper-c3-async-fused-r1.log`
+- `/data/test/paper-c3-async-fused-r2.log`
+- `/data/test/paper-c3-async-fused-r3.log`
+- `/data/test/paper-c3-integrated-abba.log`
+
+### P2: parallel per-device expert execution
+
+Code inspection showed that this mechanism was already partially present, but
+under a misleading control name. Even with `COLI_GROUP_ASYNC=0`, OpenMP worker
+threads can drive independent device contexts concurrently. The async option
+primarily adds CPU/GPU overlap; it is not the sole multi-GPU parallelism switch.
+
+Nsight Systems traces over the complete fixed replay established the timeline:
+
+| mode | expert-active time with >=2 GPUs | weighted active GPUs | peak GPUs |
+|---|---:|---:|---:|
+| existing sync group path | 62.9% | 2.34 | 6 |
+| async issue/take path | 30.7% | 1.37 | 6 |
+| forced global serialization | **0.0%** | **1.00** | **1** |
+
+The lower overlap fraction in the async row is not a regression: its GPU
+kernels overlap the CPU tier and finish in a different cadence. The important
+fact is that both production paths exhibit real cross-device overlap, while
+the mutex control removes it completely.
+
+A default-off `COLI_CUDA_SERIAL_GROUPS=1` experiment control was temporarily
+added around the synchronous CUDA group call. Three fixed-token runs per mode
+gave:
+
+| mode | tok/s runs | median | expert-time median |
+|---|---|---:|---:|
+| forced single-device-at-a-time | 6.82, 5.72, 7.32 | **6.82** | 3.906 s |
+| existing parallel dispatch | 7.44, 8.02, 7.23 | **7.44** | 3.710 s |
+| change | | **+9.1%** | **-5.0%** |
+
+Verdict: the **parallel per-device compute portion is confirmed** and retained.
+The experiment-only global serialization switch was removed after the control
+runs.
+
+The broader residual-broadcast formulation is rejected for the current
+architecture. Colibri's dense, attention, residual, and CPU-expert paths are
+host-resident; each PCIe device receives only the routed activation rows and
+returns their expert outputs. The fixed replay routed about 24,030 GPU rows.
+At `D=7168` and FP32 input plus output, that is about 1.38 GB across the entire
+56-token replay. Even a conservative PCIe 4.0 x16 lower bound puts the pure
+wire time near 45 ms, whereas observed CPU-expert work was about 6 s and the
+parallel GPU critical path about 0.4 s. Moving residual ownership to one GPU
+would also force the CPU tier to add the opposite D2H/H2D boundary.
+
+This is therefore not an unimplemented free win: it is an architecture rewrite
+aimed at a non-dominant cost. Revisit only if dense/attention and most experts
+become GPU-resident, or profiling shows host transfer on the critical path.
+
+Trace artifacts:
+
+- `/data/test/paper-p2-async.nsys-rep`
+- `/data/test/paper-p2-serial.nsys-rep`
+- `/data/test/paper-p2-forced-serial.nsys-rep`
+
+Raw logs:
+
+- `/data/test/paper-p2-serial.log`
+- `/data/test/paper-p2-forced-serial.log`
+- `/data/test/paper-p2-parallel-r2.log`
+- `/data/test/paper-p2-parallel-r3.log`
+- `/data/test/paper-p2-forced-serial-r2.log`
+- `/data/test/paper-p2-forced-serial-r3.log`
+
+### K1: physical-page ragged KV prototype
+
+The existing ragged allocator rounded each sequence to 64 tokens, but every
+growth still allocated a larger contiguous buffer and copied the old KV on the
+device. The prototype replaces that buffer with an actual page table:
+
+- latent and RoPE KV use separate 64-token physical pages;
+- crossing a boundary allocates only the new page, without copying old pages;
+- attention and append kernels translate `(sequence, token)` through the page
+ table;
+- pages remain independently owned by each sequence.
+
+The CUDA unit test now grows three sequences from `[1, 63, 64]` to
+`[1, 65, 70]`, exercising both sides of the 64-token boundary. Five fresh
+process runs on an RTX 5090 all reported `ragged_relative_rms=0` against the
+contiguous attention reference. The measured second-call page growth was
+0.051-0.057 ms.
+
+For a skewed nine-slot trace with lengths
+`[1, 17, 63, 64, 65, 127, 128, 511, 1024]` and a 1024-token slot ceiling:
+
+| allocation | reserved token positions | unused positions |
+|---|---:|---:|
+| fixed contiguous slots | 9,216 | 7,216 |
+| 64-token physical pages | 2,176 | 176 |
+
+That is 76.4% less reserved capacity than fixed-size slots, with 8.1% internal
+fragmentation inside the allocated pages. This validates physical paging,
+bounded tail waste, and copy-free growth. It does **not** yet validate the full
+PagedAttention sharing claim: the runtime still copies a matched prefix into
+the destination slot (K2) rather than aliasing shared pages with reference
+counts, and no maximum-concurrency A/B has been run.
+
+Runtime artifact:
+
+- `/data/test/test_ragged_attention-paged`
+
+The physical page size was then decoupled from the test and swept at compile
+time. Every cell retained exact output (`ragged_relative_rms=0`). Median results
+over five fresh processes were:
+
+| physical page | cross-page growth | grow to 1024 | steady 1024 attention | unused positions in the nine-slot trace |
+|---:|---:|---:|---:|---:|
+| 16 | 0.051 ms | 1.922 ms | 0.034 ms | 48 |
+| 32 | 0.051 ms | 1.505 ms | 0.034 ms | 80 |
+| 64 | 0.053 ms | 1.311 ms | 0.034 ms | 176 |
+| 128 | 0.049 ms | 1.180 ms | 0.033 ms | 432 |
+
+Steady attention is insensitive to page-table length at this scale. Sixteen
+tokens minimizes tail waste but makes 1024-token growth 47% slower than 64;
+128 saves only 0.131 ms of growth while adding 256 unused token positions in
+the skewed trace. The 64-token default is retained as the Pareto point, while
+`COLI_KV_PAGE_TOKENS` can now be overridden at compile time independently of
+prefix matching. Prefix adoption remains exact token-granular, so no page-size
+change can silently reduce its hit length.
+
+Sweep artifacts:
+
+- `/data/test/kv-page-sweep/page-16-v4.log`
+- `/data/test/kv-page-sweep/page-32-v4.log`
+- `/data/test/kv-page-sweep/page-64-v4.log`
+- `/data/test/kv-page-sweep/page-128-v4.log`
+
+### K2: current cross-slot prefix reuse
+
+The previously separate `feat/paged-ragged-kv` and
+`feat/kv-cross-slot-adopt` work is already in `dev`; the stale matrix entry was
+wrong. `c/tools/benchmark_kv_prefix.py` drives the mux protocol with two slots,
+`KVSAVE=0`, one generated token, a common long prefix, and a distinct short
+tail. The control disables cross-slot adoption; the treatment enables it.
+
+| mode | second-request TTFT runs | median |
+|---|---|---:|
+| no cross-slot reuse | 17.803, 17.154, 17.689 s | 17.689 s |
+| reuse enabled | 0.569, 0.544, 0.569 s | 0.569 s |
+
+Every treatment round adopted a prefix ending at token 257 out of a 264-token
+prompt and prefilled only 7 tokens. Median TTFT improved by 96.8%, or 31.1x.
+The first request remained 17-20 seconds in both modes, which rules out a
+general warm-run speedup as the explanation.
+
+Artifacts:
+
+- `/data/test/paper-k2-share0-r3.jsonl`
+- `/data/test/paper-k2-share0-r3.stderr`
+- `/data/test/paper-k2-share1-r3.jsonl`
+- `/data/test/paper-k2-share1-r3.stderr`
+
+### K3: cross-slot physical page alias
+
+A Linux `memfd`/`mmap` prototype kept the existing contiguous KV virtual
+addresses while aliasing complete 64-token blocks across slots. Partial blocks
+remained independent copies, and logical owners/reference counts protected
+slot lifetime. Three validation rounds compared every adopted L/R/index KV byte
+with its source and all three were exact.
+
+The real 6x5090 A/B rejected the design:
+
+| mode | second-request TTFT runs | median |
+|---|---|---:|
+| current row `memcpy` | 3.156, 2.428, 3.458 s | **3.156 s** |
+| page alias, per-block mappings | 4.069, 3.640, 3.371 s | 3.640 s |
+| page alias, coalesced mappings | 4.627, 4.051, 3.584 s | 4.051 s |
+
+The coalesced alias remained 28.3% slower than `memcpy`. Avoided copy traffic
+did not repay mapping calls and first-touch/page-table work across 79 cache
+levels and three tensor families. The runtime prototype was removed; the
+existing exact `memcpy` adoption remains the accepted implementation.
+
+Artifacts:
+
+- `/data/test/paper-k2-memcpy-current-r3.jsonl`
+- `/data/test/paper-k2-memcpy-current-r3.stderr`
+- `/data/test/paper-k2-alias-r3.jsonl`
+- `/data/test/paper-k2-alias-r3.stderr`
+- `/data/test/paper-k2-alias-coalesced-r3.jsonl`
+- `/data/test/paper-k2-alias-coalesced-r3.stderr`
+
+### D1-D4: serving interference and disaggregation boundaries
+
+#### D1: mixed prefill/decode interference
+
+`c/tools/benchmark_serving_interference.py` first records an isolated 32-token
+decode, then starts another 32-token decode and submits a 501-token prefill
+immediately after its first streamed token. Both use the same two-slot mux and
+the same full-resident placement.
+
+| case | median TBT | maximum TBT | request wall time |
+|---|---:|---:|---:|
+| isolated decode | 0.117 s | 0.188 s | 7.384 s |
+| decode plus inserted prefill | 0.126 s | **44.205 s** | 49.113 s |
+
+The interfering request's TTFT was 44.199 s. Colibri deliberately serializes
+prefill, so the active decode makes no progress for essentially the complete
+prefill. This directly confirms the interference that phase splitting targets.
+It does not confirm Splitwise goodput: this runtime cannot transfer a live KV
+cache to a separate decode instance, so there is no valid treatment system to
+compare.
+
+A scheduler prototype then moved prefill out of synchronous submission and
+ran one token chunk after each priority decode batch. All variants were
+rejected on the same 6x5090 workload:
+
+| prefill mode | median TBT | maximum TBT | prefill TTFT | decode wall |
+|---|---:|---:|---:|---:|
+| serial baseline | 0.126 s | 44.205 s | 44.199 s | 49.113 s |
+| scheduled, 32 tokens | 4.992 s | 20.381 s | 204.210 s | 214.247 s |
+| scheduled, 128 tokens | 0.176 s | 30.769 s | 93.314 s | 103.459 s |
+| scheduled, 256 tokens | 0.174 s | 57.690 s | 105.837 s | 115.194 s |
+
+The 32-token setting cut maximum TBT by 53.9% but destroyed both median TBT
+and prefill throughput. At 128 tokens maximum TBT improved 30.4%, while
+prefill TTFT and decode wall both more than doubled. At 256 tokens the chunk
+itself exceeded the original stall. Re-entering all 78 MoE layers for small
+token batches loses too much batching efficiency; token-level chunking has no
+useful operating point here. The scheduler prototype was removed. A viable
+implementation needs finer pipeline/layer preemption or separate prefill and
+decode workers.
+
+Artifacts:
+
+- `/data/test/paper-d1-interference-r2.json`
+- `/data/test/paper-d1-interference-r2.stderr`
+- `/data/test/paper-d1-scheduled-c32.json`
+- `/data/test/paper-d1-scheduled-c32.stderr`
+- `/data/test/paper-d1-scheduled-c128.json`
+- `/data/test/paper-d1-scheduled-c128.stderr`
+- `/data/test/paper-d1-scheduled-c256.json`
+- `/data/test/paper-d1-scheduled-c256.stderr`
+
+#### D2/D4: calibrated transfer sweep
+
+GLM-5.2 stores 512 latent, 64 RoPE, and 128 index floats for each of 79 cache
+levels. The measured 501-token request therefore carries 111,454,464 bytes of
+KV. `c/tools/disaggregation_break_even.py` feeds that size and the measured
+44.199-second prefill into a deterministic producer/link pipeline.
+
+| link | whole-cache transfer | visible with ideal per-layer streaming |
+|---:|---:|---:|
+| 1 Gb/s | 891.64 ms | 11.29 ms |
+| 10 Gb/s | 89.16 ms | 1.13 ms |
+| 25 Gb/s | 35.67 ms | 0.45 ms |
+| 100 Gb/s | 8.92 ms | 0.11 ms |
+| 200 Gb/s | 4.46 ms | 0.06 ms |
+
+Uniform layer production makes all but the final layer transfer overlap the
+very slow prefill, hiding 98.7% of pure link time in this trace. Consequently,
+the idealized D4 break-even is small: phase specialization needs to recover
+more than the visible value in the last column. This is an optimistic lower
+bound, not an end-to-end result; RPC, queueing, serialization, remote
+allocation, backpressure, and nonuniform layer times are excluded.
+
+Artifact:
+
+- `/data/test/paper-d2-d4-break-even.json`
+
+#### D3: prefix affinity
+
+K2 supplies the local mechanism value for a scheduler: routing a request to a
+slot holding its 257-token prefix saves 17.120 seconds of TTFT. A prefix-affinity
+scheduler therefore has a large signal on this workload. We did not launch
+multiple Colibri instances or test replication/eviction cost, so the
+multi-instance scheduling policy itself remains unvalidated.
+
+### S1/S2: MTP depth sweep after grouped/async execution
+
+The control is the NUMA-on, async-on cell above. All draft runs used the same
+model, int8 MTP head, placement, prompt, 64-token target, and greedy sampling.
+
+| draft depth | decode | change vs D0 | tok/forward | acceptance | expert matmul | expert rows |
+|---:|---:|---:|---:|---:|---:|---:|
+| 0 | 8.05 tok/s | control | 1.02 | - | 3.305 s | 10,240 |
+| 1 | 8.79 tok/s | **+9.2%** | 1.94 | 91% | 3.938 s | 11,868 |
+| 2 | 7.53 tok/s | **-6.5%** | 2.46 | 73% | 4.932 s | 13,322 |
+| 3 | 8.51 tok/s | **+5.7%** | 3.37 | 77% | 4.336 s | 13,506 |
+
+The old blanket verdict ("MTP always loses on this MoE") is no longer true.
+Grouped GPU execution, full residency, async CPU/GPU overlap, and improved
+kernel consistency have crossed the break-even point for shallow speculation.
+The mechanism is still conditional:
+
+- D1 almost halves target forwards (63 -> 33) and cuts attention 2.856 ->
+ 1.869 seconds, while adding only 1,628 expert rows.
+- D2 adds enough distinct-expert work to erase its forward-count advantage.
+- D3 reduces forwards to 19 and wins despite 3,266 extra expert rows, but is
+ slower than D1.
+- Acceptance alone is insufficient: D2 accepts 73% yet loses, while D3 at 77%
+ wins. The cost of the routed-expert union is the missing independent variable.
+
+First-prompt verdict: `DRAFT=1` is the best tested point. It must still pass
+rotated repeats and diverse prompts before becoming a default.
+
+Raw logs:
+
+- `/data/test/paper-s1-draft1-r1.log`
+- `/data/test/paper-s1-draft2-r1.log`
+- `/data/test/paper-s1-draft3-r1.log`
+
+The diverse-prompt gate changed the policy verdict. On a non-degenerate
+water-cycle explanation:
+
+| mode | decode | tok/forward | acceptance | expert matmul | expert rows |
+|---|---:|---:|---:|---:|---:|
+| D0 | 8.51 tok/s | 1.02 | - | 2.946 s | 8,300 |
+| D1 | 7.00 tok/s | 1.64 | 62% | 5.127 s | 11,146 |
+
+Here D1 is **17.7% slower**. The explanatory prompt activates a wider routed
+expert union: loads/token rise from 590.6 to 739.1, and the saved attention
+work cannot pay for 2,846 extra CPU expert rows. Therefore D1 is not a safe
+global default. A runtime policy needs a cheap predictor (recent acceptance
+plus observed union-growth/cost), or speculation must remain opt-in.
+
+Raw logs:
+
+- `/data/test/paper-s1-water-draft0-r1.log`
+- `/data/test/paper-s1-water-draft1-r1.log`
+
+#### Runtime guard
+
+The existing soft guard waited for 24 proposals but paused MTP only below 10%
+acceptance. That threshold did not protect the measured 62%-acceptance
+regression. On the same async execution path, changing the threshold to 70%
+gave:
+
+| water-cycle mode | decode | change vs old D1 | MTP proposals accepted | expert matmul | CPU expert rows |
+|---|---:|---:|---:|---:|---:|
+| old D1 guard (10%) | 7.00 tok/s | control | 24/39 (62%) | 5.127 s | 11,146 |
+| 24-window, 70% guard | 7.85 tok/s | **+12.1%** | 15/24 (62%) before pause | 3.838 s | 9,851 |
+| D0 | 8.51 tok/s | +21.6% vs old D1 | - | 2.946 s | 8,300 |
+
+The guard recovers more than half of the regression, reducing the D0 gap from
+17.7% to 7.8%; it does not make the negative case faster than disabling MTP.
+A 12-proposal window was rejected because early acceptance was too noisy and
+throughput fell to 6.97 tok/s. On the predictable-text counterexample, the
+24-window observed 32/32 accepted proposals and did not pause, so the high-value
+path is unchanged. Its absolute throughput was not compared across runs because
+machine-state drift was material.
+
+The production default is therefore 70% over 24 proposals, with
+`COLI_MTP_GUARD_PCT` and `COLI_MTP_GUARD_WINDOW` retained as explicit experiment
+overrides. This is a loss limiter, not an oracle: a future policy still needs
+routed-union cost rather than acceptance alone.
+
+Guard artifacts:
+
+- `/data/test/paper-s1-water-guard70w24-async-r1.log`
+- `/data/test/paper-s1-count-guard70w24-async-r1.log`
+
+## References
+
+- Kimi K3: Open Frontier Intelligence, technical report, 2026.
+- Kimi Linear: An Expressive, Efficient Attention Architecture, 2025.
+- Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving, 2024.
+- HybriMoE: Hybrid CPU-GPU Scheduling and Cache Management for Efficient MoE
+ Inference, 2025.
+- SparseSpec: Accelerating Large-Scale Reasoning Model Inference with Sparse
+ Self-Speculative Decoding, 2025.
+- Efficient Memory Management for Large Language Model Serving with
+ PagedAttention, 2023.
+- Splitwise: Efficient Generative LLM Inference Using Phase Splitting, 2023.
+- HCAttention: Extreme KV Cache Compression via Heterogeneous Attention
+ Computing for LLMs, 2025.