Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

qwen35: a conversation's held tokens match its state exactly (no drafts past the end of an answer or a stop), reads give the decoding slots windows, pictures x2 check

Niko12213921f57eea8a
diff --git a/docs/QWEN36.md b/docs/QWEN36.md
index 76efb57df..607d08e32 100644
--- a/docs/QWEN36.md
+++ b/docs/QWEN36.md
@@ -20,7 +20,7 @@ and `--vision-tokens N` work as there. A card under 16 GB is recommended the CPU
| Encoder | Time per picture (640x400 = 260 tokens / 800x450 = 350 tokens) | VRAM |
| --- | --- | --- |
-| GPU, RTX 3060 | 0.10 s / 0.15 s | 1.18 GiB at up to 1,024 tokens (1.34 GiB at 2,048) |
+| GPU, RTX 3060 | 0.10 s / 0.15 s | 1,179 MiB at up to 1,024 tokens (1,337 MiB at 2,048), CUDA context included |
| CPU, 32 threads (R9700 box) | 0.9 s / 1.1 s | none |
| CPU, 10 threads (3060 box) | 1.6 s / 2.1 s | none |
@@ -105,3 +105,16 @@ solo run there too, with and without `--batch-mtp`.
- A slot that stopped being alone goes back to the solo path only through the server's own hand-over; the MTP block's cache has holes for
the tokens a slot decoded in batch windows (the drafts of a later solo stretch are a little worse; the text is not affected).
- Intel Arc (SYCL) does not run this family.
+
+## Testing
+
+The gates are in `tools/qwen35/` and talk to the engine through its serve protocol (no server needed); run them under the box's GPU lock:
+
+- `q36_solo_gate.py` + `q36_cmp_gate.py`: the 10 parity prompts x 128 greedy tokens through `GEN`, compared with another build's.
+- `q36_batch_gate.py --slots N --waves --long 2500`: every slot's tokens equal its solo tokens, slots reused, a long prompt read beside
+ decoding slots. `q36_proto_edge.py`: `max_new` 1, `BSTOP`, a busy slot, `STOP` during a prompt read, held-state reuse, sampled requests,
+ the context's end. `q36_interleave_probe.py`: what the decoding slots see while a long prompt is read.
+- `q36_vision_cmp.py` (with `q36_mtmd_dump.cpp` built against llama.cpp): the picture comparison above; `q36_vision_proto.py`: pictures through
+ `GENI` / `BGENI` (solo, in a batch, the conversation cache); `q36_vision_serve.py` and `q36_serve_par.py` / `q36_serve_handoff.py`:
+ the same through the server.
+- `q36_par_bench.py`: the aggregate-throughput A/B against `llama-server -np N`.
diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu
index ff532355a..215f0194d 100644
--- a/src/qwen35/q36_engine.cu
+++ b/src/qwen35/q36_engine.cu
@@ -2285,7 +2285,13 @@ struct Engine {
/// tokens of the rows the block must redo first (the drafts the last window accepted, seeded by hmain rows
/// 0 .. fix.size() - 1 of that window). Drafts d1 .. dD, then the window [x, d1 .. dD] through the main model;
/// returns the accepted count a and writes the picks of rows 0 .. a (row a's pick is the token after them).
- int spec_step(int x_tok, const std::vector<int32_t>& fix, int D, std::vector<int32_t>& drafts, int32_t* picks) {
+ /// `max_a`: at most that many drafts are taken (the answer has room for max_a + 1 more tokens, the last of which is
+ /// not fed, as in plain decoding); and no draft past an end-of-answer token is taken (that token is the next one the
+ /// caller emits). So the state ends exactly where plain decoding would leave it.
+ /// `cancel`: a stop asked for before the state moves keeps only x (the caller then emits no draft: every token emitted but
+ /// the last is in the state, so a conversation that continues from the held tokens loses and repeats nothing).
+ int spec_step(int x_tok, const std::vector<int32_t>& fix, int D, std::vector<int32_t>& drafts, int32_t* picks,
+ int max_a = 1 << 20, const std::atomic<bool>* cancel = nullptr) {
const int N = (int) m->g.n_embd;
if (main_hybrid) D = std::min<int>(D, (int) (kRebalanceEvery - pos % kRebalanceEvery) - 1);
const int T0 = (int) fix.size() + 1; // the redo rows and the row of x
@@ -2336,6 +2342,10 @@ struct Engine {
CK(cudaStreamSynchronize(st));
int a = 0;
while (a < D && hpin[2 + a] == drafts[(size_t) a]) ++a;
+ a = std::min(a, max_a);
+ if (cancel != nullptr && cancel->load()) a = 0;
+ for (int i = 0; i < a; ++i)
+ if (drafts[(size_t) i] == 248044 || drafts[(size_t) i] == 248046) { a = i; break; } // (<|endoftext|>, <|im_end|>)
for (int i = 0; i <= a; ++i) picks[i] = hpin[2 + i];
commit(a + 1);
CK(cudaMemcpyAsync(hlast, hmain + (size_t) a * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st));
@@ -2765,8 +2775,13 @@ struct Serve {
std::vector<Slot> slots;
int n_active = 0;
std::vector<float> lg;
+ // decode windows of the other slots between two chunks of a prompt read: STRATA_Q36_READ_WINDOWS (default 1; a chunk
+ // takes ~0.15 s at 512 tokens, a window ~0.012 s: more windows give the decoding slots more of the time a read takes)
+ int read_windows = 1;
- explicit Serve(Engine& e) : E(e), slots((size_t) e.n_sess) {}
+ explicit Serve(Engine& e) : E(e), slots((size_t) e.n_sess) {
+ if (const char* v = std::getenv("STRATA_Q36_READ_WINDOWS")) read_windows = std::max(0, std::min(64, std::atoi(v)));
+ }
/// BSTOP / BYIELD lines among the queued ones: applied now (a window is a moment away at most).
void poll_control() {
@@ -3122,8 +3137,13 @@ struct Serve {
std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) fresh, ms_since(t0),
(double) done / std::max(1e-9, ms_since(t0) / 1000.0));
std::fflush(stdout);
- if (n_active > 0 && done < fresh) window(); // the slots decoding go on between a read's chunks (the
- else poll_control(); // last chunk's logits must stay for the first token)
+ if (n_active > 0 && done < fresh) {
+ poll_control();
+ // the slots decoding go on between a read's chunks (the last chunk's
+ for (int w = 0; w < read_windows && n_active > 0; ++w) window(); // logits must stay for the first token)
+ } else {
+ poll_control();
+ }
if (stop.load() && done < fresh) { cancelled = true; return false; }
return true;
});
@@ -3186,10 +3206,12 @@ struct Serve {
}
std::printf("BADM %d %d\n", slot, cont ? 1 : 0);
std::fflush(stdout);
+ std::fprintf(stderr, "strata batch: slot %d takes a prompt of %zu tokens = %zu reused + %lld read in %.0f ms (%.1f "
+ "tok/s)%s\n", slot, ids.size(), reuse, (long long) fresh, prompt_ms,
+ prompt_ms > 0 ? 1000.0 * (double) fresh / prompt_ms : 0.0, cont ? "" : ", done at once");
return;
}
- bool done = false;
- while (!done) {
+ for (;;) {
if (smp.needs_logits()) {
E.host_logits(lg);
nx = sample(lg, smp, hist, rng);
@@ -3207,15 +3229,21 @@ struct Serve {
if (!emit(nx)) break;
if (n_active > 0) window();
if (spec && n_active == 0 && E.pos + E.mtp_d + 1 <= E.ctx) {
- const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks);
+ const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks, (int) std::min<long long>(max_new - produced - 1, 1 << 20), &stop);
offered += E.mtp_d;
accepted += a;
+ // the state now holds x and the accepted drafts - spec_step took none past an end-of-answer token or past
+ // the room max_new leaves, so the state ends where plain decoding leaves it (the last token emitted is not
+ // fed) and a later request that continues this conversation neither misses nor reads a token twice
ss.live.push_back(nx);
+ for (int i = 0; i < a; ++i) ss.live.push_back(drafts[(size_t) i]);
fix.assign(drafts.begin(), drafts.begin() + a);
- for (int i = 0; i < a; ++i) {
- ss.live.push_back(drafts[(size_t) i]);
- if (!emit(drafts[(size_t) i])) { done = true; break; }
+ for (int i = 0; i < a; ++i) { // (all of them: they are in the state; a stop is seen at the next token)
+ std::printf("T %d\n", drafts[(size_t) i]);
+ ++produced;
+ hist.push_back(drafts[(size_t) i]);
}
+ std::fflush(stdout);
nx = picks[a];
continue;
}
@@ -3231,6 +3259,10 @@ struct Serve {
std::printf("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms,
decode_ms, finish, accepted, offered, reuse, (long long) fresh);
std::fflush(stdout);
+ std::fprintf(stderr, "strata serve: session %d: prompt %zu tokens = %zu reused + %lld read in %.0f ms (%.1f tok/s), "
+ "%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld (%s)\n", s, ids.size(), reuse,
+ (long long) fresh, prompt_ms, prompt_ms > 0 ? 1000.0 * (double) fresh / prompt_ms : 0.0, produced,
+ decode_ms, decode_ms > 0 ? 1000.0 * (double) produced / decode_ms : 0.0, accepted, offered, finish);
}
int run() {
diff --git a/tools/qwen35/make_big_picture.py b/tools/qwen35/make_big_picture.py
new file mode 100644
index 000000000..98ef33bfd
--- /dev/null
+++ b/tools/qwen35/make_big_picture.py
@@ -0,0 +1,27 @@
+"""make_big_picture.py OUT : a 1024x1024 test picture (about 1,024 image tokens, a prompt that spans several chunks): a heading, a
+few lines of small text and coloured shapes on white."""
+import sys
+from PIL import Image, ImageDraw, ImageFont
+
+im = Image.new("RGB", (1024, 1024), "white")
+d = ImageDraw.Draw(im)
+
+
+def font(size, bold=True):
+ for f in (("arialbd.ttf" if bold else "arial.ttf"), "C:/Windows/Fonts/arialbd.ttf",
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"):
+ try:
+ return ImageFont.truetype(f, size)
+ except OSError:
+ pass
+ return ImageFont.load_default()
+
+
+d.text((90, 60), "INVOICE 20261014", fill="black", font=font(96))
+d.text((90, 200), "Total due: 1337 EUR", fill=(20, 20, 160), font=font(64))
+for i, line in enumerate(["Item 1 widgets x 12", "Item 2 gears x 7", "Item 3 springs x 30"]):
+ d.text((90, 320 + 70 * i), line, fill="black", font=font(48, False))
+d.ellipse([560, 600, 960, 1000], fill=(30, 160, 60))
+d.rectangle([90, 640, 430, 980], fill=(220, 30, 30))
+im.save(sys.argv[1])
+print("wrote", sys.argv[1])
diff --git a/tools/qwen35/pictures/big1024.png b/tools/qwen35/pictures/big1024.png
new file mode 100644
index 000000000..b58d7023c
Binary files /dev/null and b/tools/qwen35/pictures/big1024.png differ
diff --git a/tools/qwen35/q36_interleave_probe.py b/tools/qwen35/q36_interleave_probe.py
new file mode 100644
index 000000000..f838671ee
--- /dev/null
+++ b/tools/qwen35/q36_interleave_probe.py
@@ -0,0 +1,79 @@
+"""q36_interleave_probe.py --exe E --args "..." [--long 3000] [--slots 3] : what the slots that are decoding see while a new
+request's long prompt is read: the tokens they produce during the read, and their longest pause between two tokens, against the
+same without a read. The read goes chunk by chunk with one decode window of the other slots between two chunks.
+
+ python tools/qwen35/q36_interleave_probe.py --exe build/strata-q36 --args "--model M --max-context 8192 --batch 4" --long 3000
+"""
+import argparse, shlex, sys, time
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from q36_harness import Eng, load_prompts
+
+ap = argparse.ArgumentParser()
+ap.add_argument("--exe", required=True)
+ap.add_argument("--args", default="")
+ap.add_argument("--long", type=int, default=3000)
+ap.add_argument("--slots", type=int, default=3, help="slots decoding while the long prompt is read")
+ap.add_argument("--n", type=int, default=600)
+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"))
+filler = []
+while len(filler) < a.long:
+ for p in P:
+ filler += p[3:-8]
+longids = filler[:a.long] + P[1][-8:]
+stamps = {s: [] for s in range(a.slots)}
+for s in range(a.slots): # admit the decoding slots
+ ids = P[[0, 1, 2, 3, 5, 8][s % 6]]
+ eng.send("BGEN %d %d %s" % (s, a.n, ",".join(map(str, ids))))
+ while True:
+ l = eng.line()
+ if l.startswith("BADM"):
+ break
+ if l.startswith("BT "):
+ stamps[int(l.split()[1])].append(time.time())
+# 1. a stretch of decoding with no read
+t_end = time.time() + 1.0
+while time.time() < t_end:
+ l = eng.line()
+ if l.startswith("BT "):
+ stamps[int(l.split()[1])].append(time.time())
+base = {s: v[:] for s, v in stamps.items()}
+# 2. the long request
+t0 = time.time()
+eng.send("BGEN %d 8 %s" % (a.slots, ",".join(map(str, longids))))
+pp = []
+t_adm = None
+while True:
+ l = eng.line()
+ now = time.time()
+ if l.startswith("BT "):
+ stamps[int(l.split()[1])].append(now)
+ elif l.startswith("PP "):
+ pp.append(now)
+ elif l.startswith("BADM"):
+ t_adm = now
+ break
+read_s = t_adm - t0
+during = {s: [t for t in v if t0 <= t <= t_adm] for s, v in stamps.items()}
+
+
+def gaps(v):
+ return [b - a_ for a_, b in zip(v, v[1:])]
+
+
+rate0 = sum(len(v) for s, v in base.items()) / max(1e-9, 1.0) if False else None
+n_during = sum(len(v) for v in during.values())
+mx = max((max(gaps(v)) for v in during.values() if len(v) > 1), default=0.0)
+mx0 = max((max(gaps(v[-60:])) for v in base.values() if len(v) > 2), default=0.0)
+print("a prompt of %d tokens read in %.2f s (%d chunks, %.0f tok/s) beside %d decoding slots" % (len(longids), read_s, len(pp),
+ len(longids) / read_s, a.slots))
+print("the %d decoding slots produced %d tokens during the read (%.1f tok/s together); longest pause between two tokens of a slot %.0f ms"
+ " (while only decoding: %.0f ms)" % (a.slots, n_during, n_during / read_s, 1000 * mx, 1000 * mx0))
+for s in range(a.slots):
+ eng.send("BSTOP %d" % s)
+eng.send("BSTOP %d" % a.slots)
+time.sleep(1.0)
+eng.close()
diff --git a/tools/qwen35/q36_mtmd_dump.cpp b/tools/qwen35/q36_mtmd_dump.cpp
index 55519bc32..af208b271 100644
--- a/tools/qwen35/q36_mtmd_dump.cpp
+++ b/tools/qwen35/q36_mtmd_dump.cpp
@@ -6,7 +6,7 @@
// Built against a llama.cpp checkout with its mtmd library (not part of Strata's build):
// g++ -O2 -std=c++17 q36_mtmd_dump.cpp -I<llama>/include -I<llama>/ggml/include -I<llama>/tools/mtmd -L<llama>/build/bin
// -lllama -lmtmd -lggml -lggml-base -Wl,-rpath,<llama>/build/bin -o q36_mtmd_dump
-// Usage: q36_mtmd_dump --model GGUF --mmproj F --image F --prompt TEXT [--n 32] [--ngl 99] [--max-tokens N] [--mm-cpu 1]
+// Usage: q36_mtmd_dump --model GGUF --mmproj F --image F [--image F2 ...] --prompt TEXT [--n 32] [--ngl 99] [--max-tokens N] [--mm-cpu 1]
// [--dump-full-logits F] [--force ID,ID,...]
// TEXT holds one <__media__> marker where the picture goes (the chat template's user turn); it is tokenized with
// special tokens parsed and no BOS. --force feeds that continuation instead of the greedy ids (teacher forcing).
@@ -33,13 +33,14 @@ static std::vector<int> parse_ids(const std::string& s) {
}
int main(int argc, char** argv) {
- std::string model, mmproj, image, prompt, dump_full, force;
+ std::string model, mmproj, prompt, dump_full, force;
+ std::vector<std::string> images;
int n_gen = 32, ngl = 99, max_tokens = 0, mm_cpu = 0;
for (int i = 1; i + 1 < argc; i += 2) {
const std::string a = argv[i], v = argv[i + 1];
if (a == "--model") model = v;
else if (a == "--mmproj") mmproj = v;
- else if (a == "--image") image = v;
+ else if (a == "--image") images.push_back(v); // repeat for several pictures (one <__media__> each)
else if (a == "--prompt") prompt = v;
else if (a == "--n") n_gen = std::atoi(v.c_str());
else if (a == "--ngl") ngl = std::atoi(v.c_str());
@@ -68,12 +69,17 @@ int main(int argc, char** argv) {
if (max_tokens > 0) mcp.image_max_tokens = max_tokens;
mtmd_context* mctx = mtmd_init_from_file(mmproj.c_str(), mdl, mcp);
if (!mctx) { std::fprintf(stderr, "cannot load %s\n", mmproj.c_str()); return 1; }
- mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(mctx, image.c_str(), false, mtmd_helper_init_opt_default());
- if (!bw.bitmap) { std::fprintf(stderr, "cannot read %s\n", image.c_str()); return 1; }
+ std::vector<mtmd_helper_bitmap_wrapper> bws;
+ std::vector<const mtmd_bitmap*> bms;
+ for (const std::string& image : images) {
+ mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(mctx, image.c_str(), false, mtmd_helper_init_opt_default());
+ if (!bw.bitmap) { std::fprintf(stderr, "cannot read %s\n", image.c_str()); return 1; }
+ bws.push_back(bw);
+ bms.push_back(bw.bitmap);
+ }
mtmd_input_chunks* chunks = mtmd_input_chunks_init();
mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true};
- const mtmd_bitmap* bms[1] = {bw.bitmap};
- if (mtmd_tokenize(mctx, chunks, &txt, bms, 1) != 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; }
+ if (mtmd_tokenize(mctx, chunks, &txt, bms.data(), bms.size()) != 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; }
const size_t nc = mtmd_input_chunks_size(chunks);
llama_pos n_past = 0;
for (size_t c = 0; c < nc; ++c) {
@@ -123,7 +129,7 @@ int main(int argc, char** argv) {
std::printf("\n");
if (ff) std::fclose(ff);
mtmd_input_chunks_free(chunks);
- mtmd_bitmap_free(bw.bitmap);
+ for (auto& bw : bws) mtmd_bitmap_free(bw.bitmap);
mtmd_free(mctx);
llama_free(ctx);
llama_model_free(mdl);
diff --git a/tools/qwen35/q36_par_bench.py b/tools/qwen35/q36_par_bench.py
index 7d902d25c..f9718114b 100644
--- a/tools/qwen35/q36_par_bench.py
+++ b/tools/qwen35/q36_par_bench.py
@@ -21,11 +21,16 @@ def strata(a):
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"]}
+ if n == 1 and not eng.info.get("batch_slots"): # an engine without slots: the request alone (GEN)
+ toks, done, ttft, wall = eng.solo(prompts[ORDER[0]], a.n)
+ row = {"engine": "strata", "n": 1, "round": rnd, "tokens": len(toks), "wall": wall,
+ "tok_s": len(toks) / wall, "tail_tok_s": len(toks) / max(1e-9, wall - (ttft or 0))}
+ else:
+ 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()
diff --git a/tools/qwen35/q36_serve_handoff.py b/tools/qwen35/q36_serve_handoff.py
new file mode 100644
index 000000000..96b60ce0c
--- /dev/null
+++ b/tools/qwen35/q36_serve_handoff.py
@@ -0,0 +1,46 @@
+"""q36_serve_handoff.py PORT [--n 300] : a request that runs alone (the solo path, with MTP drafts), another one arrives while it
+runs (the server stops it and continues it in a batch slot from its held state), the second one ends (the first is alone again and
+goes back to the solo path): the first request's text must be the text of the same request run entirely alone. Greedy, thinking
+off, every expert in VRAM (in the hybrid mode a different window mix can round differently: see docs/QWEN36.md).
+
+ python tools/qwen35/q36_serve_handoff.py 8199 [--n 300] [--delay 1.0]
+"""
+import argparse, json, sys, threading, time, urllib.request
+
+A = "Write a long, detailed story about a lighthouse keeper who finds a message in a bottle and follows it across the sea."
+B = "List the first twenty prime numbers and explain how you found them."
+
+
+def ask(port, text, n, out, key):
+ body = {"model": "x", "max_tokens": n, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False},
+ "messages": [{"role": "user", "content": text}]}
+ 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())
+ out[key] = (r["choices"][0]["message"]["content"], r["usage"]["completion_tokens"], time.time() - t0)
+
+
+ap = argparse.ArgumentParser()
+ap.add_argument("port", type=int)
+ap.add_argument("--n", type=int, default=300)
+ap.add_argument("--delay", type=float, default=1.0)
+a = ap.parse_args()
+alone = {}
+ask(a.port, A, a.n, alone, "A")
+ask(a.port, B, 60, alone, "B")
+for rnd in range(2):
+ mix = {}
+ ta = threading.Thread(target=ask, args=(a.port, A, a.n, mix, "A"))
+ tb = threading.Thread(target=lambda: (time.sleep(a.delay), ask(a.port, B, 60, mix, "B")))
+ ta.start()
+ tb.start()
+ ta.join()
+ tb.join()
+ ea, eb = mix["A"][0] == alone["A"][0], mix["B"][0] == alone["B"][0]
+ print("round %d: A %d tokens in %.1fs, B %d tokens in %.1fs; A equals its run alone: %s; B equals its run alone: %s"
+ % (rnd, mix["A"][1], mix["A"][2], mix["B"][1], mix["B"][2], ea, eb), flush=True)
+ if not (ea and eb):
+ x, y = mix["A"][0], alone["A"][0]
+ k = next((i for i in range(min(len(x), len(y))) if x[i] != y[i]), min(len(x), len(y)))
+ print(" A first differs from its run alone at character %d of %d: %r vs %r" % (k, len(y), x[max(0, k - 20):k + 30],
+ y[max(0, k - 20):k + 30]))
diff --git a/tools/qwen35/q36_vision_cmp.py b/tools/qwen35/q36_vision_cmp.py
index 2101f451d..59c5a7e14 100644
--- a/tools/qwen35/q36_vision_cmp.py
+++ b/tools/qwen35/q36_vision_cmp.py
@@ -23,6 +23,9 @@ QUESTIONS = {
}
TEMPLATE = "<|im_start|>user\n<__media__>{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
PAD = 248056
+TEMPLATE_PAIR = ("<|im_start|>user\nPicture 1: <__media__>\nPicture 2: <__media__>\n{q}<|im_end|>\n<|im_start|>assistant\n"
+ "<think>\n\n</think>\n\n")
+PAIR_QUESTIONS = ["What text is written in each of the two pictures? One short line for each."]
def run(cmd, lock, log, env=None):
@@ -73,7 +76,7 @@ def main():
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("--pic", action="append", required=True, help="a picture, or a+b for one request with two pictures")
ap.add_argument("--lock", default="")
ap.add_argument("--n", type=int, default=24)
ap.add_argument("--q36-args", default="--vision --max-context 4096")
@@ -81,24 +84,34 @@ def main():
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."])):
+ for pic_spec in a.pic:
+ pics = pic_spec.split("+") # "a.png+b.png": one request with two pictures (one <__media__> each)
+ name = "+".join(os.path.basename(p) for p in pics)
+ # the encoder's file (strata-vision, CPU): one record per picture, in prompt order
+ run([sys.executable, a.venc, a.vision, a.mmproj, a.model, *pics], "", os.path.join(a.out, name + ".venc.log"))
+ emb = os.path.join(a.out, name + ".sve")
+ with open(emb, "wb") as f:
+ for p in pics:
+ f.write(open(p + ".sve", "rb").read())
+ questions = QUESTIONS.get(name, ["Describe this image."] if len(pics) == 1 else PAIR_QUESTIONS)
+ for qi, q in enumerate(questions):
tag = "%s.q%d" % (name, qi)
- prompt = TEMPLATE.format(q=q)
+ prompt = TEMPLATE.format(q=q) if len(pics) == 1 else TEMPLATE_PAIR.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),
+ out = run([a.dump, "--model", a.model, "--mmproj", a.mmproj, *sum([["--image", p] for p in pics], []),
+ "--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)
+ tot_rows, off, data = 0, 0, open(emb, "rb").read()
+ while off < len(data): # the records' row counts
+ h = struct.unpack("<5i", data[off:off + 20])
+ tot_rows += h[1]
+ off += 20 + 4 * h[1] * h[4]
+ assert tot_rows == sum(v for k, v in chunks if k == "image"), "the encoders disagree on the token count %d vs %s" % (tot_rows, 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)],