diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 69e5e2f7..8ce4b45a 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -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-.json`) and restart, or run setup with diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 5bd5fbbb..1d651bbd 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -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 diff --git a/docs/QWEN36.md b/docs/QWEN36.md new file mode 100644 index 00000000..ae1d408a --- /dev/null +++ b/docs/QWEN36.md @@ -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-.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`. diff --git a/serve/test_q36_config.py b/serve/test_q36_config.py new file mode 100644 index 00000000..981ae5f3 --- /dev/null +++ b/serve/test_q36_config.py @@ -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() diff --git a/setup.py b/setup.py index a010aa64..2d9681e0 100644 --- a/setup.py +++ b/setup.py @@ -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 ) 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) diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index c49bd71b..5400cd56 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,7 @@ #include #include #include +#include #include namespace { @@ -232,16 +234,36 @@ __global__ void k_gate_rows(float* sh, const float* gate, int n, int T) { sh[i] *= sigm(gate[i / n]); } +/// Batch rows (several sessions decoded in one window, one token each): row t reads and writes the cache of session +/// slot[t] at cell[t]; its rotary position is cell[t] + delta[t]. Every field null: one session, the rows are its +/// consecutive cells *pos0 + t (the prompt, a verify window, a decode step). +struct RowSel { + const int32_t* cell = nullptr; // device [T] + const int32_t* slot = nullptr; // device [T] + const int32_t* delta = nullptr; // device [T] + float* const* kc = nullptr; // device [n_sessions]: this layer's K / V base of each session + float* const* vc = nullptr; +}; + /// The attention layer's per-token preparation for T rows at positions *pos0 + t: q (from the [q | gate] pairs) and k /// RMS-normed per head with their weights, NEOX RoPE over the first n_rot dims, k / v into the cache, the gate kept. +/// Rotary position of a cell: the cell itself (text) plus *rdelta (what the pictures before a text run did not use +/// of their cells, see mrope), or, with `mtab` (a request's prompt cells, device int32 [cell][3] = t, h, w), the +/// interleaved M-RoPE position (llama.cpp's IMROPE with sections 11 / 11 / 10: pair p takes stream p % 3). /// grid (H + HKV, T), block 256 (HD <= 256). __global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, const float* qw, const float* kw, float* q, float* gate, float* kc, float* vc, int H, int HKV, int HD, int n_rot, - const int32_t* pos0, int ctx, float base, float eps) { + const int32_t* pos0, int ctx, float base, float eps, const int32_t* rdelta, + const int32_t* mtab, RowSel rs) { __shared__ float sh[kThreads]; __shared__ float buf[256]; const int head = blockIdx.x, t = blockIdx.y; - const int pos = *pos0 + t; + const int pos = rs.cell ? rs.cell[t] : *pos0 + t; + const int dl = rs.delta ? rs.delta[t] : (rdelta ? *rdelta : 0); + if (rs.kc) { + kc = rs.kc[rs.slot[t]]; + vc = rs.vc[rs.slot[t]]; + } const bool isq = head < H; const float* src = isq ? qg + ((size_t) t * H + head) * 2 * HD : kx + ((size_t) t * HKV + head - H) * HD; const int i = threadIdx.x; @@ -255,7 +277,8 @@ __global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, c const int half = n_rot / 2; if (i < n_rot) { const int p = i < half ? i : i - half; - const float theta = (float) pos * powf(base, -2.0f * (float) p / (float) n_rot); + const int rp = mtab ? __ldg(mtab + (size_t) pos * 3 + p % 3) : pos + dl; + const float theta = (float) rp * powf(base, -2.0f * (float) p / (float) n_rot); float sn, cs; sincosf(theta, &sn, &cs); v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs; @@ -274,12 +297,16 @@ __global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, c /// cells [0, *pos0 + t]. Writes the chunk's partial accumulator, max and sum; chunks past the query's cells write /// nothing (the merge stops before them). grid (n_chunk, n_rows), block 256, HD == 256. __global__ void k_attn_part(const float* q, const float* kc, const float* vc, const int32_t* pos0, int t0, int H, - int HKV, int ctx, float scale, int n_chunk, float* pacc, float* pm, float* pl) { + int HKV, int ctx, float scale, int n_chunk, float* pacc, float* pm, float* pl, RowSel rs) { constexpr int HD = 256; __shared__ float qs[HD], sc[kChunkCells], sh[kThreads]; const int c = blockIdx.x, row = blockIdx.y; const int t = t0 + row / H, h = row % H, kvh = h / (H / HKV); - const int npos = *pos0 + t + 1; + const int npos = (rs.cell ? rs.cell[t] : *pos0 + t) + 1; + if (rs.kc) { + kc = rs.kc[rs.slot[t]]; + vc = rs.vc[rs.slot[t]]; + } const int p0 = c * kChunkCells; if (p0 >= npos) return; const int j = threadIdx.x; @@ -310,10 +337,10 @@ __global__ void k_attn_part(const float* q, const float* kc, const float* vc, co } /// The chunks merged, times sigmoid(gate): grid (n_rows), block HD. __global__ void k_attn_merge(const float* pacc, const float* pm, const float* pl, const float* gate, - const int32_t* pos0, int t0, int H, int n_chunk, float* out) { + const int32_t* pos0, int t0, int H, int n_chunk, float* out, RowSel rs) { constexpr int HD = 256; const int row = blockIdx.x, t = t0 + row / H, h = row % H, d = threadIdx.x; - const int npos = *pos0 + t + 1; + const int npos = (rs.cell ? rs.cell[t] : *pos0 + t) + 1; const int nc = (npos + kChunkCells - 1) / kChunkCells; float M = -INFINITY; for (int c = 0; c < nc; ++c) M = fmaxf(M, pm[(size_t) row * n_chunk + c]); @@ -428,6 +455,15 @@ __global__ void k_gate_mul(float* att, const float* gate, int64_t n) { if (i < n) att[i] *= sigm(gate[i]); } +/// Picture rows over the embeddings of a chunk: x[r] = img[map[r]] for the rows with map[r] >= 0 (the rows of a picture's +/// <|image_pad|> cells). grid (T), block 256. +__global__ void k_put_rows(float* x, const float* img, const int32_t* map, int n) { + const int r = blockIdx.x; + const int m = map[r]; + if (m < 0) return; + for (int i = threadIdx.x; i < n; i += blockDim.x) x[(size_t) r * n + i] = img[(size_t) m * n + i]; +} + /// The prompt's routed entries sorted by expert for MMQ: bounds[x] .. bounds[x + 1] are expert x's rows; sorted row r /// holds entry dst[r] (= t * K + k, the row of the per-slot outputs) of token src[r]. The order inside an expert is the /// atomics' (no output depends on it: every row's products are its own). cnt / cur: n_expert ints of scratch. @@ -565,8 +601,18 @@ __global__ void k_to_f16(const float* x, __half* y, int64_t n) { /// 3-entry history carried in registers across the tokens and written back at the end; SiLU, then the L2 norm of the /// q/k heads (block < qk_heads) per token - fused_gdn_conv_l2's arithmetic, token after token. History [channel][3]. __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, const float* w, float* h, int C, - int qk_heads, float eps, int T, bool write) { + int qk_heads, float eps, int T, bool write, + float* const* hist_tab = nullptr, const int32_t* slot_rows = nullptr, + const int32_t* grow0 = nullptr, const int32_t* gcnt = nullptr) { __shared__ float part[4]; + if (hist_tab) { // batch rows, grid y = group: group g's history is session slot_rows[g]'s; its rows are + // grow0[g] .. + gcnt[g] - 1 (one row at row g when there are no group arrays) + const int g = blockIdx.y, r0 = grow0 ? grow0[g] : g; + hist = hist_tab[slot_rows[g]]; + if (gcnt) T = gcnt[g]; + qkv += (size_t) r0 * C; + h += (size_t) r0 * C; + } const int c = blockIdx.x * 128 + threadIdx.x; float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; @@ -600,8 +646,20 @@ __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, /// registers across the tokens. h (T, C) = q | k | v, gate / beta (T, HV), z / y (T, ZV). __global__ void __launch_bounds__(512) k_gdn_seq(float* state, const float* h, int C, const float* gate, const float* beta, const float* z, const float* gamma, float eps, - float* y, int h_k, int h_v, int T, bool write) { + float* y, int h_k, int h_v, int T, bool write, + float* const* state_tab = nullptr, const int32_t* slot_rows = nullptr, + const int32_t* grow0 = nullptr, const int32_t* gcnt = nullptr) { constexpr int S = 128, RG = 4, RPG = 32; + if (state_tab) { // batch rows, grid y = group (see k_conv_seq) + const int g = blockIdx.y, r = grow0 ? grow0[g] : g; + state = state_tab[slot_rows[g]]; + if (gcnt) T = gcnt[g]; + h += (size_t) r * C; + gate += (size_t) r * h_v; + beta += (size_t) r * h_v; + z += (size_t) r * h_v * S; + if (y) y += (size_t) r * h_v * S; + } __shared__ float sk[S], sq[S]; __shared__ float red_kv[RG][S]; __shared__ float red_o[RG][S]; @@ -1032,6 +1090,13 @@ template T* dalloc_t(size_t n) { return p; } +/// A picture in a prompt: its first cell, its rows, and the hash the conversation cache compares it by. +struct ImgKey { + int64_t cell = 0, n = 0; + uint64_t hash = 0; + bool operator==(const ImgKey& o) const { return cell == o.cell && n == o.n && hash == o.hash; } +}; + struct Engine { const Model* m = nullptr; cudaStream_t st = nullptr; @@ -1041,7 +1106,7 @@ struct Engine { float *x, *h, *y, *qkv, *hc, *z, *alpha, *beta, *gdn_y, *qg, *kx, *vx, *q, *gate, *att, *logits_r, *eparts, *moe_out, *sg, *su, *shh, *sy, *sgate, *ewts, *logits; float* hmain = nullptr; // [tmax][N] the main model's final normed hidden of each row (the MTP seeds) - float* hlast = nullptr; // [N] that of the last processed position (zeros before the first) + float* hlast = nullptr; // [N] that of the last processed position (zeros before the first): the current session's void *q8, *xq, *escr; int32_t *ids, *grp_start, *n_groups, *ent_dst, *ent_tok, *tok, *pos0, *pick; int32_t* hpin = nullptr; // pinned staging: [0] decode token, [1] position, [2..9] picks, [10] max rows, [16..] tokens @@ -1049,7 +1114,7 @@ struct Engine { float *pacc, *pm, *pl, *amv; int32_t* ami; int n_chunk = 0, att_rows = 0; // attention partials: att_rows query rows x n_chunk chunks - std::vector conv, S, kc, vc; // per layer; the MTP block's K / V at index n_layers + std::vector conv, S, kc, vc; // per layer; the MTP block's K / V at index n_layers: the CURRENT session's (select) // verify windows (T <= kVerify): the GDN inputs of every row per layer, kept for the commit static constexpr int kVerify = 8; std::vector v_qkv, v_hc, v_alpha, v_beta; @@ -1057,7 +1122,12 @@ struct Engine { float *mtp_cat = nullptr, *hmtp = nullptr, *logits_m = nullptr; int32_t *tok_m = nullptr, *pos0_m = nullptr, *pick_m = nullptr; // graphs: [0] the decode step, [T] a verify window of T rows, mtp1 the MTP draft step - cudaGraphExec_t g1 = nullptr, gv[kVerify + 1] = {}, gm1 = nullptr; + // (the graphs hold the current session's state pointers as kernel arguments: one set per session) + struct GSet { + cudaGraphExec_t g1 = nullptr, gv[kVerify + 1] = {}, gm1 = nullptr; + }; + std::vector gsets; + GSet& gs() { return gsets[(size_t) cur]; } strata::prefill::Gemm gemm; cublasHandle_t blas = nullptr; float* att_s = nullptr; // the prompt attention's scores / probabilities, kAttScoreFloats floats @@ -1076,6 +1146,45 @@ struct Engine { bool use_graph = true; int mtp_d = 0; // MTP drafts per speculative step (0: none; greedy requests only) + // ---- sessions: the conversation states. One for a single-request engine; --batch N keeps N, each with its own + // recurrent state and KV cache, so N requests run at once: their rows share one decode window (forward_rows). The + // members conv / S / kc / vc / pos / hlast above are the CURRENT session's (select() swaps them). + struct Sess { + std::vector conv, S, kc, vc; + float* hlast = nullptr; + int64_t pos = 0; + int32_t rdelta = 0; // rotary offset of the text after the last picture (see k_attn_prep) + std::vector live; // the tokens whose state it holds (cell i = live[i]) + std::vector imgs; // the pictures among them + bool active = false; // a batch slot is decoding in it + uint64_t used = 0; // when it was last used (the LRU pick) + }; + std::vector sess; + int n_sess = 1, cur = 0; + uint64_t use_clock = 0; + // device tables for batch rows: per state index (layer, then the MTP block) the session pointers + float **d_conv_tab = nullptr, **d_S_tab = nullptr, **d_kc_tab = nullptr, **d_vc_tab = nullptr; + int32_t *d_rcell = nullptr, *d_rslot = nullptr, *d_rdelta = nullptr; // [kVerify] the rows' cell / session / rotary offset + // the GDN layers run a slot's rows in sequence: per group (a slot) its session, its first row and its row count + int32_t *d_gslot = nullptr, *d_grow0 = nullptr, *d_gcnt = nullptr; + int rows_G = 0; // groups of the rows being run + int32_t* hrow = nullptr; // pinned staging for the rows + bool rows_mode = false; // layer(): the rows are sessions' (not consecutive cells) + bool bmtp = false; // --batch-mtp: batch windows verify MTP proposals + int64_t rows_pmax = 0; // (eager) the highest cell of the rows + // pictures (--vision): the request's rows replace the embeddings of its <|image_pad|> cells; M-RoPE + bool vision = false; + int32_t* d_mtab = nullptr; // [ctx][3] t, h, w of the current request's prompt cells (vision) + const int32_t* mtab_now = nullptr; // set for a forward over prompt cells that need it, else null + int32_t* d_delta = nullptr; // device scalar: the current session's rotary offset (decode graphs read it) + float* d_img = nullptr; // the request's picture rows [n][N] + size_t img_cap = 0; // floats + int32_t* d_map = nullptr; // [tmax] a chunk's row -> picture row (or -1) + int32_t* h_map = nullptr; // pinned + bool map_on = false; // this forward's embeddings take picture rows + std::vector img_map; // the request's cell -> picture row (-1: text) + int64_t img_prompt_cells = 0; // the request's prompt length: cells below it use the table + // ---- the hybrid mode (Model::hybrid): per state index (the layers, then the MTP block) the slot tables; a // batch of up to hybrid_t rows runs its VRAM-resident experts on the GPU and the others on the CPU pool, side by // side; a bigger prompt chunk streams each layer's experts into a staging buffer for MMQ (two, double-buffered) @@ -1133,15 +1242,66 @@ struct Engine { } } - void init(const Model& model, int ctx_, int tmax_) { + void alloc_session(Sess& ss) const { + const auto& g = m->g; + const size_t C = (size_t) g.ssm_conv_channels; + for (const Layer& L : m->layers) { + if (L.attn) { + ss.conv.push_back(nullptr); + ss.S.push_back(nullptr); + ss.kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + ss.vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + } else { + ss.conv.push_back(dalloc(C * (g.ssm_d_conv - 1))); + ss.S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); + ss.kc.push_back(nullptr); + ss.vc.push_back(nullptr); + } + } + if (m->has_mtp) { // the MTP block's own K / V (an attention layer at index n_layers) + ss.conv.push_back(nullptr); + ss.S.push_back(nullptr); + ss.kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + ss.vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + } + ss.hlast = dalloc((size_t) g.n_embd); + } + + /// The current session: `i`'s state, cache and position become the engine's (conv / S / kc / vc / pos / hlast). + void select(int i) { + if (i == cur) return; + sess[(size_t) cur].pos = pos; + cur = i; + load_cur(); + } + void load_cur() { + Sess& ss = sess[(size_t) cur]; + conv = ss.conv; S = ss.S; kc = ss.kc; vc = ss.vc; + hlast = ss.hlast; + pos = ss.pos; + ss.used = ++use_clock; + set_delta(ss.rdelta); + } + /// The rotary offset the decode graphs read (a device scalar), for the current session. + void set_delta(int32_t d) { + sess[(size_t) cur].rdelta = d; + if (!d_delta) return; + hpin[60] = d; + CK(cudaMemcpyAsync(d_delta, hpin + 60, 4, cudaMemcpyHostToDevice, st)); + CK(cudaStreamSynchronize(st)); // (the pinned word is reused) + } + + void init(const Model& model, int ctx_, int tmax_, int n_sessions = 1, bool vision_ = false) { m = &model; ctx = ctx_; + n_sess = std::max(1, std::min(n_sessions, kVerify)); + vision = vision_; tmax = std::max(tmax_, kVerify); const auto& g = m->g; const size_t T = (size_t) tmax, N = (size_t) g.n_embd, Kp = (size_t) m->top_k, FF = (size_t) g.n_ff; const size_t C = (size_t) g.ssm_conv_channels; CK(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking)); - x = dalloc(T * N); h = dalloc(T * N); y = dalloc(T * N); hmain = dalloc(T * N); hlast = dalloc(N); + x = dalloc(T * N); h = dalloc(T * N); y = dalloc(T * N); hmain = dalloc(T * N); qkv = dalloc(T * C); hc = dalloc(T * C); z = dalloc(T * g.ssm_value_dim); alpha = dalloc(T * g.ssm_v_heads); beta = dalloc(T * g.ssm_v_heads); gdn_y = dalloc(T * g.ssm_value_dim); qg = dalloc(T * 2 * g.n_head * g.head_dim); kx = dalloc(T * g.n_head_kv * g.head_dim); @@ -1224,29 +1384,17 @@ struct Engine { pacc = dalloc((size_t) att_rows * n_chunk * g.head_dim); pm = dalloc((size_t) att_rows * n_chunk); pl = dalloc((size_t) att_rows * n_chunk); - for (const Layer& L : m->layers) { + for (const Layer& L : m->layers) { // the verify windows' GDN inputs (one set, whichever session runs) if (L.attn) { - conv.push_back(nullptr); - S.push_back(nullptr); - kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); - vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); for (auto* v : {&v_qkv, &v_hc, &v_alpha, &v_beta}) v->push_back(nullptr); } else { - conv.push_back(dalloc(C * (g.ssm_d_conv - 1))); - S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); - kc.push_back(nullptr); - vc.push_back(nullptr); v_qkv.push_back(dalloc((size_t) kVerify * C)); v_hc.push_back(dalloc((size_t) kVerify * C)); v_alpha.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); v_beta.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); } } - if (m->has_mtp) { // the MTP block's own K / V (an attention layer at index n_layers) - conv.push_back(nullptr); - S.push_back(nullptr); - kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); - vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + if (m->has_mtp) { mtp_cat = dalloc(T * 2 * N); hmtp = dalloc(T * N); logits_m = dalloc((size_t) g.n_vocab); @@ -1254,6 +1402,61 @@ struct Engine { pos0_m = dalloc_t(1); pick_m = dalloc_t(1); } + sess.resize((size_t) n_sess); + gsets.resize((size_t) n_sess); + { // the sessions' caches: said before they fail (a slot's K / V at the context, fp32, for the attention layers and + // the MTP block, and its recurrent state) + size_t n_attn = m->has_mtp ? 1 : 0, n_gdn = 0; + for (const Layer& L : m->layers) (L.attn ? n_attn : n_gdn) += 1; + const size_t per = (size_t) (g.n_head_kv * g.head_dim * 2 * 4) * (size_t) ctx * n_attn + + (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4 * n_gdn; + size_t fr0 = 0, tot0 = 0; + CK(cudaMemGetInfo(&fr0, &tot0)); + if (n_sess > 1) + std::fprintf(stderr, "strata-q36: %d sessions (--batch): %.2f GiB of VRAM each at a context of %d (%.2f GiB in " + "all), %.2f GiB free before them\n", n_sess, (double) per / (1 << 30), ctx, + (double) per * n_sess / (1 << 30), (double) fr0 / (1 << 30)); + if (n_sess > 1 && per * (size_t) n_sess + ((size_t) 1 << 30) > fr0) { + std::fprintf(stderr, "strata-q36: not enough VRAM for %d slots at a context of %d (%.2f GiB each, %.2f GiB " + "free): use fewer slots (\"parallel\" / --batch) or a shorter --max-context\n", n_sess, ctx, + (double) per / (1 << 30), (double) fr0 / (1 << 30)); + std::exit(1); + } + } + for (Sess& ss : sess) alloc_session(ss); + if (n_sess > 1) { // the batch rows' tables: per state index the session pointers, on the device + const size_t ns = sess[0].conv.size(); + std::vector hc(ns * (size_t) n_sess), hs(hc), hk(hc), hv(hc); + for (size_t li = 0; li < ns; ++li) + for (int s_ = 0; s_ < n_sess; ++s_) { + hc[li * n_sess + s_] = sess[(size_t) s_].conv[li]; + hs[li * n_sess + s_] = sess[(size_t) s_].S[li]; + hk[li * n_sess + s_] = sess[(size_t) s_].kc[li]; + hv[li * n_sess + s_] = sess[(size_t) s_].vc[li]; + } + const std::pair*> tabs[4] = {{&d_conv_tab, &hc}, {&d_S_tab, &hs}, + {&d_kc_tab, &hk}, {&d_vc_tab, &hv}}; + for (const auto& tb : tabs) { + CK(cudaMalloc((void**) tb.first, tb.second->size() * sizeof(float*))); + CK(cudaMemcpy((void*) *tb.first, tb.second->data(), tb.second->size() * sizeof(float*), + cudaMemcpyHostToDevice)); + } + d_rcell = dalloc_t(kVerify); + d_rslot = dalloc_t(kVerify); + d_rdelta = dalloc_t(kVerify); + d_gslot = dalloc_t(kVerify); + d_grow0 = dalloc_t(kVerify); + d_gcnt = dalloc_t(kVerify); + CK(cudaHostAlloc((void**) &hrow, 128 * sizeof(int32_t), cudaHostAllocDefault)); + } + if (vision) { + d_mtab = dalloc_t((size_t) ctx * 3); + d_map = dalloc_t(T); + CK(cudaHostAlloc((void**) &h_map, T * sizeof(int32_t), cudaHostAllocDefault)); + } + d_delta = dalloc_t(1); + cur = 0; + load_cur(); CK(cudaDeviceSynchronize()); // every legacy-stream cudaMemset of the buffers above is done size_t fr = 0, tot = 0; CK(cudaMemGetInfo(&fr, &tot)); @@ -1271,6 +1474,8 @@ struct Engine { CK(cudaMemsetAsync(hlast, 0, (size_t) g.n_embd * 4, st)); CK(cudaStreamSynchronize(st)); pos = 0; + sess[(size_t) cur].pos = 0; + set_delta(0); } /// y [T][n_out] = W x [T][n_in] on the native MMVQ, 8 columns per launch. @@ -1358,19 +1563,27 @@ struct Engine { f32mm(L.beta, h, be_b, N, HV, T); k_gdn_gb<<>>(al_b, L.dt, L.ssm_a, be_b, HV, T); } - // one token, a window or a chunk: the same kernels (every token in one launch each), so a decode step and a - // verify window compute bitwise the same rows and the MTP's greedy text is the plain greedy text. (Strata's - // fused single-token kernels are not used here: fused_gdn_conv_l2's 4-tap sum contracts into FMAs - // differently from k_conv_seq's, a 1-ulp difference in h that the Q8_1 activation rounding can turn into a - // flipped near-tie later; with them the KL is the same, 1.05x / 0.81x the floor, but MTP would not be exact.) - k_conv_seq<<>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify); - if (T > kGemmT && !verify) { // a prompt chunk: the column-split delta rule, then the norm - k_gdn_seq_cols<<>>(S[li], hc_b, C, al_b, - be_b, gdn_y, HK, HV, T); - k_gdn_norm<<>>(gdn_y, z, L.ssm_norm, m->eps, gdn_y, HV); - } else { // decode, verify windows and commits: one kernel, so a window's rows are a decode step's rows - k_gdn_seq<<>>(S[li], hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, HK, HV, - T, !verify); + if (rows_mode) { // batch rows: a slot's rows (one, or a verify window's two) in sequence on its own state + k_conv_seq<<>>(nullptr, qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, 1, + !verify, d_conv_tab + li * n_sess, d_gslot, d_grow0, d_gcnt); + k_gdn_seq<<>>(nullptr, hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, + gdn_y, HK, HV, 1, !verify, d_S_tab + li * n_sess, + d_gslot, d_grow0, d_gcnt); + } else { + // one token, a window or a chunk: the same kernels (every token in one launch each), so a decode step and a + // verify window compute bitwise the same rows and the MTP's greedy text is the plain greedy text. (Strata's + // fused single-token kernels are not used here: fused_gdn_conv_l2's 4-tap sum contracts into FMAs + // differently from k_conv_seq's, a 1-ulp difference in h that the Q8_1 activation rounding can turn into a + // flipped near-tie later; with them the KL is the same, 1.05x / 0.81x the floor, but MTP would not be exact.) + k_conv_seq<<>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify); + if (T > kGemmT && !verify) { // a prompt chunk: the column-split delta rule, then the norm + k_gdn_seq_cols<<>>(S[li], hc_b, C, al_b, + be_b, gdn_y, HK, HV, T); + k_gdn_norm<<>>(gdn_y, z, L.ssm_norm, m->eps, gdn_y, HV); + } else { // decode, verify windows and commits: one kernel, so a window's rows are a decode step's rows + k_gdn_seq<<>>(S[li], hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, HK, HV, + T, !verify); + } } mm(L.ssm_out, gdn_y, y, T); } else { @@ -1378,8 +1591,17 @@ struct Engine { apply(L.wq, xq, qg, T); apply(L.wk, xq, kx, T); apply(L.wv, xq, vx, T); - k_attn_prep<<>>(qg, kx, vx, L.q_norm, L.k_norm, q, gate, kc[li], vc[li], H, - HKV, HD, m->n_rot, dpos, ctx, m->rope_base, m->eps); + RowSel rs; + if (rows_mode) { + rs.cell = d_rcell; + rs.slot = d_rslot; + rs.delta = d_rdelta; + rs.kc = d_kc_tab + li * n_sess; + rs.vc = d_vc_tab + li * n_sess; + } + k_attn_prep<<>>(qg, kx, vx, L.q_norm, L.k_norm, q, gate, rows_mode ? nullptr : kc[li], + rows_mode ? nullptr : vc[li], H, HKV, HD, m->n_rot, dpos, ctx, + m->rope_base, m->eps, d_delta, mtab_now, rs); if (T > kGemmT) { // a prompt chunk: scores = Q K^T and out = P V as FP16 GEMMs (FP32 accumulation, FP32 scores) per KV // head (its query heads one strided batch over the shared K / V), the causal softmax in between writing @@ -1429,9 +1651,10 @@ struct Engine { const int nt = std::min(rows_per, T - t0); const int nc = graph_mode ? n_chunk : (int) std::min(n_chunk, (p0 + t0 + nt + kChunkCells - 1) / kChunkCells); - k_attn_part<<>>(q, kc[li], vc[li], dpos, t0, H, HKV, ctx, - 1.0f / sqrtf((float) HD), n_chunk, pacc, pm, pl); - k_attn_merge<<>>(pacc, pm, pl, gate, dpos, t0, H, n_chunk, att); + k_attn_part<<>>(q, rows_mode ? nullptr : kc[li], + rows_mode ? nullptr : vc[li], dpos, t0, H, HKV, ctx, + 1.0f / sqrtf((float) HD), n_chunk, pacc, pm, pl, rs); + k_attn_merge<<>>(pacc, pm, pl, gate, dpos, t0, H, n_chunk, att, rs); } } mm(L.wo, att, y, T); @@ -1518,6 +1741,7 @@ struct Engine { stream_begin(seq); } K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok, T, N, x, st); + if (map_on) k_put_rows<<>>(x, d_img, d_map, N); // a picture's cells take its rows k_rms<<>>(x, m->layers[0].attn_norm, h, N, m->eps); // later layers: from k_moe_out for (size_t l = 0; l < m->layers.size(); ++l) { const bool last = l + 1 == m->layers.size(); @@ -1542,6 +1766,7 @@ struct Engine { const int N = (int) g.n_embd; if (main_hybrid && lhy(m->layers.size()) && T > hybrid_t && use_mmq) stream_begin({(int) m->layers.size()}); K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok_m, T, N, y, st); + if (map_on) k_put_rows<<>>(y, d_img, d_map, N); k_rms_ld<<>>(y, N, m->mtp_enorm, mtp_cat, 2 * N, N, m->eps); // [e | ...] k_rms_ld<<>>(seeds, N, m->mtp_hnorm, mtp_cat + N, 2 * N, N, m->eps); // [... | h] mm(m->eh_proj, mtp_cat, x, T); @@ -1758,10 +1983,15 @@ struct Engine { CK(cudaDeviceSynchronize()); } void reset_graphs() { - for (cudaGraphExec_t* g : {&g1, &gm1}) - if (*g) { CK(cudaGraphExecDestroy(*g)); *g = nullptr; } - for (auto& g : gv) - if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } + for (GSet& gset : gsets) { + for (cudaGraphExec_t* g : {&gset.g1, &gset.gm1}) + if (*g) { CK(cudaGraphExecDestroy(*g)); *g = nullptr; } + for (auto& g : gset.gv) + if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } + } + for (auto& kv : row_graphs) + if (kv.second) CK(cudaGraphExecDestroy(kv.second)); + row_graphs.clear(); } template void graph_run(cudaGraphExec_t& gx, F body) { @@ -1777,25 +2007,87 @@ struct Engine { CK(cudaGraphLaunch(gx, st)); } + // ---- pictures (--vision). A request with pictures hands the engine its rows (the encoder's, in prompt order), the + // cell -> row map of its <|image_pad|> cells and the M-RoPE table of its prompt cells; the cells below the prompt + // length take their rotary positions from the table, the text after it continues at cell + delta (what the pictures + // did not use of their cells: llama.cpp's mtmd advances the text position by max(nx, ny) per picture). + bool img_active = false; + void set_images(const std::vector& rows, const std::vector& cell_row, const std::vector& mrope, + int64_t n_prompt, int32_t delta) { + const size_t need = rows.size(); + if (need > img_cap) { + CK(cudaDeviceSynchronize()); + if (d_img) CK(cudaFree(d_img)); + CK(cudaMalloc((void**) &d_img, need * 4)); + img_cap = need; + } + CK(cudaMemcpy(d_img, rows.data(), need * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d_mtab, mrope.data(), mrope.size() * 4, cudaMemcpyHostToDevice)); + img_map = cell_row; + img_prompt_cells = n_prompt; + img_active = true; + set_delta(delta); + } + void clear_images() { + img_map.clear(); + img_active = false; + img_prompt_cells = 0; + mtab_now = nullptr; + map_on = false; + set_delta(0); + } + /// A forward over the cells [c0, c0 + T): the picture rows of its cells, and the table when it is a prompt's. + void chunk_pictures(int64_t c0, int T) { + mtab_now = nullptr; + map_on = false; + if (!img_active) return; + if (c0 < img_prompt_cells) mtab_now = d_mtab; + bool any = false; + for (int j = 0; j < T; ++j) { + const int64_t c = c0 + j; + const int32_t v = c < (int64_t) img_map.size() ? img_map[(size_t) c] : -1; + h_map[j] = v; + any = any || v >= 0; + } + if (any) { + CK(cudaMemcpyAsync(d_map, h_map, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + map_on = true; + } + } + /// The tokens at the current position: a prompt in chunks (eager), one token from the decode graph. The last /// token's logits stay in `logits` (its greedy pick in `pick`), hlast its normed hidden. With the MTP block the - /// prompt also runs through it (its K / V for every position: row q reads h_{q-1} and token q). - template void process(const int32_t* toks, int64_t n, F on_chunk) { + /// prompt also runs through it (its K / V for every position: row q reads h_{q-1} and token q). on_chunk(done) runs + /// after every chunk; false ends the read there (a cancelled request): the tokens processed are returned. + template int64_t process(const int32_t* toks, int64_t n, F on_chunk_) { const int N = (int) m->g.n_embd; + auto on_chunk = [&](int64_t done) -> bool { // a callback returning void never cancels + if constexpr (std::is_void_v) { + on_chunk_(done); + return true; + } else { + return on_chunk_(done); + } + }; if (n == 1) { CK(cudaStreamSynchronize(st)); // the pinned staging is free again hpin[0] = toks[0]; hpin[1] = (int32_t) pos; CK(cudaMemcpyAsync(tok, hpin, 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + chunk_pictures(pos, 1); rows_deferred = true; - graph_run(g1, [&] { forward(1, pos, 1, use_graph, false); }); + // a prompt cell of a picture request (its rotary position is in the table, its row a picture's) runs eagerly + if (mtab_now || map_on) forward(1, pos, 1, false, false); + else graph_run(gs().g1, [&] { forward(1, pos, 1, use_graph, false); }); + mtab_now = nullptr; + map_on = false; rows_deferred = false; CK(cudaMemcpyAsync(hlast, hmain, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); pos += 1; after_rows(1); on_chunk(1); - return; + return 1; } for (int64_t i = 0; i < n; i += tmax) { const int T = (int) std::min(tmax, n - i); @@ -1803,6 +2095,7 @@ struct Engine { hpin[1] = (int32_t) pos; CK(cudaMemcpyAsync(tok, toks + i, (size_t) T * 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + chunk_pictures(pos, T); forward(T, pos, i + T == n ? 1 : 0, false, false); if (m->has_mtp && mtp_d > 0) { // seeds: h_{q-1} for each row q: hlast, then this chunk's rows 0 .. T - 2 (in `y`, free here) @@ -1816,9 +2109,202 @@ struct Engine { CK(cudaMemcpyAsync(hlast, hmain + (size_t) (T - 1) * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); pos += T; CK(cudaStreamSynchronize(st)); - on_chunk(i + T); + mtab_now = nullptr; + map_on = false; + if (!on_chunk(i + T)) { + if (m->hybrid) rebalance(hybrid_swaps_after_prompt); + return i + T; + } } if (m->hybrid) rebalance(hybrid_swaps_after_prompt); + return n; + } + + // ---- batch rows: one decode window for the next token of several sessions + struct Row { int slot; int32_t tok; }; + long long win_count = 0; + std::map row_graphs; // by (rows, groups, kind): graphs of the batch windows + /// A slot's rows of one window: `n` consecutive cells from the session's position (1: the next token; 2: also an MTP + /// proposal the window verifies). + struct Group { int slot; int n; int32_t tok[2]; }; + int32_t rows_pick[kVerify] = {}; + int rows_G_last = 0; // groups of the window run last (commit_rows takes their keep counts) + + void run_graph_key(int key, const std::function& body) { + if (!use_graph) { body(); return; } + graph_run(row_graphs[key], body); + } + + /// One window over the groups' rows. `verify`: a verify window - the GDN state is read, not written (commit_rows writes + /// it for the kept rows) and the sessions' positions stay. The greedy picks end up in rows_pick (one per row), every + /// row's logits in `logits`. Without verify the sessions' positions advance by their rows. + void run_rows(const Group* gr, int G, bool verify) { + sess[(size_t) cur].pos = pos; + CK(cudaStreamSynchronize(st)); // the pinned staging is free again + int64_t pmax = 0; + int T = 0; + for (int g = 0; g < G; ++g) { + const Sess& ss = sess[(size_t) gr[g].slot]; + hrow[40 + g] = gr[g].slot; + hrow[48 + g] = T; + hrow[56 + g] = gr[g].n; + for (int j = 0; j < gr[g].n; ++j) { + hrow[T] = gr[g].tok[j]; + hrow[8 + T] = (int32_t) (ss.pos + j); + hrow[16 + T] = gr[g].slot; + hrow[24 + T] = ss.rdelta; + ++T; + } + pmax = std::max(pmax, ss.pos + gr[g].n - 1); + } + CK(cudaMemcpyAsync(tok, hrow, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_gslot, hrow + 40, (size_t) G * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_grow0, hrow + 48, (size_t) G * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_gcnt, hrow + 56, (size_t) G * 4, cudaMemcpyHostToDevice, st)); + mtab_now = nullptr; + map_on = false; + rows_mode = true; + rows_G = G; + rows_deferred = true; + run_graph_key((verify ? 1000 : 0) + G * 10 + (T - G), [&] { forward(T, pmax, T, use_graph, verify); }); + rows_deferred = false; + rows_mode = false; + CK(cudaMemcpyAsync(hrow + 32, pick, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + for (int r = 0; r < T; ++r) rows_pick[r] = hrow[32 + r]; + if (!verify) + for (int g = 0; g < G; ++g) sess[(size_t) gr[g].slot].pos += gr[g].n; + pos = sess[(size_t) cur].pos; + rows_G_last = G; + if (m->hybrid) { + count_rows(T); + if (++win_count % kRebalanceEvery == 0) rebalance(8); + } + } + /// One window for the next token of each of the rows' sessions (no proposals): the greedy picks in rows_pick. + void step_rows(const Row* rows, int nb) { + Group gr[kVerify]; + for (int r = 0; r < nb; ++r) gr[r] = {rows[r].slot, 1, {rows[r].tok, 0}}; + run_rows(gr, nb, false); + } + /// After run_rows(.., verify = true): the GDN state of group g takes its first keep[g] rows (the conv history and the + /// recurrence run again over the rows' kept inputs, as commit() does) and the session advances by keep[g]. + void commit_rows(const Group* gr, const int* keep, int G) { + const auto& g = m->g; + const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, C = (int) g.ssm_conv_channels; + sess[(size_t) cur].pos = pos; + for (int i = 0; i < G; ++i) hrow[56 + i] = keep[i]; // (hrow's slot / first-row words are the window's, unchanged) + CK(cudaMemcpyAsync(d_gcnt, hrow + 56, (size_t) G * 4, cudaMemcpyHostToDevice, st)); + rows_mode = true; + rows_G = G; + run_graph_key(2000 + G, [&] { + for (size_t l = 0; l < m->layers.size(); ++l) { + const Layer& L = m->layers[l]; + if (L.attn) continue; + k_conv_seq<<>>(nullptr, v_qkv[l], L.conv, hc, C, 2 * HK, m->eps, 1, true, + d_conv_tab + l * n_sess, d_gslot, d_grow0, d_gcnt); + k_gdn_seq<<>>(nullptr, v_hc[l], C, v_alpha[l], v_beta[l], z, L.ssm_norm, + m->eps, nullptr, HK, HV, 1, true, d_S_tab + l * n_sess, + d_gslot, d_grow0, d_gcnt); + } + }); + rows_mode = false; + CK(cudaStreamSynchronize(st)); + for (int i = 0; i < G; ++i) sess[(size_t) gr[i].slot].pos += keep[i]; + pos = sess[(size_t) cur].pos; + } + + /// The MTP block over rows of several sessions: row r reads token tok at cell `cell` of session `slot` and the seed + /// hidden at `seed` (device, n_embd floats); its draft - the block's greedy pick after that row - ends up in + /// mtp_pick[r], and the block's K / V cells are written. + struct MtpRow { int slot; int32_t tok; int64_t cell; const float* seed; }; + int32_t mtp_pick[kVerify] = {}; + float* logits_mr = nullptr; + int32_t* pick_mr = nullptr; + void mtp_rows(const MtpRow* rows, int T) { + const auto& g = m->g; + const int N = (int) g.n_embd; + if (!logits_mr) { + logits_mr = dalloc((size_t) kVerify * g.n_vocab); + pick_mr = dalloc_t(kVerify); + } + sess[(size_t) cur].pos = pos; + CK(cudaStreamSynchronize(st)); + int64_t pmax = 0; + for (int r = 0; r < T; ++r) { + hrow[r] = rows[r].tok; + hrow[8 + r] = (int32_t) rows[r].cell; + hrow[16 + r] = rows[r].slot; + hrow[24 + r] = sess[(size_t) rows[r].slot].rdelta; + pmax = std::max(pmax, rows[r].cell); + CK(cudaMemcpyAsync(mtp_seed() + (size_t) r * N, rows[r].seed, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + } + CK(cudaMemcpyAsync(tok_m, hrow, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + mtab_now = nullptr; + map_on = false; + rows_mode = true; + rows_G = T; + rows_deferred = true; + run_graph_key(3000 + T, [&] { + K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok_m, T, N, y, st); + k_rms_ld<<>>(y, N, m->mtp_enorm, mtp_cat, 2 * N, N, m->eps); // [e | ...] + k_rms_ld<<>>(mtp_seed(), N, m->mtp_hnorm, mtp_cat + N, 2 * N, N, m->eps); // [... | h] + mm(m->eh_proj, mtp_cat, x, T); + k_rms<<>>(x, m->mtp.attn_norm, h, N, m->eps); + layer(m->mtp, m->layers.size(), T, pmax, pos0_m, use_graph, false, m->mtp_shnorm, hmtp); + mm(m->head, hmtp, logits_mr, T); + k_argmax<<>>(logits_mr, (int) g.n_vocab, pick_mr, amv, ami, false); + k_argmax<<>>(logits_mr, kArgBlocks, pick_mr, amv, ami, true); + }); + rows_deferred = false; + rows_mode = false; + CK(cudaMemcpyAsync(hrow + 32, pick_mr, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + for (int r = 0; r < T; ++r) mtp_pick[r] = hrow[32 + r]; + } + /// Row r's logits of the last step_rows, on the host. + void host_logits_row(int r, std::vector& out) { + out.resize((size_t) m->g.n_vocab); + CK(cudaMemcpyAsync(out.data(), logits + (size_t) r * m->g.n_vocab, out.size() * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + } + + /// Session dst takes session src's state: the recurrent state, the cache's first src.pos cells, the position, the + /// pictures' offset (for a conversation read in one session that continues in another). + void copy_session(int src, int dst) { + if (src == dst) return; + sess[(size_t) cur].pos = pos; + const auto& g = m->g; + const Sess& a = sess[(size_t) src]; + Sess& b = sess[(size_t) dst]; + const size_t C = (size_t) g.ssm_conv_channels; + const size_t row = (size_t) ctx * g.head_dim * 4; + for (size_t l = 0; l < a.conv.size(); ++l) { + if (a.conv[l]) { + CK(cudaMemcpyAsync(b.conv[l], a.conv[l], C * (g.ssm_d_conv - 1) * 4, cudaMemcpyDeviceToDevice, st)); + CK(cudaMemcpyAsync(b.S[l], a.S[l], (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4, + cudaMemcpyDeviceToDevice, st)); + } + if (a.kc[l] && a.pos > 0) { + CK(cudaMemcpy2DAsync(b.kc[l], row, a.kc[l], row, (size_t) a.pos * g.head_dim * 4, (size_t) g.n_head_kv, + cudaMemcpyDeviceToDevice, st)); + CK(cudaMemcpy2DAsync(b.vc[l], row, a.vc[l], row, (size_t) a.pos * g.head_dim * 4, (size_t) g.n_head_kv, + cudaMemcpyDeviceToDevice, st)); + } + } + CK(cudaMemcpyAsync(b.hlast, a.hlast, (size_t) g.n_embd * 4, cudaMemcpyDeviceToDevice, st)); + CK(cudaStreamSynchronize(st)); + b.pos = a.pos; + b.rdelta = a.rdelta; + b.live = a.live; + b.imgs = a.imgs; + if (dst == cur) load_cur(); } int hybrid_swaps_after_prompt = 2048; /// the MTP seed rows of a prompt chunk: a buffer the block's own forward does not use (`moe_out`, [tmax][N]) @@ -1828,7 +2314,11 @@ 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& fix, int D, std::vector& drafts, int32_t* picks) { + /// `cancel`: a stop asked for before the state moves keeps only x (the caller then emits no draft), so that a request + /// stopped mid-answer leaves the state at the tokens it has shown: a conversation that continues from them (the server's + /// hand-over of a stopped request to a batch slot) reuses it instead of reading them again. + int spec_step(int x_tok, const std::vector& fix, int D, std::vector& drafts, int32_t* picks, + const std::atomic* cancel = nullptr) { const int N = (int) m->g.n_embd; if (main_hybrid) D = std::min(D, (int) (kRebalanceEvery - pos % kRebalanceEvery) - 1); const int T0 = (int) fix.size() + 1; // the redo rows and the row of x @@ -1859,7 +2349,7 @@ struct Engine { CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(seeds, hmtp + (size_t) last_row * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); last_row = 0; - if (mtp_graph) graph_run(gm1, [&] { forward_mtp(1, pos + d, seeds, true, use_graph); }); + if (mtp_graph) graph_run(gs().gm1, [&] { forward_mtp(1, pos + d, seeds, true, use_graph); }); else forward_mtp(1, pos + d, seeds, true, false); CK(cudaMemcpyAsync(hpin + 2, pick_m, 4, cudaMemcpyDeviceToHost, st)); CK(cudaStreamSynchronize(st)); @@ -1873,12 +2363,13 @@ struct Engine { CK(cudaMemcpyAsync(tok, hpin + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); rows_deferred = true; - graph_run(gv[T], [&] { forward(T, pos, T, use_graph, true); }); + graph_run(gs().gv[T], [&] { forward(T, pos, T, use_graph, true); }); rows_deferred = false; CK(cudaMemcpyAsync(hpin + 2, pick, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); CK(cudaStreamSynchronize(st)); int a = 0; while (a < D && hpin[2 + a] == drafts[(size_t) a]) ++a; + if (cancel != nullptr && cancel->load()) a = 0; 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)); @@ -2193,49 +2684,387 @@ std::vector parse_ids(const char* s) { bool is_eos(int t) { return t == 248044 || t == 248046; } +// ------------------------------------------------------------------------------------------------ pictures +constexpr int32_t kImagePad = 248056; // <|image_pad|> + +uint64_t fnv1a(const void* p, size_t n, uint64_t h = 1469598103934665603ull) { + const uint8_t* b = (const uint8_t*) p; + for (size_t i = 0; i < n; ++i) h = (h ^ b[i]) * 1099511628211ull; + return h; +} + +/// A request's pictures: the encoder's rows in prompt order, each picture's cell run, and the positions. +struct ImgReq { + std::vector rows; + std::vector imgs; + std::vector cell_row; // per prompt cell: its row in `rows`, or -1 (text) + std::vector mrope; // [cell][3] t, h, w of every prompt cell (llama.cpp's mtmd positions) + int32_t delta = 0; // the text after the prompt: rotary position = cell + delta +}; + +/// Reads a strata-vision file (one or more records: int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats, in prompt +/// order) and lays the pictures over the prompt's <|image_pad|> runs. Positions as mtmd's: text counts up by one; a +/// picture's cells take (t, h, w) = (p, p + row, p + column) and the text after it continues at p + max(nx, ny). "" or +/// the error. `keys`: the server's key for each picture (img_keys=), else the embeddings' hash. +std::string build_images(const std::string& path, const std::vector& ids, int64_t n_embd, + const std::vector& keys, ImgReq& r) { + struct Img { int64_t n, nx, ny; size_t off; }; + std::vector imgs; + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return "cannot open " + path; + std::string ve; + while (ve.empty()) { + int32_t hdr[5]; + const size_t got = std::fread(hdr, sizeof(int32_t), 5, f); + if (got == 0) break; + if (got != 5 || hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || hdr[3] < 1 || (int64_t) hdr[2] * hdr[3] != hdr[1] || + hdr[4] != (int32_t) n_embd) { + ve = "bad embeddings file (expected strata-vision records of width " + std::to_string((long long) n_embd) + ")"; + break; + } + const size_t off = r.rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4]; + r.rows.resize(off + cnt); + if (std::fread(r.rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; } + imgs.push_back({hdr[1], hdr[2], hdr[3], off}); + } + std::fclose(f); + if (!ve.empty()) return ve; + const int64_t n = (int64_t) ids.size(); + r.cell_row.assign((size_t) n, -1); + r.mrope.assign((size_t) n * 3, 0); + auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) { + r.mrope[(size_t) c * 3] = (int32_t) t; + r.mrope[(size_t) c * 3 + 1] = (int32_t) h; + r.mrope[(size_t) c * 3 + 2] = (int32_t) w; + }; + int64_t p = 0, i = 0; + size_t k = 0; + while (i < n) { + if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; } + if (k >= imgs.size()) return "the prompt has more images than the embeddings file"; + const Img& im = imgs[k++]; + uint64_t h; + { // what the conversation cache compares: a picture is its grid and its key (or its embeddings) + const int64_t grid[3] = {im.n, im.nx, im.ny}; + h = fnv1a(grid, sizeof grid); + if (keys.size() == imgs.size()) h = fnv1a(&keys[k - 1], sizeof(uint64_t), h); + else h = fnv1a(r.rows.data() + im.off, (size_t) im.n * (size_t) n_embd * sizeof(float), h); + } + r.imgs.push_back({i, im.n, h}); + for (int64_t j = 0; j < im.n; ++j) + if (i + j >= n || ids[(size_t) (i + j)] != kImagePad) + return "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) + + " rows but fewer <|image_pad|> tokens"; + for (int64_t j = 0; j < im.n; ++j) { + const int64_t y = j / im.nx, x = j % im.nx; + put(i + j, p, p + y, p + x); + r.cell_row[(size_t) (i + j)] = (int32_t) ((im.off / (size_t) n_embd) + (size_t) j); + } + i += im.n; + p += std::max(im.nx, im.ny); + } + if (k != imgs.size()) return "the embeddings file has more images than the prompt"; + if (n > 0 && ids[(size_t) (n - 1)] == kImagePad) return "the prompt cannot end in an image"; + r.delta = (int32_t) (p - n); + return ""; +} + // ------------------------------------------------------------------------------------------------ serve -int serve(Engine& E) { - std::printf("READY %d stop\n", E.ctx); - std::fflush(stdout); +/// A batch slot: a session decoding (its next token is `x`, not yet in the state). +struct Slot { + bool active = false, stop = false; + int32_t x = 0; + int64_t produced = 0, max_new = 0; + Sampling smp; + std::mt19937_64 rng; + std::vector hist; + Clock::time_point t0; + int32_t draft = 0; // --batch-mtp: the MTP block's proposal for the token after `x` + bool draft_ready = false; + long long offered = 0, accepted = 0; +}; + +/// The engine protocol (serve/server.py). One request at a time on the control lines: GEN / GENI (alone: speculative +/// steps with the MTP block), or with --batch N BGEN / BGENI (the request's prompt is read into that slot's +/// session - the decode windows of the other slots go on between its chunks - then its tokens come as BT lines, one +/// window for every slot decoding, until BDONE). BSTOP ends a slot at its next window; STOP the request on the +/// control lines. +struct Serve { + Engine& E; std::mutex mu; std::condition_variable cv; std::deque lines; bool eof = false; std::atomic stop{false}; - std::thread reader([&] { - std::string l; - while (std::getline(std::cin, l)) { - if (!l.empty() && l.back() == '\r') l.pop_back(); - if (l == "STOP") { stop.store(true); continue; } - std::lock_guard lk(mu); - lines.push_back(l); - cv.notify_one(); - } - std::lock_guard lk(mu); - eof = true; - cv.notify_one(); - }); - reader.detach(); - std::vector live; // the tokens whose state the engine holds (cell i = live[i]) + std::vector slots; + int n_active = 0; std::vector lg; - for (;;) { - std::string line; - { - std::unique_lock lk(mu); - cv.wait(lk, [&] { return eof || !lines.empty(); }); - if (lines.empty()) return 0; - line = lines.front(); - lines.pop_front(); + // 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) { + 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() { + std::lock_guard lk(mu); + for (auto it = lines.begin(); it != lines.end();) { + if (it->rfind("BSTOP ", 0) == 0) { + const int b = std::atoi(it->c_str() + 6); + if (b >= 0 && b < (int) slots.size()) slots[(size_t) b].stop = true; + it = lines.erase(it); + } else if (it->rfind("BYIELD", 0) == 0) { // (a read here does not give way: the server then goes on) + it = lines.erase(it); + } else { + ++it; + } } - if (line.empty()) continue; - if (line.rfind("GEN ", 0) != 0) { - std::printf("ERR expected: GEN [key=value ...] \n"); + } + + /// One decode window with MTP proposals (--batch-mtp): every active slot's next token, and for up to kVerify - S of the + /// slots (the greedy ones, in turn) also the proposal its MTP block made: the window verifies both at once. A slot whose + /// proposal the main model confirms moves two tokens in the window. The proposals for the next window come right after + /// it, from the hidden states the window just produced (the first one of a slot from the state its prompt left). + int mtp_turn = 0; + void window_mtp() { + poll_control(); + const int N = (int) E.m->g.n_embd; + std::vector act; + for (int b = 0; b < E.n_sess; ++b) + if (slots[(size_t) b].active) act.push_back(b); + const int S = (int) act.size(); + if (S == 0) return; + // who verifies a proposal this window: the greedy slots in turn, as many as fit beside one row per slot + const int room = Engine::kVerify - S; + std::vector cand((size_t) S, 0); + int nc = 0; + for (int k = 0; k < S && nc < room; ++k) { + const int i = (mtp_turn + k) % S; + if (!slots[(size_t) act[(size_t) i]].smp.needs_logits()) { cand[(size_t) i] = 1; ++nc; } + } + ++mtp_turn; + // a candidate without a proposal gets its first one from the state its last row left + std::vector first; + std::vector first_of; + for (int i = 0; i < S; ++i) { + Slot& sl = slots[(size_t) act[(size_t) i]]; + if (cand[(size_t) i] && !sl.draft_ready) { + Engine::Sess& ss = E.sess[(size_t) act[(size_t) i]]; + first.push_back({act[(size_t) i], sl.x, ss.pos, ss.hlast}); + first_of.push_back(i); + } + } + if (!first.empty()) { + E.mtp_rows(first.data(), (int) first.size()); + for (size_t k = 0; k < first.size(); ++k) { + Slot& sl = slots[(size_t) act[(size_t) first_of[k]]]; + sl.draft = E.mtp_pick[k]; + sl.draft_ready = true; + } + } + std::vector gr((size_t) S); + std::vector row0((size_t) S); + int T = 0; + for (int i = 0; i < S; ++i) { + const Slot& sl = slots[(size_t) act[(size_t) i]]; + gr[(size_t) i] = {act[(size_t) i], cand[(size_t) i] ? 2 : 1, {sl.x, sl.draft}}; + row0[(size_t) i] = T; + T += gr[(size_t) i].n; + } + E.run_rows(gr.data(), S, true); + // the picks: emit, decide how many rows each slot keeps + std::vector keep((size_t) S, 1); + std::vector last((size_t) S, 0); + std::vector alive((size_t) S, 0); + for (int i = 0; i < S; ++i) { + const int b = act[(size_t) i]; + Slot& sl = slots[(size_t) b]; + Engine::Sess& ss = E.sess[(size_t) b]; + const int n = gr[(size_t) i].n, r0 = row0[(size_t) i]; + int y0 = E.rows_pick[r0]; + if (sl.smp.needs_logits()) { + E.host_logits_row(r0, lg); + y0 = sample(lg, sl.smp, sl.hist, sl.rng); + } + bool two = n == 2 && y0 == sl.draft && !is_eos(y0) && !sl.stop && sl.produced + 2 <= sl.max_new && + ss.pos + 3 <= E.ctx; // (ss.pos: the position of the slot's next token: the window did not move it) + if (n == 2) { ++sl.offered; if (two) ++sl.accepted; } + const int rows_kept = two ? 2 : 1; + keep[(size_t) i] = rows_kept; + const int32_t fed[2] = {sl.x, sl.draft}; + bool done = false; + int y = y0; + for (int j = 0; j < rows_kept; ++j) { + if (j == 1) y = E.rows_pick[r0 + 1]; + ss.live.push_back(fed[j]); + std::printf("BT %d %d\n", b, y); + ++sl.produced; + sl.hist.push_back(y); + const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" + : ss.pos + j + 2 > E.ctx ? "length" : nullptr; + if (fin) { + std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms_since(sl.t0)); + if (sl.offered > 0) + std::fprintf(stderr, "strata batch: slot %d: %lld of %lld MTP proposals accepted\n", b, sl.accepted, + sl.offered); + sl.active = false; + ss.active = false; + --n_active; + done = true; + break; + } + } + last[(size_t) i] = y; + alive[(size_t) i] = !done; + if (!done) sl.x = y; + } + E.commit_rows(gr.data(), keep.data(), S); + // the hidden state after each slot's last kept row (the seed of a later first proposal), and the next proposals + std::vector nx; + std::vector nx_of, nx_last; + for (int i = 0; i < S; ++i) { + const int b = act[(size_t) i]; + Engine::Sess& ss = E.sess[(size_t) b]; + const int r0 = row0[(size_t) i]; + CK(cudaMemcpyAsync(ss.hlast, E.hmain + (size_t) (r0 + keep[(size_t) i] - 1) * N, (size_t) N * 4, + cudaMemcpyDeviceToDevice, E.st)); + Slot& sl = slots[(size_t) b]; + sl.draft_ready = false; + if (!alive[(size_t) i] || !cand[(size_t) i]) continue; + const int64_t p_new = ss.pos; // commit_rows moved it: the cell of the token the next window feeds + if (keep[(size_t) i] == 2) { + nx.push_back({b, sl.draft, p_new - 1, E.hmain + (size_t) r0 * N}); + nx.push_back({b, last[(size_t) i], p_new, E.hmain + (size_t) (r0 + 1) * N}); + nx_last.push_back((int) nx.size() - 1); + } else { + nx.push_back({b, last[(size_t) i], p_new, E.hmain + (size_t) r0 * N}); + nx_last.push_back((int) nx.size() - 1); + } + nx_of.push_back(i); + } + std::fflush(stdout); + if (!nx.empty()) { + // (more rows than the window holds: the proposals come in two calls) + for (size_t at = 0, k = 0; at < nx.size();) { + size_t take = std::min(nx.size() - at, Engine::kVerify); + while (take > 0 && at + take < nx.size() && nx[at + take].slot == nx[at + take - 1].slot) --take; // a slot's rows together + E.mtp_rows(nx.data() + at, (int) take); + for (; k < nx_last.size() && (size_t) nx_last[k] < at + take; ++k) { + Slot& sl = slots[(size_t) act[(size_t) nx_of[k]]]; + sl.draft = E.mtp_pick[(size_t) nx_last[k] - at]; + sl.draft_ready = true; + } + at += take; + } + } + } + + /// One decode window over every active slot: one token each. + void window() { + poll_control(); + if (E.bmtp && E.mtp_d > 0) { // proposals need a row to spare and a slot that decodes greedily + int act = 0, greedy = 0; + for (const Slot& sl : slots) + if (sl.active) { ++act; greedy += !sl.smp.needs_logits(); } + if (greedy > 0 && Engine::kVerify - act > 0) { window_mtp(); return; } + } + window_plain(); + } + + /// One token of every active slot, no proposals. + void window_plain() { + std::vector rows; + for (int b = 0; b < E.n_sess; ++b) + if (slots[(size_t) b].active) rows.push_back({b, slots[(size_t) b].x}); + if (rows.empty()) return; + E.step_rows(rows.data(), (int) rows.size()); + const size_t Nb = (size_t) E.m->g.n_embd * 4; + for (size_t r = 0; r < rows.size(); ++r) { + const int b = rows[r].slot; + Slot& sl = slots[(size_t) b]; + Engine::Sess& ss = E.sess[(size_t) b]; + if (E.bmtp) // (the hidden state a later first proposal starts from) + CK(cudaMemcpyAsync(ss.hlast, E.hmain + r * (size_t) E.m->g.n_embd, Nb, cudaMemcpyDeviceToDevice, E.st)); + sl.draft_ready = false; + ss.live.push_back(sl.x); + int y; + if (sl.smp.needs_logits()) { + E.host_logits_row((int) r, lg); + y = sample(lg, sl.smp, sl.hist, sl.rng); + } else { + y = E.rows_pick[r]; + } + std::printf("BT %d %d\n", b, y); + ++sl.produced; + sl.hist.push_back(y); + const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" + : ss.pos + 1 > E.ctx ? "length" : nullptr; + if (fin) { + std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms_since(sl.t0)); + sl.active = false; + ss.active = false; + --n_active; + } else { + sl.x = y; + } + } + std::fflush(stdout); + } + + /// The length of session ss's held tokens when they are a proper start of `ids` with the same pictures, else 0. + size_t match_len(const Engine::Sess& ss, const std::vector& ids, const std::vector& imgs) const { + const size_t L = ss.live.size(); + if (L == 0 || L >= ids.size() || !std::equal(ss.live.begin(), ss.live.end(), ids.begin())) return 0; + std::vector in_live; + for (const ImgKey& k : imgs) { + if (k.cell + k.n <= (int64_t) L) in_live.push_back(k); + else if (k.cell < (int64_t) L) return 0; // the held tokens end inside a picture + } + return in_live == ss.imgs ? L : 0; + } + + /// The session a request alone takes: the one holding the longest start of its prompt, else an empty one, else the + /// least recently used (never a decoding slot). + int pick_session(const std::vector& ids, const std::vector& imgs) const { + int best = -1, free_empty = -1, lru = -1; + size_t bl = 0; + for (int i = 0; i < E.n_sess; ++i) { + const Engine::Sess& ss = E.sess[(size_t) i]; + if (ss.active) continue; + const size_t l = match_len(ss, ids, imgs); + if (l > bl) { bl = l; best = i; } + if (ss.live.empty() && free_empty < 0) free_empty = i; + if (lru < 0 || ss.used < E.sess[(size_t) lru].used) lru = i; + } + return best >= 0 ? best : free_empty >= 0 ? free_empty : lru; + } + + void request(const std::string& line) { + const bool adm = line[0] == 'B'; + const bool geni = line.rfind(adm ? "BGENI " : "GENI ", 0) == 0; + if (!adm && !geni && line.rfind("GEN ", 0) != 0) { + std::printf("ERR expected: GEN [key=value ...] or GENI [keys] \n"); std::fflush(stdout); - continue; + return; } - char* p = nullptr; - const long long max_new = std::strtoll(line.c_str() + 4, &p, 10); + char* p = const_cast(line.c_str()) + (adm ? (geni ? 6 : 5) : (geni ? 5 : 4)); + int slot = -1; + if (adm) { + char* e1 = nullptr; + const long b = std::strtol(p, &e1, 10); + p = e1; + slot = (int) b; + if (e1 == line.c_str() || b < 0 || b >= (long) slots.size() || slots[(size_t) b].active || E.n_sess < 2) { + std::printf("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n", E.n_sess < 2 ? 0 : E.n_sess); + std::fflush(stdout); + return; + } + } + const long long max_new = std::strtoll(p, &p, 10); Sampling smp; + std::vector img_keys; for (;;) { while (*p == ' ') ++p; const char* st0 = p; @@ -2254,51 +3083,159 @@ int serve(Engine& E) { else if (key == "penalty_freq") smp.freq = std::strtof(v, nullptr); else if (key == "penalty_present") smp.present = std::strtof(v, nullptr); else if (key == "seed") smp.seed = std::strtoull(v, nullptr, 10); + else if (key == "img_keys") { + const char* q = v; + img_keys.clear(); + while (*q) { + char* qe = nullptr; + const unsigned long long x = std::strtoull(q, &qe, 16); + if (qe == q) { img_keys.clear(); break; } + img_keys.push_back((uint64_t) x); + q = *qe == ',' ? qe + 1 : qe; + if (*qe != ',' && *qe != '\0') { img_keys.clear(); break; } + } + } + } + std::string emb; + if (geni) { + while (*p == ' ') ++p; + const char* e = p; + while (*e && *e != ' ') ++e; + emb.assign(p, (size_t) (e - p)); + p = const_cast(e); } const std::vector ids = parse_ids(p); - if (max_new < 1 || ids.empty()) { + if (max_new < 1 || ids.empty() || (geni && emb.empty())) { std::printf("ERR bad request: max_new or the ids\n"); std::fflush(stdout); - continue; + return; + } + if (geni && !E.vision) { + std::printf("ERR this engine was started without --vision\n"); + std::fflush(stdout); + return; } if ((int64_t) ids.size() + max_new > E.ctx) { std::printf("ERR prompt (%zu tokens) + max_new (%lld) exceeds the context (%d)\n", ids.size(), max_new, E.ctx); std::fflush(stdout); - continue; + return; } bool bad = false; for (int32_t t : ids) bad |= t < 0 || t >= (int32_t) E.m->g.n_vocab; - if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); std::fflush(stdout); continue; } - stop.store(false); - // the held state continues when the request extends it (the recurrent state cannot step back) - size_t reuse = 0; - if (live.size() < ids.size() && std::equal(live.begin(), live.end(), ids.begin())) reuse = live.size(); - else { - E.reset(); - live.clear(); + if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); std::fflush(stdout); return; } + ImgReq ir; + if (geni) { + const std::string ve = build_images(emb, ids, E.m->g.n_embd, img_keys, ir); + if (!ve.empty()) { std::printf("ERR %s\n", ve.c_str()); std::fflush(stdout); return; } } + stop.store(false); + // ---- the session: the held state continues when the request extends it (the recurrent state cannot step back) + const int s = adm ? slot : pick_session(ids, ir.imgs); + Engine::Sess& ss = E.sess[(size_t) s]; + size_t reuse = match_len(ss, ids, ir.imgs); + if (adm) { // another session holding more of this prompt (the conversation was read alone): copy its state + int src = -1; + size_t best = reuse; + for (int i = 0; i < E.n_sess; ++i) { + if (i == s || E.sess[(size_t) i].active) continue; + const size_t l = match_len(E.sess[(size_t) i], ids, ir.imgs); + if (l > best) { best = l; src = i; } + } + if (src >= 0) { + E.copy_session(src, s); + reuse = best; + } + } + E.select(s); + if (reuse == 0) { + E.reset(); + ss.live.clear(); + ss.imgs.clear(); + } + if (geni) E.set_images(ir.rows, ir.cell_row, ir.mrope, (int64_t) ids.size(), ir.delta); + else E.clear_images(); const auto t0 = Clock::now(); const int64_t fresh = (int64_t) (ids.size() - reuse); - E.process(ids.data() + reuse, fresh, [&](int64_t done) { + bool cancelled = false; + const int64_t got = E.process(ids.data() + reuse, fresh, [&](int64_t done) -> bool { 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) { + 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; }); - live.insert(live.end(), ids.begin() + (long) reuse, ids.end()); + ss.live.insert(ss.live.end(), ids.begin() + (long) reuse, ids.begin() + (long) reuse + (long) got); + ss.imgs.clear(); + bool cut = false; + for (const ImgKey& k : ir.imgs) { + if (k.cell + k.n <= (int64_t) ss.live.size()) ss.imgs.push_back(k); + else if (k.cell < (int64_t) ss.live.size()) cut = true; + } + if (cancelled && cut) { // stopped inside a picture: the state cannot be continued, the next read starts over + ss.live.clear(); + ss.imgs.clear(); + } + E.sess[(size_t) E.cur].pos = E.pos; const double prompt_ms = ms_since(t0); + if (cancelled) { + std::printf("DONE 0 %zu %.1f 0.0 cancel 0 0 %zu 0 0 0 0 0.0 %lld 0\n", ids.size(), prompt_ms, reuse, (long long) got); + if (adm) std::printf("BADM %d 0\n", slot); + std::fflush(stdout); + return; + } std::mt19937_64 rng(smp.seed); std::vector hist = ids; const auto d0 = Clock::now(); long long produced = 0, offered = 0, accepted = 0; const char* finish = "length"; - // greedy requests with the MTP block: speculative steps of mtp_d drafts (verified, so the text is the greedy - // text); sampled ones one token at a time - const bool spec = E.mtp_d > 0 && !smp.needs_logits(); + // greedy requests alone with the MTP block: speculative steps of mtp_d drafts (verified, so the text is the greedy + // text); sampled ones, and requests beside others, one token at a time + const bool spec = E.mtp_d > 0 && !smp.needs_logits() && !adm; std::vector fix, drafts; int32_t picks[16]; int nx = smp.needs_logits() ? -1 : E.greedy(); - bool done = false; - while (!done) { + if (adm) { + if (smp.needs_logits()) { + E.host_logits(lg); + nx = sample(lg, smp, hist, rng); + } + std::printf("T %d\n", nx); + ++produced; + hist.push_back(nx); + const char* fin = is_eos(nx) ? "stop" : stop.load() ? "cancel" : max_new <= 1 ? "length" + : E.pos + 1 > E.ctx ? "length" : nullptr; + const bool cont = fin == nullptr; + std::printf("DONE %lld %zu %.1f %.1f %s 0 0 %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms, + ms_since(d0), cont ? "length" : fin, reuse, (long long) fresh); + if (cont) { + Slot& sl = slots[(size_t) slot]; + sl = Slot{}; + sl.active = true; + sl.x = nx; + sl.produced = 1; + sl.max_new = max_new; + sl.smp = smp; + sl.rng = rng; + sl.hist = hist; + sl.t0 = Clock::now(); + ss.active = true; + ++n_active; + } + 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; + } + for (;;) { if (smp.needs_logits()) { E.host_logits(lg); nx = sample(lg, smp, hist, rng); @@ -2314,42 +3251,107 @@ int serve(Engine& E) { return true; }; if (!emit(nx)) break; - if (spec && E.pos + E.mtp_d + 1 <= E.ctx) { - const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks); + 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, &stop); offered += E.mtp_d; accepted += a; - live.push_back(nx); + // the state now holds x and every accepted draft, whether or not the answer ends inside them (an end of + // answer, max_new): the held tokens say so, so a later request that continues this conversation matches them + // (a prompt that has the same tokens next reuses the state, any other reads from the start) and never 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) { - live.push_back(drafts[(size_t) i]); - if (!emit(drafts[(size_t) i])) { done = true; break; } - } + bool ended = false; + for (int i = 0; i < a && !ended; ++i) + if (!emit(drafts[(size_t) i])) ended = true; + if (ended) break; nx = picks[a]; continue; } if (E.pos + 1 > E.ctx) break; const int32_t one = nx; E.process(&one, 1, [](int64_t) {}); - live.push_back(nx); + ss.live.push_back(nx); fix.clear(); if (!smp.needs_logits()) nx = E.greedy(); } + E.sess[(size_t) E.cur].pos = E.pos; const double decode_ms = ms_since(d0); 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() { + if (E.n_sess > 1) std::printf("INFO batch_slots=%d slot_cache=1\n", E.n_sess); + std::printf("READY %d stop\n", E.ctx); + std::fflush(stdout); + std::thread reader([&] { + std::string l; + while (std::getline(std::cin, l)) { + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (l == "STOP") { stop.store(true); continue; } + std::lock_guard lk(mu); + lines.push_back(l); + cv.notify_one(); + } + std::lock_guard lk(mu); + eof = true; + cv.notify_one(); + }); + reader.detach(); + for (;;) { + std::string line; + bool have = false; + { + std::unique_lock lk(mu); + if (n_active == 0) cv.wait(lk, [&] { return eof || !lines.empty(); }); + if (!lines.empty()) { + line = lines.front(); + lines.pop_front(); + have = true; + } else if (n_active == 0) { + return 0; + } + } + if (!have) { window(); continue; } + if (line.empty()) continue; + if (line.rfind("BSTOP ", 0) == 0) { + const int b = std::atoi(line.c_str() + 6); + if (b >= 0 && b < (int) slots.size()) slots[(size_t) b].stop = true; + } else if (line.rfind("BYIELD", 0) == 0) { + // (a read that has ended) + } else if (line.rfind("GEN", 0) == 0 || line.rfind("BGEN", 0) == 0) { + request(line); + } else { + std::printf("ERR expected: GEN [key=value ...] \n"); + std::fflush(stdout); + } + if (n_active > 0) window(); + } + } +}; + +int serve(Engine& E) { + Serve sv(E); + return sv.run(); } } // namespace int strata::qwen35::run(int argc, char** argv) { - std::string model, tokens, force, dump_full; + std::string model, tokens, force, dump_full, emb_file; int ctx = 32768, chunk = 0, n_gen = 64, bench_pp = 0, bench_tg = 0, mtp_d = 0, cpu_threads = 0, hybrid_rows = 128; double expert_vram = -1.0; bool warm = true; - int expert_slots = 0; - bool serve_mode = false, graph = true; + int expert_slots = 0, batch = 0; + bool serve_mode = false, graph = true, vision = false, batch_mtp = false; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; auto next = [&]() -> std::string { @@ -2369,6 +3371,7 @@ int strata::qwen35::run(int argc, char** argv) { else if (a == "--tokens") tokens = next(); else if (a == "--n") n_gen = std::atoi(next().c_str()); else if (a == "--force") force = next(); + else if (a == "--emb") emb_file = next(); // --tokens with pictures: a strata-vision file (the ids carry <|image_pad|> runs) else if (a == "--dump-full-logits") dump_full = next(); else if (a == "--bench-pp") bench_pp = std::atoi(next().c_str()); else if (a == "--bench-tg") bench_tg = std::atoi(next().c_str()); @@ -2381,6 +3384,9 @@ int strata::qwen35::run(int argc, char** argv) { else std::fprintf(stderr, "strata-q36: ignoring --mtp %s (this family's MTP is the GGUF's own block: --mtp N " "drafts)\n", v.c_str()); } + else if (a == "--vision") vision = true; // pictures (GENI): the encoder is strata-vision's + else if (a == "--batch" || a == "--slots") batch = std::atoi(next().c_str()); // sessions decoding together + else if (a == "--batch-mtp") batch_mtp = true; // ... each verifying an MTP proposal else if (a == "--expert-vram") expert_vram = std::atof(next().c_str()); // GiB for the routed experts else if (a == "--cpu-threads") cpu_threads = std::atoi(next().c_str()); else if (a == "--expert-slots") expert_slots = std::atoi(next().c_str()); @@ -2440,7 +3446,7 @@ int strata::qwen35::run(int argc, char** argv) { std::fprintf(stderr, "strata-q36: chunk rule: free %.2f GiB (with %.2f packed), main experts %.2f GiB\n", fr / 1073741824.0, packed / 1073741824.0, experts / 1073741824.0); } - E.init(m, ctx, chunk); + E.init(m, ctx, chunk, batch, vision); if (!place_experts(m, E, expert_vram, cpu_threads, hybrid_rows, expert_slots, err)) { std::fprintf(stderr, "strata-q36: %s\n", err.c_str()); return 1; @@ -2457,6 +3463,8 @@ int strata::qwen35::run(int argc, char** argv) { } report{E}; E.reset(); E.mtp_d = m.has_mtp ? mtp_d : 0; + E.bmtp = (batch_mtp || (std::getenv("STRATA_BATCH_MTP") != nullptr && std::string(std::getenv("STRATA_BATCH_MTP")) != "0")) && E.n_sess > 1 && E.mtp_d > 0; + if (batch_mtp && !E.bmtp) std::fprintf(stderr, "strata-q36: --batch-mtp needs --batch N (2 or more) and --mtp N: ignored\n"); if (warm) E.warmup(); if (serve_mode) return serve(E); if (bench_pp > 0 || bench_tg > 0) { @@ -2491,6 +3499,15 @@ int strata::qwen35::run(int argc, char** argv) { FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); std::vector lg; std::vector gen; + if (!emb_file.empty()) { + if (!vision) { std::fprintf(stderr, "strata-q36: --emb needs --vision\n"); return 2; } + ImgReq ir; + const std::string ve = build_images(emb_file, prompt, m.g.n_embd, {}, ir); + if (!ve.empty()) { std::fprintf(stderr, "strata-q36: %s\n", ve.c_str()); return 2; } + E.set_images(ir.rows, ir.cell_row, ir.mrope, (int64_t) prompt.size(), ir.delta); + std::fprintf(stderr, "strata-q36: %zu picture(s), %zu rows, text after them at cell + %d\n", ir.imgs.size(), + ir.rows.size() / (size_t) m.g.n_embd, (int) ir.delta); + } const auto t0 = Clock::now(); E.process(prompt.data(), (int64_t) prompt.size(), [](int64_t) {}); const double pp_ms = ms_since(t0); diff --git a/tools/qwen35/make_big_picture.py b/tools/qwen35/make_big_picture.py new file mode 100644 index 00000000..98ef33bf --- /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/parity_prompts.ids b/tools/qwen35/parity_prompts.ids new file mode 100644 index 00000000..81968c47 --- /dev/null +++ b/tools/qwen35/parity_prompts.ids @@ -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 diff --git a/tools/qwen35/pictures/big1024.png b/tools/qwen35/pictures/big1024.png new file mode 100644 index 00000000..b58d7023 Binary files /dev/null and b/tools/qwen35/pictures/big1024.png differ diff --git a/tools/qwen35/pictures/code4217.png b/tools/qwen35/pictures/code4217.png new file mode 100644 index 00000000..1b1cefb8 Binary files /dev/null and b/tools/qwen35/pictures/code4217.png differ diff --git a/tools/qwen35/pictures/shapes.png b/tools/qwen35/pictures/shapes.png new file mode 100644 index 00000000..4e5a72a3 Binary files /dev/null and b/tools/qwen35/pictures/shapes.png differ diff --git a/tools/qwen35/q36_batch_gate.py b/tools/qwen35/q36_batch_gate.py new file mode 100644 index 00000000..5e79bb14 --- /dev/null +++ b/tools/qwen35/q36_batch_gate.py @@ -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) diff --git a/tools/qwen35/q36_cmp_gate.py b/tools/qwen35/q36_cmp_gate.py new file mode 100644 index 00000000..078f96a7 --- /dev/null +++ b/tools/qwen35/q36_cmp_gate.py @@ -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) diff --git a/tools/qwen35/q36_harness.py b/tools/qwen35/q36_harness.py new file mode 100644 index 00000000..48a6e4bd --- /dev/null +++ b/tools/qwen35/q36_harness.py @@ -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() diff --git a/tools/qwen35/q36_interleave_probe.py b/tools/qwen35/q36_interleave_probe.py new file mode 100644 index 00000000..f838671e --- /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 new file mode 100644 index 00000000..af208b27 --- /dev/null +++ b/tools/qwen35/q36_mtmd_dump.cpp @@ -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/include -I/ggml/include -I/tools/mtmd -L/build/bin +// -lllama -lmtmd -lggml -lggml-base -Wl,-rpath,/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 +#include +#include +#include +#include + +static std::vector parse_ids(const std::string& s) { + std::vector 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 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 bws; + std::vector 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 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 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; +} diff --git a/tools/qwen35/q36_par_bench.py b/tools/qwen35/q36_par_bench.py new file mode 100644 index 00000000..f9718114 --- /dev/null +++ b/tools/qwen35/q36_par_bench.py @@ -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) diff --git a/tools/qwen35/q36_proto_edge.py b/tools/qwen35/q36_proto_edge.py new file mode 100644 index 00000000..a7d623f1 --- /dev/null +++ b/tools/qwen35/q36_proto_edge.py @@ -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) diff --git a/tools/qwen35/q36_serve_handoff.py b/tools/qwen35/q36_serve_handoff.py new file mode 100644 index 00000000..96b60ce0 --- /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_serve_par.py b/tools/qwen35/q36_serve_par.py new file mode 100644 index 00000000..fe6f4a06 --- /dev/null +++ b/tools/qwen35/q36_serve_par.py @@ -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) diff --git a/tools/qwen35/q36_solo_gate.py b/tools/qwen35/q36_solo_gate.py new file mode 100644 index 00000000..09caadab --- /dev/null +++ b/tools/qwen35/q36_solo_gate.py @@ -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() diff --git a/tools/qwen35/q36_venc.py b/tools/qwen35/q36_venc.py new file mode 100644 index 00000000..2520a03f --- /dev/null +++ b/tools/qwen35/q36_venc.py @@ -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() diff --git a/tools/qwen35/q36_vision_cmp.py b/tools/qwen35/q36_vision_cmp.py new file mode 100644 index 00000000..370183eb --- /dev/null +++ b/tools/qwen35/q36_vision_cmp.py @@ -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\n\n\n\n" +PAD = 248056 +TEMPLATE_PAIR = ("<|im_start|>user\nPicture 1: <__media__>\nPicture 2: <__media__>\n{q}<|im_end|>\n<|im_start|>assistant\n" + "\n\n\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() diff --git a/tools/qwen35/q36_vision_proto.py b/tools/qwen35/q36_vision_proto.py new file mode 100644 index 00000000..d64ccea2 --- /dev/null +++ b/tools/qwen35/q36_vision_proto.py @@ -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 (.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) diff --git a/tools/qwen35/q36_vision_serve.py b/tools/qwen35/q36_vision_serve.py new file mode 100644 index 00000000..5bb59c1e --- /dev/null +++ b/tools/qwen35/q36_vision_serve.py @@ -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) diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py index 7358a3d8..3c76181c 100644 --- a/tools/test_setup_qwen36.py +++ b/tools/test_setup_qwen36.py @@ -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