Merge f-q36-vp (Qwen3.6 parallel requests and pictures)

This commit is contained in:
Niko1221 committed 2026-10-14 06:51:43 +02:00
commit db4dd65e56
26 files changed
+2691 -134

No files matched your search

+3
View File
@@ -9,6 +9,9 @@ conversations at the same time instead of waiting for each other.
It is opt-in and changes nothing when the options are absent (#465; the engine part is PR #559).
**Qwen3.6-35B-A3B** has the same option on its own engine path (`"parallel": N`, `--batch N`, `--batch-mtp`, up to 8 slots, the same
engine protocol and the same server): its numbers, what a slot costs and where setup recommends it are in [QWEN36.md](QWEN36.md).
## Turning it on
One GPU: add `"parallel": 2` to the model's config (`strata-<model>.json`) and restart, or run setup with
+2
View File
@@ -1463,6 +1463,8 @@ The config snippets for every client, the tool arguments and the safety rules ar
## Images (vision)
(Qwen3.6-35B-A3B reads pictures the same way, with its own `mmproj-F16.gguf`: [QWEN36.md](QWEN36.md).)
The model has a vision encoder: [`mmproj-Qwen3.8-Flash-Next-BF16.gguf`](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF)
(0.9 GB, a 27-layer ViT plus the projector into the language model). It is **optional**: say yes when the setup asks
"Images?", or run it again with `--vision gpu` (or `--vision cpu`). The setup downloads the encoder, builds a small
+137
View File
@@ -0,0 +1,137 @@
# Qwen3.6-35B-A3B: pictures and several requests at once
Strata runs [Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B) (35B mixture of experts, 3B active, 256 experts, top-8) from
[Unsloth's GGUFs with the MTP layer](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-MTP-GGUF) (UD-Q4_K_XL, UD-Q6_K_XL, Q8_0) on its own
engine path (`src/qwen35`; `strata` switches to it from the file's architecture). Pick it in setup (`--family qwen36`). Besides text it
reads **pictures** and serves **several requests at once**, the same two options the Flash-Next models have.
Measured on an AMD Radeon AI PRO R9700 32 GB (HIP, Linux, UD-Q4_K_XL, every expert in VRAM) and on an RTX 3060 12 GB (CUDA, 20 threads,
UD-Q4_K_XL in the hybrid mode: 22-37 of 256 experts per layer in VRAM, the rest on the CPU), llama.cpp 972b5fc on the same files.
## Pictures
The vision encoder is Unsloth's `mmproj-F16.gguf` (0.9 GB, pinned revision, SHA-256 checked by setup): a 27-layer ViT with a 2x2 merger,
the same projector family as the Flash-Next models' (`qwen3vl_merger`; only its output width differs: 2048 here, 2560 there). Strata runs
it with the same helper (`strata-vision`, llama.cpp's `mtmd`), so the encoder choices are the Flash-Next ones
([Images](DETAILS.md#images-vision)): **setup asks "Do you want images?"**, the default answer is yes on an NVIDIA card of 16 GB or more
(GPU encoder, ~1.2 GB of VRAM at up to 1,024 image tokens) and on AMD under Linux (CPU encoder, no VRAM); `--vision yes|no|gpu|cpu`
and `--vision-tokens N` work as there. A card under 16 GB is recommended the CPU encoder (the GPU one takes room from the experts);
`--vision gpu` is kept as asked, with a note.
| Encoder | Time per picture (640x400 = 260 tokens / 800x450 = 350 tokens) | VRAM |
| --- | --- | --- |
| 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 |
A picture becomes up to 1,024 tokens of the context (the CPU default is 300). The engine puts the encoder's rows where the prompt has
`<|image_pad|>` tokens and gives every row its 2-D position, interleaved M-RoPE exactly as llama.cpp does for this model (rotary sections
11 / 11 / 10, a picture's rows at (t, h, w) = (p, p + row, p + column), the text after it continuing at p + max(columns, rows)).
**Checked against llama.cpp** (its `mtmd` and its own graph, the encoder on the CPU on both sides, the same prompt ids, the answer
llama.cpp gives fed to both so the logits are compared step by step, 24 steps; the "floor" is llama.cpp's CPU backend against its own
HIP run, the noise two correct engines have on this model):
| Picture and question | Prompt tokens | First token | Mean KL, llama.cpp HIP vs Strata | Floor (llama.cpp CPU vs HIP) |
| --- | ---: | --- | ---: | ---: |
| 640x400, text in the image | 288 | same | 0.029 | 0.056 |
| 640x400, list the shapes | 294 | same | 0.035 | 0.039 |
| 800x450, text in the image | 378 | same | 0.021 | 0.031 |
| 800x450, describe the shapes | 381 | same | 0.0005 | 0.0019 |
| 1024x1024, the title (1,024 image tokens, read in 3 chunks) | 1,042 | same | 0.0022 | 0.0026 |
| two pictures in one request, the text in each | 655 | differs (a near tie: the floor's KL at this step is 0.16 too) | 0.014 | 0.022 |
The answers are the same text as llama.cpp's: `STRATA 42` (with llama.cpp's own spelling ` STRATA42`), `CODE 4217`, `Red circle / Blue square
/ Green triangle`, `A red square is positioned on the left ... A blue circle is positioned on the right ...`. With the picture options on,
a request without pictures gives the same tokens as without them (10 prompts x 128 greedy tokens, identical).
Pictures work with several requests at once, with the MTP drafts and with the conversation cache: the same conversation sent again (a chat
app resends its pictures) continues from the held state when its pictures are the same (they are matched by the server's key for each
picture); a different picture starts that conversation again.
## Several requests at once
`"parallel": N` in the model's config (`strata-qwen36-<size>.json`, or `--parallel N` at setup) makes the engine keep N conversations open
(`--batch N`, up to 8) and decode them together: every window carries one token of each conversation, so the dense weights, the head and
every routed expert two conversations share are read once for all of them. The server needs no change: it speaks the same engine protocol
as for Flash-Next ([BATCHING.md](BATCHING.md)). A request that arrives while another is read waits only for that read: the prompt of a
new request is read **between** the decode windows of the others, and a conversation continues in the slot that holds its start (or the
engine copies the longer held start from another slot). A 3,008-token prompt read in 0.95 s (3,200 tok/s, 6 chunks) beside three decoding
slots: each of them paused at most 160 ms (one chunk) instead of the whole read, and produced 20 tokens meanwhile (one window per chunk,
the default); `STRATA_Q36_READ_WINDOWS=4` gives them 65 tokens during a 1.14 s read (more of the time, a slower read).
A request that runs alone (the solo path, with its MTP drafts) and is moved into a batch slot when another arrives, and back when it is
alone again, gives the text it gives running alone (the server's hand-over reuses the held state).
Aggregate decode speed, N requests at once, same prompts, greedy, 128 new tokens each, wall time from the first request to the last
answer, **R9700 32 GB, UD-Q4_K_XL, llama.cpp `llama-server -np N`** (5 interleaved pairs, median; Strata `--batch 8 --mtp 0`):
| Requests at once | Strata | llama.cpp | Ratio | Pairs faster |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 83.9 tok/s | 73.8 | 1.14 | 5/5 |
| 2 | 173.5 | 107.4 | 1.61 | 5/5 |
| 4 | 252.0 | 165.0 | 1.53 | 5/5 |
| 8 | 325.4 | 208.1 | 1.56 | 5/5 |
**RTX 3060 12 GB, UD-Q4_K_XL in the hybrid mode** (each engine with the slots it needs: `--batch N` takes room from the expert slots; llama.cpp
`llama-server -np N -ncmoe 28 -t 8`, the best split of a sweep on this card; 5 interleaved pairs, medians; the box was shared with other
jobs between runs, never during one):
| Requests at once | Strata | llama.cpp | Ratio | Pairs faster |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 64.0 tok/s | 41.1 | 1.56 | 5/5 |
| 2 | 85.1 | 52.5 | 1.62 | 5/5 |
| 4 | 99.3 | 63.0 | 1.58 | 5/5 |
Every slot's tokens equal the tokens of the same request alone (the base engine's), at 2, 4 and 8 slots, with a 2.5K-token prompt read beside
decoding slots, with slots reused for later requests, with pictures and with sampling (same seed). Through the server: four concurrent chat
requests give the texts of the same four one after the other.
**MTP drafts.** A request that has the engine to itself keeps its MTP drafts (the server sends it alone while nothing else runs). With
several requests the batch window has no drafts unless `--batch-mtp` is in the config's `args` (opt-in): every slot's window then also
carries the proposal its MTP block made (one per slot, up to the rows to spare in the 8-row window) and a confirmed proposal moves two
tokens in the window. Same prompts, 5 interleaved pairs, R9700:
| Requests at once | `--mtp 0` | `--mtp 2 --batch-mtp` | Ratio | Pairs faster |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 83.7 tok/s | 134.0 | 1.60 | 5/5 |
| 2 | 173.1 | 207.0 | 1.20 | 5/5 |
| 4 | 251.0 | 275.0 | 1.10 | 5/5 |
| 8 | 324.0 | 320.5 | 0.99 | 0/5 (no row to spare: no proposals) |
The text is the same with and without it (every slot equal to its solo tokens).
**What a slot costs.** Each slot keeps its own cache in VRAM: 1.5 GB at a context of 32K (fp32 keys and values of the 10 attention layers
and the MTP block, 45 KB per token) and 0.07 GB of recurrent state. Setup writes the context for one conversation, so N slots take N times
that from the room the experts would have: on a card that does not hold every expert (12 and 16 GB, the hybrid mode) that is room the
expert slots lose, and a batch reads more distinct experts from RAM. Setup therefore **recommends `--parallel` only where every expert still
fits** (about 3 on a 32 GB card at 32K) and says why it leaves it at one otherwise; any number you give is kept. It still pays on a card
that does not: on the RTX 3060 12 GB, `--batch 4` leaves 37 of 256 experts per layer in VRAM instead of 54, so a request alone decodes
64.7 tok/s instead of 68.3 (-5%, 3 interleaved runs each, medians of the 10 parity prompts), and four requests at once ran 99 tok/s together
against 64 for one (table above; each of them slower: ~25 tok/s). The engine says what the sessions take before it
allocates them and refuses (with the numbers) a count that cannot fit.
In the hybrid mode the text of a request can differ a little between running alone and running beside others: the experts that sit on the
GPU or on the CPU change with the routing of all the requests, and the two compute with different rounding. With the slot tables fixed (`STRATA_Q36_FIXED_SLOTS=1`, a test setting) every slot equals its
solo run there too, with and without `--batch-mtp`.
## Not done / limits
- Eight slots at most (the window holds 8 rows); `--batch-mtp` shares those rows between slots and proposals.
- A sampling request in a batch decodes one token per window without proposals. `logit_bias` is not available on this engine path: the
server refuses a request that has it (as it does with `--batch` for Flash-Next).
- 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`.
+48
View File
@@ -0,0 +1,48 @@
"""serve/test_q36_config.py - what the server hands the Qwen3.6-35B-A3B engine (arch qwen35moe): the config's pictures
("vision" section -> --vision) and parallel requests ("parallel": N -> --batch N), as for Flash-Next's engine.
python -m unittest serve.test_q36_config
"""
from __future__ import annotations
import unittest
from unittest import mock
from serve.server import engine_args, parallel_args
def cfg(**kw):
base = {"arch": "qwen35moe", "exe": "strata", "args": ["--native", "/m/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf",
"--max-context", "32768", "--prefill", "auto", "--mtp", "2"]}
base.update(kw)
return base
class Q36Config(unittest.TestCase):
def test_parallel_becomes_batch(self):
a = engine_args(cfg(parallel=4))
self.assertEqual(a[a.index("--batch") + 1], "4")
self.assertNotIn("--batch", engine_args(cfg()))
self.assertNotIn("--batch", engine_args(cfg(parallel=1)))
def test_more_than_the_window_is_said(self):
with mock.patch("builtins.print") as pr:
a = engine_args(cfg(parallel=12))
self.assertEqual(a[a.index("--batch") + 1], "12") # the engine caps it at 8 and says so
self.assertTrue(any("at most 8" in str(c) for c in pr.call_args_list))
def test_a_vision_section_starts_the_engine_with_pictures(self):
v = {"exe": "strata-vision", "mmproj": "/m/mmproj-F16.gguf", "model": "/m/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf",
"gpu": False, "max_tokens": 300}
self.assertIn("--vision", engine_args(cfg(vision=v)))
self.assertIn("--vision", engine_args(cfg(vision=v, args=cfg()["args"] + ["--vision"])))
self.assertEqual(engine_args(cfg(vision=v, args=cfg()["args"] + ["--vision"])).count("--vision"), 1)
self.assertNotIn("--vision", engine_args(cfg()))
def test_an_explicit_batch_in_the_args_wins(self):
c = cfg(parallel=4, args=cfg()["args"] + ["--batch", "2"])
self.assertEqual(parallel_args(c, c["args"]), [])
if __name__ == "__main__":
unittest.main()
+135 -7
View File
@@ -453,7 +453,10 @@ OWN_PATH_FAMILIES = {
# V in fp32 (strata-q36)
"kv_bytes_per_token": 11 * 2 * 256 * 2 * 4,
"mtp": 2, # drafts per step (greedy requests): measured best on the R9700
"vision": False}, # the image encoder for this family is not wired up yet
# pictures: Unsloth's mmproj (the same projector family as Flash-Next's: qwen3vl_merger) through
# strata-vision; a parallel slot's session: its KV cache (kv_bytes_per_token) and the recurrent state of
# the 30 GDN layers (state_gb)
"vision": True, "state_gb": 0.07}
}
PREVIEW_FAMILIES = OWN_PATH_FAMILIES # the earlier name (tools and tests that import it)
# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README
@@ -4579,8 +4582,9 @@ def choices_from_config(cfg_path: Path) -> dict:
size = next((m for m in d["models"] if m.lower() == tag[len(d["tag"]):].lower()), None)
a = cfg.get("args", [])
ctx = a[a.index("--max-context") + 1] if "--max-context" in a and a.index("--max-context") + 1 < len(a) else None
vis = cfg.get("vision")
return {"family": own, "model": size, "context": int(ctx) if ctx and ctx.isdigit() else None, "kv": None,
"vision": "none", "esp": "off", "host": cfg.get("host"), "api_key": cfg.get("api_key"),
"vision": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none", "esp": "off", "host": cfg.get("host"), "api_key": cfg.get("api_key"),
"port": cfg.get("port"), "gpu": cfg.get("gpu"), "layer_split": None,
"cuda": 12 if config_toolkit(cfg) == 12 else None, "vram_reserve_mib": None}
family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen")
@@ -5531,6 +5535,91 @@ def own_path_size(fam: dict, ram: float) -> str:
return max(fits, key=lambda m: fam["sha256"][fam["file"].format(q=m)][0]) if fits else next(iter(fam["models"]))
def own_path_vision(a, fam: dict, gpu: dict, hip: bool) -> str:
"""The image encoder for an own-path family (Qwen3.6-35B-A3B): "gpu", "cpu" or "none". The Flash-Next families' rules:
--vision yes|no|gpu|cpu, else a question whose default answer is yes where the GPU encoder costs little - an NVIDIA
card of 16 GB or more (its ~1.4 GB is under a tenth of it) - and, on AMD under Linux, yes with the CPU encoder (it takes
no VRAM; there is no GPU encoder for AMD yet). A smaller NVIDIA card is recommended the CPU encoder (the GPU one takes
room from the experts); what is asked for with --vision gpu is kept, with a note (recommend, never force)."""
asked = a.vision
vram = float(gpu.get("vram_gb", 0.0))
big = vram >= UNSLOTH_IMAGES_MIN_VRAM_GB
if asked in ("no", "none"):
return "none"
if asked is None:
say()
say(f" Images: {fam['title']} can also read pictures (screenshots, photos, scanned pages). This adds a "
f"{fam['sha256'][fam['mmproj']][0] / 1e9:.1f} GB download" + (
"; the encoder runs on the CPU (no VRAM), a few seconds per picture." if hip else
" and the image encoder runs on the GPU (~1.4 GB of VRAM kept free, 0.1-0.5 s per picture)." if big else
"; the encoder runs on the CPU (a few seconds per picture), because the GPU encoder would take ~1.4 GB "
"of VRAM from the experts on this card."))
default = "n" if (hip and WIN) else "y" if (big or hip) else "n"
if ask("Do you want images?", ["y", "n"], default, a.yes) != "y":
return "none"
asked = "cpu" if (hip or not big) else "gpu"
if hip:
if asked == "gpu":
say(" The AMD backend has no GPU image encoder yet: the encoder runs on the CPU.")
if WIN:
warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no "
"image encoder): images off")
return "none"
return "cpu"
if asked == "yes":
asked = "gpu" if big else "cpu"
if asked == "gpu" and not big and vram > 0:
warn(f"the GPU image encoder takes ~1.4 GB of VRAM, which on a {vram:.0f} GB card is room the experts would use: "
"--vision cpu reads pictures on the CPU instead (a few seconds each); kept as you chose")
return asked
def own_path_parallel_slot_gb(fam: dict, ctx: int) -> float:
"""The VRAM one batch slot's session takes: its KV cache (fp32 K and V of the attention layers and the MTP block) and
the recurrent state of the GDN layers."""
return ctx * fam["kv_bytes_per_token"] / 1e9 + fam["state_gb"]
def own_path_parallel_recommend(fam: dict, model: str, vram_gb: float, ctx: int) -> int:
"""How many requests at once to recommend: 0 = one at a time. Only where every routed expert still fits in VRAM with
the slots' sessions (a batch then reads each expert once for all its rows); where some experts run on the CPU the
batch reads more distinct experts from RAM and every slot's VRAM is room the expert slots lose."""
size = fam["sha256"][fam["file"].format(q=model)][0] / 1e9
base = size * 0.93 + 4.5 # the routed experts + the dense weights and buffers (the file's 7% beyond them)
slot = own_path_parallel_slot_gb(fam, ctx)
best = 0
for n in (2, 3, 4):
if base + (n + 1) * slot <= vram_gb:
best = n
return best
def own_path_parallel_note(a_parallel, fam: dict, model: str, vram_gb: float, ctx: int) -> list:
"""What setup says about "parallel" for an own-path family: the recommendation, or how the asked count compares with
it (kept as asked: recommend, never force)."""
rec = own_path_parallel_recommend(fam, model, vram_gb, ctx)
slot = own_path_parallel_slot_gb(fam, ctx)
if a_parallel is None or a_parallel <= 1:
if not rec:
return ["Several requests at once (opt-in, --parallel N): left at one at a time, because this card does not hold every "
"expert beside more sessions. Measured there (RTX 3060 12 GB), 4 requests together ran about 1.5x the speed "
"of one (99 against 64 tok/s) but each of them slower, and a request alone about 5% slower, as the "
"slots take VRAM from the expert cache (docs/QWEN36.md)."]
return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one after "
f"the other (each takes ~{slot:.1f} GB of VRAM at this context; docs/BATCHING.md)."]
lines = [f"parallel requests: {a_parallel} at once (each takes ~{slot:.1f} GB of VRAM at this context, "
f"{a_parallel * slot:.1f} GB in all)"]
if a_parallel > PARALLEL_MAX:
lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}")
if not rec:
lines.append("recommended for this card: one at a time - not every expert fits in VRAM beside more sessions; "
"kept as you chose")
elif a_parallel > rec:
lines.append(f"recommended for this card: {rec} - more slots leave fewer experts in VRAM, which can make every "
"request slower; kept as you chose")
return lines
def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
"""Steps 2-7 for a family with its own engine path (OWN_PATH_FAMILIES: Qwen3.6-35B-A3B): the size, the context, the
engine, the GGUF (pinned revision, size and SHA-256), the tokenizer from the GGUF, the config and the start
@@ -5582,8 +5671,8 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
warn(f"{ctx // 1024}K is past {fam['title']}'s trained 262,144 positions and this engine path has no rope "
"scaling yet: kept as you chose, but answers past 256K are untested")
ok(f"context: {ctx} tokens")
if a.vision not in (None, "no", "none"):
warn(f"images are not available with {fam['title']} yet: off")
vision = own_path_vision(a, fam, gpu, hip)
ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision])
if a.rope_scaling or a.rope_scale or a.kv or a.resident_budget_gib is not None or a.low_ram not in (None, "auto"):
warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} "
"does not use them")
@@ -5600,7 +5689,10 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
"numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil")
step(4, "the Strata engine")
llama, eng, meta, lib_dirs, gpu, _ = engine_step(a, gpu, hip, amd, cuda_tk, "none")
llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision)
if vision != "none" and not (eng / VEXE).exists():
warn("this engine has no image encoder: images off (run setup again with --build to compile it)")
vision = "none"
if fam["arch"] not in engine_families(eng):
fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet",
"update Strata, or compile the engine with --build, and run setup again")
@@ -5615,6 +5707,16 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
download(fam["hf"] + gguf.name, gguf)
verify_sha256(gguf, *fam["sha256"][gguf.name])
ok(f"model file: {gguf}")
mmproj = folder / fam["mmproj"]
if vision != "none": # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked
if mmproj.exists() and done(mmproj):
ok(f"{mmproj.name} already downloaded")
else:
if a.gguf_dir:
fail(f"{mmproj} is missing", f"put {mmproj.name} in {folder}, or drop --gguf-dir to download it")
download(fam["mmproj_hf"] + mmproj.name, mmproj, "vision encoder")
verify_sha256(mmproj, *fam["sha256"][mmproj.name])
ok(f"vision encoder: {mmproj}")
step(6, "preparing the model for Strata")
data, _ = data_folder(a.data_dir)
@@ -5649,6 +5751,27 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
cfg["open_browser"] = a.browser
cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too
cfg_path = ROOT / f"strata-{tag.lower()}.json"
if vision != "none":
old_cfg = cfg_path if cfg_path.is_file() else adopted
vt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg)
cfg["args"].append("--vision")
cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu",
"max_tokens": vt} # the text model, opened vocab-only
if vision == "cpu":
cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2)
elif getattr(a, "vision_tokens", None) is not None:
warn("--vision-tokens: images are off, so it is not used")
# requests at once ("parallel", opt-in): written only when given; the recommendation is said once
vram_gb = float(gpu.get("vram_gb", 0.0))
par = getattr(a, "parallel", None)
if par is not None:
if par >= 2:
cfg["parallel"] = par
for i, line in enumerate(own_path_parallel_note(par, fam, model, vram_gb, ctx)):
(ok if i == 0 else warn)(line)
else:
cfg["parallel"] = 1
ok("parallel requests: one at a time (--parallel 1)")
write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None)
script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False)
ok(f"start script: {script.name}")
@@ -5657,6 +5780,11 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)")
say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages")
say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")
if vision != "none":
say(" Images: send them in the chat page, in chat.py (/image <path>) or over the API")
if par is None: # the opt-in, said once (nothing changes)
for line in own_path_parallel_note(None, fam, model, vram_gb, ctx):
say(" " + line)
if a.no_start:
return 0
return start(cfg_path, port)
@@ -5711,8 +5839,8 @@ def main() -> int:
return mac_setup(sys.argv[1:])
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES),
help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5 (qwen36 = Qwen3.6-35B-A3B: download only, the "
"engine does not run it yet)")
help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5, qwen36 = Qwen3.6-35B-A3B (pictures with --vision, "
"several requests at once with --parallel; docs/QWEN36.md)")
ap.add_argument("--model", choices=list(dict.fromkeys([*MODELS, *(m for f in PREVIEW_FAMILIES.values()
for m in f["models"])])))
ap.add_argument("--context", type=int)
+1137 -120
View File
File diff suppressed because it is too large. Load diff
+27
View File
@@ -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])
+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: 47 KiB

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()
+79
View File
@@ -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()
+138
View File
@@ -0,0 +1,138 @@
// tools/qwen35/q36_mtmd_dump.cpp - llama.cpp's side of the Qwen3.6 PICTURE check: the same GGUF and mmproj, llama.cpp's own
// mtmd library and graph (the M-RoPE positions of mtmd_helper_eval_chunk_single, qwen35moe's IMROPE). Prints the prompt's
// chunks (the text ids, the picture's token count) and the greedy ids, and dumps every step's full logits (f32,
// [step][vocab]) so the first token's logits can be compared with strata-q36's (--dump-full-logits there).
//
// 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 [--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).
#include "llama.h"
#include "mtmd.h"
#include "mtmd-helper.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
static std::vector<int> parse_ids(const std::string& s) {
std::vector<int> v;
const char* p = s.c_str();
while (*p) {
while (*p == ',' || *p == ' ') ++p;
if (!*p) break;
v.push_back(std::atoi(p));
while (*p && *p != ',' && *p != ' ') ++p;
}
return v;
}
int main(int argc, char** argv) {
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") 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());
else if (a == "--max-tokens") max_tokens = std::atoi(v.c_str());
else if (a == "--mm-cpu") mm_cpu = std::atoi(v.c_str()); // the encoder on the CPU (as strata-vision's default)
else if (a == "--dump-full-logits") dump_full = v;
else if (a == "--force") force = v;
else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; }
}
llama_backend_init();
llama_model_params mp = llama_model_default_params();
mp.n_gpu_layers = ngl;
llama_model* mdl = llama_model_load_from_file(model.c_str(), mp);
if (!mdl) { std::fprintf(stderr, "cannot load %s\n", model.c_str()); return 1; }
const llama_vocab* vocab = llama_model_get_vocab(mdl);
llama_context_params cp = llama_context_default_params();
cp.n_ctx = 8192;
cp.n_batch = cp.n_ubatch = 2048;
cp.op_offload = ngl > 0;
llama_context* ctx = llama_init_from_model(mdl, cp);
if (!ctx) { std::fprintf(stderr, "cannot create the context\n"); return 1; }
mtmd_context_params mcp = mtmd_context_params_default();
mcp.use_gpu = ngl > 0 && !mm_cpu;
mcp.print_timings = false;
mcp.warmup = false;
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; }
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};
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) {
const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c);
if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_TEXT) {
size_t n = 0;
const llama_token* t = mtmd_input_chunk_get_tokens_text(ch, &n);
std::printf("text:");
for (size_t i = 0; i < n; ++i) std::printf(" %d", (int) t[i]);
std::printf("\n");
} else {
std::printf("image: %d tokens, %d positions\n", (int) mtmd_input_chunk_get_n_tokens(ch),
(int) mtmd_input_chunk_get_n_pos(ch));
}
llama_pos np = n_past;
if (mtmd_helper_eval_chunk_single(mctx, ctx, ch, n_past, 0, (int32_t) cp.n_batch, c + 1 == nc, &np) != 0) {
std::fprintf(stderr, "eval failed at chunk %zu\n", c);
return 1;
}
n_past = np;
}
const std::vector<int> forced = parse_ids(force);
if (!forced.empty()) n_gen = (int) forced.size() + 1;
const int V = llama_vocab_n_tokens(vocab);
FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb");
std::vector<llama_token> gen;
for (int i = 0; i < n_gen; ++i) {
const float* lg = llama_get_logits_ith(ctx, -1);
int a = 0;
for (int j = 1; j < V; ++j) if (lg[j] > lg[a]) a = j;
if (i == 0) {
int b = -1;
for (int j = 0; j < V; ++j) if (j != a && (b < 0 || lg[j] > lg[b])) b = j;
std::printf("first: top1 %d (%.4f) top2 %d (%.4f)\n", a, lg[a], b, lg[b]);
}
gen.push_back(a);
if (ff) std::fwrite(lg, 4, V, ff);
if (i + 1 == n_gen) break;
llama_token t = i < (int) forced.size() ? forced[i] : a;
llama_pos pp = n_past++; // the text after a picture continues at n_past (max(nx, ny) past its first position)
llama_batch one = llama_batch_get_one(&t, 1);
one.pos = &pp;
if (llama_decode(ctx, one) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; }
}
std::printf("gen:");
for (int t : gen) std::printf(" %d", t);
std::printf("\n");
if (ff) std::fclose(ff);
mtmd_input_chunks_free(chunks);
for (auto& bw : bws) mtmd_bitmap_free(bw.bitmap);
mtmd_free(mctx);
llama_free(ctx);
llama_model_free(mdl);
llama_backend_free();
return 0;
}
+103
View File
@@ -0,0 +1,103 @@
"""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):
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()
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)
+46
View File
@@ -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]))
+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()
+145
View File
@@ -0,0 +1,145 @@
"""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
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):
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, 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")
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_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) 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, *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
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)],
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, *sum([["--image", p] for p in pics], []),
"--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()
+94
View File
@@ -0,0 +1,94 @@
"""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).
Start the engine without --mtp for the cache check: the held tokens of a request that ran with drafts include the drafts accepted past
its last emitted token, so a prompt that does not repeat them reads from the start (correct, but the check wants the reuse)."""
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)
+75 -7
View File
@@ -93,6 +93,9 @@ class InstallOwnPath(unittest.TestCase):
def engine_step(a, gpu, hip, amd, cuda_tk, vision):
self.calls.append(("engine", vision))
if vision != "none": # the image encoder beside the engine
eng.mkdir(parents=True, exist_ok=True)
(eng / setup.VEXE).write_text("x")
return self.root / "llama", eng, {"version": "0.1.44"}, ["/libs"], gpu, vision
def write_cfg(path, cfg, source=None):
@@ -115,13 +118,13 @@ class InstallOwnPath(unittest.TestCase):
p.start()
self.addCleanup(p.stop)
def install(self, ram=64.0, vram=16.0, **kw):
def install(self, ram=64.0, vram=16.0, hip=False, **kw):
gpu = {"index": 0, "count": 1, "vram_gb": vram, "name": "Test GPU"}
return run(setup.install_own_path, args(models_dir=str(self.root / "models"), **kw), "qwen36", gpu, False, [],
return run(setup.install_own_path, args(models_dir=str(self.root / "models"), **kw), "qwen36", gpu, hip, [],
13, [], 8080, ram, None)
def test_installs_the_pinned_file_and_writes_the_config(self):
rc, out = self.install(model="UD-Q4_K_XL")
rc, out = self.install(model="UD-Q4_K_XL", vision="no")
self.assertEqual(rc, 0, out)
get = [c for c in self.calls if c[0] == "get"]
self.assertEqual(len(get), 1)
@@ -129,7 +132,9 @@ class InstallOwnPath(unittest.TestCase):
self.assertEqual(get[0][1], setup.hf(REPO) + gguf.name)
self.assertEqual(get[0][2], gguf)
self.assertIn(("sha", gguf.name), self.calls)
self.assertIn(("engine", "none"), self.calls) # no image encoder for this family yet
self.assertIn(("engine", "none"), self.calls) # --vision no: no image encoder
self.assertNotIn("--vision", self.cfg["args"])
self.assertNotIn("vision", self.cfg)
tok = [c for c in self.calls if c[0] == "run"]
self.assertTrue(tok and "strata_tokenizer.py" in str(tok[0][1]))
a = self.cfg["args"]
@@ -176,12 +181,74 @@ class InstallOwnPath(unittest.TestCase):
self.assertEqual(rc, 1)
self.assertIn("not enough free disk space", out)
def test_bigger_card_bigger_context_and_vision_said_off(self):
rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="yes")
def test_bigger_card_bigger_context(self):
rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no")
self.assertEqual(rc, 0, out)
a = self.cfg["args"]
self.assertEqual(a[a.index("--max-context") + 1], "131072")
self.assertIn("images are not available", out)
def test_images_by_default_on_a_16gb_nvidia_card_use_the_gpu_encoder(self):
rc, out = self.install(model="UD-Q4_K_XL", vram=16.0) # --yes: the question's default answer
self.assertEqual(rc, 0, out)
self.assertIn(("engine", "gpu"), self.calls)
mm = self.root / "models" / "qwen36-UD-Q4_K_XL" / "mmproj-F16.gguf"
self.assertIn(("get", setup.hf(REPO) + "mmproj-F16.gguf", mm), self.calls)
self.assertIn(("sha", "mmproj-F16.gguf"), self.calls) # pinned: size + SHA-256 (899283584 bytes)
self.assertEqual(setup.OWN_PATH_FAMILIES["qwen36"]["sha256"]["mmproj-F16.gguf"][0], 899283584)
a = self.cfg["args"]
self.assertIn("--vision", a)
v = self.cfg["vision"]
self.assertTrue(v["gpu"])
self.assertEqual(v["mmproj"], str(mm))
self.assertTrue(v["model"].endswith("Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf")) # the text model, opened vocab-only
self.assertEqual(Path(v["exe"]).name, setup.VEXE)
self.assertEqual(v["max_tokens"], 1024)
self.assertIn("images: on", out)
def test_a_12gb_card_is_recommended_the_cpu_encoder_never_forced(self):
rc, out = self.install(model="UD-Q4_K_XL", vram=12.0) # the default answer is no
self.assertEqual(rc, 0, out)
self.assertNotIn("vision", self.cfg)
rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="yes") # yes: the CPU encoder, said why
self.assertEqual(rc, 0, out)
self.assertFalse(self.cfg["vision"]["gpu"])
self.assertEqual(self.cfg["vision"]["max_tokens"], 300)
self.assertIn("threads", self.cfg["vision"])
rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="gpu") # gpu asked for: kept, with a note
self.assertEqual(rc, 0, out)
self.assertTrue(self.cfg["vision"]["gpu"])
self.assertIn("kept as you chose", out)
def test_amd_reads_pictures_on_the_cpu(self):
with mock.patch.object(setup, "WIN", False):
rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="yes")
self.assertEqual(rc, 0, out)
self.assertFalse(self.cfg["vision"]["gpu"])
self.assertIn("--vision", self.cfg["args"])
with mock.patch.object(setup, "WIN", True):
rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="cpu")
self.assertNotIn("vision", self.cfg)
self.assertIn("Linux-only", out)
def test_parallel_is_opt_in_and_recommended_where_the_experts_fit(self):
fam = setup.OWN_PATH_FAMILIES["qwen36"]
# nothing written without --parallel; the recommendation is said
rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no", context=32768)
self.assertEqual(rc, 0, out)
self.assertNotIn("parallel", self.cfg)
self.assertIn("--parallel 3", out)
# a 12 GB card runs the hybrid mode: one at a time recommended, any asked number kept
self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 12.0, 32768), 0)
rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", parallel=4)
self.assertEqual(self.cfg["parallel"], 4)
self.assertIn("recommended for this card: one at a time", out)
self.assertIn("kept as you chose", out)
rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", parallel=1)
self.assertEqual(self.cfg["parallel"], 1)
rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no", parallel=12)
self.assertIn("at most 8", out)
self.assertEqual(self.cfg["parallel"], 12) # written as asked; the server and the engine cap it
self.assertGreater(setup.own_path_parallel_slot_gb(fam, 32768), 1.4)
def test_config_read_back(self):
self.install(model="UD-Q6_K_XL", context=65536)
@@ -189,6 +256,7 @@ class InstallOwnPath(unittest.TestCase):
p.write_text(json.dumps(self.cfg), encoding="utf-8")
ch = setup.choices_from_config(p)
self.assertEqual((ch["family"], ch["model"], ch["context"]), ("qwen36", "UD-Q6_K_XL", 65536))
self.assertEqual(ch["vision"], "gpu") # 16 GB NVIDIA, the default answer
self.assertTrue(setup.own_path_config(self.cfg))
self.assertEqual(setup.calibration_targets([p], None, None), []) # the tuning is Flash-Next's