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
"""Multi-turn session through PortEngine (the engine behind serve.py) with the prompt cache on: per-turn TTFT, cached tokens,
# Variant of ds41_session.py from perf/ds41-hot-protect: adds MemAvailable minimum and Engram fetch timing per turn (single draft depth, --ctx).
tier misses/bytes of the prefill part and of the decode part, DSpark decode tok/s. Turn kinds: ctx (first, big), follow (30-80 tok),
tool (~2K tok). Texts are real token rows (data/short.npy, long.npy), appended to the running id list."""
import argparse, json, os, sys, time
import threading, hashlib
import numpy as np, torch
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
H = os.environ.get("DS41_WORK", "ds41_work")
ap = argparse.ArgumentParser()
ap.add_argument("pack"); ap.add_argument("--arm", required=True); ap.add_argument("--out", required=True)
ap.add_argument("--chunk", type=int, default=16384); ap.add_argument("--new", type=int, default=96); ap.add_argument("--draft", type=int, default=4)
ap.add_argument("--first", type=int, default=6144); ap.add_argument("--plan", default="f50,f30,t2048,f80,f40,t2000,f60,t2048,f35")
ap.add_argument("--ctx", type=int, default=32768); ap.add_argument("--engram-dir"); ap.add_argument("--data", default=os.path.join(H, "ds41ready_data"))
a = ap.parse_args()
from ds41_serving import build_model
from ds41_engine import HFTokenizer
from ds41_model import PortEngine, TopPSampler
m = build_model(a.pack, device="cuda:0", dtype="float16", layers=None, mtp=True, moe="auto", prefill_chunk=a.chunk, engram_dir=a.engram_dir)
blk = [b for b in m.pack_modules[0].modules if getattr(b, "tier", None) is not None]
from exllamav3.modules.expert_store import get_store
store = get_store(blk[0].config)
eng = PortEngine(m, HFTokenizer(os.path.join(a.pack, "tokenizer.json")), ctx=a.ctx, num_draft=a.draft, eos_id=None, prefix_cache=True)
s_, l_ = (np.load(os.path.join(a.data, f"{n}.npy")).astype(np.int64) for n in ("short", "long"))
pool = np.concatenate([s_.reshape(-1), l_.reshape(-1)]); off = 0
def take(n):
global off
x = pool[off:off + n].tolist(); off += n; return x
def S(): return store.stats()
# minimum MemAvailable (GiB) seen since the last reset, sampled every 0.25 s; torch free memory is the same pool on the APU
memmin = [1e9]
def _sample():
while True:
try:
with open("/proc/meminfo") as f:
for ln in f:
if ln.startswith("MemAvailable:"):
memmin[0] = min(memmin[0], int(ln.split()[1]) / 1048576); break
except OSError:
pass
time.sleep(0.25)
threading.Thread(target=_sample, daemon=True).start()
# Engram row fetch time (host side, random O_DIRECT reads): wall seconds and calls since the last reset
eg = {"s": 0.0, "n": 0}
try:
from exllamav3.dsv41 import engram as _eg
_depth = [0]
for _n in dir(_eg):
_c = getattr(_eg, _n)
if isinstance(_c, type) and issubclass(_c, _eg.EngramRowStore) and _c is not _eg.EngramRowStore and "fetch" in _c.__dict__:
def _wrap(f):
def g(self, *x, **k):
t = time.perf_counter(); _depth[0] += 1
try: return f(self, *x, **k)
finally:
_depth[0] -= 1
if _depth[0] == 0: eg["s"] += time.perf_counter() - t; eg["n"] += 1
return g
_c.fetch = _wrap(_c.fetch)
except Exception as e: # noqa: BLE001
print("engram timing off:", e)
KEYS = ("uses", "hits", "misses", "bytes", "read_s", "wait_s", "copy_s", "sync_s")
def diff(x, y): return {k: y[k] - x[k] for k in KEYS}
ids = take(a.first); rows = []
plan = ["c%d" % a.first] + a.plan.split(",")
for i, p in enumerate(plan):
if i > 0: ids = ids + take(int(p[1:]))
snap = {}; marks = {}; out_toks = []; eg0 = dict(eg); memmin[0] = 1e9
def cb(t):
out_toks.extend(t)
if "first" not in marks: marks["first"] = time.perf_counter(); snap.update(S()); marks["eg"] = dict(eg)
s0 = S(); t0 = time.perf_counter()
st = eng._run(list(ids), a.new, TopPSampler(0.0, 1.0, None), -1, None, cb)
t1 = time.perf_counter(); s1 = S()
pre, dec = diff(s0, snap), diff(snap, s1)
nt = st["new_tokens"]
r = {"turn": i, "kind": p, "prompt": len(ids), "cached": st.get("cached_tokens", 0), "ttft_s": round(marks["first"] - t0, 2),
"prefill_misses": pre["misses"], "prefill_GB": round(pre["bytes"] / 1e9, 1), "prefill_hit": round(pre["hits"] / max(pre["uses"], 1), 3),
"dec_tok_s": round((nt - 1) / max(t1 - marks["first"], 1e-9), 2), "dec_hit": round(dec["hits"] / max(dec["uses"], 1), 4),
"dec_misses": dec["misses"], "dec_GB": round(dec["bytes"] / 1e9, 2), "acc_per_step": st.get("accepted_per_step"),
"dec_read_s": round(dec["read_s"], 2), "dec_wait_s": round(dec["wait_s"], 2), "dec_copy_s": round(dec["copy_s"], 2),
"dec_sync_s": round(dec["sync_s"], 2), "pre_hits": pre["hits"], "pre_uses": pre["uses"],
"engram_dec_s": round(eg["s"] - marks["eg"]["s"], 3), "engram_dec_calls": eg["n"] - marks["eg"]["n"],
"engram_pre_s": round(marks["eg"]["s"] - eg0["s"], 3), "memavail_min_gib": round(memmin[0], 1),
"tokhash": hashlib.sha1(json.dumps(out_toks).encode()).hexdigest()[:12], "new_tokens": nt}
print(a.arm, r, flush=True); rows.append(r)
# extend the running history with what the engine generated is not possible without ids: keep prompt-only history
open(a.out, "a").write(json.dumps({"arm": a.arm, "env": {k: v for k, v in os.environ.items() if k.startswith(("EXL3_EXPERT", "EXL3_TIER"))}, "turns": rows}) + "\n")