Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
tools/depth: per-dispatch decode census and an in-process interleaved A/B harness
YanissAmzb54d6b07740d
diff --git a/tools/depth/census.py b/tools/depth/census.pynew file mode 100644index 0000000..f314b47--- /dev/null+++ b/tools/depth/census.py@@ -0,0 +1,188 @@+#!/usr/bin/env python+"""Per-dispatch decode census from a rocprofv3 --kernel-trace CSV.++ census.py TRACE.csv [--steps N] [--top 40] [--json out.json] [--dump out.tsv]++Reports, for one decode step (totals divided by --steps):+ * every dispatch: class, kernel, duration, and the gap before it (start_i - the+ latest end seen so far, so a dispatch queued behind another stream still shows+ the true hole in the GPU timeline);+ * per class: dispatches, busy ms, mean us/call, and the gap mass before the class;+ * the biggest gaps, attributed to the kernel that precedes them;+ * tiny-op chains: runs of consecutive dispatches shorter than --tiny us, i.e. the+ candidates a capture would have to cover for a graph to pay.++Timestamps are rocprofv3 ns on the mono or the boot clock; both are handled (the+clock that yields a positive timeline inside the trace is used).+"""+import argparse+import collections+import csv+import json+import re+import sys++# class of a kernel, by name. First match wins; order matters (norm before add, hc before norm).+CLASSES = [+ ("hc", r"\bhc_|hc_mix|hc_apply|hc_pf|gr_dots|gr_finalize|gr_g1|gr_g2|_gr_"),+ ("router", r"router|topk|top_k|softmax|sinkhorn|moe_gate|gate_softmax|\bgating\b"),+ ("norm", r"rms_norm|layernorm|\bnorm\b|gated_rms|normalize|ple_norm"),+ ("rotary", r"rope|rotary|freqs"),+ ("dequant", r"dequant|exl3_dec|\bdq\b|_dq_|reconstruct|unpack|scales"),+ ("copy", r"copy|memcpy|cat|_cast|cast_|contiguous|transpose|permute|fill|zero|slice|view_"),+ ("residual", r"\badd\b|fused_add|residual|elementwise|_elt_|eltwise|mul_|fma"),+ ("attn", r"attn|attention|qdec|qsa|dsa|mla|paged|kv_update|plane_update|stage_kernel|deinterleave|pool_update"),+ ("moe", r"moe_|mpw|mf9|grouped|expert|union"),+ ("gemv", r"gemv|hgemm|Cijk|blas|skinny|gemm"),+ ("gdn", r"gdn|kda|recurrent|conv1d|delta_rule|chunk|wy_|inter_solve"),+ ("lm_head", r"lm_head|_head|logits|sampl|argmax"),+ ("other", r"."),+]+CLASSES = [(c, re.compile(p, re.I)) for c, p in CLASSES]+++def klass(name):+ for c, rx in CLASSES:+ if rx.search(name):+ return c+ return "other"+++def short(n):+ n = n.replace("(anonymous namespace)::", "")+ n = re.sub(r"^void\s+", "", n)+ return re.sub(r"\(.*$", "", n)[:96]+++def load(path):+ rows = []+ with open(path, newline="") as f:+ for r in csv.DictReader(f):+ try:+ s = int(r["Start_Timestamp"]); e = int(r["End_Timestamp"])+ except (KeyError, ValueError):+ continue+ rows.append((s, e, r.get("Kernel_Name", "?"), r.get("Stream_Id", "")))+ rows.sort()+ return rows+++def census(rows, steps, tiny_us):+ if not rows:+ raise SystemExit("no rows")+ t0 = rows[0][0]+ # timeline with a running max end: the gap before a dispatch is the hole it waits in+ hi = rows[0][1]+ disp = []+ for s, e, n, st in rows:+ gap = max(0, s - hi)+ hi = max(hi, e)+ disp.append(dict(t_ns=s - t0, name=short(n), full=n, cls=klass(n), dur_us=(e - s) / 1e3,+ gap_us=gap / 1e3, stream=st))+ wall_ms = (hi - t0) / 1e6+ busy_ns = sum(e - s for s, e, _, _ in rows)+ per_cls = collections.defaultdict(lambda: dict(n=0, us=0.0, gap_us=0.0, n_gap=0))+ for d in disp:+ c = per_cls[d["cls"]]+ c["n"] += 1; c["us"] += d["dur_us"]; c["gap_us"] += d["gap_us"]+ per_k = collections.defaultdict(lambda: dict(n=0, us=0.0, gap_us=0.0, cls=None))+ for d in disp:+ k = per_k[d["name"]]+ k["n"] += 1; k["us"] += d["dur_us"]; k["gap_us"] += d["gap_us"]; k["cls"] = d["cls"]+ # chains of tiny dispatches+ chains, cur = [], []+ for d in disp:+ if d["dur_us"] <= tiny_us:+ cur.append(d)+ else:+ if len(cur) >= 3:+ chains.append(cur)+ cur = []+ if len(cur) >= 3:+ chains.append(cur)+ return dict(disp=disp, wall_ms=wall_ms, busy_ms=busy_ns / 1e6, steps=steps, per_cls=per_cls,+ per_k=per_k, chains=chains)+++def report(cc, top, tiny_us):+ s = cc["steps"]+ print(f"dispatches {len(cc['disp'])} ({len(cc['disp'])/s:.1f}/step) wall {cc['wall_ms']/s:.3f} ms/step "+ f"busy {cc['busy_ms']/s:.3f} gaps {cc['wall_ms']/s - cc['busy_ms']/s:.3f}")+ print(f"\n{'class':10s} {'n/step':>8s} {'ms/step':>8s} {'us/call':>8s} {'gap ms':>7s} {'gap/call us':>11s} {'%busy':>6s}")+ for c, v in sorted(cc["per_cls"].items(), key=lambda kv: -kv[1]["us"]):+ print(f"{c:10s} {v['n']/s:8.1f} {v['us']/1e3/s:8.3f} {v['us']/v['n']:8.2f} "+ f"{v['gap_us']/1e3/s:7.3f} {v['gap_us']/v['n']:11.2f} {100*v['us']/cc['busy_ms']/1e3:6.2f}")+ print(f"\ntop kernels ({top})")+ print(f"{'kernel':46s} {'cls':9s} {'n/step':>7s} {'us/call':>8s} {'ms/step':>8s} {'gap/call':>9s}")+ for k, v in sorted(cc["per_k"].items(), key=lambda kv: -kv[1]["us"])[:top]:+ print(f"{k[:46]:46s} {v['cls']:9s} {v['n']/s:7.1f} {v['us']/v['n']:8.2f} {v['us']/1e3/s:8.3f} {v['gap_us']/v['n']:9.2f}")+ gaps = sorted(cc["disp"], key=lambda d: -d["gap_us"])[:top]+ print(f"\nbiggest gaps, attributed to the kernel before them")+ for i, d in enumerate(cc["disp"]):+ pass+ idx = {id(d): i for i, d in enumerate(cc["disp"])}+ for d in gaps:+ i = idx[id(d)]+ prev = cc["disp"][i - 1]["name"] if i else "(start)"+ nxt = cc["disp"][i + 1]["name"] if i + 1 < len(cc["disp"]) else "(end)"+ print(f" {d['gap_us']:8.2f} us after {prev[:40]:40s} before {d['name'][:40]:40s}")+ tot = sum(d["gap_us"] for d in gaps)+ print(f" top-{top} gaps carry {tot/1e3/cc['steps']:.3f} of {cc['wall_ms']/cc['steps'] - cc['busy_ms']/cc['steps']:.3f} ms/step")+ print(f"\ntiny-op chains (>=3 consecutive dispatches <= {tiny_us} us)")+ allc = sorted(cc["chains"], key=lambda c: -sum(d["dur_us"] + d["gap_us"] for d in c))[:top]+ for c in allc:+ span = sum(d["dur_us"] + d["gap_us"] for d in c)+ names = " + ".join(collections.Counter(d["name"] for d in c).most_common(4)[0][0] for _ in [0])+ print(f" len {len(c):2d} span {span:8.2f} us busy {sum(d['dur_us'] for d in c):7.2f} "+ f"{', '.join(f'{k}x{v}' for k, v in collections.Counter(d['name'] for d in c).most_common(5))}")+++def window_rows(path, rows):+ """Rows inside the biggest timed window of a depth_profile.py --kernels JSON (mono or boot clock)."""+ P = json.load(open(path))+ best = []+ for d, pt in P.get("points", {}).items():+ for kind, v in pt.items():+ w = v.get("window") if isinstance(v, dict) else None+ if not w:+ continue+ for clk in ("mono", "boot"):+ sel = [r for r in rows if w["start"][clk] <= r[0] <= w["end"][clk]]+ if len(sel) > len(best):+ best, best_k = sel, (d, kind, w.get("steps", 1))+ if not best:+ raise SystemExit(f"no window in {path} contains any kernel")+ print(f"window {best_k[0]}/{best_k[1]}: {len(best)} dispatches / {best_k[2]} steps")+ return best, best_k[2]+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("trace")+ ap.add_argument("--steps", type=int, default=1)+ ap.add_argument("--top", type=int, default=30)+ ap.add_argument("--tiny", type=float, default=20.0)+ ap.add_argument("--prof", help="depth_profile.py JSON: restrict to its timed decode window")+ ap.add_argument("--json")+ ap.add_argument("--dump")+ a = ap.parse_args()+ rows = load(a.trace)+ if a.prof:+ rows, steps = window_rows(a.prof, rows)+ a.steps = steps+ cc = census(rows, a.steps, a.tiny)+ report(cc, a.top, a.tiny)+ if a.json:+ json.dump(dict(wall_ms=cc["wall_ms"], busy_ms=cc["busy_ms"], steps=cc["steps"],+ per_cls={k: v for k, v in cc["per_cls"].items()},+ per_k={k: v for k, v in cc["per_k"].items()},+ disp=cc["disp"]), open(a.json, "w"), indent=1)+ if a.dump:+ with open(a.dump, "w") as f:+ f.write("i\tcls\tus\tgap_us\tname\n")+ for i, d in enumerate(cc["disp"]):+ f.write(f"{i}\t{d['cls']}\t{d['dur_us']:.3f}\t{d['gap_us']:.3f}\t{d['name']}\n")+++if __name__ == "__main__":+ main()diff --git a/tools/depth/glueab.py b/tools/depth/glueab.pynew file mode 100644index 0000000..69b58e5--- /dev/null+++ b/tools/depth/glueab.py@@ -0,0 +1,223 @@+#!/usr/bin/env python+"""Interleaved served-style A/B for the HIP glue levers, one model load.++ glueab.py MODEL --serve glm|qwen [--depths 4096,32768] [--steps 12] [--reps 3]+ [--knob KYOJIN_HIP_GLUE] [--gen 64] [-o out.json]++Loads the model once with the server's EXL3 defaults, fills one cache with synthetic pages+(the same construction as tools/depth/depth_profile.py), then runs the arms in ABAB order,+visit by visit, at every depth:+ * decode: --steps single-token steps per arm and visit at position D, ms/step (mean +- SE+ over visits of the per-visit median), after one dropped warm-up step per arm/visit;+ * exactness: md5 over the float logits of every timed step, and md5 over the greedy ids of+ a --gen-token generation from one fixed prompt at depth 0.+Arms are flipped with exllamav3.util.knobs.set_knobs inside the process, so build/load state+is identical between them and the only variable is the knob.+"""+import argparse, hashlib, json, os, statistics, sys, time++ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+PAGE = 256+++def served_env(which):+ import ast+ path, name = {"qwen": ("tools/qwen/serve.py", "SERVE_ENV"), "glm": ("tools/glm/serve.py", "SPEED_ENV")}[which]+ for node in ast.parse(open(os.path.join(ROOT, path)).read()).body:+ if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == name for t in node.targets):+ return dict(ast.literal_eval(node.value))+ raise SystemExit(f"{name} not found in {path}")+++def fill_cache(cache, seed):+ """Fill every cache tensor with synthetic data (random fp16 K/V and packed pages), inside+ inference_mode: the cache tensors are inference tensors and may only be mutated there."""+ import torch+ with torch.inference_mode():+ g = torch.Generator(device="cuda:0"); g.manual_seed(seed)+ for layer in cache.layers.values():+ for name, v in vars(layer).items():+ if name.startswith("_") or not (isinstance(v, torch.Tensor) and v.is_cuda):+ continue+ f = v.view(-1)+ scale_like = name in ("sk", "sv", "pool_s")+ for i in range(0, f.numel(), 1 << 26):+ sl = f[i: i + (1 << 26)]+ if sl.dtype == torch.half:+ x = torch.randn(sl.shape, generator=g, device=sl.device, dtype=torch.float32)+ sl.copy_((x.abs().mul_(0.05) if scale_like else x.mul_(0.5)).to(torch.half))+ elif sl.dtype in (torch.int32, torch.int16, torch.uint8, torch.int8):+ sl.copy_(torch.randint(-2**31, 2**31 - 1, sl.shape, generator=g, device=sl.device, dtype=torch.int64).to(sl.dtype))+++def avail_gb():+ for line in open("/proc/meminfo"):+ if line.startswith("MemAvailable"):+ return int(line.split()[1]) / 1048576+ return -1.0+++def _main():+ ap = argparse.ArgumentParser()+ ap.add_argument("model")+ ap.add_argument("--serve", choices=["glm", "qwen"], required=True)+ ap.add_argument("--depths", default="4096,32768")+ ap.add_argument("--steps", type=int, default=12)+ ap.add_argument("--reps", type=int, default=3, help="visits per arm")+ ap.add_argument("--knob", default="KYOJIN_HIP_GLUE", help="run-time knob flipped per arm; none = do not touch a knob")+ ap.add_argument("--arm-attr", default="", help="module:ATTR to flip instead of --knob (arm on = True, off = False)")+ ap.add_argument("--purge", default="", help="module:function called between arms (e.g. a graph cache purge)")+ ap.add_argument("--gen", type=int, default=64)+ ap.add_argument("--cache-bits", type=int, default=16)+ ap.add_argument("--seed", type=int, default=1234)+ ap.add_argument("--min-avail-gb", type=float, default=5.0)+ ap.add_argument("-o", "--out", default="glueab.json")+ a = ap.parse_args()++ for k, v in served_env(a.serve).items():+ os.environ.setdefault(k, v)+ os.environ.setdefault("TQDM_DISABLE", "1")+ sys.path.insert(0, ROOT)+ import torch+ from exllamav3 import Config, Model, Cache+ from exllamav3.util.knobs import set_knobs, knob+ from exllamav3.cache import CacheLayer_quant+ torch.set_grad_enabled(False)++ depths = [int(x) for x in a.depths.split(",")]+ top = max(depths) + 2 * a.steps + 256+ cap = ((top + PAGE - 1) // PAGE + 1) * PAGE+ R = {"model": a.model, "args": vars(a), "points": {}, "md5": {}, "gen": {}}++ def save():+ json.dump(R, open(a.out + ".tmp", "w"), indent=1)+ os.replace(a.out + ".tmp", a.out)++ t0 = time.time()+ config = Config.from_directory(a.model)+ model = Model.from_config(config)+ qkw = dict(layer_type=CacheLayer_quant, k_bits=a.cache_bits, v_bits=a.cache_bits) if a.cache_bits < 16 else {}+ cache = Cache(model, max_num_tokens=cap, max_history=4, max_batch_size=1, **qkw)+ model.load(device="cuda:0", progressbar=False)+ av = avail_gb()+ R["load_s"] = round(time.time() - t0, 1); R["avail_after_load_gb"] = round(av, 1)+ print(f"loaded {R['load_s']}s avail {av:.1f} GiB knob {a.knob}={knob(a.knob)}", flush=True)+ if av < a.min_avail_gb:+ R["abort"] = f"MemAvailable {av:.1f} < {a.min_avail_gb}"; save(); sys.exit(3)++ fill_cache(cache, a.seed)++ bt_full = torch.arange(cap // PAGE, dtype=torch.int32).unsqueeze(0)+ st = {"s": cache.get_new_state()}+ V = config.vocab_size if hasattr(config, "vocab_size") else 100000+ gg = torch.Generator().manual_seed(a.seed)+ one = torch.randint(1000, min(V, 100000), (1, 1), generator=gg)++ def fresh(pos):+ st["s"].free(); st["s"] = cache.get_test_state(pos)++ def fwd(ids, pos):+ pages = (pos + ids.shape[-1] + PAGE - 1) // PAGE+ params = {"attn_mode": "flash_attn", "block_table": bt_full[:, :pages], "cache": cache,+ "cache_seqlens": torch.tensor([pos], dtype=torch.int32), "recurrent_states": [st["s"]]}+ return model.forward(ids, params)++ arms = ["off", "on"]++ ARM = {}+ if a.arm_attr:+ import importlib+ mod_name, _, attr = a.arm_attr.partition(":")+ ARM["mod"] = importlib.import_module(mod_name)+ ARM["attr"] = attr+ PURGE = None+ if a.purge:+ import importlib+ m, _, f = a.purge.partition(":")+ PURGE = getattr(importlib.import_module(m), f)++ def set_arm(arm):+ if a.knob and a.knob != "none" and not a.arm_attr:+ set_knobs({a.knob: "1" if arm == "on" else "0"})+ if a.arm_attr:+ setattr(ARM["mod"], ARM["attr"], arm == "on")+ if PURGE is not None:+ try:+ PURGE()+ except TypeError:+ PURGE(None)++ def run_arm(arm, d, step_seed):+ set_arm(arm)+ fresh(d)+ ids = torch.randint(1000, min(V, 100000), (1, 1), generator=torch.Generator().manual_seed(step_seed))+ fwd(ids, d) # dropped warm-up step+ torch.cuda.synchronize()+ ts, h = [], hashlib.md5()+ for k in range(a.steps):+ torch.cuda.synchronize(); t = time.perf_counter()+ lg = fwd(ids, d + 1 + k)+ tok = int(lg[0, -1].argmax().item())+ ts.append((time.perf_counter() - t) * 1e3)+ h.update(lg.float().cpu().numpy().tobytes())+ return ts, h.hexdigest()++ for d in depths:+ pt = R["points"][str(d)] = {arm: [] for arm in arms}+ R["md5"][str(d)] = {arm: None for arm in arms}+ for v in range(a.reps):+ for arm in (arms if v % 2 == 0 else arms[::-1]):+ ts, h = run_arm(arm, d, a.seed + d)+ pt[arm].append(round(statistics.median(ts), 3))+ if R["md5"][str(d)][arm] is None:+ R["md5"][str(d)][arm] = h+ elif R["md5"][str(d)][arm] != h:+ R["md5"][str(d)][arm] += f"!{h}"+ print(f" d={d} visit={v} arm={arm} median {statistics.median(ts):.3f} ms [{min(ts):.2f}..{max(ts):.2f}]", flush=True)+ save()++ # greedy generation exactness at depth 0, one prompt, both arms+ if a.gen:+ from exllamav3 import Tokenizer, Generator, Job+ from exllamav3.generator.sampler import GreedySampler+ tok = Tokenizer.from_config(config)+ prompt = "Write one paragraph about the speed of light in a vacuum, then a short list of its consequences."+ ids = tok.encode(prompt, add_bos=True, encode_special_tokens=True)+ out = {}+ for arm in arms:+ set_arm(arm)+ # a generator needs its own page table: the timed phases above used a manually mapped one+ gcache = Cache(model, max_num_tokens=cap, max_history=4, max_batch_size=1, **qkw)+ gen = Generator(model=model, cache=gcache, tokenizer=tok)+ gen.enqueue(Job(input_ids=ids, max_new_tokens=a.gen, sampler=GreedySampler()))+ toks = []+ while gen.num_remaining_jobs():+ for r in gen.iterate():+ for t in (r.get("token_ids") or []):+ toks.append(int(t))+ out[arm] = dict(md5=hashlib.md5(",".join(map(str, toks)).encode()).hexdigest(), n=len(toks), ids=toks[:8])+ print(f" gen arm={arm} {out[arm]['md5']} n={out[arm]['n']} head={out[arm]['ids']}", flush=True)+ R["gen"] = out+ save()++ for d in depths:+ o, n = R["points"][str(d)]["off"], R["points"][str(d)]["on"]+ mo, mn = statistics.mean(o), statistics.mean(n)+ se = statistics.stdev([x - y for x, y in zip(o, n)]) / max(1, len(o)) ** 0.5 if len(o) > 1 else 0.0+ print(f"depth {d}: off {mo:.3f} ms ({1000/mo:.2f} tok/s) on {mn:.3f} ({1000/mn:.2f}) "+ f"delta {100*(mn-mo)/mo:+.2f} % +- {100*se/mo:.2f} md5 {'EQUAL' if R['md5'][str(d)]['off']==R['md5'][str(d)]['on'] else 'DIFFER'}")+ if R["gen"]:+ print("greedy md5", "EQUAL" if R["gen"]["off"]["md5"] == R["gen"]["on"]["md5"] else "DIFFER")+ save()+++def main():+ # the cache tensors are created by the engine under inference mode: updating them needs it too+ # (same wrapper as tools/depth/depth_profile.py)+ import torch+ with torch.inference_mode():+ _main()+++if __name__ == "__main__":+ main()