tools/qwen35: the Qwen3.6 pictures and parallel-requests gates (engine protocol harness, solo / batch identity, protocol edges, llama.cpp picture comparison, throughput A/B)

This commit is contained in:
Niko1221 committed 2026-10-14 01:11:42 +02:00
1 parent a9adfa5dad
commit cfc7686c00
14 files changed
+842

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
248045,846,198,7734,264,2716,3255,883,264,324,55965,51624,852,13325,264,1876,303,264,16002,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,60856,449,436,34810,6297,303,12654,440,615,321,2113,303,496,7,16,681,321,884,2250,4821,6813,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,3710,369,220,16,22,348,220,17,18,478,220,16,19,19,593,220,16,17,30,6712,279,7123,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,814,20139,1204,264,43447,4138,310,264,5600,4514,6086,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,26583,1083,5753,25,561,5257,310,44663,10583,506,4139,3162,7840,11,5171,2943,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,826,4097,11461,1881,25804,321,40986,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,8917,5437,537,279,6868,314,67815,321,68613,303,2250,22157,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,7734,264,4566,1576,21988,264,2236,440,2192,11,3049,11,1007,321,2250,9212,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,2592,660,13805,3595,513,427,9510,536,321,660,427,9510,536,513,1147,10090,536,11,513,660,13805,3595,1147,10090,536,30,79091,13,248046,198,248045,74455,198,248068,271,248069,271
248045,846,198,7734,264,6185,36974,883,40297,10849,383,264,3177,8329,13,248046,198,248045,74455,198,248068,271,248069,271
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

+115
View File
@@ -0,0 +1,115 @@
"""batch_gate.py - the parallel-requests gate for strata-q36 (the tools/batch_test.py idea over the serve protocol).
python q36_batch_gate.py --exe E --args "--model M --max-context 8192 --batch 4" --slots 4 --n 128 [--golden G.json]
[--long 3000] [--keys "temperature=0.7 seed=3"] [--out F.json]
1. every prompt alone (GEN) on the same engine -> solo tokens (and, with --golden, equal to the base engine's);
2. the first --slots prompts through BGEN, admitted one after the other, then decoding together -> every slot's tokens
must equal its solo tokens; the decode rate of the window phase;
3. --waves: the 10 prompts in waves of --slots (slot reuse: the cached state of a finished slot is taken over);
4. --long L: a prompt of about L tokens admitted into the last slot while the others decode (its prompt chunks run
between their windows); the others' tokens must still equal their solo tokens, and so must the long one's.
"""
from pathlib import Path
import argparse, json, shlex, sys, time
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
from q36_harness import Eng, load_prompts
def same(a, b):
return a == b
ap = argparse.ArgumentParser()
ap.add_argument("--exe", required=True)
ap.add_argument("--args", default="")
ap.add_argument("--slots", type=int, default=4)
ap.add_argument("--n", type=int, default=128)
ap.add_argument("--prompts", default=str(Path(__file__).resolve().parent / "parity_prompts.ids"))
ap.add_argument("--golden", default=None)
ap.add_argument("--keys", default="")
ap.add_argument("--long", type=int, default=0)
ap.add_argument("--waves", action="store_true")
ap.add_argument("--skip-solo-bench", action="store_true")
ap.add_argument("--out", default=None)
ap.add_argument("--log", default=None)
ap.add_argument("--env", default="")
a = ap.parse_args()
env = dict(kv.split("=", 1) for kv in a.env.split() if "=" in kv)
eng = Eng(a.exe, shlex.split(a.args), env=env, log=a.log)
print("ready:", eng.ready, "info:", eng.info, "load %.1fs" % eng.load_s, flush=True)
prompts = load_prompts(a.prompts)
ok = True
res = {"args": a.args, "slots": a.slots}
# 1. solo
solo, solo_rate = [], []
for i, ids in enumerate(prompts):
toks, done, ttft, wall = eng.solo(ids, a.n, a.keys)
solo.append(toks)
solo_rate.append(len(toks) / max(1e-9, wall - (ttft or 0)))
print("solo: %d prompts, decode %.1f tok/s median" % (len(solo), sorted(solo_rate)[len(solo_rate) // 2]), flush=True)
if a.golden:
g = json.load(open(a.golden))["tokens"]
eq = [same(x, y) for x, y in zip(solo, g)]
print("solo vs golden (base engine):", "identical %d of %d" % (sum(eq), len(eq)), flush=True)
ok &= all(eq)
res["solo_tok_s_median"] = sorted(solo_rate)[len(solo_rate) // 2]
# 2. batch
S = min(a.slots, len(prompts))
reqs = [{"ids": prompts[i], "n": a.n, "slot": i, "keys": a.keys} for i in range(S)]
r = eng.batch(reqs)
eq = [same(r["tokens"][i], solo[i]) for i in range(S)]
print("batch %d: %d of %d slots identical to solo | wall %.2fs, window phase %d tokens in %.2fs = %.1f tok/s (aggregate)"
% (S, sum(eq), S, r["wall"], r["tail_tokens"], r["tail_s"], r["tail_tok_s"]), flush=True)
for i, e in enumerate(eq):
if not e:
x, y = r["tokens"][i], solo[i]
k = next((k for k in range(min(len(x), len(y))) if x[k] != y[k]), min(len(x), len(y)))
print(" slot %d differs at token %d (lens %d / %d)" % (i, k, len(x), len(y)))
ok &= all(eq)
res["batch"] = {"slots": S, "identical": sum(eq), "wall": r["wall"], "tail_tok_s": r["tail_tok_s"], "tail_tokens": r["tail_tokens"]}
# 3. waves (slot reuse)
if a.waves:
wave_ok = True
for w0 in range(0, len(prompts), S):
idx = list(range(w0, min(w0 + S, len(prompts))))
rq = [{"ids": prompts[i], "n": a.n, "slot": j, "keys": a.keys} for j, i in enumerate(idx)]
rr = eng.batch(rq)
for j, i in enumerate(idx):
if not same(rr["tokens"][j], solo[i]):
wave_ok = False
print(" wave %d prompt %d differs" % (w0 // S, i))
print("waves of %d: %s" % (S, "all identical" if wave_ok else "DIFFERENT"), flush=True)
ok &= wave_ok
# 4. a long prompt admitted while the others decode
if a.long and S >= 2:
base = prompts[0]
filler = []
while len(filler) < a.long:
for p in prompts:
filler += p[3:-8] if len(p) > 12 else p
longids = filler[:a.long] + prompts[1][-8:]
toks, done, ttft, wall = eng.solo(longids, 48, a.keys)
reqs = [{"ids": prompts[i], "n": a.n * 2, "slot": i, "keys": a.keys} for i in range(S - 1)]
# the first S-1 are admitted first; then the long one is admitted while they decode
longreq = {"ids": longids, "n": 48, "slot": S - 1, "keys": a.keys}
solo2 = []
for i in range(S - 1):
t2, _, _, _ = eng.solo(prompts[i], a.n * 2, a.keys)
solo2.append(t2)
rr = eng.batch(reqs + [longreq])
eq = [same(rr["tokens"][i], solo2[i]) for i in range(S - 1)] + [same(rr["tokens"][S - 1], toks)]
print("long prompt (%d tokens) admitted beside %d decoding slots: %s | admission stamps %s"
% (len(longids), S - 1, "%d of %d identical" % (sum(eq), len(eq)), ["%.2f" % x for x in rr["admit_stamps"]]), flush=True)
ok &= all(eq)
res["ok"] = ok
if a.out:
json.dump(res, open(a.out, "w"))
eng.close()
print("GATE", "PASS" if ok else "FAIL", flush=True)
sys.exit(0 if ok else 1)
+13
View File
@@ -0,0 +1,13 @@
"""q36_cmp_gate.py A.json B.json : per prompt identical or the first differing index."""
import json, sys
a, b = json.load(open(sys.argv[1]))["tokens"], json.load(open(sys.argv[2]))["tokens"]
same = 0
for i, (x, y) in enumerate(zip(a, b)):
n = next((k for k in range(min(len(x), len(y))) if x[k] != y[k]), None)
if n is None and len(x) == len(y):
same += 1
print("p%02d identical (%d tokens)" % (i, len(x)))
else:
print("p%02d DIFFERENT at %s (len %d vs %d)" % (i, n, len(x), len(y)))
print("identical: %d of %d" % (same, len(a)))
sys.exit(0 if same == len(a) else 1)
+143
View File
@@ -0,0 +1,143 @@
"""harness.py - drives strata-q36 / `strata` (qwen35moe) --serve over the engine protocol, for the q36-vp gates.
Eng(exe, args) starts `exe --serve args`, waits for READY (INFO lines kept)
.solo(ids, n, keys, emb) GEN / GENI one request -> (tokens, DONE line)
.batch(reqs) reqs = [{"ids":[..], "n":N, "keys":"", "slot":b, "emb":path}] admitted one after the
other (BGEN, as the server does: one admission at a time), then every slot decodes
together -> dict(tokens=[..per req], wall, steady_tok_s, ...)
Run on the lent box; the box's lock / memory cap wrap the whole python call (see run.sh).
"""
import json, os, queue, subprocess, sys, threading, time
def load_prompts(path):
return [[int(x) for x in l.strip().split(",") if x] for l in open(path) if l.strip()]
class Eng:
def __init__(self, exe, args, env=None, log=None, quiet=False):
e = dict(os.environ)
e.update(env or {})
self.logf = open(log, "w") if log else subprocess.DEVNULL
self.p = subprocess.Popen([exe, "--serve", *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=self.logf, text=True, bufsize=1, env=e)
self.q = queue.Queue()
self.info = {}
threading.Thread(target=self._pump, daemon=True).start()
t0 = time.time()
while True:
l = self.line(600)
if l is None:
raise SystemExit("engine ended before READY (see %s)" % log)
if l.startswith("INFO "):
for kv in l.split()[1:]:
k, _, v = kv.partition("=")
self.info[k] = v
if l.startswith("READY"):
self.ready = l
break
self.load_s = time.time() - t0
def _pump(self):
for l in self.p.stdout:
self.q.put(l.rstrip("\n"))
self.q.put(None)
def line(self, timeout=600):
try:
return self.q.get(timeout=timeout)
except queue.Empty:
raise SystemExit("engine silent for %ds" % timeout)
def send(self, s):
self.p.stdin.write(s + "\n")
self.p.stdin.flush()
def solo(self, ids, n, keys="", emb=None):
head = ("GENI %d" % n if emb else "GEN %d" % n) + (" " + keys if keys else "") + (" " + emb if emb else "")
t0 = time.time()
self.send(head + " " + ",".join(map(str, ids)))
toks, ttft, pp = [], None, []
while True:
l = self.line()
if l is None:
raise SystemExit("engine died")
if l.startswith("T "):
if ttft is None:
ttft = time.time() - t0
toks.append(int(l.split()[1]))
elif l.startswith("PP "):
pp.append(l)
elif l.startswith("DONE"):
return toks, l, ttft, time.time() - t0
elif l.startswith("ERR"):
raise SystemExit("ERR: " + l)
def batch(self, reqs, hold_s=0.0):
"""Admit every request (BGEN) in order, then read until every slot is done."""
toks = [[] for _ in reqs]
by_slot = {r["slot"]: i for i, r in enumerate(reqs)}
done = [False] * len(reqs)
t0 = time.time()
first_bt = None
admitted_at = None
stamps = []
for i, r in enumerate(reqs):
head = ("BGENI %d %d" if r.get("emb") else "BGEN %d %d") % (r["slot"], r["n"])
keys = r.get("keys", "")
self.send(head + (" " + keys if keys else "") + (" " + r["emb"] if r.get("emb") else "") + " " +
",".join(map(str, r["ids"])))
while True:
l = self.line()
if l is None:
raise SystemExit("engine died")
if l.startswith("T "):
toks[i].append(int(l.split()[1]))
elif l.startswith("BT "):
f = l.split()
j = by_slot[int(f[1])]
toks[j].append(int(f[2]))
if first_bt is None:
first_bt = time.time()
elif l.startswith("BDONE "):
done[by_slot[int(l.split()[1])]] = True
elif l.startswith("BADM "):
f = l.split()
if f[2] == "0":
done[i] = True
break
elif l.startswith("ERR"):
raise SystemExit("ERR: " + l)
stamps.append(time.time() - t0)
admitted_at = time.time()
n_at_admit = sum(len(t) for t in toks)
while not all(done):
l = self.line()
if l is None:
raise SystemExit("engine died")
if l.startswith("BT "):
f = l.split()
toks[by_slot[int(f[1])]].append(int(f[2]))
elif l.startswith("BDONE "):
done[by_slot[int(l.split()[1])]] = True
elif l.startswith("ERR"):
raise SystemExit("ERR: " + l)
t1 = time.time()
tot = sum(len(t) for t in toks)
return {"tokens": toks, "wall": t1 - t0, "admit_s": admitted_at - t0, "admit_stamps": stamps,
"tail_tokens": tot - n_at_admit, "tail_s": t1 - admitted_at,
"tail_tok_s": (tot - n_at_admit) / max(1e-9, t1 - admitted_at)}
def close(self):
try:
self.send("STOP")
except Exception:
pass
try:
self.p.stdin.close()
except Exception:
pass
try:
self.p.wait(timeout=30)
except Exception:
self.p.kill()
+98
View File
@@ -0,0 +1,98 @@
"""par_bench.py - aggregate decode throughput of N requests at once: strata-q36 (--batch) and llama.cpp (llama-server -np N),
same GGUF, same prompt ids, greedy, 128 new tokens each. One JSON line per (engine, N, round).
python q36_par_bench.py strata --exe E --args "--model M --max-context 8192 --batch 8 --mtp 0" --ns 1,2,4,8 --rounds 3 --out F
python q36_par_bench.py llama --server BIN --model M --ns 1,2,4,8 --rounds 3 --out F [--port 8197]
The strata wall time runs from the first BGEN to the last BDONE (admissions included); the llama one from the first request
sent to the last answer (prompt reading included); tok/s = tokens produced / wall. `tail_tok_s` (strata): the window phase
only, after the last admission."""
from pathlib import Path
import argparse, json, os, shlex, subprocess, sys, threading, time, urllib.request
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
from q36_harness import Eng, load_prompts
ORDER = [0, 1, 2, 3, 5, 8, 0, 1] # the prompts that run the full 128 tokens, repeated to fill 8 slots
def strata(a):
prompts = load_prompts(a.prompts)
eng = Eng(a.exe, shlex.split(a.args), log=a.log)
out = open(a.out, "a")
for n in [int(x) for x in a.ns.split(",")]:
for rnd in range(a.rounds):
reqs = [{"ids": prompts[ORDER[i]], "n": a.n, "slot": i} for i in range(n)]
r = eng.batch(reqs)
tot = sum(len(t) for t in r["tokens"])
row = {"engine": "strata", "n": n, "round": rnd, "tokens": tot, "wall": r["wall"], "tok_s": tot / r["wall"],
"tail_tok_s": r["tail_tok_s"]}
print(json.dumps(row), flush=True)
out.write(json.dumps(row) + "\n")
out.flush()
eng.close()
def post(port, body):
return json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/completion", json.dumps(body).encode(),
{"Content-Type": "application/json"}), timeout=900).read())
def llama(a):
prompts = load_prompts(a.prompts)
out = open(a.out, "a")
for n in [int(x) for x in a.ns.split(",")]:
cmd = [a.server, "-m", a.model, "-ngl", "99", "-fa", "on", "-c", str(8192 * n), "-np", str(n), "--port", str(a.port),
"--no-webui", "-t", "16"] + shlex.split(a.llama_args)
log = open(a.log or os.devnull, "a")
p = subprocess.Popen(cmd, stdout=log, stderr=log)
try:
for _ in range(240):
try:
urllib.request.urlopen(f"http://127.0.0.1:{a.port}/health", timeout=2)
break
except Exception: # noqa: BLE001
time.sleep(1)
for rnd in range(a.rounds + 1): # round 0: the warm-up
res = [None] * n
def one(i):
res[i] = post(a.port, {"prompt": prompts[ORDER[i]], "n_predict": a.n, "temperature": 0, "top_k": 1,
"cache_prompt": False, "id_slot": i})
ts = [threading.Thread(target=one, args=(i,)) for i in range(n)]
t0 = time.time()
for t in ts:
t.start()
for t in ts:
t.join()
wall = time.time() - t0
tot = sum(r["tokens_predicted"] for r in res)
if rnd == 0:
continue
row = {"engine": "llama", "n": n, "round": rnd - 1, "tokens": tot, "wall": wall, "tok_s": tot / wall}
print(json.dumps(row), flush=True)
out.write(json.dumps(row) + "\n")
out.flush()
finally:
p.terminate()
try:
p.wait(timeout=60)
except subprocess.TimeoutExpired:
p.kill()
ap = argparse.ArgumentParser()
ap.add_argument("mode", choices=["strata", "llama"])
ap.add_argument("--exe")
ap.add_argument("--args", default="")
ap.add_argument("--server")
ap.add_argument("--model")
ap.add_argument("--llama-args", default="")
ap.add_argument("--ns", default="1,2,4,8")
ap.add_argument("--rounds", type=int, default=3)
ap.add_argument("--n", type=int, default=128)
ap.add_argument("--prompts", default=str(Path(__file__).resolve().parent / "parity_prompts.ids"))
ap.add_argument("--port", type=int, default=8197)
ap.add_argument("--out", required=True)
ap.add_argument("--log", default=None)
a = ap.parse_args()
(strata if a.mode == "strata" else llama)(a)
+112
View File
@@ -0,0 +1,112 @@
"""proto_edge.py - the protocol's edges for parallel requests (engine level): max_new 1, BSTOP, a busy slot, STOP during an
admission's prompt read, slot reuse (the held state), sampled requests in a batch against the same request alone, a
request that reaches the context's end."""
from pathlib import Path
import argparse, shlex, sys, time
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
from q36_harness import Eng, load_prompts
ap = argparse.ArgumentParser()
ap.add_argument("--exe", required=True)
ap.add_argument("--args", default="")
ap.add_argument("--log", default=None)
a = ap.parse_args()
eng = Eng(a.exe, shlex.split(a.args), log=a.log)
P = load_prompts(str(Path(__file__).resolve().parent / "parity_prompts.ids"))
ok = True
def check(name, cond, extra=""):
global ok
ok &= bool(cond)
print(("PASS " if cond else "FAIL ") + name + (" - " + extra if extra else ""), flush=True)
def lines_until(pred, timeout=120):
out = []
t0 = time.time()
while time.time() - t0 < timeout:
l = eng.line(timeout)
out.append(l)
if pred(l):
return out
return out
# 1. max_new 1: T, DONE, BADM slot 0
eng.send("BGEN 0 1 " + ",".join(map(str, P[0])))
r = lines_until(lambda l: l.startswith("BADM"))
check("BGEN max_new 1 ends at the admission", r[-1] == "BADM 0 0" and any(l.startswith("T ") for l in r), str(r[-3:]))
# 2. a long answer, BSTOP after a few tokens, then a longer request on the held state
eng.send("BGEN 0 200 " + ",".join(map(str, P[1])))
r = lines_until(lambda l: l.startswith("BADM"))
check("BGEN max_new 200 continues", r[-1] == "BADM 0 1", r[-1])
bts = []
while len(bts) < 5:
l = eng.line()
if l.startswith("BT 0"):
bts.append(int(l.split()[2]))
# the slot is busy: another BGEN for it is refused (BT lines of the running slot may come first)
eng.send("BGEN 0 5 " + ",".join(map(str, P[2])))
seen = lines_until(lambda l: l.startswith("ERR") or l.startswith("BADM"))
for l in seen:
if l.startswith("BT 0"):
bts.append(int(l.split()[2]))
check("BGEN into a busy slot is refused", seen[-1].startswith("ERR BGEN"), seen[-1])
eng.send("BSTOP 0")
done = lines_until(lambda l: l.startswith("BDONE 0"))
for l in done:
if l.startswith("BT 0"):
bts.append(int(l.split()[2]))
check("BSTOP ends the slot with cancel", done[-1].split()[3] == "cancel", done[-1])
first = [int(l.split()[1]) for l in r if l.startswith("T ")]
# the slot holds the prompt and every token a window fed (all but the last one): a continuation extends exactly that
eng.send("BGEN 0 3 " + ",".join(map(str, P[1] + first + bts)))
r2 = lines_until(lambda l: l.startswith("BADM"))
dn = [l for l in r2 if l.startswith("DONE")][0].split()
check("a continuation reuses the slot's held state", int(dn[8]) == len(P[1]) + len(first) + len(bts) - 1,
"reused %s of %d" % (dn[8], len(P[1] + first + bts)))
lines_until(lambda l: l.startswith("BDONE 0"))
# 3. STOP during an admission's prompt read
filler = []
while len(filler) < 3000:
for p in P:
filler += p[3:-8]
filler = filler[:3000]
eng.send("BGEN 1 8 " + ",".join(map(str, filler)))
time.sleep(0.15)
eng.send("STOP")
r3 = lines_until(lambda l: l.startswith("BADM"))
dn = [l for l in r3 if l.startswith("DONE")][0].split()
pp = [l for l in r3 if l.startswith("PP ")]
check("STOP during the prompt read ends it with cancel", dn[5] == "cancel" and r3[-1] == "BADM 1 0",
"%d PP line(s), DONE %s" % (len(pp), " ".join(dn[:6])))
# the engine is in step: a normal request on the same slot works
eng.send("BGEN 1 6 " + ",".join(map(str, P[3])))
r4 = lines_until(lambda l: l.startswith("BADM"))
check("a request after the cancelled read works", r4[-1] == "BADM 1 1", r4[-1])
lines_until(lambda l: l.startswith("BDONE 1"))
# 4. sampled: batch against alone, same seed
keys = "temperature=0.8 top_k=40 top_p=0.95 seed=11"
toks, _, _, _ = eng.solo(P[4], 40, keys)
res = eng.batch([{"ids": P[4], "n": 40, "slot": 2, "keys": keys}, {"ids": P[5], "n": 40, "slot": 3, "keys": "temperature=0.5 seed=3"}])
check("a sampled request in a batch equals the same request alone", res["tokens"][0] == toks,
"%d / %d tokens" % (len(res["tokens"][0]), len(toks)))
# 5. the context's end: a prompt of ctx - 40 tokens and max_new 400 finishes with length
ctx = int(eng.ready.split()[1])
long_prompt = (filler * 4)[:ctx - 60]
eng.send("BGEN 3 400 " + ",".join(map(str, long_prompt)))
r5 = lines_until(lambda l: l.startswith("ERR") or l.startswith("BADM"))
check("a request that cannot fit its answer is refused with the engine's message", r5[-1].startswith("ERR prompt"), r5[-1][:80])
eng.send("BGEN 3 50 " + ",".join(map(str, long_prompt[:ctx - 80])))
r6 = lines_until(lambda l: l.startswith("BADM"))
bd = lines_until(lambda l: l.startswith("BDONE 3"))
check("a request to the context's end finishes", bd[-1].split()[3] in ("length", "stop"), bd[-1])
eng.close()
print("GATE", "PASS" if ok else "FAIL")
sys.exit(0 if ok else 1)
+65
View File
@@ -0,0 +1,65 @@
"""q36_serve_par.py PORT [--n 128] [--conc 4] [--img PATH] : N concurrent chat requests through the server (parallel: N), against
the same requests one after the other (the solo path). Greedy, thinking off: the texts must be equal. Prints the
aggregate rate of the concurrent round. With --img: half of the requests carry the picture (and ask about it)."""
import argparse, base64, json, sys, threading, time, urllib.request
PROMPTS = json.load(open(sys.argv[0].rsplit("/", 1)[0] + "/parity_prompts.json")) if False else [
"Write a short story about a lighthouse keeper who finds a message in a bottle.",
"Implement an LRU cache in Python with get and put in O(1), and add three unit tests.",
"What is 17 * 23 + 144 / 12? Show the steps.",
"Explain how a refrigerator works to a ten-year-old.",
"Translate into German: The train to Munich leaves at half past seven, platform four.",
"List five differences between TCP and UDP.",
"Summarize the plot of Romeo and Juliet in three sentences.",
"Write a JSON object describing a book with title, author, year and three tags.",
]
def ask(port, content, n, out, i, stream=False):
body = {"model": "x", "max_tokens": n, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "user", "content": content}]}
t0 = time.time()
try:
r = json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions",
json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=900).read())
out[i] = (r["choices"][0]["message"]["content"], r["usage"]["completion_tokens"], time.time() - t0)
except Exception as e: # noqa: BLE001
out[i] = ("ERROR %s" % e, 0, time.time() - t0)
ap = argparse.ArgumentParser()
ap.add_argument("port", type=int)
ap.add_argument("--n", type=int, default=128)
ap.add_argument("--conc", type=int, default=4)
ap.add_argument("--img", default=None)
a = ap.parse_args()
contents = []
for i in range(a.conc):
p = PROMPTS[i % len(PROMPTS)]
if a.img and i % 2 == 1:
b64 = base64.b64encode(open(a.img, "rb").read()).decode()
contents.append([{"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}},
{"type": "text", "text": "What text is written in the image? Answer with the text only."}])
else:
contents.append(p)
solo = [None] * a.conc
for i, c in enumerate(contents):
ask(a.port, c, a.n, solo, i)
print("one after the other: %d requests, %d tokens, %.1fs" % (a.conc, sum(x[1] for x in solo), sum(x[2] for x in solo)), flush=True)
for rnd in range(2):
conc = [None] * a.conc
ts = [threading.Thread(target=ask, args=(a.port, c, a.n, conc, i)) for i, c in enumerate(contents)]
t0 = time.time()
for t in ts:
t.start()
for t in ts:
t.join()
wall = time.time() - t0
tot = sum(x[1] for x in conc)
same = [conc[i][0] == solo[i][0] for i in range(a.conc)]
print("concurrent round %d: %d requests, %d tokens in %.1fs = %.1f tok/s aggregate; texts equal to the solo run: %s"
% (rnd, a.conc, tot, wall, tot / wall, same), flush=True)
for i, ok in enumerate(same):
if not ok:
print(" request %d: %r vs %r" % (i, conc[i][0][:80], solo[i][0][:80]))
sys.exit(0)
+26
View File
@@ -0,0 +1,26 @@
"""q36_solo_gate.py --exe E --args "..." --out F.json [--n 128] [--prompts F] [--keys K] : greedy tokens of the 10 parity
prompts, one request each through the serve protocol; the JSON is what two builds are compared on (cmp_gate.py)."""
from pathlib import Path
import argparse, json, shlex, sys, time
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
from q36_harness import Eng, load_prompts
ap = argparse.ArgumentParser()
ap.add_argument("--exe", required=True)
ap.add_argument("--args", default="")
ap.add_argument("--out", required=True)
ap.add_argument("--n", type=int, default=128)
ap.add_argument("--prompts", default=str(Path(__file__).resolve().parent / "parity_prompts.ids"))
ap.add_argument("--keys", default="")
ap.add_argument("--log", default=None)
a = ap.parse_args()
eng = Eng(a.exe, shlex.split(a.args), log=a.log)
print("ready", eng.ready, "info", eng.info, "load %.1fs" % eng.load_s, flush=True)
res = []
for i, ids in enumerate(load_prompts(a.prompts)):
toks, done, ttft, wall = eng.solo(ids, a.n, a.keys)
dec = done.split()
print("p%02d %d tok %.1f tok/s %s" % (i, len(toks), len(toks) / max(1e-9, wall - (ttft or 0)), done[:70]), flush=True)
res.append(toks)
json.dump({"args": a.args, "tokens": res}, open(a.out, "w"))
eng.close()
+18
View File
@@ -0,0 +1,18 @@
"""q36_venc.py EXE MMPROJ MODEL IMG [IMG ...] : drive strata-vision (ENC protocol), print each picture's header + stats."""
import subprocess, sys, struct, os, time
exe, mm, model, *imgs = sys.argv[1:]
args = [exe, "--mmproj", mm, "--model", model] + [a for a in os.environ.get("STRATA_VARGS", os.environ.get("VARGS", "")).split() if a]
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
print(p.stdout.readline().strip())
for img in imgs:
out = img + ".sve"
p.stdin.write(f"ENC {img} {out}\n"); p.stdin.flush()
r = p.stdout.readline().strip()
print(img, r)
if r.startswith("OK"):
d = open(out, "rb").read()
magic, n, nx, ny, ne = struct.unpack("<5i", d[:20])
import array
a = array.array("f"); a.frombytes(d[20:])
print(" hdr", hex(magic), n, nx, ny, ne, "floats", len(a), "mean %.5f" % (sum(a) / len(a)), "first", [round(x, 4) for x in a[:6]])
p.stdin.write("QUIT\n"); p.stdin.flush(); p.wait()
+131
View File
@@ -0,0 +1,131 @@
"""vcmp.py - the picture gate: strata-q36 against llama.cpp (mtmd) on the same GGUF + mmproj, same pictures.
For each (picture, question): llama.cpp HIP (q36_mtmd_dump, encoder on the CPU like strata-vision's) gives the prompt's
chunks, its greedy answer and every step's full logits; the encoder file of strata-vision (venc.py) is laid over the same
ids; strata-q36 (--tokens ids --emb file --force llama's greedy ids) gives its logits on the same sequence. Reported:
the answer text agreement, the first token's logits (top-1/top-2 both, max |diff| over the top-5), the teacher-forced
mean KL(P_llama || Q_strata) and top-1 agreement over the steps, and - the floor - the same numbers for llama.cpp's CPU
backend against llama.cpp HIP.
python q36_vision_cmp.py --dump BIN --q36 BIN --vision BIN --model GGUF --mmproj F --out DIR --pic shapes.png --pic code4217.png
[--lock "flock ..."] [--n 24] [--q36-args "--vision --max-context 4096"]
"""
from pathlib import Path
import argparse, json, os, shlex, struct, subprocess, sys
import numpy as np
V = 248320
QUESTIONS = {
"shapes.png": ["What text is written in the image? Answer with the text only.",
"List every shape in the image with its colour, from left to right. One short line each."],
"code4217.png": ["What text is written in the image? Answer with the text only.",
"Describe the shapes in the image with their colours and positions, one short line each."],
}
TEMPLATE = "<|im_start|>user\n<__media__>{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
PAD = 248056
def run(cmd, lock, log, env=None):
full = (shlex.split(lock) if lock else []) + cmd
e = dict(os.environ)
e.update(env or {})
r = subprocess.run(full, capture_output=True, text=True, timeout=3600, env=e)
open(log, "w").write(r.stdout + "\n--- stderr ---\n" + r.stderr)
if r.returncode != 0:
raise SystemExit("%s failed (rc %d), see %s" % (cmd[0], r.returncode, log))
return r.stdout
def parse_dump(out):
chunks, gen, first = [], [], None
for l in out.splitlines():
if l.startswith("text:"):
chunks.append(("text", [int(x) for x in l.split(":", 1)[1].split()]))
elif l.startswith("image:"):
chunks.append(("image", int(l.split()[1])))
elif l.startswith("gen:"):
gen = [int(x) for x in l.split(":", 1)[1].split()]
elif l.startswith("first:"):
first = l
return chunks, gen, first
def log_softmax(x):
x = x.astype(np.float64)
m = x.max(axis=1, keepdims=True)
return x - m - np.log(np.exp(x - m).sum(axis=1, keepdims=True))
def kl_stats(p_logits, q_logits):
n = min(len(p_logits), len(q_logits))
lp, lq = log_softmax(p_logits[:n]), log_softmax(q_logits[:n])
kl = (np.exp(lp) * (lp - lq)).sum(axis=1)
top1 = (p_logits[:n].argmax(axis=1) == q_logits[:n].argmax(axis=1))
return kl, top1
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dump", required=True)
ap.add_argument("--q36", required=True)
ap.add_argument("--vision", required=True)
ap.add_argument("--venc", default=str(Path(__file__).resolve().parent / "q36_venc.py"))
ap.add_argument("--model", required=True)
ap.add_argument("--mmproj", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--pic", action="append", required=True)
ap.add_argument("--lock", default="")
ap.add_argument("--n", type=int, default=24)
ap.add_argument("--q36-args", default="--vision --max-context 4096")
ap.add_argument("--floor", action="store_true", help="also llama.cpp CPU (ngl 0) vs HIP")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
rows = []
for pic in a.pic:
name = os.path.basename(pic)
# the encoder's file (strata-vision, CPU)
run([sys.executable, a.venc, a.vision, a.mmproj, a.model, pic], "", os.path.join(a.out, name + ".venc.log"))
emb = pic + ".sve"
for qi, q in enumerate(QUESTIONS.get(name, ["Describe this image."])):
tag = "%s.q%d" % (name, qi)
prompt = TEMPLATE.format(q=q)
ref_log = os.path.join(a.out, tag + ".llama.log")
logit_f = os.path.join(a.out, tag + ".llama.logits")
out = run([a.dump, "--model", a.model, "--mmproj", a.mmproj, "--image", pic, "--prompt", prompt, "--n", str(a.n),
"--dump-full-logits", logit_f, "--mm-cpu", "1", "--max-tokens", "1024"], a.lock, ref_log)
chunks, gen, first = parse_dump(out)
ids = []
for kind, v in chunks:
ids += v if kind == "text" else [PAD] * v
hdr = struct.unpack("<5i", open(emb, "rb").read(20))
assert hdr[1] == sum(v for k, v in chunks if k == "image"), "the encoders disagree on the token count %s vs %s" % (hdr, chunks)
q_logit_f = os.path.join(a.out, tag + ".q36.logits")
qout = run([a.q36, "--model", a.model, "--tokens", ",".join(map(str, ids)), "--emb", emb, "--n", str(a.n),
"--force", ",".join(map(str, gen[:-1])), "--dump-full-logits", q_logit_f, *shlex.split(a.q36_args)],
a.lock, os.path.join(a.out, tag + ".q36.log"))
qgen = [int(x) for x in [l for l in qout.splitlines() if l.startswith("gen:")][0].split(":", 1)[1].split()]
P = np.fromfile(logit_f, dtype=np.float32).reshape(-1, V)
Q = np.fromfile(q_logit_f, dtype=np.float32).reshape(-1, V)
kl, top1 = kl_stats(P, Q)
d5 = np.abs(np.sort(P[0])[-5:] - np.sort(Q[0])[-5:]).max()
row = {"tag": tag, "prompt_tokens": len(ids), "llama_gen": gen, "strata_gen_forced": qgen,
"first_top1_same": bool(P[0].argmax() == Q[0].argmax()), "first_max_top5_diff": float(d5),
"kl_mean": float(kl.mean()), "kl_first": float(kl[0]), "top1": float(top1.mean()), "steps": int(len(kl))}
if a.floor:
fl = os.path.join(a.out, tag + ".cpu.logits")
run([a.dump, "--model", a.model, "--mmproj", a.mmproj, "--image", pic, "--prompt", prompt, "--n", str(a.n),
"--dump-full-logits", fl, "--mm-cpu", "1", "--max-tokens", "1024", "--ngl", "0", "--force",
",".join(map(str, gen[:-1]))], "", os.path.join(a.out, tag + ".cpu.log"))
C = np.fromfile(fl, dtype=np.float32).reshape(-1, V)
klc, t1c = kl_stats(P, C)
row.update({"floor_kl_mean": float(klc.mean()), "floor_kl_first": float(klc[0]), "floor_top1": float(t1c.mean()),
"floor_first_max_top5_diff": float(np.abs(np.sort(P[0])[-5:] - np.sort(C[0])[-5:]).max())})
rows.append(row)
print(json.dumps({k: v for k, v in row.items() if k not in ("llama_gen", "strata_gen_forced")}), flush=True)
print(" llama :", gen[:16], flush=True)
print(" strata :", qgen[:16], "(teacher-forced on llama's ids: its own greedy at each step)", flush=True)
json.dump(rows, open(os.path.join(a.out, "summary.json"), "w"), indent=1)
if __name__ == "__main__":
main()
+91
View File
@@ -0,0 +1,91 @@
"""vision_proto.py - pictures over the engine protocol (GENI / BGENI), no server: the ids come from llama.cpp's own tokenizer
output (vc1/*.llama.log of vcmp.py), the rows from strata-vision (<picture>.sve).
python q36_vision_proto.py --exe E --args "--model M --max-context 8192 --vision --batch 4" --vc DIR --pics DIR
Checks: 1. a solo GENI answers like llama.cpp's greedy (the first 24 tokens); 2. two pictures and a text prompt decoding
together (BGENI / BGEN) give each the tokens of its solo run; 3. the conversation cache: the same request again and a
longer one (the first, its answer and more text) reuse the held state, a different picture does not; a text request after
a picture request is not disturbed (the rotary offset is back at 0)."""
from pathlib import Path
import argparse, json, os, shlex, sys
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
from q36_harness import Eng, load_prompts
PAD = 248056
def case(vc, pics, name, q):
log = open(os.path.join(vc, "%s.q%d.llama.log" % (name, q))).read()
ids, gen = [], []
for l in log.splitlines():
if l.startswith("text:"):
ids += [int(x) for x in l.split(":", 1)[1].split()]
elif l.startswith("image:"):
ids += [PAD] * int(l.split()[1])
elif l.startswith("gen:"):
gen = [int(x) for x in l.split(":", 1)[1].split()]
return ids, gen, os.path.join(pics, name + ".sve")
ap = argparse.ArgumentParser()
ap.add_argument("--exe", required=True)
ap.add_argument("--args", default="")
ap.add_argument("--vc", required=True)
ap.add_argument("--pics", required=True)
ap.add_argument("--n", type=int, default=24)
ap.add_argument("--log", default=None)
a = ap.parse_args()
eng = Eng(a.exe, shlex.split(a.args), log=a.log)
print("ready", eng.ready, eng.info, flush=True)
ok = True
S0, G0, E0 = case(a.vc, a.pics, "shapes.png", 0)
S1, G1, E1 = case(a.vc, a.pics, "shapes.png", 1)
C0, GC0, EC0 = case(a.vc, a.pics, "code4217.png", 0)
C1, GC1, EC1 = case(a.vc, a.pics, "code4217.png", 1)
# 1. solo vs llama.cpp's greedy
solo = {}
for tag, (ids, gen, emb) in {"shapes.q0": (S0, G0, E0), "shapes.q1": (S1, G1, E1), "code.q0": (C0, GC0, EC0),
"code.q1": (C1, GC1, EC1)}.items():
toks, done, ttft, wall = eng.solo(ids, a.n, emb=emb)
solo[tag] = toks
k = next((i for i in range(min(len(toks), len(gen))) if toks[i] != gen[i]), None)
print("solo %-10s %d tokens, vs llama.cpp greedy: %s | %s" % (tag, len(toks), "same %d tokens" % len(toks) if k is None else "first difference at %d" % k, done[:60]), flush=True)
# 2. batch: two pictures + a text prompt
text = load_prompts(str(Path(__file__).resolve().parent / "parity_prompts.ids"))[0]
t_toks, _, _, _ = eng.solo(text, a.n)
reqs = [{"ids": S1, "n": a.n, "slot": 0, "emb": E1}, {"ids": C1, "n": a.n, "slot": 1, "emb": EC1},
{"ids": text, "n": a.n, "slot": 2}]
r = eng.batch(reqs)
eq = [r["tokens"][0] == solo["shapes.q1"], r["tokens"][1] == solo["code.q1"], r["tokens"][2] == t_toks]
print("batch (2 pictures + 1 text): identical to solo %s" % eq, flush=True)
ok &= all(eq)
# slot reuse: the same again into other slots
r2 = eng.batch([{"ids": C1, "n": a.n, "slot": 3, "emb": EC1}, {"ids": S1, "n": a.n, "slot": 0, "emb": E1}])
eq2 = [r2["tokens"][0] == solo["code.q1"], r2["tokens"][1] == solo["shapes.q1"]]
print("batch again (slot 3 new, slot 0 held): identical %s" % eq2, flush=True)
ok &= all(eq2)
# 3. the conversation cache (solo path)
def reused(done):
return int(done.split()[8])
toks1, done1, _, _ = eng.solo(S0, 16, emb=E0)
toks1b, done1b, _, _ = eng.solo(S0, 16, emb=E0)
print("same request again (a state that has moved past the prompt cannot step back: no reuse): reused %d of %d, tokens %s" % (reused(done1b), len(S0), "same" if toks1b == toks1 else "DIFFERENT"), flush=True)
ok &= toks1b == toks1
longer = S0 + toks1 + text[:12]
toks2, done2, _, _ = eng.solo(longer, 16, emb=E0)
print("longer request (picture + answer + more): reused %d of %d" % (reused(done2), len(longer)), flush=True)
ok &= reused(done2) >= len(S0)
toks3, done3, _, _ = eng.solo(C0, 16, emb=EC0) # a different picture
print("a different picture: reused %d" % reused(done3), "tokens vs its solo: %s" % ("same" if toks3 == solo["code.q0"][:16] else "DIFFERENT"), flush=True)
ok &= toks3 == solo["code.q0"][:16]
t2, done4, _, _ = eng.solo(text, a.n)
print("a text request after pictures: tokens vs the text solo: %s" % ("identical" if t2 == t_toks else "DIFFERENT"), flush=True)
ok &= t2 == t_toks
eng.close()
print("GATE", "PASS" if ok else "FAIL")
sys.exit(0 if ok else 1)
+20
View File
@@ -0,0 +1,20 @@
"""vq.py PORT IMG [IMG2] : the picture questions through the server (chat completions, image_url data URL), greedy,
thinking off. Prints each answer and the usage."""
import base64, json, sys, time, urllib.request
port, img = sys.argv[1], sys.argv[2]
QS = {"code4217.png": ["What text is written in the image? Answer with the text only.",
"Describe the shapes in the image with their colours and positions, one short line each."],
"shapes.png": ["What text is written in the image? Answer with the text only.",
"List every shape in the image with its colour, from left to right. One short line each."]}
name = img.rsplit("/", 1)[-1]
b64 = base64.b64encode(open(img, "rb").read()).decode()
for q in QS.get(name, ["Describe this image."]):
body = {"model": "x", "max_tokens": 120, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}},
{"type": "text", "text": q}]}]}
t0 = time.time()
r = json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions",
json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=900).read())
print("Q:", q)
print("A:", repr(r["choices"][0]["message"]["content"]), "%.1fs" % (time.time() - t0))
print("usage", r.get("usage"), flush=True)