diff --git a/CMakeLists.txt b/CMakeLists.txt index 724c3c48..86b90ec1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1056,6 +1056,12 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) + if(STRATA_BUILD_TESTS) + # the Q5_1 block dequantizer (a Q5_1 PLE table) against ggml's, synthetic blocks: no model, no GPU + add_executable(dequant_q5_1_test tests/core/dequant_q5_1_test.cpp) + target_link_libraries(dequant_q5_1_test PRIVATE strata_artifact ggml-base) + add_test(NAME dequant_q5_1_test COMMAND dequant_q5_1_test) + endif() # the router lookahead's dot on each rung this CPU has (AVX2, the older CPUs' AVX1) against a double reference add_executable(router_dot_parity src/kernels/cpu/router_dot_parity.cpp) target_link_libraries(router_dot_parity PRIVATE strata_kernels_cpu) @@ -1205,7 +1211,9 @@ if(STRATA_NATIVE_EXPERTS) # kernel for it before; q5_0/q5_0 (both roles Q5_0) is left out of this list since stacking the same # lower-precision format on both roles pushes the GPU path over this test's 3% threshold (quantization # noise, not a kernel bug -- see the PR). - foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0) + # q4_0/q4_0 and q4_0/q4_1: a plain llama-quantize Q4_0 file (bartowski's Qwen3.8-Flash-Next-Q4_0: gate/up Q4_0, + # down Q4_0 on 42 layers and Q4_1 on 6) + foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0 q4_0/q4_0 q4_0/q4_1) string(REPLACE "/" "_" _name "${_pair}") add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md b/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md new file mode 100644 index 00000000..2935e016 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md @@ -0,0 +1,70 @@ +# Community benchmark on 2x Intel Arc Pro B60 + +Measured on 2026-10-04 by LocalXPU. This is the SYCL port (`sycl/`) on two Arc Pro B60 cards, one request at a time, at an 8,192-token context. It is a short test: two prompt sizes, 2 to 3 requests each. It is not a 4K/32K/128K sweep. + +## Hardware and software + +- 2x Intel Arc Pro B60 24 GB (`8086:e211`, 456 GB/s each), PCIe 3.0 x8 per card; Ryzen 5 5600; 64 GB DDR4; storage type not recorded +- Ubuntu 24.04, kernel 6.17 (`xe` driver), Level Zero V2, compute runtime NEO 26.09.37435.12, oneAPI DPC++ 2026.1.1, oneMKL 2026.1.0 +- Strata `6f32ec0` plus two `sycl/` fixes (the build fix for #559/#626 and the `cudaStreamQuery` fix in the ring wait); engine reports `0.1.39-sycl`; AOT `-DSTRATA_SYCL_AOT=bmg-g21`; source build, no Docker +- Nothing else ran on the GPUs. The kernel log was watched for `xe` resets during every run: none. + +## Model and configuration + +- Coder IQ1_M (`Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M`, shard hashes checked against the Hugging Face LFS ids), `--layer-split 24` +- Flash-Next IQ2_XS (`Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS`), `--layer-split 25` +- Packs from `tools/iq_pack.py`, MTP layer from `tools/mtp_fetch.py` / `mtp_pack.py` / `mtp_rt.py`, profiles from `data/` +- Context 8,192; KV int8; `--spec 4 --spec-min-p 0.5`; greedy (`temperature 0`), `enable_thinking: false`; no vision + +`data/coder2.json` and `data/iq2b.json` are the exact server configs (engine arguments and environment); the engine's startup and stage lines are in `data/coder2.engine.txt`, `data/iq2b.engine.txt` and, for the one-card run, `data/B2.run.txt`. Served with +`sycl/serve/server_intel.py --engine strata --config --port 8085`. + +## Method + +Requests went through `/v1/chat/completions`, one at a time. Prompt and decode speed are the server's own `timings` object +(`prompt_per_second`, `predicted_per_second`), per request; `bench.py` prints them (copy in `data/`, raw output in `data/c2-*.txt`, `data/i2-*.txt`). +Model loading is not included. Three prompts: + +- short: "Write a Python function that returns the n-th Fibonacci number" (23 prompt tokens cold, 7 fresh after the cached prefix) +- 2K code: about 2,000 tokens of the repository's `tools/*.py` plus "write a binary search tree class" (1,922 prompt tokens, none reused); the second turn reuses the first +- 2K prose: about 2,100 tokens of source plus "say what this code is for" (2,129 prompt tokens, none reused); the repeat reuses 2,122 of them + +## Results + +All experts were resident in VRAM on both cards in both runs (engine line `layer split: 100% of the experts resident`), so `STRATA_VERIFY_NO_HOST=1` was set. + +| Configuration | Prompt tokens (fresh) | Reused | Generated | Requests | Prompt tok/s | Decode tok/s | Drafts accepted | +| --- | ---: | ---: | ---: | ---: | --- | --- | --- | +| Coder IQ1_M, short | 23 / 7 | 0 / 16 | 159 | 3 | 50.4 cold, 74-80 | 52.8 first, 56.6 and 56.6 | 112/138, 114/133 | +| Coder IQ1_M, 2K code | 1,922 | 0 | 256 | 1 | 425.3 | 57.2 | 186/208 | +| Coder IQ1_M, 2K code, next turn | 21 | 2,178 | 256 | 1 | 61.4 | 71.4 | 209/212 | +| Coder IQ1_M, 2K prose | 2,129 | 0 | 128 | 1 | 427.9 | 40.1 | 70/98 | +| Coder IQ1_M, 2K prose, repeat | 7 | 2,122 | 128 | 1 | 78.1 | 41.3 | 70/98 | +| IQ2_XS, short | 23 / 7 | 0 / 16 | 112 | 2 | 50.4 cold, 81.7 | 58.6 and 61.3 | 84/88, 84/89 | +| IQ2_XS, 2K code | 1,922 | 0 | 256 | 1 | 445.1 | 55.5 | 183/213 | +| IQ2_XS, 2K code, next turn | 284 | 1,915 | 256 | 1 | 177.0 | 72.5 | 211/217 | +| IQ2_XS, 2K prose | 2,129 | 0 | 104 | 1 | 436.4 | 38.8 | 56/87 | +| IQ2_XS, 2K prose, repeat | 7 | 2,122 | 104 | 1 | 79.3 | 40.0 | 56/87 | + +The two prose rows are slower because fewer drafts were accepted (71% and 64%), not because of the context: the 256-token code reply at the same context ran 57.2 and 55.5. +Time to first token was not measured separately. + +One card, Coder IQ1_M, 4,042 of 12,288 experts mirrored in pinned RAM (`STRATA_MIRROR_MIB=8192`, `ONEAPI_DEVICE_SELECTOR=level_zero:0`), +by-hand `--tokens` run, 11-token prompt, 128 greedy tokens: **11.9 tok/s** (11.2 to 11.9 over five builds that differ only in experiments), coherent Python. +Without the ring-wait fix this configuration stopped at layer 15 with `never rang (graph finished)` in 5 of 5 tries. +The engine's stage table shows `wait for rings` at 186.8 ms per round, about 3.9 ms per layer. It drops to 72.9 ms and 25.1 tok/s with `kSpinMax` 2,000 in +`sycl/include/strata/sycl_doorbell.hpp`, which suggests the GPU does not see the host's flag stores during the spin kernel and waits out the bound. That change +risks proceeding before a slow host answers, so it is not part of this report. + +Memory after load (`xpu-smi`, MiB, card 0 / card 1): Coder 14,592 / 17,456; IQ2_XS 20,246 / 20,573. The tightest card kept 3.7 GB free of the 24 GB with `--vram-reserve-mib 1536`. + +## Correctness and limitations + +- Both models, `/v1/chat/completions`: a Fibonacci function executed against the first ten values and `fn(50) == 12586269025`; a Euclid `gcd` executed on four pairs; a palindrome check (IQ2_XS); `sum(i*i for i in range(1,11))` answered `385`. All passed. +- A three-turn conversation (a name and a number, then arithmetic on it, then a lambda using both) was answered correctly by both models, and the conversation cache reused 41 and 74 tokens. +- No NaN, garbage or repetition loop in any output. +- Not done: the 19-token chat-templated prompt from the docs (no token-for-token comparison with the reference text), streaming, the Anthropic route, tool calls, contexts above 2.2K, `--layer-split auto`, a run with `STRATA_VERIFY_NO_HOST=1` and experts outside VRAM. +- Kernel tests (`ctest`, one B60): 21 of 25 pass; `iq_parity` passes for all 10 formats once its fixtures exist; `ple_parity` needs the Q2_0 shard; `s2_expert_grouped_parity` fails 4 bitwise comparisons while its host-reference check is within tolerance; `conversation_snapshot_test` aborts with `munmap_chunk(): invalid pointer`. +- One `xe` GT reset on card 0, during the first `iq_parity` run (it did not finish in 300 s and was killed by a timeout; the same binary then passed in under 90 s). The card recovered without a reboot. + +Paths in `data/` were shortened: `` is the directory with the models, packs and MTP layer, `` the Strata source tree. diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/B2.run.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/B2.run.txt new file mode 100644 index 00000000..aa646dd2 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/B2.run.txt @@ -0,0 +1,54 @@ +IDS=7734,264,12654,709,421,4523,279,307,7324,76938,1324 +strata generate: PCIe probe: 7.0 GB/s host->device (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 (default 0.55) +strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows) +strata generate: native pack: /packs/coder-iq1_m experts (largest blob 2.66 MB), token embedding IQ4_XS in mapped host memory (322 MiB) +strata generate: 1406 MiB of weights loaded from /packs/coder-iq1_m (302 canonical tensors skipped: served natively) +strata generate: 300 native projection matrices, 2018.88 MiB of weights +strata generate: the SSD is kept awake while rows are read: one page of the table after 100 ms without a read, until 60 s after the last request (STRATA_SSD_KEEPALIVE=0 turns it off) +strata generate: profile data/expert-profile-coder.bin: 12288 ranked pairs, built for 12288 slots +strata generate: PLE on, table 320001536 rows of /models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf +strata mtp: draft layer loaded, 802 MiB of VRAM (experts 675, dense 111), files read in 0.45 s (1746 MiB/s) +strata generate: experimental native Q5_K head, 521472000 bytes +strata generate: GPU 0: Intel(R) Arc(TM) Pro B60 Graphics, compute capability 20.1 +strata generate: WARNING: this engine was compiled with CUDA 12.8 headers but loaded a CUDA 0.2 runtime (libcudart): GPU properties can read wrong and some kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542) +strata generate: experts streamed from the GGUF on demand (--stream-experts): no host arena; every expert must fit the VRAM cache +strata generate: expert cache auto: 18.90 GiB free, 1536 MiB reserved (+218 MiB for the draft head) -> 6331 slots +strata generate: expert cache 8246 slots, 15.70 GiB of VRAM; policy is +strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU, + so a reply can differ slightly from a run without the cache (same quality: + bench/results/2026-09-27-cache-parity). + PROFILE, ranked by routing frequency, no eviction. +strata generate: profile fill: 15.70 GiB in 2.5 s (6.79 GB/s, pipelined) +strata generate: pre-filled 8246 of 8246 slots from the profile; slot 0 verified +strata generate: 4042 of 4042 experts missing from VRAM mirrored in pinned host memory (7.72 GiB, 1.3 s); the GPU reads them over PCIe +strata generate: R4 hit path ON - resident experts are computed on the GPU +strata generate: 5 expert-pool workers + the host thread +strata generate: session is up (engine 0.1.39-sycl) +strata generate: sampling greedy +strata generate: token graph hit path: 8246 resident experts, decided on the device +strata generate: prompt path allocates its own buffers (no cache slots to borrow) +strata mtp: draft head over 106299 tokens (212.9 MiB) +strata generate: prefill 10 tokens in 1 chunks, 563.9 ms (17.7 tok/s); experts streamed 354 (354 by DMA, host 5.2 ms), resident 1689; PLE 2.7 ms +strata verify: window up to 6 tokens, 74.0 MiB of device buffers +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 5-token window (upload , sync ) +strata verify: captured the 6-token window (upload , sync ) +strata generate: window and draft graphs captured in 125 ms +speculation 50 rounds of 6, drafts accepted 81 of 98 (0.827), 2.62 tokens per round +window sizes T1:11 T2:8 T3:3 T4:28 T5:0 T6:0 (min draft probability 0.50) +suffix drafts 3 windows, drafts accepted 8 of 9 +accepted per round 0:14 1:10 2:7 3:19 4:0 5:0 +verify window wait for rings 186.845 pool 10.966 host 1.142 commit 9.963 ms/round; CPU experts 2.50 distinct / 3.33 routed per layer +pool multi gate/up 6.183 quantize 0.025 down 2.868 ms/round; 27.1 GB/s over the rows phases; CPU pool call 10.958 ms/round +dispatch plan 0.100 activation quantize 0.254 jobs 1.514 run 9.080 ms/round +adaptive tier 1069 experts swapped into the VRAM tier (every 4 rounds, 0.839 ms/round) +pcie experts 0.21 distinct experts per layer read over PCIe (share 49/256 of the misses) +mtp 10.095 ms/round drafting (49 rounds), MTP prompt 6.8 ms, 1015 MiB of VRAM +prompt : 7734 264 12654 709 421 4523 279 307 7324 76938 1324 +output : 1608 48575 13 271 727 15336 1393 1590 198 262 413 307 2564 220 16 25 198 285 460 307 198 262 460 15336 1393 12 16 8 478 15336 1393 12 17 8 271 760 709 3294 369 264 4145 29812 7873 314 279 76938 8240 13 4213 11 424 369 524 10727 364 3349 2663 314 307 1521 424 95272 3205 942 279 1788 2663 5081 2942 13 1946 7042 14588 11 567 628 958 20781 1954 310 3436 8334 16100 2663 13 248046 198 248045 846 198 7734 264 12654 709 421 4523 279 307 7324 76938 1324 1608 48575 248046 198 248045 74455 198 248068 198 760 1156 6587 264 12654 709 421 4523 279 307 7324 76938 1324 1608 48575 13 1061 369 +decode 128 tokens in 10735.2 ms -> 11.92 tok/s +prefill 10 tokens in 563.9 ms -> 17.73 tok/s (time to first token 809.0 ms) +EXIT=0 diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/bench.py b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/bench.py new file mode 100644 index 00000000..41b46ad7 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/bench.py @@ -0,0 +1,41 @@ +import json,sys,re,urllib.request,time,glob +URL="http://127.0.0.1:8085/v1/chat/completions" +def ask(msgs,max_tokens=256): + body={"messages":msgs,"max_tokens":max_tokens,"temperature":0,"chat_template_kwargs":{"enable_thinking":False}} + t=time.time() + r=urllib.request.urlopen(urllib.request.Request(URL,json.dumps(body).encode(),{"content-type":"application/json"}),timeout=900) + d=json.load(r); d["wall"]=time.time()-t + return d +def show(tag,d): + tm=d["timings"];u=d["usage"] + print(f"[{tag}] prompt_n={tm['prompt_n']} cache_n={tm['cache_n']} prompt {tm['prompt_per_second']:.1f} tok/s | decode {tm['predicted_n']} tok {tm['predicted_per_second']:.1f} tok/s | drafts {tm.get('draft_n_accepted')}/{tm.get('draft_n')} | wall {d['wall']:.1f}s | finish {d['choices'][0]['finish_reason']}") +def code(text): + m=re.search(r"```python\n(.*?)```",text,re.S); return m.group(1) if m else text +def run_tests(src,tests): + g={} + try: + exec(src,g); exec(tests,g); return "PASS" + except Exception as e: return f"FAIL {e!r}" +mode=sys.argv[1] +if mode=="short": + for i in range(2): + d=ask([{"role":"user","content":"Write a Python function that returns the n-th Fibonacci number"}],256); show(f"fib run{i}",d) + print(d["choices"][0]["message"]["content"]) + print("fib tests:",run_tests(code(d["choices"][0]["message"]["content"]),"fn=[v for k,v in list(globals().items()) if callable(v) and not k.startswith('_') and k!='exec'][-1]\nassert [fn(i) for i in range(10)]==[0,1,1,2,3,5,8,13,21,34]; assert fn(50)==12586269025")) + d=ask([{"role":"user","content":"Write a Python function gcd(a, b) that returns the greatest common divisor using Euclid's algorithm. Only the code."}],200); show("gcd",d) + c=d["choices"][0]["message"]["content"]; print(c) + print("gcd tests:",run_tests(code(c),"assert gcd(48,18)==6; assert gcd(17,5)==1; assert gcd(0,9)==9; assert gcd(270,192)==6")) + d=ask([{"role":"user","content":"What is the output of this Python code? print(sum(i*i for i in range(1,11))) Answer with just the number."}],20); show("known",d); print(d["choices"][0]["message"]["content"], "(expected 385)") +if mode=="long": + src="".join(open(f).read() for f in sorted(glob.glob("/tools/*.py"))[:6])[:int(sys.argv[2])] + msgs=[{"role":"user","content":"Here is some Python source:\n\n"+src+"\n\nIn one paragraph, say what this code is for, then write a short Python function that reverses a string."}] + for i in range(2): + d=ask(msgs,256); show(f"long run{i}",d) + print(d["choices"][0]["message"]["content"][:1200]) +if mode=="long2": + fs=sorted(glob.glob("/tools/*.py")) + src="".join(open(f).read() for f in fs[6:12])[:7000] + msgs=[{"role":"user","content":"Here is some Python source:\n\n"+src+"\n\nWrite a Python implementation of a binary search tree class with insert, search, delete and in-order traversal methods, with docstrings."}] + d=ask(msgs,256); show("long2 BST",d) + d2=ask(msgs+[{"role":"assistant","content":d["choices"][0]["message"]["content"]},{"role":"user","content":"Now add a height() method."}],256); show("long2 turn2",d2) + print(d["choices"][0]["message"]["content"][:600]) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-fib1.json b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-fib1.json new file mode 100644 index 00000000..8b6e53d2 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-fib1.json @@ -0,0 +1 @@ +{"id": "chatcmpl-9a1c5ae9d2084c8f9b34ac8c", "object": "chat.completion", "created": 1791157128, "model": "coder-iq1_m", "choices": [{"index": 0, "message": {"role": "assistant", "content": "```python\ndef fibonacci(n: int) -> int:\n \"\"\"Return the n-th Fibonacci number (0-indexed).\n \n fibonacci(0) = 0\n fibonacci(1) = 1\n fibonacci(2) = 1\n fibonacci(3) = 2\n ...\n \"\"\"\n if n < 0:\n raise ValueError(\"n must be a non-negative integer\")\n if n == 0:\n return 0\n if n == 1:\n return 1\n \n a, b = 0, 1\n for _ in range(2, n + 1):\n a, b = b, a + b\n return b\n```"}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 23, "completion_tokens": 159, "total_tokens": 182, "prompt_tokens_details": {"cached_tokens": 0}}, "timings": {"cache_n": 0, "prompt_n": 23, "prompt_ms": 456.3, "prompt_per_token_ms": 19.839, "prompt_per_second": 50.4, "predicted_n": 159, "predicted_ms": 3009.9, "predicted_per_token_ms": 18.93, "predicted_per_second": 52.8, "draft_n": 138, "draft_n_accepted": 112}} \ No newline at end of file diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long.txt new file mode 100644 index 00000000..679f45b1 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long.txt @@ -0,0 +1,8 @@ +[long run0] prompt_n=2129 cache_n=0 prompt 427.9 tok/s | decode 128 tok 40.1 tok/s | drafts 70/98 | wall 8.2s | finish stop +[long run1] prompt_n=7 cache_n=2122 prompt 78.1 tok/s | decode 128 tok 41.3 tok/s | drafts 70/98 | wall 3.2s | finish stop +This code is a comprehensive integration test script for a batched inference engine (likely named "Strata") that verifies the correctness of multi-slot decoding, specifically ensuring that tokens generated in parallel slots match those generated in solo mode, even when long prompts are interleaved with other decoding operations or when requests are continued from checkpoints. The script sets up various scenarios involving different prompt lengths, slot assignments, and continuation logic to validate that the engine's internal state management, expert caching, and token generation remain consistent across different execution paths. + +```python +def reverse_string(s: str) -> str: + return s[::-1] +``` diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long2.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long2.txt new file mode 100644 index 00000000..59051151 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long2.txt @@ -0,0 +1,26 @@ +[long2 BST] prompt_n=1922 cache_n=0 prompt 425.3 tok/s | decode 256 tok 57.2 tok/s | drafts 186/208 | wall 9.0s | finish length +[long2 turn2] prompt_n=21 cache_n=2178 prompt 61.4 tok/s | decode 256 tok 71.4 tok/s | drafts 209/212 | wall 3.9s | finish length +```python +class BinarySearchTree: + """A binary search tree implementation with insert, search, delete, and in-order traversal.""" + + def __init__(self): + """Initialize an empty binary search tree.""" + self.root = None + + def insert(self, value): + """Insert a value into the binary search tree. + + Args: + value: The value to insert into the tree. + + Returns: + None + """ + if self.root is None: + self.root = _Node(value) + return + + current = self.root + while True: + if value < curr diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-short.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-short.txt new file mode 100644 index 00000000..4bf19ec8 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-short.txt @@ -0,0 +1,35 @@ +[fib run0] prompt_n=7 cache_n=16 prompt 74.3 tok/s | decode 159 tok 56.6 tok/s | drafts 114/133 | wall 2.9s | finish stop +[fib run1] prompt_n=7 cache_n=16 prompt 80.1 tok/s | decode 159 tok 56.6 tok/s | drafts 114/133 | wall 2.9s | finish stop +```python +def fibonacci(n: int) -> int: + """Return the n-th Fibonacci number (0-indexed). + + fibonacci(0) = 0 + fibonacci(1) = 1 + fibonacci(2) = 1 + fibonacci(3) = 2 + ... + """ + if n < 0: + raise ValueError("n must be a non-negative integer") + if n == 0: + return 0 + if n == 1: + return 1 + + a, b = 0, 1 + for _ in range(2, n + 1): + a, b = b, a + b + return b +``` +fib tests: PASS +[gcd] prompt_n=37 cache_n=0 prompt 71.7 tok/s | decode 32 tok 60.8 tok/s | drafts 23/24 | wall 1.0s | finish stop +```python +def gcd(a, b): + while b: + a, b = b, a % b + return a +``` +gcd tests: PASS +[known] prompt_n=42 cache_n=0 prompt 69.5 tok/s | decode 4 tok 25.1 tok/s | drafts 4/6 | wall 0.8s | finish stop +385 (expected 385) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.engine.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.engine.txt new file mode 100644 index 00000000..a8651328 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.engine.txt @@ -0,0 +1,66 @@ +strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 24) +strata generate: PCIe probe: 7.0 GB/s host->device (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 (default 0.55) +strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows) +strata generate: native pack: /packs/coder-iq1_m experts (largest blob 2.66 MB), token embedding IQ4_XS in mapped host memory (322 MiB) +strata generate: layer split: CUDA0 loads the dense weights of layers 0-23 only +strata generate: 741 MiB of weights loaded from /packs/coder-iq1_m (686 canonical tensors skipped: served natively) +strata generate: 150 native projection matrices, 988.19 MiB of weights +strata generate: the SSD is kept awake while rows are read: one page of the table after 100 ms without a read, until 60 s after the last request (STRATA_SSD_KEEPALIVE=0 turns it off) +strata generate: layer split: CUDA1 loads the dense weights of layers 24-47 only +strata generate: layer split: CUDA1 PCIe probe 7.0 GB/s (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 +strata generate: layer split: CUDA1 holds its weights; 22.04 GiB free (its session follows the split search) +strata generate: profile data/expert-profile-coder.bin: 12288 ranked pairs, built for 12288 slots +strata generate: PLE on, table 320001536 rows of /models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf +strata generate: layer split: CUDA1 holds its weights, session [24, 48) and the head; 21.43 GiB free +strata mtp: draft layer loaded, 802 MiB of VRAM (experts 675, dense 111), files read in 0.44 s (1769 MiB/s) +strata generate: GPU 0: Intel(R) Arc(TM) Pro B60 Graphics, compute capability 20.1 +strata generate: WARNING: this engine was compiled with CUDA 12.8 headers but loaded a CUDA 0.2 runtime (libcudart): GPU properties can read wrong and some kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542) +strata generate: experts streamed from the GGUF on demand (--stream-experts): no host arena; every expert must fit the VRAM cache +strata generate: expert cache auto: 21.95 GiB free, 1536 MiB reserved (+0 MiB for the draft head) -> 6144 slots +strata generate: expert cache 6144 slots, 11.07 GiB of VRAM; policy is +strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU, + so a reply can differ slightly from a run without the cache (same quality: + bench/results/2026-09-27-cache-parity). + PROFILE, ranked by routing frequency, no eviction. +strata generate: profile fill: 11.07 GiB in 1.9 s (6.27 GB/s, pipelined) +strata generate: pre-filled 6144 of 6144 slots from the profile; slot 0 verified +strata generate: 3024 of 6144 experts missing from VRAM mirrored in pinned host memory (6.00 GiB, 1.0 s); the GPU reads them over PCIe +strata generate: WARNING: 3120 experts are neither in VRAM nor mirrored; with STRATA_VERIFY_NO_HOST the device plan cannot run them and their layers' windows fall back slowly - raise STRATA_MIRROR_MIB or the free RAM, or lower --max-context +strata generate: layer split, CUDA1: 20.65 GiB free of 23.91, room for experts 17.33 GiB +strata generate: layer split: CUDA1 runs layers 24-47, expert cache 6144 slots (12.35 GiB), 6144 of its 6144 profiled pairs; slot 0 verified +strata generate: layer split: CUDA0 runs layers 0-23 +strata generate: R4 hit path ON - resident experts are computed on the GPU +strata generate: 5 expert-pool workers + the host thread +strata generate: session is up (engine 0.1.39-sycl) +strata generate: token graph hit path: 12288 resident experts, decided on the device +strata serve: layer split: 100% of the experts resident, the prompt path's streamed ring 96 slots +strata serve: the prompt path allocates its own buffers (too few cache slots to borrow) +strata verify: window up to 6 tokens, 74.0 MiB of device buffers +strata serve: layer split: layers 0-23 (CUDA0), 24-47 (CUDA1), one hand-off per window +strata verify: window up to 6 tokens, 74.0 MiB of device buffers +strata mtp: draft head over 106299 tokens (212.9 MiB) +strata serve: 9890 MiB of VRAM free with everything loaded +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata serve: prompt 23 tokens = 0 reused + 23 read in 456 ms (50.4 tok/s), 159 generated in 3010 ms (52.8 tok/s), drafts accepted 112 of 138, 1 checkpoints +strata serve: suffix drafts: 1 windows, 1 of 5 drafts accepted +strata serve: prompt 23 tokens = 16 reused + 7 read in 94 ms (74.3 tok/s), 159 generated in 2810 ms (56.6 tok/s), drafts accepted 114 of 133, 1 checkpoints +strata serve: prompt 23 tokens = 16 reused + 7 read in 87 ms (80.1 tok/s), 159 generated in 2808 ms (56.6 tok/s), drafts accepted 114 of 133, 1 checkpoints +strata serve: prompt 37 tokens = 0 reused + 37 read in 516 ms (71.7 tok/s), 32 generated in 526 ms (60.8 tok/s), drafts accepted 23 of 24, 1 checkpoints +strata verify: captured the 5-token window (upload , sync ) +strata verify: captured the 5-token window (upload , sync ) +strata serve: prompt 42 tokens = 0 reused + 42 read in 604 ms (69.5 tok/s), 4 generated in 160 ms (25.1 tok/s), drafts accepted 4 of 6, 1 checkpoints +strata verify: captured the 3-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata serve: prompt 2129 tokens = 0 reused + 2129 read in 4975 ms (427.9 tok/s), 128 generated in 3189 ms (40.1 tok/s), drafts accepted 70 of 98, 1 checkpoints +strata serve: prompt 2129 tokens = 2122 reused + 7 read in 90 ms (78.1 tok/s), 128 generated in 3101 ms (41.3 tok/s), drafts accepted 70 of 98, 1 checkpoints +strata serve: prompt 1922 tokens = 0 reused + 1922 read in 4519 ms (425.3 tok/s), 256 generated in 4475 ms (57.2 tok/s), drafts accepted 186 of 208, 1 checkpoints +strata serve: suffix drafts: 1 windows, 2 of 5 drafts accepted +strata serve: prompt 2199 tokens = 2178 reused + 21 read in 342 ms (61.4 tok/s), 256 generated in 3587 ms (71.4 tok/s), drafts accepted 209 of 212, 2 checkpoints +strata serve: suffix drafts: 37 windows, 185 of 185 drafts accepted diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.json b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.json new file mode 100644 index 00000000..dec1a68c --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.json @@ -0,0 +1,47 @@ +{ + "engine": "strata", + "exe": "/strata-native.sh", + "cwd": "", + "tokenizer": "/packs/coder-iq1_m/tokenizer", + "model_name": "coder-iq1_m", + "backend": "sycl", + "log": "/logs/w2/coder2.engine.log", + "args": [ + "--pack", + "/packs/coder-iq1_m", + "--native", + "/models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf", + "--ple-gguf", + "/models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf", + "--expert-profile", + "data/expert-profile-coder.bin", + "--expert-cache", + "auto", + "--stream-experts", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/mtp/rt", + "--max-context", + "8192", + "--kv", + "int8", + "--vram-reserve-mib", + "1536", + "--no-prefill-borrow", + "--layer-split", + "24" + ], + "env": { + "ONEAPI_DEVICE_SELECTOR": "level_zero:0,1", + "SYCL_CACHE_PERSISTENT": "0", + "STRATA_MIRROR_MIB": "6144", + "STRATA_VERIFY_DEVICE_PLAN": "1", + "STRATA_STAGE_TRIM": "1", + "STRATA_VERIFY_NO_HOST": "1" + } +} \ No newline at end of file diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long.txt new file mode 100644 index 00000000..c9aedcee --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long.txt @@ -0,0 +1,8 @@ +[long run0] prompt_n=2129 cache_n=0 prompt 436.4 tok/s | decode 104 tok 38.8 tok/s | drafts 56/87 | wall 7.6s | finish stop +[long run1] prompt_n=7 cache_n=2122 prompt 79.3 tok/s | decode 104 tok 40.0 tok/s | drafts 56/87 | wall 2.7s | finish stop +This code serves as a comprehensive test harness for a batch inference engine, specifically designed to verify that token generation remains consistent when multiple prompts are processed concurrently in separate slots. It compares the output tokens from parallel execution against those from sequential "solo" runs to ensure that interleaving, checkpointing, and resource sharing (such as expert cache borrowing) do not introduce drift or errors in the model's responses. + +```python +def reverse_string(s: str) -> str: + return s[::-1] +``` diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long2.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long2.txt new file mode 100644 index 00000000..943b358e --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long2.txt @@ -0,0 +1,23 @@ +[long2 BST] prompt_n=1922 cache_n=0 prompt 445.1 tok/s | decode 256 tok 55.5 tok/s | drafts 183/213 | wall 9.0s | finish length +[long2 turn2] prompt_n=284 cache_n=1915 prompt 177.0 tok/s | decode 256 tok 72.5 tok/s | drafts 211/217 | wall 5.1s | finish length +```python +class BinarySearchTree: + """A binary search tree implementation with insert, search, delete, and in-order traversal.""" + + class Node: + """Internal node of the binary search tree.""" + + def __init__(self, value): + """Initialize a node with a value and no children.""" + self.value = value + self.left = None + self.right = None + + def __init__(self): + """Initialize an empty binary search tree.""" + self.root = None + + def insert(self, value): + """Insert a value into the binary search tree. + + Args: diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-short.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-short.txt new file mode 100644 index 00000000..e6c92f98 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-short.txt @@ -0,0 +1,27 @@ +[fib run0] prompt_n=23 cache_n=0 prompt 50.4 tok/s | decode 112 tok 58.6 tok/s | drafts 84/88 | wall 2.4s | finish stop +[fib run1] prompt_n=7 cache_n=16 prompt 81.7 tok/s | decode 112 tok 61.3 tok/s | drafts 84/89 | wall 1.9s | finish stop +```python +def fibonacci(n): + """Return the n-th Fibonacci number (0-indexed).""" + if n < 0: + raise ValueError("n must be a non-negative integer") + if n == 0: + return 0 + if n == 1: + return 1 + a, b = 0, 1 + for _ in range(2, n + 1): + a, b = b, a + b + return b +``` +fib tests: PASS +[gcd] prompt_n=37 cache_n=0 prompt 73.3 tok/s | decode 32 tok 61.8 tok/s | drafts 23/24 | wall 1.0s | finish stop +```python +def gcd(a, b): + while b: + a, b = b, a % b + return a +``` +gcd tests: PASS +[known] prompt_n=42 cache_n=0 prompt 71.1 tok/s | decode 4 tok 25.4 tok/s | drafts 4/6 | wall 0.7s | finish stop +385 (expected 385) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.engine.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.engine.txt new file mode 100644 index 00000000..6dcb24c0 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.engine.txt @@ -0,0 +1,69 @@ +strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 25) +strata generate: PCIe probe: 7.0 GB/s host->device (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 (default 0.55) +strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows) +strata generate: native pack: /packs/qwen-iq2_xs experts (largest blob 1.51 MB), token embedding IQ4_XS in mapped host memory (322 MiB) +strata generate: layer split: CUDA0 loads the dense weights of layers 0-24 only +strata generate: 799 MiB of weights loaded from /packs/qwen-iq2_xs (670 canonical tensors skipped: served natively) +strata generate: 156 native projection matrices, 766.85 MiB of weights +strata generate: the SSD is kept awake while rows are read: one page of the table after 100 ms without a read, until 60 s after the last request (STRATA_SSD_KEEPALIVE=0 turns it off) +strata generate: layer split: CUDA1 loads the dense weights of layers 25-47 only +strata generate: layer split: CUDA1 PCIe probe 7.0 GB/s (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 +strata generate: layer split: CUDA1 holds its weights; 22.36 GiB free (its session follows the split search) +strata generate: profile data/expert-profile.bin: 24576 ranked pairs, built for 24576 slots +strata generate: PLE on, table 320001536 rows of /models/qwen-iq2_xs/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +strata generate: layer split: CUDA1 holds its weights, session [25, 48) and the head; 21.93 GiB free +strata mtp: draft layer loaded, 802 MiB of VRAM (experts 675, dense 111), files read in 0.75 s (1053 MiB/s) +strata generate: GPU 0: Intel(R) Arc(TM) Pro B60 Graphics, compute capability 20.1 +strata generate: WARNING: this engine was compiled with CUDA 12.8 headers but loaded a CUDA 0.2 runtime (libcudart): GPU properties can read wrong and some kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542) +strata generate: experts streamed from the GGUF on demand (--stream-experts): no host arena; every expert must fit the VRAM cache +strata generate: expert cache auto: 22.11 GiB free, 1536 MiB reserved (+0 MiB for the draft head) -> 12800 slots +strata generate: expert cache 12800 slots, 16.91 GiB of VRAM; policy is +strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU, + so a reply can differ slightly from a run without the cache (same quality: + bench/results/2026-09-27-cache-parity). + PROFILE, ranked by routing frequency, no eviction. +strata generate: profile fill: 16.91 GiB in 3.8 s (4.81 GB/s, pipelined) +strata generate: pre-filled 12800 of 12800 slots from the profile; slot 0 verified +strata generate: 4473 of 11776 experts missing from VRAM mirrored in pinned host memory (6.00 GiB, 1.1 s); the GPU reads them over PCIe +strata generate: WARNING: 7303 experts are neither in VRAM nor mirrored; with STRATA_VERIFY_NO_HOST the device plan cannot run them and their layers' windows fall back slowly - raise STRATA_MIRROR_MIB or the free RAM, or lower --max-context +strata generate: layer split, CUDA1: 21.14 GiB free of 23.91, room for experts 17.93 GiB +strata generate: layer split: CUDA1 runs layers 25-47, expert cache 11776 slots (16.11 GiB), 11776 of its 11776 profiled pairs; slot 0 verified +strata generate: layer split: CUDA0 runs layers 0-24 +strata generate: R4 hit path ON - resident experts are computed on the GPU +strata generate: 5 expert-pool workers + the host thread +strata generate: session is up (engine 0.1.39-sycl) +strata generate: token graph hit path: 24576 resident experts, decided on the device +strata serve: layer split: 100% of the experts resident, the prompt path's streamed ring 96 slots +strata serve: the prompt path allocates its own buffers (too few cache slots to borrow) +strata verify: window up to 6 tokens, 56.4 MiB of device buffers +strata serve: layer split: layers 0-24 (CUDA0), 25-47 (CUDA1), one hand-off per window +strata verify: window up to 6 tokens, 56.4 MiB of device buffers +strata mtp: draft head over 106299 tokens (137.9 MiB) +strata serve: 4235 MiB of VRAM free with everything loaded +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata serve: prompt 23 tokens = 0 reused + 23 read in 456 ms (50.4 tok/s), 112 generated in 1910 ms (58.6 tok/s), drafts accepted 84 of 88, 1 checkpoints +strata serve: prompt 23 tokens = 16 reused + 7 read in 86 ms (81.7 tok/s), 112 generated in 1827 ms (61.3 tok/s), drafts accepted 84 of 89, 1 checkpoints +strata serve: suffix drafts: 1 windows, 1 of 3 drafts accepted +strata serve: prompt 37 tokens = 0 reused + 37 read in 505 ms (73.3 tok/s), 32 generated in 518 ms (61.8 tok/s), drafts accepted 23 of 24, 1 checkpoints +strata verify: captured the 5-token window (upload , sync ) +strata verify: captured the 5-token window (upload , sync ) +strata serve: prompt 42 tokens = 0 reused + 42 read in 591 ms (71.1 tok/s), 4 generated in 157 ms (25.4 tok/s), drafts accepted 4 of 6, 1 checkpoints +strata verify: captured the 2-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata serve: prompt 2129 tokens = 0 reused + 2129 read in 4878 ms (436.4 tok/s), 104 generated in 2680 ms (38.8 tok/s), drafts accepted 56 of 87, 1 checkpoints +strata serve: prompt 2129 tokens = 2122 reused + 7 read in 88 ms (79.2 tok/s), 104 generated in 2602 ms (40.0 tok/s), drafts accepted 56 of 87, 1 checkpoints +strata serve: prompt 1922 tokens = 0 reused + 1922 read in 4318 ms (445.1 tok/s), 256 generated in 4616 ms (55.5 tok/s), drafts accepted 183 of 213, 1 checkpoints +strata serve: suffix drafts: 1 windows, 1 of 5 drafts accepted +strata serve: prompt 2199 tokens = 1915 reused + 284 read in 1604 ms (177.0 tok/s), 256 generated in 3532 ms (72.5 tok/s), drafts accepted 211 of 217, 2 checkpoints +strata serve: suffix drafts: 41 windows, 205 of 205 drafts accepted +strata serve: prompt 30 tokens = 0 reused + 30 read in 454 ms (66.1 tok/s), 11 generated in 255 ms (43.2 tok/s), drafts accepted 7 of 9, 1 checkpoints +strata serve: prompt 70 tokens = 41 reused + 29 read in 412 ms (70.3 tok/s), 3 generated in 97 ms (30.9 tok/s), drafts accepted 3 of 3, 2 checkpoints +strata serve: prompt 108 tokens = 74 reused + 34 read in 479 ms (70.9 tok/s), 14 generated in 307 ms (45.6 tok/s), drafts accepted 8 of 11, 3 checkpoints +strata serve: prompt 33 tokens = 0 reused + 33 read in 487 ms (67.8 tok/s), 39 generated in 813 ms (47.9 tok/s), drafts accepted 28 of 38, 1 checkpoints diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.json b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.json new file mode 100644 index 00000000..ae1884ed --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.json @@ -0,0 +1,47 @@ +{ + "engine": "strata", + "exe": "/strata-native.sh", + "cwd": "", + "tokenizer": "/packs/qwen-iq2_xs/tokenizer", + "model_name": "qwen3.8-flash-next-iq2_xs", + "backend": "sycl", + "log": "/logs/w2/iq2b.engine.log", + "args": [ + "--pack", + "/packs/qwen-iq2_xs", + "--native", + "/models/qwen-iq2_xs/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "--ple-gguf", + "/models/qwen-iq2_xs/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf", + "--expert-profile", + "data/expert-profile.bin", + "--expert-cache", + "auto", + "--stream-experts", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/mtp/rt", + "--max-context", + "8192", + "--kv", + "int8", + "--vram-reserve-mib", + "1536", + "--no-prefill-borrow", + "--layer-split", + "25" + ], + "env": { + "ONEAPI_DEVICE_SELECTOR": "level_zero:0,1", + "SYCL_CACHE_PERSISTENT": "0", + "STRATA_MIRROR_MIB": "6144", + "STRATA_VERIFY_DEVICE_PLAN": "1", + "STRATA_STAGE_TRIM": "1", + "STRATA_VERIFY_NO_HOST": "1" + } +} \ No newline at end of file diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.md index e6903faf..adb9f736 100644 --- a/docs/COMMUNITY_BENCHMARKS.md +++ b/docs/COMMUNITY_BENCHMARKS.md @@ -18,6 +18,9 @@ and their limits. Report what you actually measured and label estimates separate - [2026-10-03: 2x AMD Instinct MI50 16 GB (gfx906), Xeon E5-2666 v3, 32 GB RAM](../bench/results/2026-10-03-community-2x-mi50/README.md): the gfx906 build (#638) with #639 and #640, Coder IQ1_M, 131,072-token context, layer split across both cards; three runs each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks. +- [2026-10-04: 2x Intel Arc Pro B60 24 GB, Ryzen 5 5600, 64 GB RAM](../bench/results/2026-10-04-community-2x-arc-pro-b60/README.md): + the SYCL port at `6f32ec0` with two fixes, Coder IQ1_M and Flash-Next IQ2_XS, 8,192-token context, layer split across both cards; + short prompts and 2K-token prompts, plus one run on a single B60. Intel's SYCL engine, no 4,096/32,768/128,000-token sweep. ## What to record diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d9484e65..20e93343 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -517,6 +517,20 @@ print(r.choices[0].message.content) server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a broken state that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` in `strata-.json` sets the run length; `0` turns it off (for a request that really wants one token many times). +- **Repeated reasoning (opt-in, #728).** The single-token guard above does not see a model that repeats whole + passages. `"reasoning_loop_recovery"` in `strata-.json` is `false` (the default), `"stop"` or `"recover"` + (`true` means `"recover"`). Every 512 output tokens, at a complete character and parser boundary, the reasoning is + measured over its last 2,000 words and punctuation marks (counting passages over the last 30,000 words). If at + least 25% belong to 12-word passages seen three times, `"stop"` ends the reply there as `"length"` and says so in + the server window. `"recover"` stops and drains that generation, then goes on once from all its generated token + ids with the template's low-effort sentence in place of the xhigh one in the first system message (a splice of + token ids: the rest of the prompt is not decoded or re-encoded). The task stays the same; no answer or `` + is inserted, and both passes share the original output limit. On recovery only, temperature is raised to at least + 1.0 and presence penalty to at least 1.5; a client's top-p, top-k and seed are never changed. `/metrics` records + `reasoning_recoveries` and the coverage. This is a policy, not a numerical engine fix or a guarantee of an answer. + `"recover"` needs the exact xhigh sentence in the first system message and skips requests with images; re-reading + the changed prefix costs prompt time. Either mode can mistake repeated useful code or checks for a loop, so keep + the recorded answer quality alongside the completion rate when testing it. - **Changing the effort without re-reading the prompt (opt-in, 0.1.39, #458).** The effort's instruction is the first thing in the prompt, so a request that only changes the effort (an agent's "think harder" switch, `none` for a quick tool step) reads the whole conversation again. `"effort_position": "end"` in `strata-.json` renders @@ -534,6 +548,15 @@ print(r.choices[0].message.content) long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every 15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing the connection or pressing stop in your app really stops the model, so the next request starts at once. +- **Prefill progress in the stream (opt-in).** `"return_progress": true` puts that progress on the stream instead of + sending only the keep-alive, as one extra field on a chunk with an empty delta: `prompt_progress` with `total`, + `cache`, `processed` and `time_ms`. Those are llama.cpp's four fields and mean the same there (`time_ms` is the time + since the prompt started reading, and the work still to do is `(total-cache) - (processed-cache)`), so a client that + draws a prefill bar for llama.cpp draws one here too. It is off unless the request asks, as it is in llama.cpp. + The engine says one line per `--prefill` chunk, so that chunk is the step: measured on two RTX 3090s with + `--prefill auto` (8192 tokens), a 42,131 token prompt read in 15 s sent six of them. A prompt shorter than one chunk + sends nothing, and that is on purpose: its only line arrives once the prompt is read, because the last tokens go + through the verify windows rather than the batched path, so it stops up to `--short-read` tokens short of the end. - **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key. - **OpenCode** (#543). A starting point for `opencode.jsonc` (in your project, or `~/.config/opencode/`); the field names are OpenCode's, so check its config docs if your version differs: @@ -635,6 +658,11 @@ reading after it instead of from token 0. A prompt read from the start is also c prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that root exists for agent clients with long system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, `--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`. +A one-shot request that no later request continues (a classification call, a probe) can send +`"strata_checkpoint": false` in its body: it saves no checkpoint at its last turn nor every 16K tokens, so what +follows the reused prefix (or the root) is read in one run, and its session is not kept or parked for a next request. +It still starts from a checkpoint it matches, and still saves the system-prompt root when that reaches +`--prompt-cache-root`. Without the field (or with `true`) nothing changes. **Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192 --conversation-cache-slots 4` to the engine arguments to park up to four conversations @@ -686,7 +714,9 @@ persisted across restarts. **Current limits (v1):** one request at a time unless `"parallel": N` is set (opt-in batch slots, up to N requests decoded together: [BATCHING.md](BATCHING.md)), and one conversation cached at a time (switching between two chats re-reads the other one unless the opt-in cache above is enabled, or each conversation keeps its own batch slot); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / -seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result +seed** are honored per request (OpenAI and Anthropic fields), and so are stop strings (OpenAI `stop`, a string or up +to 4; Anthropic `stop_sequences`): the answer ends before the first one, which is not sent, and the engine stops +there (`finish_reason` "stop"; `stop_reason` "stop_sequence" with `stop_sequence` set to the one found); with the default adaptive expert tier a sampled result is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out (`"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20}`); a request's own fields always win, and with no @@ -871,7 +901,7 @@ helper (`strata-vision`, from llama.cpp's `mtmd` library) and adds it to your st | Encoder on | Time per picture | Cost | | --- | --- | --- | | **GPU** (recommended) | **0.1-0.5 s** (up to 1,024 image tokens) | ~1.4 GB of VRAM is kept free for it, so the expert cache is smaller: text output is a few % slower (table below) | -| CPU | 10-30 s (pictures are scaled down to ~300 image tokens) | nothing on the GPU | +| CPU | about 3 s at 300 image tokens on 8 cores (6-13 s on 4 threads); more tokens take longer, in proportion (#767, #625) | nothing on the GPU | A picture becomes up to 1,024 tokens of the context (a 640x480 photo: 300). The same picture sent again, as chat apps do on every turn, is encoded only once. @@ -881,11 +911,23 @@ do on every turn, is encoded only once. `strata-.json`, which you can also edit by hand. More tokens keep more detail (small text, charts, screenshots) and take longer to encode, on the CPU most of all; a setup run again keeps the value. +**A minimum number of image tokens (0.1.40, #767):** `"min_tokens": N` in the `"vision"` section of +`strata-.json` (edit it by hand; a setup run again keeps it) is passed to the encoder as `--min-tokens N` +(mtmd's `image_min_tokens`): a small picture is scaled up to at least N tokens. llama.cpp's mtmd prints that Qwen-VL +models want at least 1,024 for grounding tasks (pointing, counting small items); the CPU default stays at 300 at most +and no minimum, because a larger minimum changes the image answers and costs encode time (about 3 s at 300 tokens on +8 cores, in proportion to the tokens). + **A Q8_0 encoder (#625):** `"mmproj"` in the `"vision"` section can point to another mmproj file of this model, for example a Q8_0 one (llama.cpp's `convert_hf_to_gguf.py --mmproj --outtype q8_0` makes one): the encoder's library -reads quantized weights, the file is half the size, and on the CPU it can encode faster than BF16. Setup downloads -the BF16 file, and a setup run again keeps a file of your own that still exists. We have not measured its accuracy -against BF16 yet; numbers are welcome in #625. +reads quantized weights, the file is smaller (590 MiB against 865 MiB for the BF16 one, from `llama-quantize +mmproj-Qwen3.8-Flash-Next-BF16.gguf mmproj-Qwen3.8-Flash-Next-Q8_0.gguf Q8_0`), and on the CPU it uses less RAM +(about 280 MiB less in the encoder) and can encode faster than BF16 at the default 300 tokens. Setup downloads the +BF16 file, and a setup run again keeps a file of your own that still exists. **Recommended for `--vision cpu`.** +Accuracy against BF16, per image token: the cosine of the embeddings is 0.997-0.999 on average (#625's report, with +a community Q8_0 file, at 300, 768 and 1,024 tokens), and 0.9988 and 0.9987 on two pictures with the file made by +the command above (300 tokens; the worst single token 0.94-0.96). Encode time above 768 tokens is the same as BF16's +within about 3%. Numbers on more pictures (charts, small text) are welcome in #625. **A spare GPU for the encoder (0.1.33, #408):** with a card the engine doesn't use, add `"cuda_device": 2` (numbered like `nvidia-smi`) to the `"vision"` section of `strata-.json`: the encoder then runs on that card alone. Lower @@ -1008,7 +1050,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | | `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | | A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | -| Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | +| Pictures are slow (3-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | | A request never finishes: "reading the prompt", GPU "100%" at low power | The GPU ran out of VRAM (engines before 0.1.9 could end with ~30 MiB free at large contexts). Run `START-HERE.bat` once to get engine 0.1.9 or newer; the log then says `... MiB of VRAM free with everything loaded` (a few hundred) and names the `--vram-reserve-mib` to add if it is low. | | Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving ends with an error instead of hanging (after 2 minutes; 1 minute from 0.1.13): the log says `no progress for ... s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. Engine 0.1.13 adds a stall report under it (what every expert-pool thread and the GPU handshake were doing, memory and page faults) and, on Windows, a `strata-stall-.dmp` file with every thread's stack: attach both. (`STRATA_WATCHDOG_S` sets the time in seconds; 0 turns it off.) Engine 0.1.14 fixes the stall those reports found (issue #31: with the IQ packs the host could wait forever inside the NVIDIA driver while copying experts in a verify window; the experts are now copied by a GPU kernel, `--pcie-mode dma` restores the old way). | | `no progress for 60 s ... reading the prompt` on Linux, and the stall report says `threads waiting on the disk (state D): 16 ...` | The engine waits for the drive, not a deadlock: the n-gram table is read at random (`--ple-io direct`), which a rotational disk cannot keep up with (#605). The engine warns at start when the table is on one; `--ple-io ram` (Linux, needs RAM for the table) or the model on an SSD fixes it. Setup adds `--ple-io ram` itself on a rotational disk when the RAM holds the table (0.1.39). | @@ -1028,7 +1070,13 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. - **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same time as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). - **SSD:** the 28.8 GB n-gram table, a few rows per token, read unbuffered past the OS cache (`--ple-io direct`, the - default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). + default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). The engine reads the table + in the format the GGUF has it: IQ4_NL (the default table), Q4_0, Q5_0, Q5_1, Q8_0, FP8 (E4M3 with a scale) or BF16. + Measured on 4,000 random rows against the checkpoint's own BF16 table, the mean per-row error is Q8_0 0.53%, FP8 2.64%, + Q5_1 3.78%, Q5_0 4.25%, IQ4_NL 7.60%, Q4_1 7.80%, Q4_0 8.55% (a Q8_0 table is 54 GB, an IQ4_NL one 28.8 GB). On the Q2_0 model, 700 teacher-forced tokens, the mean KL against the BF16 table is 0.0117 (Q5_0), 0.0121 (Q5_1), 0.0125 + (Q8_0), 0.0128 (FP8), 0.0140 (Q4_0) and 0.0146 (IQ4_NL), with the perplexity within 1% of BF16's either way: any change to the + table moves the 2-bit model by about 0.012, so the formats are hard to tell apart. Setup does not offer another table; + it only changes which GGUF the engine is given. - **Speculation:** the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them. 2.4-3.2 tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** (engine 0.1.7) drafts up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays: @@ -1094,7 +1142,10 @@ times out, the server keeps ownership and reports an error rather than claiming `POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or `{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`. -The schema must describe an object at its root. Local `#` references work; remote references are refused. +The schema must accept only JSON objects at its root: `"type":"object"`, or an `anyOf`/`oneOf` whose branches are all +object schemas (an `allOf` with an object member, or a local `$ref` to one, also counts), as apps written for +llama.cpp's `json_schema` send. A root that also allows an array, string, number, boolean or null is refused. Local +`#` references work; remote references are refused. `json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install "jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the server says so once. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 4ab28fb1..05b1035d 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -69,8 +69,8 @@ On Linux setup uses a system ROCm 7 when there is one, or installs ROCm into `.v sudo), and compiles the engine on your PC for the card (10-20 minutes, once; it needs a C++ compiler and git: `sudo apt install build-essential git`). Several AMD cards share the model with `--gpus`, as on NVIDIA. -What differs from NVIDIA for now: pictures are read by the image encoder on the CPU (`--vision cpu`, 10-30 s per -picture), `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the +What differs from NVIDIA for now: pictures are read by the image encoder on the CPU (`--vision cpu`, about 3 s per +picture at the default 300 image tokens on 8 cores), `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the build by hand and the tuning tables: [AMD_HIP.md](AMD_HIP.md). ## Two or three cards @@ -197,7 +197,7 @@ says so and starts the engine you had. covering factor; `--rope-scaling`/`--rope-scale` override) ([details](DETAILS.md): "Context extension past 262K"). - **Images?** Whether it should also read pictures. The image encoder (0.9 GB) runs on the GPU (0.1-0.5 s per - picture, ~1.4 GB of VRAM kept free for it) or on the CPU (10-30 s per picture, nothing on the GPU); with AMD cards + picture, ~1.4 GB of VRAM kept free for it) or on the CPU (about 3-13 s per picture, nothing on the GPU); with AMD cards on the CPU for now. [Details](DETAILS.md#images-vision). - **Experimental speed projection?** Off unless you say yes - [read what it does](DETAILS.md#experimental-speed-projection-experimental-off-by-default) first. It changes how the model answers, and only the original model offers it. diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 7b6acfeb..2f65b3bd 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -19,11 +19,20 @@ There is **no ready-made Intel engine** in the release zips. You build it from s | Community | 2x Arc Pro B70, `--layer-split` | Flash-Next IQ3_XXS 66 tok/s decode, 394 tok/s prompt (with the `stage_room` fix that is now in 0.1.39) | #423 | | Community | Arc Pro B50 16 GB | Coder IQ1_M ~23 tok/s, IQ2_XS ~25-27 tok/s, up to 128K | #423 | | Community | Arc B580 12 GB, WSL2 | IQ2_XS ~21 tok/s, Coder ~15 tok/s; **device loss also seen** | #423 | +| Community | 2x Arc Pro B60 24 GB, `--layer-split` | Coder IQ1_M: 56.6 tok/s decode, 428 tok/s prompt (2,129 tokens); Flash-Next IQ2_XS: 58.6-61.3 tok/s decode, 436 tok/s prompt; all experts in VRAM; 8K context | [bench/results/2026-10-04-community-2x-arc-pro-b60](../bench/results/2026-10-04-community-2x-arc-pro-b60/README.md) | +| Community | one Arc Pro B60 24 GB | Coder IQ1_M with 4,042 of 12,288 experts mirrored in RAM: 11.9 tok/s decode (needs the ring-wait fix from the same report) | same | | Strata maintainers | no Arc | compile check and kernel tests on a CPU device only (below) | this release | The 0.1.39 port re-migrates 0.1.38's port onto the 0.1.39 engine sources (the #606 NaN fix, the #649 verify -trace, the new prompt paths). It compiles and its kernel tests run, but **nobody has run the 0.1.39 port on an Arc -yet**. The numbers in the table were measured on earlier versions. +trace, the new prompt paths). 0.1.39's `sycl/` did not compile against 0.1.39's own engine sources (#784: the +`ThreadAffinity` type of #626 and the layer range of `NativeDense::load` from #559), and its ring waits never saw a +slow layer as still running (#866, #867). Both are fixed in 0.1.40, and the two B60 reports below were measured with +exactly those two fixes on top of 0.1.39. **No one has run an unpatched 0.1.39 port on an Arc**, and the other rows were +measured on earlier versions. + +The two B60 rows ran `6f32ec0` plus two small `sycl/` fixes (the compile fix and the ring-wait fix), AOT `bmg-g21`, on Ubuntu 24.04 with +`xe`, Level Zero V2, NEO 26.09.37435.12 and oneAPI 2026.1.1, without Docker. Host: Ryzen 5 5600, 64 GB RAM, PCIe 3.0 x8 per card. +Full flags, per-request timings and engine logs are in the report linked in the table. ## What was tested here (0.1.39) @@ -108,6 +117,16 @@ Things that matter on an Arc (details in INTEL.md): - `SYCL_CACHE_PERSISTENT=0`: the persistent JIT cache crashed on Xe2 during the first compile. - Two cards: `ONEAPI_DEVICE_SELECTOR=level_zero:*` (the image pins `level_zero:0`; `strata-sycl.sh` now passes the variable through) and `--layer-split`. +- **Arc Pro B60:** the PCI id is `8086:e211` (`lspci -nn`, the kernel's `xe` id list files it with the BMG-G21 cards), `sycl-ls` prints + `Intel(R) Arc(TM) Pro B60 Graphics 20.1.0`, and `ocloc ids bmg-g21` prints 20.1.0, so `-DSTRATA_SYCL_AOT=bmg-g21` is the right target. + `setup_intel.py` knows both B60 ids, `e211` and `e221` (both seen on B60 cards). On a `--layer-split` the startup line "N experts are neither in VRAM nor mirrored" + counts the other card's layers; the lines `100% of the experts resident` that follow are the ones to read. Set `STRATA_MIRROR_MIB=0` there, + or the pinned mirror is allocated and not used. +- **`setvars.sh` and `set -u`:** `source /opt/intel/oneapi/setvars.sh` in a shell with `set -u` stops at `OCL_ICD_FILENAMES: unbound variable` + (oneAPI 2026.1.1). Source it before `set -u`, or run `set +u` around it. +- **Without Docker:** `sycl/serve/strata-sycl.sh` needs Docker. Natively, `source setvars.sh`, export `SYCL_CACHE_PERSISTENT=0`, + `ZES_ENABLE_SYSMAN=1` and `STRATA_VERIFY_DEVICE_PLAN=1`, then run `build-sycl-aot/strata` or `sycl/serve/server_intel.py` with an `exe` that does this. + A normal user is not in the `render` group on Ubuntu, and then `sycl-ls` shows only the CPU device. - `STRATA_VERIFY_NO_HOST=1` (set by `strata-sycl.sh`) is only valid when every expert is in VRAM. On smaller cards that path is the one that has hung, and #667 found the likely reason: the GPU does not see the CPU's flag stores without a system fence. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 7287409e..bd9226c6 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -56,7 +56,7 @@ its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. **Pictures are refused, or slow.** "this server was started without the vision encoder": the model was set up for text only - run setup again with -`--vision gpu` (or `--vision cpu`). Pictures that take 10-30 s are read by the encoder on the CPU; `--vision gpu` +`--vision gpu` (or `--vision cpu`). Pictures that take several seconds (about 3 s at 300 image tokens on 8 cores, more with more tokens) are read by the encoder on the CPU; `--vision gpu` (NVIDIA, ~1.4 GB of VRAM) makes it 0.1-0.5 s. ## AMD cards diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.md index e275dec7..9e260101 100644 --- a/docs/UNSLOTH_Q4.md +++ b/docs/UNSLOTH_Q4.md @@ -248,13 +248,44 @@ the pack rounds the file's Q8_0 hyper-connection projections to BF16, and on the perplexity 6-9% above llama.cpp's on the same file (teacher-forced, short context). Reading the Q8_0 values instead closes most of that gap; it is measured on AMD only and not in this release. +## Q4_0 files + +A plain `llama-quantize` Q4_0 file of this model runs the same way: pack shard 1 with `--compat-bf16` as above and +point `--native` at it. Tested: +[bartowski/Qwen3.8-Flash-Next-GGUF, `Qwen3.8-Flash-Next-Q4_0`, revision `928589f`](https://huggingface.co/bartowski/Qwen3.8-Flash-Next-GGUF/tree/928589fdb66c6ff07f22ac561e3fbce76553548f/Qwen3.8-Flash-Next-Q4_0) +(3 shards, 100.6 GB). Its routed experts are Q4_0 for gate/up and for down, except down in layers 0-5, which is Q4_1; +the PLE table and the token embedding are Q4_0. The pack serves 302 tensors from the GGUF as stored and converts 362 +(168 exact, 194 rounded to BF16, largest absolute error 0.0156; 1.23 GiB). + +The Q4_0 expert kernels centre the codes (q - 8) before the integer dot product, as ggml-cpu's Q4_0 x Q8_0 dot does, +instead of llama.cpp's CUDA form (uncentred codes, minus 8 x the Q8_1 block sum in float); Q4_1 follows the Q5_1 +kernel without the fifth bit. `native_expert_parity` on this file (layers 0 and 5: Q4_0/Q4_1, layers 20 and 47: +Q4_0/Q4_0): relative error against the float product 1.1-1.3e-2 on the CPU and the GPU alike, CPU vs GPU 1.1e-7 for +Q4_0/Q4_0 and 5e-4 to 1.1e-3 with Q4_1 down. + +Measured on one RTX 3060 12 GB (PCIe 3.0 x16), Xeon E5-2696 v4, 121 GiB DDR4-2400, Linux, CUDA 12.4; every expert in +RAM, `--max-context 131072 --kv int8 --kv-resident 20480`, expert cache `auto` (1,960 slots, 5.06 GiB), prompt chunk +`auto` (6,144 tokens); greedy, `reasoning_effort` medium, one request at a time: + +| Prompt | Prompt read | Output | +| --- | --- | --- | +| 63 tokens (prose) | - | 25.4 tok/s | +| 111 tokens (code) | - | 28.0 tok/s | +| 24,461 tokens | 787 tok/s | 24.0 tok/s | +| 67,934 tokens (a fact hidden in the middle: found) | 737 tok/s | 26.4 tok/s | + +A coding prompt was answered correctly. Not measured: agreement with llama.cpp on this file (as +[above](#quality-against-llamacpp-on-the-same-file) for UD-Q4_K_XL), AMD, Windows, and bartowski's Swift-1.5 Q4_0, +whose header shows the same formats. + ## Scope and validation -- UD-Q4_K_XL and UD-IQ4_XS at revision `38bb39e` are targeted. Other Unsloth quantizations use formats this engine may - not have kernels for; the engine checks every layer's formats at start and refuses an unsupported one by name. +- UD-Q4_K_XL and UD-IQ4_XS at revision `38bb39e` are targeted, and plain Q4_0 files ([above](#q4_0-files)). Other + quantizations use formats this engine may not have kernels for; the engine checks every layer's formats at start + and refuses an unsupported one by name. - Tests: the packer's synthetic 4-shard and conversion tests (`.venv/bin/python -m unittest discover -s tools -p test_iq_pack.py`); CTests `gguf_split_test`, `expert_layout_test`, `native_expert_parity_*` (the three real expert - format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the + format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows, Q4_0/Q4_0 and Q4_0/Q4_1), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the prompt path's MMQ products for Q4_K / Q5_K / Q5_1 / Q8_0 against ggml's dequantized weights); the in-place mode against `experts.bin` on the Coder (identical tokens and logits). - Real runs: greedy answers to a coding prompt (correct) at every budget and setting above, identical across them; diff --git a/include/strata/artifact/dequant.hpp b/include/strata/artifact/dequant.hpp index d5a314ce..b177c8ec 100644 --- a/include/strata/artifact/dequant.hpp +++ b/include/strata/artifact/dequant.hpp @@ -109,6 +109,22 @@ inline void dequantize_q5_0(const uint8_t* block, float* out) { out[j + 16] = (float)(x1 - 16) * d; } } +// ---- Q5_1: 32 elements from a 24-byte block: fp16 d, fp16 m, then Q5_0's qh[4] and qs[16]. The 5-bit codes are +// unsigned and the block's minimum m is added instead of Q5_0's fixed -16 offset (dequantize_row_q5_1). +inline void dequantize_q5_1(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const float m = fp16_to_fp32(read_u16(block + 2)); + const uint8_t* qh = block + 4; + const uint8_t* qs = block + 8; + const uint32_t h = + (uint32_t)qh[0] | ((uint32_t)qh[1] << 8) | ((uint32_t)qh[2] << 16) | ((uint32_t)qh[3] << 24); + for (int j = 0; j < 16; ++j) { + const int x0 = (int)(qs[j] & 0x0F) | (int)(((h >> j) & 1u) << 4); + const int x1 = (int)(qs[j] >> 4) | (int)(((h >> (j + 16)) & 1u) << 4); + out[j] = (float)x0 * d + m; + out[j + 16] = (float)x1 * d + m; + } +} // ---- IQ4_NL: 32 elements from an 18-byte block. Non-linear 4-bit codebook, NOT a linear grid, so // the table must be exact. Copied verbatim from ggml-common.h `kvalues_iq4nl` at 3cf03257: // -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index a321ea70..84291476 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -46,7 +46,35 @@ inline constexpr float NG_RMS_EPS = 1e-6f; inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull; inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value -inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; +inline constexpr int PLE_ROW_BYTES_Q5_1 = (PLE_HEAD_DIM / 32) * 24; // 120: a Q5_1 row (a Q5_K_M finetune) +inline constexpr int PLE_ROW_BYTES_Q8_0 = (PLE_HEAD_DIM / 32) * 34; // 170: a Q8_0 row (UD-Q6_K_XL, Swift-1.5 Q4_K_L) +inline constexpr int PLE_ROW_BYTES_BF16 = PLE_HEAD_DIM * 2; // 320: a BF16 row, two bytes a value +inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_BF16; // the widest row any format in `ple_formats()` has + +/// THE FORMATS OF THE TABLE, ONE ROW EACH. A table type is one entry here (its GGUF type name, the bytes of one +/// 160-value row, how to turn a row into floats) and nothing else: `PleTable::open`, `format()`, the reader's row size, +/// the error string and the buffers' size all read this list, so a new format cannot be in one switch and missing from +/// another. A row is always `PLE_HEAD_DIM` = 160 values = 5 blocks of 32 for the block formats. +enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0, Q4_0, BF16 }; + +struct PleFormatInfo { + PleFormat id; + const char* name; ///< what `PleTable::format()` returns + const char* gguf_type; ///< `TensorInfo::type_name()` of the table tensor ("I8" for F8_E4M3: GGUF has no FP8 type) + uint32_t row_bytes; ///< bytes of one 160-value row in the file + bool needs_scale; ///< the table has one scale in the GGUF metadata (`strata.ple.scale`), F8_E4M3 only + void (*dequant)(const uint8_t* row, float scale, float* out160); +}; + +/// Every format, in the order of `PleFormat`; `ple_format_count()` entries. +const PleFormatInfo* ple_formats(); +int ple_format_count(); +const PleFormatInfo& ple_format_info(PleFormat f); +/// The format whose table tensor has this GGUF type name, or nullptr. F8_E4M3's name is "I8"; the caller checks the +/// `strata.ple.format` marker and the scale. +const PleFormatInfo* ple_format_for_type(const char* gguf_type_name); +/// "IQ4_NL, Q5_0 or FP8 (I8)": the formats for an error message, built from the list. +std::string ple_format_list(); /// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`: /// @@ -103,6 +131,12 @@ void iq4nl_dequant_row(const uint8_t* row, float* out160); /// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row. void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160); +/// One BF16 row -> 160 floats, EXACTLY: bfloat16 is the top half of a float32, so this is a shift and a copy with no +/// rounding anywhere. It is the other published form of this same table - the full checkpoint stores +/// `...ngram_embedding.shard_k` as BF16 (2 B a value, 102.4 GB), the source of record rather than a re-quantization. +/// There is no scale, because BF16 values are the values. +void bf16_dequant_row(const uint8_t* row, float* out160); + /// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD, /// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the /// A/B arm; it returns the same bytes. @@ -115,7 +149,8 @@ enum class PleIo { Direct, Mmap }; struct PleIoOptions { PleIo mode = PleIo::Direct; uint32_t max_inflight = 256; ///< outstanding SSD reads (decode needs 16; a prompt chunk saturates the SSD at 256) - uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables + uint64_t cache_rows = 1u << 20; ///< bounded row cache, in ROWS: 1,048,576 x 90 B ~ 95 MB (IQ4_NL), ~160 MB (FP8), + ///< ~335 MB (BF16); 0 disables bool io_thread = true; ///< reads submitted by a worker thread, not the caller /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome. diff --git a/serve/frontend.py b/serve/frontend.py index 02a1d2f9..a6e181d2 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -16,6 +16,7 @@ and the formats change often; the engine boundary is token ids in, text deltas o from __future__ import annotations import json +import os import re import uuid from dataclasses import dataclass, field @@ -49,6 +50,12 @@ class ChatTemplate: def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True, **kwargs) -> str: + # Do not use completed empty assistant turns as examples for the next reply. Keep the final message. + # (#843. STRATA_KEEP_EMPTY_TURNS=1 renders them as before.) + messages = [m for i, m in enumerate(messages) + if i == len(messages) - 1 or os.environ.get("STRATA_KEEP_EMPTY_TURNS") == "1" or not (isinstance(m, dict) and m.get("role") == "assistant" + and not _text_of(m.get("content")).strip() + and not _has_image(m.get("content")) and not m.get("tool_calls"))] return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs) @@ -141,11 +148,17 @@ def images_of(messages: list[dict]) -> list[str]: # a user quoting "" used to hand the model a real end-of-reasoning token. Before the template is rendered # they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text. THINK_TAGS = {"": "\U000F0E01", "": "\U000F0E02"} -THINK_MARKS = {v: k for k, v in THINK_TAGS.items()} +# #554: the vision markers the same way. They are special tokens only where the template writes them for an image +# item; the same strings in a message's text (an agent reading chat_template.jinja, a tool result quoting it) became +# the same special ids, so text with <|vision_start|><|image_pad|> before a picture took that picture's embeddings +VISION_TAGS = {"<|vision_start|>": "\U000F0E03", "<|image_pad|>": "\U000F0E04", "<|vision_end|>": "\U000F0E05", + "<|video_pad|>": "\U000F0E06"} +LITERAL_TAGS = {**THINK_TAGS, **VISION_TAGS} +THINK_MARKS = {v: k for k, v in LITERAL_TAGS.items()} def _mark(text: str) -> str: - for tag, mark in THINK_TAGS.items(): + for tag, mark in LITERAL_TAGS.items(): text = text.replace(tag, mark) return text @@ -162,7 +175,7 @@ def _mark_deep(v): def _has_tag(v) -> bool: if isinstance(v, str): - return "" in v or "" in v + return any(tag in v for tag in LITERAL_TAGS) if isinstance(v, dict): return any(_has_tag(x) for x in v.values()) if isinstance(v, list): @@ -171,7 +184,8 @@ def _has_tag(v) -> bool: def mark_think_literals(messages: list[dict], tools: list[dict] | None): - """#537: (messages, tools) with every literal / in their text swapped for THINK_TAGS' marks, and + """#537: (messages, tools) with every literal / (#554: and vision marker) in their text swapped for + LITERAL_TAGS' marks, and whether there was one (None: no change, the same objects back - a prompt without them renders as it always did). An assistant message whose content opens with a whole ... block (clients that send the reasoning inline) keeps that one block as the model's markers, as before.""" @@ -257,6 +271,23 @@ def _tool_list(value, wrapper: str | None) -> list[dict]: return tools +def tool_arguments(raw) -> dict: + """A call's arguments from a client's history -> the mapping the template renders (both APIs). A JSON object + (as text or already parsed) is used as it is; empty is {}; anything else (cut-off or malformed JSON, a list, a + number) is kept as text under "arguments" instead of refusing the whole conversation (#510).""" + if raw is None or (isinstance(raw, str) and not raw.strip()): + return {} + if isinstance(raw, dict): + return raw + if isinstance(raw, str): + try: + value = json.loads(raw) + except ValueError: + return {"arguments": raw} + return value if isinstance(value, dict) else {"arguments": raw} + return {"arguments": json.dumps(raw, ensure_ascii=False)} + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -273,10 +304,7 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: fn = c.get("function", c) if not isinstance(fn, dict): raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") - args = fn.get("arguments") - if isinstance(args, str): # the template requires a mapping, not a JSON string - args = json.loads(args) if args.strip() else {} - calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}}) + calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}}) out["tool_calls"] = calls messages.append(out) tools = [t.get("function", t) if t.get("type") == "function" else t @@ -311,19 +339,25 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d isinstance(b, dict) and b.get("type") == "tool_result" for b in content): messages.append({"role": "user", "content": _parts_of(content)}) continue - text, reasoning, calls = [], [], [] + text, reasoning, calls, parts = [], [], [], [] for block in content or []: kind = block.get("type") if kind == "text": text.append(block.get("text", "")) + parts.append(block) + elif kind in IMAGE_PARTS: + parts.append(block) elif kind == "thinking": reasoning.append(block.get("thinking", "")) elif kind == "tool_use": - calls.append({"function": {"name": block.get("name"), "arguments": block.get("input") or {}}}) + calls.append({"function": {"name": block.get("name"), "arguments": tool_arguments(block.get("input"))}}) elif kind == "tool_result": - messages.append({"role": "tool", "content": _text_of(block.get("content"))}) - if text or calls or reasoning: - out = {"role": m["role"], "content": "".join(text)} + # A tool's image (Claude Code's Read of a picture) reaches the encoder like a user's, as the OpenAI + # path's tool messages already do; a text-only result is one string, as before. + messages.append({"role": "tool", "content": _parts_of(block.get("content"))}) + if text or calls or reasoning or parts: + # an image sent beside tool results stays in this turn instead of being dropped + out = {"role": m["role"], "content": _parts_of(parts) if _has_image(parts) else "".join(text)} if reasoning: out["reasoning_content"] = "".join(reasoning) if calls: @@ -374,6 +408,7 @@ CALL_END = "" PARAM_END = "" +FUNC_START = " int: return text.find(CALL_END, pos) +def tool_choice_of(tool_choice) -> tuple[str, str | None]: + """A client's `tool_choice` in either API's shape -> ("auto" | "none" | "required" | "named", name). OpenAI: + "auto" / "none" / "required", {"type": "function", "function": {"name": N}} or the flat {"type": "function", + "name": N}; Anthropic: {"type": "auto" | "any" | "none"} and {"type": "tool", "name": N}. A value it does not + know is ("unknown", None).""" + if tool_choice is None: + return "auto", None + if isinstance(tool_choice, str): + return (tool_choice, None) if tool_choice in ("auto", "none", "required") else ("unknown", None) + if isinstance(tool_choice, dict): + kind = tool_choice.get("type") + if kind in ("auto", "none"): + return kind, None + if kind in ("any", "required"): + return "required", None + if kind in ("function", "tool"): + fn = tool_choice.get("function") + name = (fn.get("name") if isinstance(fn, dict) else None) or tool_choice.get("name") + if isinstance(name, str) and name: + return "named", name + return "unknown", None + + +def forced_call(tool_choice, tools: list[dict] | None) -> str | None: + """`tool_choice` -> the text that opens the call the reply must make, or None (the model decides). + There is no grammar here: the server writes this opening itself, so the model can only go on with a call. + "required" / Anthropic "any": any of the tools; a named function: that one. A value it cannot honour (an + unknown shape, a name that is not one of the tools, "required" with no tools) is logged and acts as "auto", + not a 400: a client's odd choice must not stop its request. "none" is handled by the caller (no tools).""" + kind, name = tool_choice_of(tool_choice) + names = {t.get("name") for t in tools or [] if isinstance(t, dict)} + if kind in ("auto", "none"): + return None + if kind == "required" and len(names) == 1: # one tool to call: name it, the model cannot invent another + kind, name = "named", next(iter(names)) + if kind == "required" and names: + return CALL_START + "\n\n" + print(f"[strata] tool_choice {json.dumps(tool_choice)[:200]} is not supported here (or names no tool of the " + "request): the model decides, as with \"auto\"", flush=True) + return None + + def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall: """`\\n\\nVALUE\\n...` -> ToolCall. Values are JSON-decoded when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON @@ -461,6 +540,9 @@ def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall: return ToolCall(name=name, arguments=args) +RCALL_MAX = 32768 # the most of a `` inside the reasoning that is held while waiting for its end (#804) + + class OutputParser: """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back until it is complete, so clients never see `` inside the reasoning, with tools declared. It is held whole (never streamed + # as a call) until it ends: a declared name is then a tool call, anything else stays reasoning text. + body = self.buf[len(CALL_START):] + end, think = call_end(body), body.find(THINK_END) + if end >= 0 and (think < 0 or think >= end): + call = None + try: + name = body[:end].strip()[len("", 1)[0] + if name in self.schemas: + call = parse_tool_call(body[:end], self.schemas.get(name)) + except ValueError: + pass + if call is not None: + out.append(Event("tool_call", call=call)) + else: + out.append(Event("reasoning", self.buf[:len(CALL_START) + end + len(CALL_END)])) + self.buf = body[end + len(CALL_END):] + self.state = "reasoning" + elif think >= 0: # the thinking ended inside it: it never was a call + out.append(Event("reasoning", self.buf[:len(CALL_START) + think])) + self.buf = body[think:] + self.state = "reasoning" + elif len(body) > RCALL_MAX: # a tag in the prose that never closes: stop holding the thinking back + out.append(Event("reasoning", self.buf)) + self.buf = "" + self.state = "reasoning" + else: + return out + elif self.state == "reasoning": i = self.buf.find(THINK_END) + tool = self.buf.find(CALL_START) if self.schemas else -1 + if tool >= 0 and (i < 0 or tool < i): + if tool: + out.append(Event("reasoning", self.buf[:tool])) + self.buf = self.buf[tool:] + self.state = "rcall" + continue if i < 0: - keep = self._hold(self.buf, (THINK_END,)) + keep = self._hold(self.buf, (THINK_END, CALL_START) if self.schemas else (THINK_END,)) if len(self.buf) > keep: out.append(Event("reasoning", self.buf[:len(self.buf) - keep])) self.buf = self.buf[len(self.buf) - keep:] @@ -631,6 +749,22 @@ class OutputParser: out.append(Event("content", self.buf[:j])) self.buf = self.buf[j:] return out + # A call is `` and then (after whitespace) ` block") - content, not a malformed call + # that ends the request. Until its follower has arrived it is held, like a partial tag. + after = self.buf[i + len(CALL_START):].lstrip() + if after and not after.startswith(FUNC_START) and not FUNC_START.startswith(after): + out.append(Event("content", self.buf[:i + len(CALL_START)])) + self.buf = self.buf[i + len(CALL_START):] + continue + if not after.startswith(FUNC_START): + j = i + while j > 0 and self.buf[j - 1] == "\n": + j -= 1 + if j > 0: + out.append(Event("content", self.buf[:j])) + self.buf = self.buf[j:] + return out if i and self.buf[:i].strip(): out.append(Event("content", self.buf[:i].rstrip("\n"))) self.buf = self.buf[i + len(CALL_START):] @@ -669,7 +803,8 @@ class OutputParser: self._reset_scan() return out if self.buf: - kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content") + # an unfinished call inside the reasoning (#804) is reasoning text, never a call + kind = {"reasoning": "reasoning", "rcall": "reasoning", "content": "content"}.get(self.state, "content") text = self.buf if self.state != "call" else CALL_START + self.buf out.append(Event(kind, text)) self.buf = "" diff --git a/serve/responses.py b/serve/responses.py index 4a017c38..01f2b17d 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -257,6 +257,10 @@ def request_tools(req: dict): "required": ["input"]} tools.append({"name": flat, "description": description, "parameters": params}) names[flat] = (namespace, name, kind) + if namespace: + # Qwen writes Codex's MCP tools as `mcp__server__tool` (the flat name it + # learned), not `mcp__server.tool`: map that spelling back as well. + names.setdefault(f"{namespace}__{name}", (namespace, name, kind)) for i, tool in enumerate(given): param = f"tools[{i}]" diff --git a/serve/server.py b/serve/server.py index bfc2a4f2..e755e00b 100644 --- a/serve/server.py +++ b/serve/server.py @@ -43,6 +43,7 @@ import threading import time import urllib.request import uuid +from http.client import HTTPException from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Iterator, Protocol @@ -52,7 +53,8 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 - images_of, mark_think_literals, openai_to_messages, unmark_think_literals) + forced_call, images_of, mark_think_literals, openai_to_messages, tool_choice_of, + unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 from serve.winjob import contain # noqa: E402 @@ -68,7 +70,11 @@ EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the " "conclusion without unnecessary elaboration.", "medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary " - "elaboration."} + "elaboration.", + # the template's own xhigh sentence (chat_template.jinja), which #728's recovery swaps for the low one + "xhigh": "Reasoning effort is set to xhigh. Please think carefully through the task, validate key " + "assumptions, consider plausible alternatives, and prioritize correctness, consistency, and " + "clarity in the final answer."} VISION_START = "<|vision_start|>" # #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a # broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens" @@ -76,6 +82,54 @@ VISION_START = "<|vision_start|>" REPEAT_STOP_TOKENS = 256 # #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n\n\n" +# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see). +# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the +# low-effort instruction in place of the xhigh one. Both off by default. +HIGH_EFFORT = EFFORT_TEXT["xhigh"] +LOW_EFFORT = EFFORT_TEXT["low"] +LOOP_CHECK_EVERY = 512 # output tokens between two looks at the reasoning (at a clean parser boundary) +LOOP_COVERAGE = 0.25 # the share of the last 2,000 words inside 12-word passages seen three times +LOOP_HISTORY_WORDS = 30000 # how far back the passages are counted (bounds the cost of a look) + + +def reasoning_repeat_coverage(text): + """Coverage of recent words by 12-word passages seen at least three times. + + Only reasoning is supplied. The history (the last LOOP_HISTORY_WORDS words) detects repeated verification passes + separated by long code drafts; the recent window excludes old repetitions. + """ + words = re.findall(r"\w+|[^\w\s]", text.lower())[-LOOP_HISTORY_WORDS:] + width, window = 12, 2000 + if len(words) < window: + return 0.0 + grams = [tuple(words[i:i + width]) for i in range(len(words) - width + 1)] + counts = collections.Counter(grams) + start = max(0, len(words) - window) + covered = set() + for i in range(start, len(grams)): + if counts[grams[i]] >= 3: + covered.update(range(i, i + width)) + return len(covered) / (len(words) - start) + + +def focused_recovery_prompt(tok, ids, generated): + """The prompt's ids with the xhigh effort sentence of the first system message replaced by the low one, then + every token generated so far. A splice of token ids: the prompt is never decoded and encoded again, so a literal + `` or vision marker in it (#537, #554) stays what it was. None when the sentence is not there as whole + tokens in the first system message (a user's text never counts). No answer or end-of-thinking is inserted.""" + end = tok.encode(IM_END, parse_special=True) + if len(end) != 1 or end[0] not in ids: + return None + head = ids[:ids.index(end[0])] + if not tok.decode(head).startswith("<|im_start|>system\n"): + return None + old, new = tok.encode(HIGH_EFFORT, parse_special=False), tok.encode(LOW_EFFORT, parse_special=False) + for i in range(len(head) - len(old) + 1): + if head[i:i + len(old)] == old: + return ids[:i] + new + ids[i + len(old):] + list(generated) + return None + + LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1") CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here # The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first @@ -388,6 +442,12 @@ def btrace(*a): EOS_IDS = {248044, 248046} # <|endoftext|>, <|im_end|>: the engine's default --eos-ids +# The engine's own words for a verifier that cannot go on (its GPU waits were released, or an earlier window never +# finished, #267): the process may stay alive and even print DONE, but it must not take another request. +FATAL_PREFIXES = ("ERR verify: timed out at layer ", "ERR verify batch: timed out at layer ", + "ERR verify: an earlier window never finished", "ERR verify batch: an earlier window never finished") + + class StrataEngine: """The resident engine: `strata --serve` reads `GEN ` lines and streams `T ` lines, then `DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough. @@ -432,6 +492,8 @@ class StrataEngine: self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) self.prefill_tok_s_mean = None self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines + self.progress_ms = 0 # PP's own milliseconds since the prompt started (its third field) + self.reused = 0 # RESUME: prompt tokens not read again (a client takes them out of the work) self.silent_note = None try: # a ready-made engine's BUILD.json says its version self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") @@ -518,6 +580,18 @@ class StrataEngine: proc, lines = self.proc, self.lines # this process's: a restart replaces both (#344) slot_q = self.slot_q for line in proc.stdout: + # checked before batch routing: a fatal line is never a slot's own + if line.startswith(FATAL_PREFIXES): + # release_gpu_waits invalidates the verifier, even if the native + # process stays alive and prints DONE afterwards. + if self.proc is proc: + self.silent_note = "Unrecoverable native verification failure: " + line[4:].strip() + self.ended = True + try: + proc.terminate() + except OSError: + pass + break # publish EOF, never the trailing DONE if line.startswith(("BT ", "BDONE ")) and slot_q: # --batch: a batch slot's own lines try: slot_q[int(line.split()[1])].put(line) @@ -696,6 +770,10 @@ class StrataEngine: v = tune.get(k) if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0: keys += f" {k}={float(v)!r}" + # "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request + # extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before. + if sampling.get("strata_checkpoint") is False: + keys += " ckpt=0" return keys + StrataEngine.projection_key(sampling) @staticmethod @@ -742,6 +820,7 @@ class StrataEngine: f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): self.progress = (int(f[1]), int(f[2])) + self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0 self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None if not stopped and cancel.is_set(): # #879: a Stop during the prompt read went out only after the first token (or after 10 s of @@ -875,7 +954,9 @@ class StrataEngine: with a much shorter prompt (#656: `BYIELD `; the part read waits in a slot and the read goes on after). A consumer that stops early leaves the engine in step: the solo request is STOPped and read to its DONE, an admission to its BADM, a slot is BSTOPped and freed at its BDONE.""" - self.progress = None + if not self.alive(): + raise EngineDied("the engine is unavailable; this request was not sent") + self.progress, self.progress_ms, self.reused = None, 0, 0 keys = self.sampling_keys(sampling or {}) out: list[int] = [] pending: list[int] = [] @@ -1115,10 +1196,12 @@ class StrataEngine: """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" + if not self.alive(): + raise EngineDied("the engine is unavailable; this request was not sent") if getattr(self, "batch", 0): yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings) return - self.progress = None + self.progress, self.progress_ms, self.reused = None, 0, 0 self.prefill_tok_s_mean = None # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ @@ -1164,6 +1247,7 @@ class StrataEngine: f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the + self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0 self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None rate, chunk = self.prefill_tok_s_mean or 0.0, int(f[1]) - read_to read_to = int(f[1]) @@ -1174,7 +1258,7 @@ class StrataEngine: yield None elif line.startswith("RESUME "): # the reused tokens: the first chunk starts after them try: - read_to = int(line.split()[1]) + read_to = self.reused = int(line.split()[1]) except (IndexError, ValueError): pass elif line.startswith("DONE"): @@ -1255,13 +1339,28 @@ class StrataEngine: if self.proc.poll() is not None: if self.pump is not None: self.pump.join(timeout=2) - self.proc.stdin.close() + try: + self.proc.stdin.close() # buffered data may flush again after the engine has exited + except OSError: + pass self.proc.stdout.close() if self.log not in (None, subprocess.DEVNULL): self.log.close() self.proc = None self.ended = True self.progress, self.last = None, {} + self.progress_ms, self.reused = 0, 0 + + +IMAGE_URL_MAX = 32 << 20 # an image URL is read up to this (the web app attaches pictures of up to 20 MB) + + +def network_path(path: str) -> bool: + r"""A path to another computer: \\host\share or //host/share (either slash), \\?\UNC\host\..., \\.\UNC\host\... + or the NT form \??\UNC\host\... Windows connects to that host at the first look at the path (os.path.isfile is + enough) and signs in with the user's NTLM credentials. \\?\ and \??\ name local files too; no client needs them.""" + p = path.replace("/", "\\") + return p.startswith("\\\\") or p.startswith("\\??\\") class Vision: @@ -1277,6 +1376,8 @@ class Vision: args += ["--threads", str(cfg["threads"])] if cfg.get("max_tokens"): args += ["--max-tokens", str(cfg["max_tokens"])] + if cfg.get("min_tokens"): # #767: mtmd's image_min_tokens (a hand-edited key) + args += ["--min-tokens", str(cfg["min_tokens"])] self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-")) self.spawn = (args, log, env) # to start it again after an unload self.stopped = False @@ -1313,16 +1414,43 @@ class Vision: @staticmethod def load(source: str) -> bytes: if source.startswith("data:"): - return base64.b64decode(source.split(",", 1)[1]) + try: + return base64.b64decode(source.split(",", 1)[1]) + except (IndexError, ValueError) as e: # no comma, or not base64 + raise ValueError(f"the image's data: URL could not be read ({e})") from None if source.startswith(("http://", "https://")): - req = urllib.request.Request(source, headers={"User-Agent": "strata"}) - with urllib.request.urlopen(req, timeout=60) as r: - return r.read() + return Vision.download(source) path = source[7:] if source.startswith("file://") else source + # refused before anything looks at the path: file://host/share/x.png is \\host\share\x.png ("file://C:/x.png", + # a drive, is a client's spelling of file:///C:/x.png) + host = re.split(r"[/\\]", path, maxsplit=1)[0] if source.startswith("file://") else "" + if network_path(path) or host and not re.fullmatch(r"[A-Za-z]:|localhost", host, re.IGNORECASE): + raise ValueError("an image file must be on this computer: network paths (\\\\host\\share, //host/share, " + "file://host/...) are not read") if path and os.path.isfile(path): - return Path(path).read_bytes() + try: + return Path(path).read_bytes() + except OSError as e: + raise ValueError(f"the image could not be read from {path} ({e})") from None raise ValueError("an image must be a data: URL, an http(s) URL or a local file path") + @staticmethod + def download(url: str) -> bytes: + """An image URL's bytes, at most IMAGE_URL_MAX of them: the whole response was read, so a huge or endless one + filled the memory. One that cannot be read is a ValueError (a 400 that says so), not a dropped connection.""" + too_big = f"the image URL's file is over {IMAGE_URL_MAX >> 20} MiB" + try: + with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "strata"}), timeout=60) as r: + size = r.headers.get("Content-Length") or "" + if size.isdigit() and int(size) > IMAGE_URL_MAX: + raise ValueError(too_big) + data = r.read(IMAGE_URL_MAX + 1) + except (OSError, HTTPException) as e: + raise ValueError(f"the image URL could not be read: {e}") from None + if len(data) > IMAGE_URL_MAX: + raise ValueError(too_big) + return data + @staticmethod def normalize(data: bytes) -> bytes: """The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG.""" @@ -1351,9 +1479,9 @@ class Vision: im.save(out, format="PNG") return out.getvalue() - def encode(self, source: str) -> tuple[Path, int]: - """-> (embeddings file, number of image tokens).""" - data = self.normalize(self.load(source)) + def encode(self, source: str | bytes) -> tuple[Path, int]: + """-> (embeddings file, number of image tokens). `source`: what load() reads, or the image's bytes.""" + data = self.normalize(source if isinstance(source, bytes) else self.load(source)) key = hashlib.sha256(data).hexdigest()[:32] with self.lock: if key in self.cache: @@ -1652,6 +1780,63 @@ class Detokenizer: return delta +OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop` + + +def stop_strings(req: dict) -> list[str]: + """The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences` + (a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated.""" + req = req or {} + if req.get("stop") is not None: + stop = req["stop"] + stop = [stop] if isinstance(stop, str) else stop + if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop): + raise ValueError("stop must be a string or a list of strings") + if len(stop) > OPENAI_MAX_STOP: + raise ValueError(f"stop takes at most {OPENAI_MAX_STOP} strings") + elif req.get("stop_sequences") is not None: + stop = req["stop_sequences"] + if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop): + raise ValueError("stop_sequences must be a list of strings") + else: + return [] + return [x for x in stop if x] + + +class StopMatcher: + """Cuts the answer's text at the first stop string. Text that could still be the start of a stop string is held + back (only that tail, never more), so a stop string split across tokens or chunks is still found and never sent.""" + + def __init__(self, stops: list[str]): + self.stops, self.held, self.hit = stops, "", None + + def push(self, text: str) -> str: + """-> the text that is safe to send now; after a match, self.hit is the stop string and nothing more comes.""" + if self.hit is not None: + return "" + buf = self.held + text + first = None + for s in self.stops: + i = buf.find(s) + if i >= 0 and (first is None or i < first[0]): + first = (i, s) + if first is not None: + self.held, self.hit = "", first[1] + return buf[:first[0]] + keep = 0 # the longest end of buf that a stop string starts with + for s in self.stops: + for k in range(min(len(s) - 1, len(buf)), keep, -1): + if buf.endswith(s[:k]): + keep = k + break + self.held = buf[len(buf) - keep:] if keep else "" + return buf[:len(buf) - keep] + + def flush(self) -> str: + held, self.held = self.held, "" + return held + + class Service: def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", vision: Vision | None = None, sampling_defaults: dict | None = None, @@ -1708,6 +1893,7 @@ class Service: self.min_free_vram_mib = 0 self.before_load = None self.vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's) + self.reasoning_loop_recovery = False self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False @@ -2147,10 +2333,43 @@ class Service: prompt, plain = unmark_think_literals(prompt) return self.tok.encode(prompt, parse_special=True, plain=plain) - def prepare(self, messages, tools, kwargs, max_new=None): + def _note_unreadable_tool_images(self, messages): + """A picture a tool returned (Claude Code's Read of an image file) that this server cannot read - it has no + image encoder, or the encoder refuses that picture - becomes a short note in its place instead of a 400. + Clients resend the whole history every turn, so one unreadable tool picture would fail every later request of + the conversation; a picture the user sends keeps the 400. A picture that encodes stays in the cache, so the + prompt's own encode below finds it.""" + fetched = {} # a URL's bytes, so prepare() does not download the same picture again + for m in messages: + content = m.get("content") + if m.get("role") != "tool" or not isinstance(content, list): + continue + for n, item in enumerate(content): + if not isinstance(item, dict) or item.get("type") != "image": + continue + why = "this server has no image encoder" if self.vision is None else None + if why is None: + src = item["source"] + try: + if src.startswith(("http://", "https://")): + src = fetched[item["source"]] = Vision.download(src) # outside the FIFO, as in prepare() + with self.fifo: # the encoder takes its turn with the requests (see below) + self.vision.encode(src) + except (ValueError, OSError) as e: + why = str(e) + if why is not None: + print(f"[strata] a picture a tool returned was left out of the prompt: {why}", flush=True) + content[n] = {"type": "text", "text": f"[image omitted: {why}]"} + return fetched + + def prepare(self, messages, tools, kwargs, max_new=None, force=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": - the rest of the context.""" + the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the + prompt; with thinking, Service.run writes it once the thinking is over.""" + fetched = self._note_unreadable_tool_images(messages) ids = self.encode_prompt(messages, tools, kwargs) + if force and kwargs.get("enable_thinking", True) is False: + ids = ids + self.tok.encode(force, parse_special=True) self.embeddings.path = None images = images_of(messages) if images: @@ -2159,6 +2378,10 @@ class Service: "'vision'), so it cannot read images") pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0] start = self.tok.encode(VISION_START, parse_special=True)[0] + # An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request + # for as long as urlopen waited. + images = [fetched[src] if src in fetched else Vision.download(src) if src.startswith(("http://", "https://")) + else src for src in images] # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not # run on the GPU at the same time - an encode during a running request left that request stuck at # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the @@ -2171,7 +2394,10 @@ class Service: literal = self.tok.encode(IMAGE_PAD, parse_special=False) out, k = [], 0 for j, t in enumerate(ids): - if t == pad and j > 0 and ids[j - 1] == start and k < len(encoded): + if t == pad and j > 0 and ids[j - 1] == start: + # more pairs than images: text parts that cut both markers apart (the literal marks keep whole ones text) + if k == len(encoded): + raise ValueError("the prompt and its images do not match") out += [pad] * encoded[k][1] k += 1 elif t == pad: @@ -2181,11 +2407,6 @@ class Service: if k != len(encoded): raise ValueError("the prompt and its images do not match") ids = out - combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve" - with open(combined, "wb") as f: - for path, _ in encoded: - f.write(path.read_bytes()) - self.embeddings.path = combined ctx = self.engine.max_context if ctx <= 0: if getattr(self.engine, "starting", False): # #344: (re)starting, not a prompt that is too long @@ -2208,8 +2429,25 @@ class Service: f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the " "model's strata-.json to shorten it to the room left (#545)") max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400 + if images: + # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the + # request: one refused after it (the engine starting, no room) left it in the vision directory for good, + # one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts. + combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve" + self.embeddings.path = combined # first, so a half-written one is found as well + with open(combined, "wb") as f: + for path, _ in encoded: + f.write(path.read_bytes()) return ids, kwargs.get("enable_thinking", True) is not False, max_new + def drop_embeddings(self) -> None: + """Delete the combined image file prepare() wrote when no run() took it over (a run deletes its own as it + ends): a request can end before its answer starts - its client gone, anything raised after prepare() - and + then nothing else would. The handler calls this when a request is done.""" + path, self.embeddings.path = getattr(self.embeddings, "path", None), None + if path is not None: + Path(path).unlink(missing_ok=True) + def _note(self, n, evs, st=None, rate=None): with self.status_lock: s = self.status if st is None else st @@ -2246,8 +2484,9 @@ class Service: f"{el:.0f} s", flush=True) return now - def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]: - """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).""" + def run(self, ids, thinking, tools, max_new, sampling, cancel, force=None) -> Iterator[tuple[str, object]]: + """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}). + `force` (forced_call): the opening of the call the reply must make - see prepare().""" budget = self.reasoning_budget(sampling) if thinking else None # #123: opt-in, off by default defaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with apps if defaults: # the request's own fields win (explicit 0 stays greedy) @@ -2257,9 +2496,36 @@ class Service: detok, n, finish = Detokenizer(self.tok), 0, "length" run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) + stop_list = stop_strings(sampling) + stops = StopMatcher(stop_list) if stop_list else None + + def cut(evs): + """The events with the answer's text cut at a stop string (OpenAI stop, Anthropic stop_sequences).""" + if stops is None: + return evs + out = [] + for ev in evs: + if stops.hit is not None: + break # nothing after the stop string is sent + if ev.kind == "content": + text = stops.push(ev.text or "") + if text: + out.append(Event("content", text)) + continue + held = stops.flush() # a stop string does not run across a tool call or thinking + if held: + out.append(Event("content", held)) + out.append(ev) + return out + opening = [] # without thinking the prompt ends with the forced opening: + if force and not thinking: # the parser reads it as if the model had written it + opening, force = parser.feed(force), None + tail = "" # the last characters written (the newlines before a call) timings, before = None, None # this request's timings; the engine's `last` before it + recovery_count, reasoning_text, repeat_coverage = 0, "", 0.0 + looped, next_loop_check = False, LOOP_CHECK_EVERY # #728: reasoning that repeats whole passages raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) - emb = getattr(self.embeddings, "path", None) + emb, self.embeddings.path = getattr(self.embeddings, "path", None), None # this run's to delete now # Identity token: only a DONE line replaces engine.last, so a request that died, errored or was # disconnected must not have the PREVIOUS request's decode figures recorded as its own. engine_last0 = getattr(self.engine, "last", None) @@ -2288,7 +2554,7 @@ class Service: with self.status_lock: st.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids), generated=0, started=time.time(), first_token=None, tool=None, tail="", - max_tokens=max_new) + max_tokens=max_new, reasoning_recoveries=0) if par: self.live_reqs[id(st)] = (st, rate) self.status.update(st) @@ -2297,10 +2563,14 @@ class Service: before = getattr(self.engine, "last", None) last_print = time.time() prompt, thought = ids, 0 # thought: the reasoning tokens so far (the budget's count) + for ev in opening: + yield "event", ev while True: gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \ else self.engine.generate(prompt, max_new - n, sampling, cancel) + recover_prompt = None seg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closed + opens = False # the thinking is over: write the forced call's opening try: for t in gen: if t is None: # heartbeat while the engine is quiet @@ -2317,23 +2587,48 @@ class Service: break raw_ids.append(t) seg.append(t) - thinking_n += parser.state == "reasoning" + thinking_n += parser.state in ("reasoning", "rcall") run_len = run_len + 1 if t == run_tok else 1 run_tok = t if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens: repeated = True # #606: a degenerate output, not an answer: end it here break - evs = parser.feed(detok.push(t)) + piece = detok.push(t) + tail = (tail + piece)[-2:] + evs = cut(parser.feed(piece)) self._note(n, evs, st, rate) last_print = self._progress(last_print, st=st) for ev in evs: + if self.reasoning_loop_recovery and ev.kind == "reasoning": + reasoning_text += ev.text or "" yield "event", ev + if stops is not None and stops.hit is not None: + finish = "stop" # gen.close() below STOPs the engine, as for a stop token + break + if (self.reasoning_loop_recovery and not recovery_count and parser.state == "reasoning" + and n >= next_loop_check and not parser.buf and not detok.pending()): + next_loop_check = n + LOOP_CHECK_EVERY + repeat_coverage = reasoning_repeat_coverage(reasoning_text) + if repeat_coverage >= LOOP_COVERAGE: + if self.reasoning_loop_recovery == "stop": + looped = True # #728: end the reply here, as for a repeated token + break + if not emb: # "recover": not for a request with pictures + recover_prompt = focused_recovery_prompt(self.tok, ids, raw_ids) + if recover_prompt is not None: + break if budget and parser.state == "reasoning": thought += 1 # at a clean point: no tag held back, no character split across tokens if thought >= budget and not parser.buf and not detok.pending(): wrap = True break + if force: + if any(ev.kind in ("tool_start", "tool_call") for ev in evs): + force = None # the model is writing a call of its own + elif parser.state == "content" and not parser.buf and not detok.pending(): + opens = True + break except EngineDied as e: finish = "error" self._say_died(e) @@ -2355,28 +2650,63 @@ class Service: self._say_died(e) if not leaving and not cancel.is_set(): raise - if not wrap or cancel.is_set(): + if recover_prompt is not None and not cancel.is_set() and n < max_new: + recovery_count += 1 + # Only the two settings that keep the same words coming are raised (temperature to at + # least 1.0, presence penalty to at least 1.5): a client's top_p and top_k are never + # touched, and its own request dict is copied, not changed. + want = (max(1.0, float((sampling or {}).get("temperature") or 0)), + max(1.5, float((sampling or {}).get("presence_penalty") or 0))) + if want != tuple(float((sampling or {}).get(k) or 0) + for k in ("temperature", "presence_penalty")): + sampling = {**(sampling or {}), "temperature": want[0], "presence_penalty": want[1]} + prompt = recover_prompt + with self.status_lock: + st["reasoning_recoveries"] = recovery_count + if trace is not None: + trace["reasoning_recoveries"] = recovery_count + trace["reasoning_repeat_coverage"] = round(repeat_coverage, 3) + print(f"[strata] repeated reasoning detected at {n} tokens " + f"(coverage={repeat_coverage:.3f}); resuming the same output with the low-effort " + "instruction (reasoning_loop_recovery)", flush=True) + continue + if not (wrap or opens) or cancel.is_set(): break # #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a # short wrap-up and ) and let it answer: the next pass's prompt is this one plus what # was generated plus the wrap-up, so the engine continues from the prefix it already holds. - budget = None - extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True) + # A forced call (tool_choice) is opened the same way: after the wrap-up, or where the + # thinking ended, after the blank line the template puts before a call. + if wrap: + budget = None + text = REASONING_WRAP_UP + (force or "") + else: + text = "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force + force = None + extra = self.tok.encode(text, parse_special=True) if max_new - n - len(extra) < 1: break # no room left to answer: "length", as without a budget - print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking", - flush=True) + if wrap: + print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking", + flush=True) for t in extra: n += 1 raw_ids.append(t) - thinking_n += parser.state == "reasoning" - evs = parser.feed(detok.push(t)) + thinking_n += parser.state in ("reasoning", "rcall") + evs = cut(parser.feed(detok.push(t))) self._note(n, evs, st, rate) for ev in evs: yield "event", ev + if stops is not None and stops.hit is not None: + finish = "stop" + break prompt = prompt + seg + extra if cancel.is_set(): finish = "cancel" + elif looped: + print(f"[strata] the thinking repeated the same passages (coverage={repeat_coverage:.3f}) at " + f"{n} tokens: ended as \"length\" (reasoning_loop_recovery: \"stop\" in " + "strata-.json; remove it to turn this off)", flush=True) elif repeated: print(f"[strata] the reply repeated one token ({self.tok.decode([run_tok])!r}) " f"{run_len} times in a row: ended as \"length\" (repeat_stop_tokens in " @@ -2411,6 +2741,8 @@ class Service: "prompt_tokens": seen, "reused": last.get("reused"), "output_tokens": n, # the request's whole prompt, and the tokens read of it (None: an older engine) "prompt_total": len(ids), "prompt_read": last.get("prompt_read"), + "reasoning_recoveries": recovery_count, + "reasoning_repeat_coverage": round(repeat_coverage, 3), "engine_generated": last.get("generated"), "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) @@ -2443,7 +2775,7 @@ class Service: hit_msg += f" (+{pcie_share*100:.1f}% of the routed experts over PCIe)" print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) " f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True) - if finish == "length" and parser.state == "reasoning": # #530 + if finish == "length" and parser.state in ("reasoning", "rcall"): # #530 print("[strata] the reply reached max tokens while still thinking, so it has no " "answer: a thinking budget (reasoning_budget_tokens, in the request or in " "strata-.json for every request) leaves room to answer", flush=True) @@ -2463,10 +2795,16 @@ class Service: finally: if emb: Path(emb).unlink(missing_ok=True) - for ev in parser.finish(): + for ev in cut(parser.finish()): yield "event", ev - yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), - "timings": timings, "reasoning_tokens": thinking_n} + if stops is not None and stops.hit is None and stops.held: + yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all + done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), + "timings": timings, "reasoning_tokens": thinking_n, + "reasoning_recoveries": recovery_count} + if stops is not None and stops.hit is not None: + done["stop_sequence"] = stops.hit + yield "done", done def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int: @@ -2604,11 +2942,41 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, # ------------------------------------------------------------------------------------------------ OpenAI -def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None): +# The engine's last PP line stops short of the prompt: up to `--short-read` tokens (generate.cpp's `short_read`, 64 by +# default) are read through the verify windows instead of the batched path, so the batched path never reports the whole +# prompt. A PP that close to the end says the prompt is read. It matters because a prompt shorter than one `--prefill` +# chunk sends exactly one PP, that one: a client would see a bar that appears already full. Such a line is dropped, and +# the answer's first token ends the progress for the client anyway. +PP_DONE_TAIL = 64 + + +def prompt_progress(svc: Service): + """The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the + same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a + client takes the reused prefix out with `cache` (llama.cpp's rule: the timed progress is + `(processed-cache)/(total-cache)`). None when there is nothing to say: no PP yet, or the line that says the prompt + is read. An engine too old to print RESUME gives `cache` 0, which only makes a reused prefix count as work.""" + engine = svc.engine + if getattr(engine, "batch", 0): # --batch: the engine's progress is one global line, not this request's + return None + progress = getattr(engine, "progress", None) + if not progress: + return None + read, total = progress + if total <= 0 or total - read <= PP_DONE_TAIL: + return None + return {"total": int(total), "cache": int(getattr(engine, "reused", 0) or 0), "processed": int(read), + "time_ms": int(getattr(engine, "progress_ms", 0) or 0)} + + +def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None, force=None): """`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with - an empty delta and a `strata_mcp` field, which only the web app reads.""" + an empty delta and a `strata_mcp` field, which only the web app reads. `force`: see Service.run.""" cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time()) model = svc.model_for(req) + # llama.cpp's flag, and its default: a client that wants prompt progress asks for it, and nothing changes for one + # that does not. Strata already sends a keep-alive comment on every PP line, so this only fills that line in. + want_progress = bool(req.get("return_progress")) def chunk(delta, finish=None): return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model, @@ -2618,9 +2986,12 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel calls = 0 streamed = {} # tool call id -> index, for calls sent piece by piece finished = set() # ... and the ones whose final tool_call came (#211) - for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel): + for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force): if kind == "ping": - yield None + # a PP line: the prompt is being read and there is nothing to say yet. It used to be only the SSE comment; + # now it carries the progress when the client asked, and stays the comment when there is nothing to report. + pp = prompt_progress(svc) if want_progress else None + yield None if pp is None else {**chunk({}), "prompt_progress": pp} elif kind == "mcp": c = chunk({}) c["strata_mcp"] = x @@ -2710,11 +3081,12 @@ def structured_chunks(chunks, validator): heartbeat = time.monotonic() try: for chunk in chunks: - if chunk is not None: - buffered.append(chunk) - if chunk is None or time.monotonic() - heartbeat >= 1: + progress = chunk is not None and "prompt_progress" in chunk + if chunk is not None and not progress: + buffered.append(chunk) # a progress chunk carries no content: there is nothing in it to validate + if chunk is None or progress or time.monotonic() - heartbeat >= 1: heartbeat = time.monotonic() - yield None + yield chunk if progress else None result = openai_collect(buffered) choice = result["choices"][0] content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) @@ -2729,7 +3101,7 @@ def structured_chunks(chunks, validator): # ------------------------------------------------------------------------------------------------ Anthropic -def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel): +def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, force=None): mid = "msg_" + uuid.uuid4().hex[:24] yield "message_start", {"type": "message_start", "message": { "id": mid, "type": "message", "role": "assistant", "model": svc.model_for(req), "content": [], @@ -2740,7 +3112,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can return ("content_block_stop", {"type": "content_block_stop", "index": index}) streamed, finished = set(), set() # calls sent piece by piece; those whose final tool_call came (#211) - for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): + for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel, force=force): if kind == "ping": yield None continue @@ -2784,12 +3156,14 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can else: if open_kind is not None: yield close() - stop = "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ + stop = "stop_sequence" if x.get("stop_sequence") is not None else \ + "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] # the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held, # which is cache_read_input_tokens (message_start could only say the whole prompt) reused = min(x.get("reused") or 0, len(ids)) - yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, + yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, + "stop_sequence": x.get("stop_sequence")}, "usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}} yield "message_stop", {"type": "message_stop"} @@ -2821,6 +3195,7 @@ def anthropic_collect(events) -> dict: blocks.pop() elif name == "message_delta": msg["stop_reason"] = e["delta"]["stop_reason"] + msg["stop_sequence"] = e["delta"].get("stop_sequence") msg["usage"].update(e["usage"]) msg["content"] = blocks return msg @@ -2833,10 +3208,47 @@ def make_handler(svc: Service): record = None # #332: this request's monitor record, if kept watch_done = None # #430 #431: stops this request's disconnect watcher + body_read = False # whether a handler took this request's body + DRAIN_SECONDS = 5 # the longest an unread body is read and dropped def log_message(self, fmt, *args): pass + def handle_one_request(self): + super().handle_one_request() + self._drain_body() + + def _body(self) -> bytes: + self.body_read = True + return self.rfile.read(int(self.headers.get("Content-Length", 0))) + + def _drain_body(self): + """An answer sent before the body was read (a 401, a 403, /load, a method with no handler) must not close + the connection on unread bytes: the close then sends a reset, and a client that sends its body after the + headers (http.client, urllib, requests) gets a connection error instead of the answer. So the body is + read and dropped here, once, after an answer, in pieces so that its size is never held in memory. What + has not arrived DRAIN_SECONDS later is left unread: the limit is time, so that a conversation of many + megabytes, at any speed the client has, still gets its answer.""" + headers = getattr(self, "headers", None) + if self.body_read or headers is None: + return + try: + left = int(headers.get("Content-Length", 0)) + except ValueError: + return + if left <= 0: + return + deadline = time.monotonic() + self.DRAIN_SECONDS + try: + while left > 0 and (wait := deadline - time.monotonic()) > 0: + self.connection.settimeout(wait) # a client that never sends what it announced + piece = self.rfile.read1(min(left, 1 << 20)) # one socket read: read() would wait for it all + if not piece: + break + left -= len(piece) + except OSError: + pass + def parse_request(self): """Without an API key, every request (any method) first passes the Host check: DNS rebinding protection (host_allowed). With a key a rebinding page cannot authenticate, so the check is skipped: tunnels and @@ -2877,6 +3289,14 @@ def make_handler(svc: Service): return True return False + def end_headers(self): + # HTTP/1.0 without keep-alive: the server closes the connection after every response. Say so, or a + # client that pools connections (.NET's SocketsHttpHandler) can put its next request on this socket + # before the close reaches it, and that request fails with "response ended prematurely" without the + # server ever reading it (a .NET agent app, 2026-10-03: 25 of ~1000 requests, 1-24 ms after the previous answer). + self.send_header("Connection", "close") + super().end_headers() + def _watch_client(self, cancel: threading.Event) -> None: """#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up @@ -3113,7 +3533,7 @@ def make_handler(svc: Service): self._json(503, {"error": {"type": "server_error", "message": str(e)}}) return try: - req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + req = json.loads(self._body() or b"{}") if not isinstance(req, dict): raise ValueError("send a JSON object") if path.startswith("/v1/responses/"): # retrieve/delete/cancel/compact: nothing is stored @@ -3168,6 +3588,7 @@ def make_handler(svc: Service): else: self._json(404, {"error": {"message": "not found"}}) except ValueError as e: + print(f"[strata] 400 invalid request: {e}", flush=True) if path == "/v1/responses": self._json(400, responses_error_body(str(e))) else: @@ -3188,6 +3609,7 @@ def make_handler(svc: Service): self._note(outcome="disconnected") raise # as before #332: the server's own handling finally: + svc.drop_embeddings() # the images' file of a request that never got to run() if self.watch_done is not None: self.watch_done.set() record = self.record @@ -3241,6 +3663,7 @@ def make_handler(svc: Service): complete = False finally: self.connection.settimeout(timeout) + self.body_read = True # nothing left for the drain to wait for (#594) if not complete: self._json(400, {"error": {"message": "incomplete control request body"}}) return complete @@ -3251,12 +3674,7 @@ def make_handler(svc: Service): if not self.headers.get("Content-Type", "").startswith("application/json"): self._json(415, {"error": {"message": "send application/json"}}) return False - # The Origin must be this server's own address (host and port), or an origin the config trusts - # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*, - # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing. - origin = (self.headers.get("Origin") or "").rstrip("/") - if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ - origin not in svc.trusted_origins: + if self._foreign_origin(): self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the " f"config's trusted_origins)"}}) return False @@ -3276,7 +3694,7 @@ def make_handler(svc: Service): def _config_post(self): """#564: change a few documented keys of the run config - JSON from Strata's own page only, as /settings (the key is checked before); every other key of the file stays as it is.""" - body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = self._body() if not self._own_page("the run config can be changed"): return if not svc.config_path: @@ -3299,10 +3717,30 @@ def make_handler(svc: Service): print(f"[strata] the Settings view changed {', '.join(changed)} in {Path(svc.config_path).name} " f"(the earlier file: {bak.name}); used from the next start", flush=True) self._json(200, {**runconfig.view(new, svc.config_path), "changed": changed}) + def _foreign_origin(self) -> bool: + """A web page of another origin sent this. The Origin must be this server's own address (host and port), + or an origin the config trusts (trusted_origins: the web app behind a reverse proxy or tunnel); no Origin + is a client that is no browser. Headers a proxy adds (X-Forwarded-*, CF-Ray, CF-Connecting-IP) prove + nothing about the page that sent the request, so they open nothing.""" + origin = (self.headers.get("Origin") or "").rstrip("/") + return bool(origin) and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ + origin not in svc.trusted_origins + + def _no_local_images(self, messages): + """A web page of another origin must not have a file on this computer read as an image. Without an + api_key, _foreign_page refuses such a page unless cors_origins lets it in - and a page cors_origins lets + in (["*"]: every page) could name any file and, CORS allowing, read what the model says about it. data: + and http(s) images are the page's own to send; files come from Strata's own page, a trusted origin or a + client that is no browser. ValueError (a 400).""" + if self._foreign_origin() and any(not src.startswith(("data:", "http://", "https://")) + for src in images_of(messages)): + raise ValueError("a web page of another origin cannot have a file on this computer read as an " + "image: send it as a data: URL (or add the page's origin to the config's " + "trusted_origins)") def _settings(self): # They change what every client gets, so only the app's own page may set them - body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = self._body() if not self._own_page("settings can be changed"): return try: @@ -3366,6 +3804,10 @@ def make_handler(svc: Service): def _openai(self, req): req = svc.with_shared(req, "openai") messages, tools, kw = openai_to_messages(req) + self._no_local_images(messages) + if tool_choice_of(req.get("tool_choice"))[0] == "none": # as the Responses route: no tools are offered + tools = None + force = forced_call(req.get("tool_choice"), tools) # a bad value is a 400 before anything is sent messages, validator = prepare_format(req.get("response_format"), messages) if validator is not None and (tools or req.get("strata_mcp")): raise ValueError("structured response_format with tools/MCP is not supported") @@ -3380,14 +3822,17 @@ def make_handler(svc: Service): extra = svc.mcp.template_tools(exclude=own) # the request's own tools win a name clash use_mcp = bool(extra) tools = (tools or []) + extra or None + if force and use_mcp: + raise ValueError("a forced tool_choice with MCP tools is not supported") svc.reasoning_budget(req) # a bad value is a 400 before anything is sent - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + stop_strings(req) # ... and so is a bad stop / stop_sequences + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force) _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() self._watch_client(cancel) # #430 #431 run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, {t["name"] for t in extra}) if use_mcp else None - chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run) + chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force) if validator is not None: chunks = structured_chunks(chunks, validator) chunks = self._capture(chunks, "openai") @@ -3507,6 +3952,10 @@ def make_handler(svc: Service): messages = responses_api.input_messages(req) tools, names, skipped = responses_api.request_tools(req) kw = responses_api.template_kwargs(req, svc.shared) + try: + self._no_local_images(messages) # as on the chat route: no file read for a foreign page + except ValueError as e: + raise ResponsesError(str(e), "input") from None try: messages, validator = prepare_format(responses_api.text_format(req), messages) except ValueError as e: @@ -3525,6 +3974,10 @@ def make_handler(svc: Service): svc.reasoning_budget(req) # a bad value is a 400 before anything is sent except ValueError as e: raise ResponsesError(str(e), "reasoning_budget_tokens") from None + try: + stop_strings(req) + except ValueError as e: + raise ResponsesError(str(e), "stop") from None svc.load() try: ids, thinking, max_new = svc.prepare(messages, tools, kw, req.get("max_output_tokens") or 0) @@ -3545,19 +3998,25 @@ def make_handler(svc: Service): read for the same request, rendered and tokenized - the model does not run.""" req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + stop_strings(req) # the same 400 as the request itself would get self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))}) def _anthropic(self, req): svc.load() req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + self._no_local_images(messages) + if tool_choice_of(req.get("tool_choice"))[0] == "none": # Anthropic's {"type": "none"}: no tools offered + tools = None + force = forced_call(req.get("tool_choice"), tools) # "any" / {"type": "tool", "name": N} max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + stop_strings(req) # ... and so is a bad stop / stop_sequences + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force) _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() self._watch_client(cancel) # #430 #431 - events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel) + events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel, force=force) events = self._capture(events, "anthropic") if not req.get("stream"): return self._json(200, anthropic_collect(events)) @@ -4074,6 +4533,13 @@ def main() -> int: if budget: print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)", flush=True) + recovery = cfg.get("reasoning_loop_recovery", False) # #728: false (default) | "stop" | "recover" (true) + if recovery is True: + recovery = "recover" + if recovery is not False and recovery not in ("stop", "recover"): + raise SystemExit("[strata] config \"reasoning_loop_recovery\" must be false, \"stop\" or \"recover\", " + f"not {recovery!r}") + svc.reasoning_loop_recovery = recovery svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51) svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112) svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301) diff --git a/serve/structured.py b/serve/structured.py index b5f079cc..101c78f6 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -51,6 +51,35 @@ def jsonschema_modules(): return _jsonschema or None +def _only_objects(node, root, refs=()): + """True when every value `node` accepts is a JSON object, so "return one JSON object" stays true. + + `type: object`, an anyOf/oneOf whose branches all qualify (e.g. a root union of object shapes, which llama.cpp's + grammar path accepts and apps send), an allOf with a qualifying member, or a local `$ref` to one of these. + Anything that can also be an array, string, number, boolean or null (including `type: ["object", "null"]`) is + not, and a `$ref` cycle never qualifies. + """ + if not isinstance(node, dict): + return False + if node.get("type") == "object": + return True + ref = node.get("$ref") + if isinstance(ref, str) and ref.startswith("#") and ref not in refs: + target = root + for part in ref[1:].split("/")[1:]: + part = part.replace("~1", "/").replace("~0", "~") + if not isinstance(target, dict) or part not in target: + return False + target = target[part] + return _only_objects(target, root, refs + (ref,)) + for key in ("anyOf", "oneOf"): + branches = node.get(key) + if isinstance(branches, list) and branches and all(_only_objects(b, root, refs) for b in branches): + return True + branches = node.get("allOf") + return isinstance(branches, list) and any(_only_objects(b, root, refs) for b in branches) + + def prepare_format(response_format, messages): if response_format is None: return messages, None @@ -71,8 +100,9 @@ def prepare_format(response_format, messages): if "strict" in spec and not isinstance(spec["strict"], bool): raise ValueError("response_format.json_schema.strict must be boolean") schema = spec["schema"] - if schema.get("type") != "object": - raise ValueError("response_format schema must have type object at its root") + if not _only_objects(schema, schema): + raise ValueError("response_format schema must accept only JSON objects at its root " + "(type object, or anyOf/oneOf of object schemas)") modules = jsonschema_modules() else: raise ValueError("response_format.type must be text, json_object or json_schema") @@ -118,6 +148,43 @@ def prepare_format(response_format, messages): return messages, validator +def _extract_json(text: str) -> str: + s = (text or "").strip() + if not s: + return "" + if s.startswith("```"): + first = s.find("\n") + if first != -1: + end = s.find("```", first + 1) + if end != -1: + s = s[first + 1:end].strip() + start = s.find("{") + if start == -1: + return s + depth = 0 + in_str = False + esc = False + for i in range(start, len(s)): + ch = s[i] + if in_str: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == "\"": + in_str = False + else: + if ch == "\"": + in_str = True + elif ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + return s[start:i + 1] + return s[start:] + + def validated_json(text, validator, finish): def pairs(items): obj = {} @@ -133,7 +200,7 @@ def validated_json(text, validator, finish): if finish != "stop": raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") try: - value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant) + value = json.loads(_extract_json(text), object_pairs_hook=pairs, parse_constant=constant) canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) except (ValueError, TypeError) as exc: raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc diff --git a/serve/test_fatal_recovery.py b/serve/test_fatal_recovery.py new file mode 100644 index 00000000..bdd378bc --- /dev/null +++ b/serve/test_fatal_recovery.py @@ -0,0 +1,116 @@ +"""Real pipe/process protocol regression for a native ERR that leaves its process alive.""" +import os +from pathlib import Path +import sys +import tempfile +import threading +import time +import unittest +import json +import urllib.request +from serve.server import StrataEngine, Service, ChatTemplate, EngineDied, serve +from serve.test_server import ByteTokenizer + +FAKE=r''' +import sys +from pathlib import Path +state=Path(sys.argv[sys.argv.index('--state')+1]) +mode=sys.argv[sys.argv.index('--mode')+1] +print('READY 4096 stop',flush=True) +for line in sys.stdin: + if line.startswith('QUIT'):break + if line.startswith(('GEN','BGEN')): + if not state.exists(): + state.write_text('first request was attempted') + if mode=='invalid':print('ERR prompt exceeds context',flush=True) + else: + kind='verify batch' if mode=='batch' else 'verify' + print(f'ERR {kind}: timed out at layer 18; its GPU waits were released and the GPU finished (#267)',flush=True) + print('DONE 0 1 0 1 error',flush=True) + continue + print('T 90\nDONE 1 1 0 1 stop',flush=True) +''' + +class FatalRecovery(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.root=Path(self.tmp.name);py=self.root/'native.py' + if os.name=='nt': # no shebangs on Windows: a .cmd runs the same fake engine + py.write_text(FAKE);self.script=self.root/'native.cmd' + self.script.write_text(f'@"{sys.executable}" "{py}" %*\r\n') + else: + self.script=py;py.write_text('#!'+sys.executable+'\n'+FAKE);py.chmod(0o700) + def engine(self,mode='fatal'): + e=StrataEngine(str(self.script),['--state',str(self.root/'state'),'--mode',mode]) + self.addCleanup(e.close);return e + def service(self,e): + return Service(e,ByteTokenizer(),ChatTemplate(Path(__file__).parent/'chat_template.jinja')) + def wait_dead(self,e): + end=time.monotonic()+2 + while e.alive() and time.monotonic()", prompt) + self.assertIn("file.txt", prompt) + self.assertEqual(messages, before) + + def test_image_only_assistant_turn_is_kept(self): + messages, tools, kwargs = openai_to_messages({"messages": [ + {"role": "user", "content": "describe the image"}, + {"role": "assistant", "content": [{"type": "image_url", "image_url": "image.png"}]}, + {"role": "user", "content": "thanks"}, + ]}) + self.assertIn("<|vision_start|><|image_pad|><|vision_end|>", + self.template.render(messages, tools=tools, **kwargs)) + + def test_final_empty_assistant_turn_is_kept(self): + prompt = self.template.render([{"role": "user", "content": "hi"}, + {"role": "assistant", "content": ""}], add_generation_prompt=False) + self.assertIn("<|im_start|>assistant\n", prompt) + + def test_empty_user_and_tool_turns_are_kept(self): + prompt = self.template.render([{"role": "user", "content": ""}, + {"role": "tool", "content": ""}, + {"role": "user", "content": "hi"}]) + self.assertEqual(prompt.count("<|im_start|>user\n"), 3) + self.assertIn("\n\n", prompt) + + +if __name__ == "__main__": + unittest.main() + + +class EmptyTurnsSwitch(unittest.TestCase): + def test_keep_empty_turns_restores_the_old_prompt(self): + import os + from unittest import mock + template = ChatTemplate(Path(__file__).with_name("chat_template.jinja")) + msgs = [{"role": "user", "content": "a"}, {"role": "assistant", "content": ""}, + {"role": "user", "content": "b"}] + clean = template.render([msgs[0], msgs[2]]) + self.assertEqual(template.render(msgs), clean) + with mock.patch.dict(os.environ, {"STRATA_KEEP_EMPTY_TURNS": "1"}): + self.assertNotEqual(template.render(msgs), clean) + + +class ForcedCallOpening(unittest.TestCase): + def test_required_with_one_tool_names_it(self): + from serve.frontend import forced_call + one, two = [{"name": "a"}], [{"name": "a"}, {"name": "b"}] + self.assertTrue(forced_call("required", one).endswith("\n")) + self.assertTrue(forced_call("required", two).endswith("= 256 else bytes([token]) + + +class RecordingEngine(MockEngine): + def __init__(self, tokenizer, scripts): + super().__init__(tokenizer, scripts, max_context=100000) + self.calls = [] + self.sampling_calls = [] + self.sampling_objects = [] + + def generate(self, ids, max_new, sampling, cancel, **kwargs): + self.calls.append((list(ids), max_new)) + self.sampling_calls.append(dict(sampling or {})) + self.sampling_objects.append(sampling) + yield from super().generate(ids, max_new, sampling, cancel, **kwargs) + + +class ReasoningLoopRecovery(unittest.TestCase): + def setUp(self): + self.tok = Tokenizer() + self.ids = self.tok.encode('<|im_start|>system\n' + HIGH_EFFORT + + '<|im_end|>\n<|im_start|>user\nSolve this unchanged task<|im_end|>\n' + '<|im_start|>assistant\n\n', parse_special=True) + self.loop = 'Need maybe Agent support agent seven b. ' * 700 + + def test_repetition_and_novel_work(self): + self.assertEqual(reasoning_repeat_coverage(' '.join(str(i) for i in range(4000))), 0) + self.assertGreater(reasoning_repeat_coverage(self.loop), .9) + + def test_user_instruction_is_never_rewritten(self): + ids = self.tok.encode('<|im_start|>user\n' + HIGH_EFFORT, parse_special=True) + self.assertIsNone(focused_recovery_prompt(self.tok, ids, [])) + + def test_preserves_task_and_exact_generated_tokens(self): + generated = self.tok.encode('中文 partially checked code', parse_special=False) + prompt = focused_recovery_prompt(self.tok, self.ids, generated) + self.assertEqual(prompt[-len(generated):], generated) + self.assertIn('Solve this unchanged task', self.tok.decode(prompt)) + self.assertNotIn('', self.tok.decode(prompt)) + + def run_case(self, enabled): + engine = RecordingEngine(self.tok, [self.loop, + 'I have verified the solution.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = enabled + events = list(service.run(self.ids, True, [], 40000, {}, threading.Event())) + return engine, events + + def test_old_explicit_sampler_recovers_without_mutating_request(self): + engine = RecordingEngine(self.tok, [self.loop, + 'Verified.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + request = {'temperature': .2, 'presence_penalty': 0, 'top_p': .95, 'top_k': 64, 'seed': 2} + list(service.run(self.ids, True, [], 40000, request, threading.Event())) + self.assertEqual(engine.sampling_calls[0], request) + self.assertEqual(engine.sampling_calls[1]['temperature'], 1.0) + self.assertEqual(engine.sampling_calls[1]['presence_penalty'], 1.5) + self.assertEqual(engine.sampling_calls[1]['top_k'], 64) # a client's top_k and top_p are never touched + self.assertEqual(engine.sampling_calls[1]['top_p'], .95) + self.assertEqual(engine.sampling_calls[1]['seed'], request['seed']) + self.assertEqual(request['temperature'], .2) + self.assertEqual(request['presence_penalty'], 0) + + def test_frozen_cohort_sampler_is_unchanged_during_recovery(self): + engine = RecordingEngine(self.tok, [self.loop, 'Done.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + sampler = {'temperature': 1.0, 'top_p': .95, 'top_k': 20, 'presence_penalty': 1.5, 'seed': 2} + list(service.run(self.ids, True, [], 40000, sampler, threading.Event())) + self.assertEqual(len(engine.sampling_objects), 2) + self.assertIs(engine.sampling_objects[0], engine.sampling_objects[1]) + self.assertIs(engine.sampling_objects[1], sampler) + + def test_a_lower_top_p_and_top_k_are_never_raised_or_lowered(self): + engine = RecordingEngine(self.tok, [self.loop, 'Verified.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = "recover" + list(service.run(self.ids, True, [], 40000, {'temperature': 0, 'top_p': .5, 'top_k': 5}, threading.Event())) + self.assertEqual((engine.sampling_calls[1]['top_p'], engine.sampling_calls[1]['top_k']), (.5, 5)) + self.assertEqual((engine.sampling_calls[1]['temperature'], engine.sampling_calls[1]['presence_penalty']), (1.0, 1.5)) + + def test_the_splice_keeps_a_literal_think_tag_as_text(self): + """#537: the prompt is spliced as token ids, never decoded and encoded again.""" + from serve.frontend import THINK_TAGS + head = '<|im_start|>system\n' + HIGH_EFFORT + marked = self.tok.encode(head + '<|im_end|>\n<|im_start|>user\nquote ' + THINK_TAGS[''] + + ' please<|im_end|>\n<|im_start|>assistant\n\n', parse_special=True) + spliced = focused_recovery_prompt(self.tok, marked, []) + tail = marked[len(self.tok.encode(head, parse_special=True)):] + self.assertEqual(spliced[-len(tail):], tail) # everything after the sentence is the same ids + self.assertNotEqual(spliced, marked) + + def test_stop_mode_ends_the_reply_at_the_loop(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = "stop" + events = list(service.run(self.ids, True, [], 40000, {}, threading.Event())) + self.assertEqual(len(engine.calls), 1) # no second pass + self.assertEqual(events[-1][1]['finish'], 'length') + self.assertLess(events[-1][1]['completion_tokens'], 20000) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_disabled_is_one_pass(self): + engine, events = self.run_case(False) + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_default_single_token_guard_does_not_detect_passage_loop(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + events = list(service.run(self.ids, True, [], 16384, {}, threading.Event())) + self.assertEqual(service.repeat_stop_tokens, 256) + self.assertEqual(events[-1][1]['finish'], 'length') + self.assertEqual(events[-1][1]['completion_tokens'], 16384) + self.assertFalse(any(e.kind == 'content' for kind, e in events if kind == 'event')) + + def test_recovery_is_once_and_never_extends_output_limit(self): + engine = RecordingEngine(self.tok, [self.loop, self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + events = list(service.run(self.ids, True, [], 16384, {}, threading.Event())) + self.assertEqual(len(engine.calls), 2) + self.assertEqual(events[-1][1]['finish'], 'length') + self.assertEqual(events[-1][1]['completion_tokens'], 16384) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 1) + + def test_repeated_final_text_does_not_change_sampler_or_prompt(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + events = list(service.run(self.ids, False, [], 40000, {}, threading.Event())) + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_missing_native_high_hint_skips_recovery(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + ids = self.tok.encode('<|im_start|>user\nTask<|im_end|>\n', parse_special=True) + events = list(service.run(ids, True, [], 40000, {}, threading.Event())) + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_cancel_during_reasoning_does_not_start_recovery(self): + engine = RecordingEngine(self.tok, [self.loop, 'Unused']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + cancel = threading.Event() + events = [] + for event in service.run(self.ids, True, [], 40000, {}, cancel): + events.append(event) + if event[0] == 'event': + cancel.set() + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['finish'], 'cancel') + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_batch_status_and_history_record_recovery(self): + engine = RecordingEngine(self.tok, [self.loop, 'Done.\n\nAnswer.']) + engine.batch = 2 + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + events = list(service.run(self.ids, True, [], 40000, {}, threading.Event())) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 1) + self.assertEqual(service.history[-1]['reasoning_recoveries'], 1) + self.assertGreaterEqual(service.history[-1]['reasoning_repeat_coverage'], .25) + self.assertFalse(service.status['busy']) + self.assertEqual(service.live_reqs, {}) + + def test_natural_answer_with_shared_budget_and_preserved_prefix(self): + engine, events = self.run_case(True) + self.assertEqual(len(engine.calls), 2) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 1) + self.assertEqual(events[-1][1]['finish'], 'stop') + content = ''.join(e.text or '' for kind, e in events if kind == 'event' and e.kind == 'content') + self.assertEqual(content, 'Complete solution.') + head_size = len(focused_recovery_prompt(self.tok, self.ids, [])) + retained = engine.calls[1][0][head_size:] + self.assertEqual(retained, self.tok.encode(self.loop)[:len(retained)]) + self.assertEqual(engine.calls[1][1], 40000 - len(retained)) + self.assertNotIn('', self.tok.decode(engine.calls[1][0])) + + +if __name__ == '__main__': + unittest.main() diff --git a/serve/test_reasoning_tools.py b/serve/test_reasoning_tools.py new file mode 100644 index 00000000..4468fbd3 --- /dev/null +++ b/serve/test_reasoning_tools.py @@ -0,0 +1,148 @@ +"""serve/test_reasoning_tools.py - #804 (strict form of PR #787): a tool call the model writes inside its reasoning. + +A call inside the reasoning counts only when tools are declared and the name is one of them; anything else stays +reasoning text. Without tools the parser is byte-identical to before. + + python -m unittest serve.test_reasoning_tools -v +""" +from __future__ import annotations + +import json +import sys +import unittest +import unittest.mock +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate, OutputParser # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 +from serve.test_server import CTX, UnfinishedToolCall # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +CALL = "\n\n\n120\n\n\nfile.txt\n\n\n" +OTHER = CALL.replace("read_file", "not_declared") +TOOLS = [{"name": "read_file", "parameters": {"properties": {"limit": {"type": "integer"}, "path": {"type": "string"}}}}] + + +def run(text, width, tools=TOOLS, thinking=True, stream_tools=True): + p = OutputParser(thinking=thinking, tools=tools, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), width): + evs += p.feed(text[i:i + width]) + return evs + p.finish() + + +def joined(evs, kind): + return "".join(e.text for e in evs if e.kind == kind) + + +class Parser(unittest.TestCase): + def test_a_declared_call_in_the_reasoning_is_a_call(self): + text = "before " + CALL + " after\n\nanswer" + for width in (1, 2, 7, 100_000): + with self.subTest(width=width): + evs = run(text, width) + calls = [e.call for e in evs if e.kind == "tool_call"] + self.assertEqual([(c.name, c.arguments) for c in calls], + [("read_file", {"limit": 120, "path": "file.txt"})]) + self.assertEqual(joined(evs, "reasoning"), "before after") + self.assertEqual(joined(evs, "content"), "answer") + self.assertFalse([e for e in evs if e.kind in ("tool_start", "tool_args")]) # never streamed + + def test_an_undeclared_name_stays_reasoning(self): + text = "see " + OTHER + " done\n\nanswer" + for width in (1, 5, 100_000): + with self.subTest(width=width): + evs = run(text, width) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), "see " + OTHER + " done") + self.assertEqual(joined(evs, "content"), "answer") + + def test_no_tools_declared_is_unchanged(self): + text = "before " + CALL + " after\n\nanswer" + for tools in (None, []): + for width in (1, 7, 100_000): + with self.subTest(tools=tools, width=width): + evs = run(text, width, tools=tools) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), "before " + CALL + " after") + self.assertEqual(joined(evs, "content"), "answer") + + def test_an_unfinished_call_is_never_a_call(self): + for text in ("before\n\n", + "before\n\n\nfile.txt\n\n"): + for width in (1, 100_000): + with self.subTest(text=text[-20:], width=width): + evs = run(text, width) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), text) + + def test_the_thinking_ending_inside_a_call_makes_it_text(self): + text = "a\n\nhmm\n\nthe answer" + for width in (1, 100_000): + with self.subTest(width=width): + evs = run(text, width) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), "a\n\nhmm") + self.assertEqual(joined(evs, "content"), "the answer") + + def test_a_call_in_the_answer_is_unchanged(self): + text = "think\n\nok " + CALL + for width in (1, 100_000): + evs = run(text, width) + self.assertEqual(len([e for e in evs if e.kind == "tool_call"]), 1) + self.assertEqual(joined(evs, "reasoning"), "think") + + def test_a_tag_that_never_closes_does_not_hold_the_thinking_back(self): + from serve import frontend + text = "a " + "thinking on and on " * 3000 + "\n\nanswer" + with unittest.mock.patch.object(frontend, "RCALL_MAX", 1000): + evs = run(text, 50) + first_reasoning_at = next(i for i, e in enumerate(evs) if e.kind == "reasoning" and len(e.text) > 100) + self.assertLess(first_reasoning_at, 100) # streamed, not kept until + self.assertEqual(joined(evs, "reasoning"), text.split("")[0]) + self.assertEqual(joined(evs, "content"), "answer") + + def test_a_partial_tag_is_held(self): + p = OutputParser(thinking=True, tools=TOOLS) + evs = p.feed("hello "), "reasoning"), " More thought.\n\ndone" + a = helper.answers(script) + self.assertEqual((a["openai", False][0], [json.loads(x) for x in a["openai", False][1]]), + ("tool_calls", [{"path": "file.txt"}])) + self.assertEqual(a["anthropic", False], ("tool_use", [{"path": "file.txt"}])) + # the order of the Anthropic stream's blocks: thinking, the call, more thinking, the answer + tok = ByteTokenizer() + svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + body = {"model": "x", "max_tokens": 500, "stream": True, "messages": [{"role": "user", "content": "hi"}], + "tools": [{"name": "write", "input_schema": {"type": "object", "properties": helper.PROPS}}]} + req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/v1/messages", + data=json.dumps(body).encode(), headers={"Content-Type": "application/json", + "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + order = [e["content_block"]["type"] for e in evs if e["type"] == "content_block_start"] + self.assertEqual(order, ["thinking", "tool_use", "thinking", "text"]) + tool = [e["delta"]["partial_json"] for e in evs if e["type"] == "content_block_delta" + and e["delta"]["type"] == "input_json_delta"] + self.assertEqual(json.loads("".join(tool)), {"path": "file.txt"}) + finally: + httpd.shutdown() + httpd.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_responses.py b/serve/test_responses.py index 2bae9869..b146852d 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -264,6 +264,22 @@ class OverHttp(Server): code, r = self.post({"model": "m", "input": "hi"}, headers={"Origin": "https://evil.example.com"}) self.assertEqual(code, 403) + def test_a_foreign_page_cannot_name_a_file_as_an_image(self): + """#553: the chat routes refuse a file image from another origin; so does /v1/responses.""" + def body(src): + return {"model": "m", "input": [{"role": "user", "content": [ + {"type": "input_text", "text": "what is it?"}, {"type": "input_image", "image_url": src}]}]} + self.svc.cors_origins = ["*"] # a page cors_origins lets in may send JSON, not name a file + for src in (r"\\host\share\x.png", "/etc/passwd", "file:///C:/x.png"): + with self.subTest(src=src): + code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"}) + self.assertEqual(code, 400, r) + self.assertIn("another origin", r["error"]["message"]) + # data: and http(s) are the page's own to send: not refused by this check (no vision here, so a 400 of another kind) + for src in ("data:image/png;base64,iVBORw0KGgo=", "https://example.com/x.png"): + code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"}) + self.assertNotIn("another origin", json.dumps(r)) + def test_json_schema_text_format(self): self.engine.scripts = [self.tok.encode("\n\n{\"n\": 3}<|im_end|>", parse_special=True)] self.engine.script = self.engine.scripts[0] @@ -275,7 +291,12 @@ class OverHttp(Server): code, events = self.post({"model": "m", "input": "a number", "text": {"format": fmt}, "stream": True}) self.assertEqual([e["delta"] for e in events if e["type"] == "response.output_text.delta"], ["{\"n\":3}"]) self.assertEqual(events[-1]["type"], "response.completed") - # an answer that fails the schema + # an answer that fails the schema - only jsonschema can tell: it is optional (serve/structured.py), and + # without it a json_schema answer is checked to be one JSON object, which {"n": 3} is + try: + import jsonschema # noqa: F401 + except ImportError: + return bad = {**fmt, "schema": {**fmt["schema"], "properties": {"n": {"type": "string"}}}} code, r = self.post({"model": "m", "input": "a number", "text": {"format": bad}}) self.assertEqual((code, r["error"]["code"]), (502, "structured_output_failed")) @@ -332,6 +353,22 @@ class ToolRoundTrip(Server): self.assertIn("\nbefore\n", second_prompt) self.assertEqual(r["output"][-1]["content"][0]["text"], "The file says before.") + def test_namespace_call_written_with_double_underscore(self): + # Qwen writes Codex's MCP tools in their flat `mcp__server__tool` form; Codex only + # runs the call when it comes back with its namespace. + self.engine.scripts = [self.tok.encode( + "\n\n\n\n\nstrata\n" + "\n\n<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + tools = [{"type": "namespace", "name": "mcp__websearch", "description": "Search.", "tools": [ + {"type": "function", "name": "web_search", + "parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}]}] + code, r = self.post({"model": "m", "input": "go", "tools": tools}) + self.assertEqual(code, 200, r) + call, = r["output"] + self.assertEqual((call["namespace"], call["name"], json.loads(call["arguments"])), + ("mcp__websearch", "web_search", {"query": "strata"})) + def test_namespace_and_custom_calls_come_back_under_their_own_names(self): self.engine.scripts = [self.tok.encode( "\n\n\n\n\nhi\n\n" diff --git a/serve/test_server.py b/serve/test_server.py index 0ffe2f6c..4130ede1 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -8,6 +8,7 @@ import contextlib import io import json import os +import socket import sys import tempfile import threading @@ -20,9 +21,9 @@ from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 -from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402 - engine_args, layer_split_value, prompt_tokens_seen, request_timings, serve, - start_failure_hint) +from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, PP_DONE_TAIL, Service, # noqa: E402 + StrataEngine, engine_args, layer_split_value, prompt_progress, prompt_tokens_seen, + request_timings, serve, start_failure_hint) from types import SimpleNamespace # noqa: E402 ROOT = Path(__file__).resolve().parents[1] @@ -214,6 +215,84 @@ class FitMaxTokens(unittest.TestCase): self.assertIn("no room to answer", b["error"]["message"]) +class VisionTempFiles(unittest.TestCase): + """A request's combined image file (req-*.sve, ~10 MB a picture) goes with the request: one refused after prepare() + wrote it (the engine starting, no room) or whose answer never started left it in the vision directory for good.""" + + MSGS = [{"role": "user", "content": [{"type": "text", "text": "what is it?"}, + {"type": "image", "source": "x.png"}]}] + + @staticmethod + def leftovers(d): + return sorted(p.name for p in Path(d).glob("req-*.sve")) + + def test_a_refused_request_writes_none(self): + from serve.server import EngineStarting + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + engine = MockEngine(tok, "ok", max_context=0) + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=ImageMarkers.FakeVision(d)) + with self.assertRaises(EngineStarting): + svc.prepare(self.MSGS, None, {}, 16) + engine.max_context = 64 # the prompt alone fills it + with self.assertRaisesRegex(ValueError, "no room to answer"): + svc.prepare(self.MSGS, None, {}) + engine.max_context = CTX + with self.assertRaisesRegex(ValueError, "exceeds the context"): + svc.prepare(self.MSGS, None, {}, CTX) + self.assertEqual(self.leftovers(d), []) + svc.prepare(self.MSGS, None, {}, 16) # one that fits has it + self.assertEqual(len(self.leftovers(d)), 1) + svc.drop_embeddings() # ... until the request is done + self.assertEqual(self.leftovers(d), []) + + def test_over_http(self): + import serve.server as server + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + engine = MockEngine(tok, "\n\nok", max_context=0) + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=ImageMarkers.FakeVision(d)) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + + def post(path): + image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}} \ + if path.endswith("completions") else \ + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}} + body = {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": [ + {"type": "text", "text": "what is it?"}, image]}]} + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status + except urllib.error.HTTPError as e: + with e: + return e.code + + try: + paths = ("/v1/chat/completions", "/v1/messages") + for path in paths: + self.assertEqual(post(path), 503) # the engine is starting (#344); clients retry + engine.max_context = 64 + for path in paths: + self.assertEqual(post(path), 400) # no room to answer + engine.max_context = CTX + # the client gone after prepare(), before the answer started + with mock.patch.object(server, "_debug_req", side_effect=ConnectionResetError("the client is gone")): + for path in paths: + with self.assertRaises(OSError): + post(path) + for path in paths: + self.assertEqual(post(path), 200) + self.assertEqual(self.leftovers(d), []) + finally: + httpd.shutdown() + httpd.server_close() + + class ImageMarkers(unittest.TestCase): """#150: the text "<|image_pad|>" inside a message is text, not an image's place.""" @@ -242,6 +321,137 @@ class ImageMarkers(unittest.TestCase): self.assertIn("<|image_pad|> marks" if "docs" in text else "plain", tok.decode(ids)) svc.embeddings.path.unlink(missing_ok=True) + def test_anthropic_tool_result_image(self): + """Claude Code's Read of a picture returns it inside a tool_result: it reaches the encoder, in place.""" + import tempfile + from serve.frontend import anthropic_to_messages + tok = ByteTokenizer() + img = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}} + call = {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": "a.png"}}]} + with tempfile.TemporaryDirectory() as d: + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.FakeVision(d)) + pad = tok.encode("<|image_pad|>", parse_special=True)[0] + for result, extra, n in (([img], [], 3), ([{"type": "text", "text": "a.png"}, img], [], 3), + ("plain text", [img, {"type": "text", "text": "and this one"}], 3), + ([img], [img], 6)): + with self.subTest(result=str(result)[:30], extra=len(extra)): + msgs = [{"role": "user", "content": "look at a.png"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": result}] + extra}] + m, _, _ = anthropic_to_messages({"messages": msgs}) + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual(ids.count(pad), n) + prompt = tok.decode(ids) + inside = prompt.split("", 1)[1].split("", 1)[0] + self.assertEqual("<|vision_start|>" in inside, not isinstance(result, str)) + self.assertEqual("<|vision_start|>" in prompt.split("", 1)[1], bool(extra)) + svc.embeddings.path.unlink(missing_ok=True) + # a tool's picture the server cannot read is a note, not a 400 (the client resends it every turn); the user's + # own picture still fails + class Refusing(self.FakeVision): + def encode(self, source): + if "bad" in str(source): + raise ValueError("this image format needs Pillow") + return super().encode(source) + good = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}} + bad = {"type": "image", "source": {"type": "base64", "media_type": "image/webp", "data": "badd"}} + tool_msgs = [{"role": "user", "content": "look"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [bad, good]}]}] + with tempfile.TemporaryDirectory() as d: + for vision, n, note in ((None, 0, "[image omitted: this server has no image encoder]"), + (Refusing(d), 3, "[image omitted: this image format needs Pillow]")): + with self.subTest(vision=vision is not None): + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=vision) + m, _, _ = anthropic_to_messages({"messages": tool_msgs}) + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual(ids.count(pad), n) + self.assertIn(note, tok.decode(ids)) + if svc.embeddings.path: + svc.embeddings.path.unlink(missing_ok=True) + # a tool's picture at a URL is downloaded once (the check and the prompt share the bytes), and one that + # cannot be fetched is a note too + import serve.server as server + url = {"type": "image", "source": {"type": "url", "url": "http://x/ok.png"}} + url_msgs = [{"role": "user", "content": "look"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [url]}]}] + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.FakeVision(d)) + m, _, _ = anthropic_to_messages({"messages": url_msgs}) + with mock.patch.object(server.Vision, "download", return_value=b"the picture") as dl: + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual((dl.call_count, ids.count(pad)), (1, 3)) + svc.embeddings.path.unlink(missing_ok=True) + m, _, _ = anthropic_to_messages({"messages": url_msgs}) + with mock.patch.object(server.Vision, "download", side_effect=ValueError("the image URL could not be read")): + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual(ids.count(pad), 0) + self.assertIn("[image omitted: the image URL could not be read]", tok.decode(ids)) + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + m, _, _ = anthropic_to_messages({"messages": [{"role": "user", "content": [good]}]}) + with self.assertRaises(ValueError): + svc.prepare(m, None, {}) + # a text-only tool result renders exactly as before: one string + msgs = [{"role": "user", "content": "q"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "r"}]}]}] + self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r"}) + + + def test_the_whole_marker_in_text_before_images(self): + # Text quoting the template's marker (an agent reading chat_template.jinja) took the first picture's rows, the + # later pictures moved up one and the last real marker became text - every count still matched. + tok = ByteTokenizer() + start, pad, end = (tok.encode(s, parse_special=True)[0] + for s in ("<|vision_start|>", "<|image_pad|>", "<|vision_end|>")) + quoted = "the template writes <|vision_start|><|image_pad|><|vision_end|> per picture" + + class TwoPictures(self.FakeVision): + def encode(self, source): + return self.rows, {"a.png": 2, "b.png": 5}[source] + + def holds(ids, part): + return any(ids[i:i + len(part)] == part for i in range(len(ids) - len(part) + 1)) + + with tempfile.TemporaryDirectory() as d: + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=TwoPictures(d)) + pictures = [{"type": "image", "source": "a.png"}, {"type": "text", "text": "and"}, + {"type": "image", "source": "b.png"}] + tools = [{"name": "read", "description": quoted, "parameters": {}}] + cases = {"text part": ([{"role": "user", "content": [{"type": "text", "text": quoted}, *pictures]}], None), + "earlier turns and tools": ([{"role": "user", "content": "read it"}, + {"role": "assistant", "content": quoted, "reasoning_content": quoted, + "tool_calls": [{"function": {"name": "read", + "arguments": {"text": quoted}}}]}, + {"role": "tool", "content": quoted}, + {"role": "user", "content": pictures}], tools)} + for name, (msgs, tools) in cases.items(): + with self.subTest(case=name): + ids, _, _ = svc.prepare(msgs, tools, {}) + starts = [j for j, t in enumerate(ids) if t == start] + self.assertEqual(len(starts), 2) # the pictures' markers, nothing else + for j, rows in zip(starts, (2, 5)): # each followed by its own picture's rows + self.assertEqual(ids[j + 1:j + 2 + rows], [pad] * rows + [end]) + self.assertEqual((ids.count(pad), ids.count(end)), (7, 2)) + self.assertTrue(holds(ids, tok.encode(quoted))) # the text kept its own tokens + # no picture: the quoted markers are text too + ids, _, _ = svc.prepare([{"role": "user", "content": quoted}], None, {}) + self.assertEqual([t for t in ids if t in (start, pad, end)], []) + # markers cut apart across three text parts are no picture's: refused, not a silent shift + cut = [{"type": "text", "text": "<|vision_sta"}, {"type": "text", "text": "rt|><|image_pa"}, + {"type": "text", "text": "d|>"}, *pictures] + with self.assertRaisesRegex(ValueError, "do not match"): + svc.prepare([{"role": "user", "content": cut}], None, {}) + # a prompt without the marker strings has exactly the ids it had (other special tokens as well) + old = lambda m, t=None: tok.encode(svc.template.render(m, tools=t), parse_special=True) # noqa: E731 + for msgs, tools in (([{"role": "user", "content": "plain <|im_end|> <|endoftext|>"}], None), + ([{"role": "system", "content": "s"}, {"role": "user", "content": pictures}], None), + ([{"role": "user", "content": "x"}, {"role": "assistant", "content": "", + "tool_calls": [{"function": {"name": "f", "arguments": {"a": "<|image"}}}]}], + [{"name": "f", "description": "<|vision_", "parameters": {}}])): + with self.subTest(msgs=msgs): + self.assertEqual(svc.encode_prompt(msgs, tools, {}), old(msgs, tools)) + class ThinkTokenizer(ByteTokenizer): """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special, @@ -482,6 +692,41 @@ class ToolCallTerminators(unittest.TestCase): self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT}) +class ToolCallTagInProse(unittest.TestCase): + """A reply that names the `` tag in its prose before the real call keeps the tag as content and still + returns the call; it was a "malformed tool call" ValueError that ended the request. A call is the tag followed + (after whitespace) by `\n\n\na.md\n\n\nhi\n" + "\n\n") + + def parse(self, text, stream_tools, step): + from serve.frontend import OutputParser + p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + evs += p.finish() + return ([e.call.arguments for e in evs if e.kind == "tool_call"], + "".join(e.text for e in evs if e.kind == "content")) + + def test_named_tag_is_content(self): + call = {"path": "a.md", "content": "hi"} + for prose in ("I will use the `` format now.", "Next I emit a block.", + "Two tags and x, then the call."): + for stream_tools in (False, True): + for step in (1, 7, 10_000): + with self.subTest(prose=prose, stream_tools=stream_tools, step=step): + calls, content = self.parse(f"\n\n{prose}\n{self.CALL}", stream_tools, step) + self.assertEqual((calls, content), ([call], prose)) + + def test_tag_alone_at_the_end_is_content(self): + for step in (1, 7, 10_000): + with self.subTest(step=step): + self.assertEqual(self.parse("\n\nThe format starts with ", False, step), + ([], "The format starts with ")) + + class UnfinishedToolCall(unittest.TestCase): """#211: a call the output ends inside is not reported as a whole one - its streamed JSON is not closed and the finish reason is not "tool_calls" / "tool_use" - so a client can tell it from a call to run.""" @@ -766,6 +1011,42 @@ class ClientShapes(unittest.TestCase): with self.subTest(calls=calls), self.assertRaisesRegex(ValueError, "tool_calls must be a list of objects"): openai_to_messages({"messages": [{"role": "assistant", "content": "", "tool_calls": calls}]}) + def test_tool_call_malformed_arguments_fallback(self): + from serve.frontend import openai_to_messages + bad_call = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{malformed_json"}}] + msgs, tools, kwargs = openai_to_messages({"messages": [{"role": "user", "content": "u"}, + {"role": "assistant", "content": "", "tool_calls": bad_call}]}) + self.assertEqual(msgs[1]["tool_calls"], [{"function": {"name": "f", "arguments": {"arguments": "{malformed_json"}}}]) + tpl = ChatTemplate(ROOT / "serve/chat_template.jinja") + rendered = tpl.render(msgs, tools=tools, **kwargs) + self.assertIn("", rendered) + self.assertIn("\n{malformed_json", rendered) + + +class ToolArguments(unittest.TestCase): + """#510: one helper for both frontends; a history whose arguments are not a JSON object is kept, not a 500.""" + + def test_helper(self): + from serve.frontend import tool_arguments + for raw, want in ((None, {}), ("", {}), (" ", {}), ({"a": 1}, {"a": 1}), ('{"a": 1}', {"a": 1}), + ("{cut", {"arguments": "{cut"}), ("[1, 2]", {"arguments": "[1, 2]"}), + ("5", {"arguments": "5"}), ([1, 2], {"arguments": "[1, 2]"}), (7, {"arguments": "7"})): + with self.subTest(raw=raw): + self.assertEqual(tool_arguments(raw), want) + + def test_both_frontends_render_it(self): + from serve.frontend import anthropic_to_messages, openai_to_messages + for bad in ("{cut", "[1]", "3"): + with self.subTest(bad=bad): + m = openai_to_messages({"messages": [{"role": "user", "content": "u"}, {"role": "assistant", "content": "", + "tool_calls": [{"id": "c", "type": "function", "function": {"name": "f", "arguments": bad}}]}]})[0] + self.assertEqual(m[1]["tool_calls"][0]["function"]["arguments"], {"arguments": bad}) + for bad in ([1], 3, "{cut"): + with self.subTest(anthropic=bad): + m = anthropic_to_messages({"messages": [{"role": "user", "content": "u"}, {"role": "assistant", "content": [ + {"type": "tool_use", "id": "t", "name": "f", "input": bad}]}]})[0] + self.assertIn("arguments", m[1]["tool_calls"][0]["function"]["arguments"]) + class SamplingKeys(unittest.TestCase): """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used @@ -789,6 +1070,11 @@ class SamplingKeys(unittest.TestCase): bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2}) self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")]) + def test_checkpoint_key(self): + self.assertIn("ckpt=0", self.keys(temperature=0, strata_checkpoint=False)) + for absent in ({}, {"strata_checkpoint": True}, {"strata_checkpoint": 0}, {"cache_prompt": False}): + self.assertNotIn("ckpt=0", self.keys(**absent), absent) + def test_penalty_window(self): self.assertIn("penalty_last_n=64", self.keys(presence_penalty=1.5)) self.assertIn("penalty_last_n=4096", self.keys(repetition_penalty=1.1, penalty_last_n=4096)) @@ -1461,6 +1747,79 @@ class LiveRate(unittest.TestCase): httpd.server_close() +class PromptProgress(unittest.TestCase): + """`return_progress: true` puts the engine's PP line on the stream as llama.cpp's `prompt_progress`, so a client + written for llama.cpp shows prefill progress from either server. Off by default, as it is in llama.cpp.""" + + TOKENS, TOTAL = 40, 25000 + + class Reading(MockEngine): + """A prompt read in three chunks and then answered: the engine's PP lines reach the HTTP layer as pings.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.progress, self.progress_ms, self.reused, self.total = None, 0.0, 0, 0 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + for read, ms in ((8192, 2200.0), (16384, 4400.0), (24576, 6600.0)): + self.progress, self.progress_ms = (read, self.total), ms + yield None + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + def setUp(self): + tok = ByteTokenizer() + self.engine = self.Reading(tok, "y" * self.TOKENS, max_context=CTX) + self.engine.total = self.TOTAL + self.engine.reused = 4096 # RESUME: the conversation checkpoint's reused prefix + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def stream(self, **req): + body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "stream": True, + "messages": [{"role": "user", "content": "hi"}], **req}).encode() + with urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}), + timeout=30) as r: + return r.read().decode() + + def test_a_client_that_asks_gets_one_progress_per_chunk(self): + steps = [json.loads(line[6:]) for line in self.stream(return_progress=True).splitlines() + if line.startswith("data: ") and "prompt_progress" in line] + self.assertEqual([s["prompt_progress"] for s in steps], + [{"total": self.TOTAL, "cache": 4096, "processed": 8192, "time_ms": 2200}, + {"total": self.TOTAL, "cache": 4096, "processed": 16384, "time_ms": 4400}, + {"total": self.TOTAL, "cache": 4096, "processed": 24576, "time_ms": 6600}], + "llama.cpp's four fields, time_ms elapsed since the read started") + self.assertTrue(all(s["choices"][0]["delta"] == {} for s in steps), "a progress chunk carries no content") + + def test_a_client_that_does_not_ask_gets_nothing(self): + text = self.stream() + self.assertNotIn("prompt_progress", text) + self.assertIn(": keep-alive", text, "the PP line still keeps the connection alive as it used to") + + def test_the_line_that_says_the_prompt_is_read_is_dropped(self): + # the batched path leaves up to --short-read tokens to the verify windows, so its last PP stops short of the + # prompt. A prompt under one --prefill chunk sends only that line, and it would show a bar already full. + for short in (PP_DONE_TAIL, PP_DONE_TAIL - 1, 1): + self.engine.progress, self.engine.progress_ms = (self.TOTAL - short, self.TOTAL), 6600.0 + self.assertIsNone(prompt_progress(self.svc), f"a PP {short} token(s) short of the end says it is read") + self.engine.progress = (self.TOTAL - PP_DONE_TAIL - 1, self.TOTAL) + self.assertEqual(prompt_progress(self.svc)["processed"], self.TOTAL - PP_DONE_TAIL - 1) + + def test_nothing_before_the_first_chunk(self): + self.engine.progress = None + self.assertIsNone(prompt_progress(self.svc), "no PP line yet: there is no rate to show") + self.engine.progress = (8192, self.TOTAL) + self.engine.reused = 0 # an engine too old to print RESUME never sets it + self.assertEqual(prompt_progress(self.svc)["cache"], 0, + "an engine too old to print RESUME counts the reused prefix as work") + + class SharedSettings(unittest.TestCase): """The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults.""" @@ -2098,6 +2457,13 @@ class ThinkingBudget(unittest.TestCase): self.assertEqual(b["usage"]["completion_tokens"], 20 + len(extra) + len(ThinkingEngine.ANSWER) + 1) self.assertEqual(b["usage"]["prompt_tokens"], len(first)) + def test_a_stop_string_is_found_in_the_answer_after_the_wrap_up(self): + """#454: the continuation after the thinking budget is cut at a stop string too.""" + code, b = self.openai(reasoning_budget_tokens=20, stop=["answer is"]) + self.assertEqual(code, 200, b) + msg = b["choices"][0]["message"] + self.assertEqual((msg["content"], b["choices"][0]["finish_reason"]), ("The ", "stop")) + def test_anthropic_stream(self): from serve.server import REASONING_WRAP_UP code, raw = self.post("/v1/messages", {"model": "m", "max_tokens": 400, "stream": True, @@ -2160,6 +2526,183 @@ class ThinkingBudget(unittest.TestCase): self.assertEqual(self.engine.prompts, []) +class CallingEngine(MockEngine): + """Thinks, then answers in text - unless its prompt already opens a call (a forced tool_choice): then it finishes + that call. Records every prompt it is given.""" + THOUGHT = "I could look this up. " * 8 # 176 reasoning tokens (one per byte) + ANSWER = "The answer is 4." + ARGS = "\n2+2\n\n\n" + + def __init__(self, tok): + super().__init__(tok, "x", max_context=CTX) + self.prompts = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.prompts.append(list(ids)) + prompt = self.tok.decode(ids) + if prompt.endswith("\n"): + text = self.ARGS + elif prompt.endswith("\n\n"): + text = self.ANSWER + else: + text = self.THOUGHT + "\n\n" + self.ANSWER + for t in (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]: + if cancel.is_set(): + return + yield t + + +class ForcedToolChoice(unittest.TestCase): + """tool_choice "required" or a named function: the server writes the call's opening - after the thinking, or at + the end of the prompt without thinking - so the model can only go on with a call.""" + TOOLS = [{"type": "function", "function": {"name": "search", "description": "search the web", + "parameters": {"type": "object", + "properties": {"q": {"type": "string"}}}}}, + {"type": "function", "function": {"name": "done", "parameters": {"type": "object", "properties": {}}}}] + NAMED = {"type": "function", "function": {"name": "search"}} + NO_THINKING = {"chat_template_kwargs": {"enable_thinking": False}} + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = CallingEngine(self.tok) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def openai(self, **extra): + body = {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], "max_tokens": 400, + "tools": self.TOOLS, **extra} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + return r.status, (json.loads(raw) if not body.get("stream") else raw) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def call_of(self, code, b, stream): + """-> (finish_reason, [(name, arguments)], reasoning) of a whole or a streamed reply.""" + self.assertEqual(code, 200, b) + if not stream: + choice = b["choices"][0] + calls = [(c["function"]["name"], json.loads(c["function"]["arguments"])) + for c in choice["message"].get("tool_calls") or []] + return choice["finish_reason"], calls, choice["message"].get("reasoning_content") or "" + chunks = [json.loads(line[6:]) for line in b.splitlines() if line.startswith("data: {")] + names, args, reasoning, finish = {}, {}, "", None + for c in chunks: + d = c["choices"][0]["delta"] + reasoning += d.get("reasoning_content") or "" + for tc in d.get("tool_calls") or []: + names.setdefault(tc["index"], tc["function"].get("name")) + args[tc["index"]] = args.get(tc["index"], "") + tc["function"].get("arguments", "") + finish = c["choices"][0]["finish_reason"] or finish + return finish, [(names[i], json.loads(args[i])) for i in sorted(names)], reasoning + + def test_required_and_named_after_the_thinking(self): + for choice in ("required", self.NAMED): + for stream in (False, True): + with self.subTest(choice=choice, stream=stream): + self.engine.prompts = [] + code, b = self.openai(tool_choice=choice, stream=stream) + finish, calls, reasoning = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})])) + self.assertEqual(reasoning, CallingEngine.THOUGHT) + first, second = self.engine.prompts + opening = "\n\n" if choice == self.NAMED else "") + # where the thinking ended, after the blank line the template puts before a call + self.assertEqual(second, first + self.tok.encode(CallingEngine.THOUGHT + "\n\n" + opening)) + + def test_without_thinking_the_prompt_ends_with_the_opening(self): + for choice in ("required", self.NAMED): + for stream in (False, True): + with self.subTest(choice=choice, stream=stream): + self.engine.prompts = [] + code, b = self.openai(tool_choice=choice, stream=stream, **self.NO_THINKING) + finish, calls, reasoning = self.call_of(code, b, stream) + self.assertEqual((finish, calls, reasoning), ("tool_calls", [("search", {"q": "2+2"})], "")) + self.assertEqual(len(self.engine.prompts), 1) + opening = "\n\n" if choice == self.NAMED else "") + self.assertTrue(self.tok.decode(self.engine.prompts[0]).endswith("\n\n" + opening)) + + def test_the_budget_wrap_up_opens_the_call(self): + from serve.server import REASONING_WRAP_UP + code, b = self.openai(tool_choice="required", reasoning_budget_tokens=20) + finish, calls, reasoning = self.call_of(code, b, False) + self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})])) + self.assertEqual(reasoning, CallingEngine.THOUGHT[:20] + REASONING_WRAP_UP.split("")[0]) + first, second = self.engine.prompts + extra = self.tok.encode(REASONING_WRAP_UP + "\n\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=vision) + httpd = serve(svc, port=0) + host = f"127.0.0.1:{httpd.server_address[1]}" + + def post(path, src, headers): + image = {"type": "image_url", "image_url": {"url": src}} if path.endswith("completions") else \ + {"type": "image", "source": {"type": "url", "url": src}} + body = {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": [ + {"type": "text", "text": "what is it?"}, image]}]} + req = urllib.request.Request(f"http://{host}{path}", data=json.dumps(body).encode(), headers=headers) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + try: + f = str(Path(d) / "secret.png") + # a page on any site, no api_key (the default): text/plain needs no CORS preflight - 0.1.38 refuses + # such a page outright (403) + page = {"Content-Type": "text/plain;charset=UTF-8", "Origin": "https://evil.example"} + status, b = post("/v1/chat/completions", f, page) + self.assertEqual(status, 403, b) + # a page cors_origins lets in (here every page) may send JSON, and still cannot name a file + svc.cors_origins = ["*"] + page = {"Content-Type": "application/json", "Origin": "https://evil.example"} + for path in ("/v1/chat/completions", "/v1/messages"): + for src in (f, "file://" + f): + with self.subTest(path=path, src=src): + status, b = post(path, src, page) + self.assertEqual(status, 400, b) + self.assertIn("another origin", b["error"]["message"]) + self.assertEqual(vision.got, []) # nothing was read + svc.trusted_origins = ["https://app.example"] + data = "data:image/png;base64,iVBORw0KGgo=" + for src, headers in ((data, page), # the page's own picture + (f, {"Content-Type": "application/json"}), # curl, SDKs, agents + (f, {"Content-Type": "application/json", "Origin": "http://" + host}), + (f, {"Content-Type": "application/json", "Origin": "https://app.example"})): + with self.subTest(src=src[:20], headers=headers): + status, b = post("/v1/chat/completions", src, headers) + self.assertEqual(status, 200, b) + self.assertEqual(vision.got, [data, f, f, f]) + finally: + httpd.shutdown() + httpd.server_close() + + +class CountingEngine(MockEngine): + """Counts the tokens the engine was asked for, so a test can see it stopped early.""" + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.yielded = 0 + for t in super().generate(ids, max_new, sampling, cancel, embeddings): + self.yielded += 1 + yield t + + +class StopStrings(unittest.TestCase): + """OpenAI `stop` and Anthropic `stop_sequences`: the answer ends before the first stop string, which is not sent, + and the engine stops there. The byte tokenizer gives one token per byte, so every stop string here is split + across tokens (and across streamed chunks).""" + ANSWER = "alpha END beta STOP gamma" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = CountingEngine(tok, "\n\n" + cls.ANSWER, max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def post(self, api, stream, **extra): + """-> (status, text, finish or stop_reason, stop_sequence, the streamed text pieces)""" + path = "/v1/chat/completions" if api == "openai" else "/v1/messages" + body = {"model": "x", "max_tokens": 200, "stream": stream, "messages": [{"role": "user", "content": "hi"}], + **extra} + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={ + "Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()), None, None, None + if not stream: + b = json.loads(raw) + if api == "openai": + c = b["choices"][0] + return 200, c["message"]["content"] or "", c["finish_reason"], None, None + text = "".join(x.get("text", "") for x in b["content"] if x["type"] == "text") + return 200, text, b["stop_reason"], b["stop_sequence"], None + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + if api == "openai": + pieces = [e["choices"][0]["delta"].get("content") or "" for e in evs] + return 200, "".join(pieces), evs[-1]["choices"][0]["finish_reason"], None, [p for p in pieces if p] + pieces = [e["delta"]["text"] for e in evs if e["type"] == "content_block_delta" + and e["delta"]["type"] == "text_delta"] + delta = [e for e in evs if e["type"] == "message_delta"][0]["delta"] + return 200, "".join(pieces), delta["stop_reason"], delta["stop_sequence"], pieces + + def stop_field(self, api, stops): + return {"stop": stops} if api == "openai" else {"stop_sequences": stops} + + def test_cut_at_the_stop_string(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + code, text, finish, seq, pieces = self.post(api, stream, **self.stop_field(api, ["END"])) + self.assertEqual(code, 200, text) + self.assertEqual(text, "alpha ") + if api == "openai": + self.assertEqual(finish, "stop") + else: + self.assertEqual((finish, seq), ("stop_sequence", "END")) + if stream: + self.assertFalse(any("E" in p for p in pieces), pieces) # no part of it was sent + # the engine stopped at the stop string, it did not run to the end of the answer + self.assertLess(self.engine.yielded, len("\n\n" + self.ANSWER)) + + def test_the_first_of_several(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + _, text, finish, seq, _ = self.post(api, stream, **self.stop_field(api, ["STOP", "beta", "zzz"])) + self.assertEqual(text, "alpha END ") + if api == "anthropic": + self.assertEqual((finish, seq), ("stop_sequence", "beta")) + + def test_openai_takes_a_string(self): + _, text, finish, _, _ = self.post("openai", False, stop="STOP") + self.assertEqual((text, finish), ("alpha END beta ", "stop")) + + def test_a_prefix_that_is_not_a_stop_is_sent(self): + """"ENDX" begins like the answer's "END" but is not in it: the held tail goes out and nothing is lost.""" + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + _, text, finish, seq, _ = self.post(api, stream, **self.stop_field(api, ["ENDX", "gammaZ"])) + self.assertEqual(text, self.ANSWER) + self.assertEqual(finish, "stop" if api == "openai" else "end_turn") + self.assertIsNone(seq) + + def test_no_stop_and_an_empty_list(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + for extra in ({}, self.stop_field(api, []), self.stop_field(api, ["nowhere"])): + with self.subTest(api=api, stream=stream, extra=extra): + _, text, finish, seq, _ = self.post(api, stream, **extra) + self.assertEqual(text, self.ANSWER) + self.assertEqual(finish, "stop" if api == "openai" else "end_turn") + self.assertIsNone(seq) + + def test_bad_values_are_a_400(self): + for api, extra in (("openai", {"stop": ["a", "b", "c", "d", "e"]}), ("openai", {"stop": 5}), + ("anthropic", {"stop_sequences": "END"}), ("anthropic", {"stop_sequences": [1]})): + with self.subTest(api=api, extra=extra): + code, *_ = self.post(api, False, **extra) + self.assertEqual(code, 400) + + def test_matcher_holds_back_only_a_possible_prefix(self): + from serve.server import StopMatcher + m = StopMatcher([""]) + self.assertEqual(m.push("a <"), "a ") # "<" may start "" + self.assertEqual(m.push("b"), " d"), "") + self.assertEqual(m.hit, "") + self.assertEqual(m.push("more"), "") + + +class ConnectionClose(unittest.TestCase): + """The server is HTTP/1.0 and closes the connection after every response. Without saying so, .NET's pooled + HttpClient put its next request on the closing socket and got "response ended prematurely" (2026-10-03).""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def headers(self, stream): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + r.read() + return r.headers + + def test_a_non_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=False).get("Connection"), "close") + + def test_a_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=True).get("Connection"), "close") + + +class AnswerBeforeTheBody(unittest.TestCase): + """An answer sent before the request body was read must still reach a client that sends the body after the headers + (http.client, urllib and requests do): closing the connection on unread bytes sends a reset that eats the answer.""" + + def setUp(self): + tok = ByteTokenizer() + self.engine = UnloadableEngine(tok, "\n\nok", max_context=CTX) + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.port = self.httpd.server_address[1] + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def status(self, method, path, headers=None, body=b'{"x": 1}'): + """The status line of the answer to a request whose body follows the headers after a pause.""" + head = {"Host": f"127.0.0.1:{self.port}", "Content-Type": "application/json", "Content-Length": str(len(body)), + **(headers or {})} + with socket.create_connection(("127.0.0.1", self.port), timeout=10) as s: + s.sendall((f"{method} {path} HTTP/1.1\r\n" + "".join(f"{k}: {v}\r\n" for k, v in head.items()) + + "\r\n").encode()) + time.sleep(0.3) # the server answers (and, unfixed, closes) meanwhile + try: + s.sendall(body) + except OSError: + pass + answer = b"" + while chunk := s.recv(65536): # Windows raises a reset here, where Linux keeps the answer + answer += chunk + time.sleep(0.2) + # Linux shows the reset only as a pending socket error, after the answer and the end of the stream + self.assertEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0, "the connection was reset") + return answer.split(b"\r\n", 1)[0].decode() + + def test_a_wrong_key(self): + self.svc.api_key = "secret" + try: + self.assertEqual(self.status("POST", "/v1/chat/completions"), "HTTP/1.0 401 Unauthorized") + finally: + self.svc.api_key = "" + + def test_a_wrong_key_and_a_body_of_megabytes(self): + """An agent client's conversation, or one screenshot, is several MiB, and a rotated key is when the 401 matters.""" + self.svc.api_key = "secret" + try: + self.assertEqual(self.status("POST", "/v1/chat/completions", body=b'{"x": "' + b"a" * (80 << 20) + b'"}'), + "HTTP/1.0 401 Unauthorized") + finally: + self.svc.api_key = "" + + def test_a_body_that_comes_in_drops_does_not_hold_the_connection(self): + """A client that announces a body and sends it a byte at a time is let go after DRAIN_SECONDS, with its + answer: the time limit is on the whole body, not on each read.""" + self.svc.api_key = "secret" + try: + with mock.patch.object(self.httpd.RequestHandlerClass, "DRAIN_SECONDS", 0.5), \ + socket.create_connection(("127.0.0.1", self.port), timeout=10) as s: + s.sendall((f"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\n" + f"Content-Length: {1 << 20}\r\n\r\n").encode()) + started, answer = time.monotonic(), b"" + s.settimeout(0.2) + while True: + try: + if not (chunk := s.recv(65536)): + break + answer += chunk + except TimeoutError: + s.sendall(b"a") # a byte every 0.2 s keeps each read of the server alive + self.assertEqual(answer.split(b"\r\n", 1)[0], b"HTTP/1.0 401 Unauthorized") + self.assertLess(time.monotonic() - started, 5) + finally: + self.svc.api_key = "" + + def test_load_and_unload(self): + self.assertEqual(self.status("POST", "/unload"), "HTTP/1.0 200 OK") + self.assertEqual(self.status("POST", "/load"), "HTTP/1.0 200 OK") + + def test_not_the_apps_own_page(self): + self.assertEqual(self.status("POST", "/load", {"Origin": "https://example.com"}), "HTTP/1.0 403 Forbidden") + + def test_a_body_a_handler_read_is_not_waited_for(self): + """#594: /config and /load read their body themselves: the close must not wait for the drain's 5 s.""" + for path in ("/config", "/load", "/unload"): + with self.subTest(path=path): + t0 = time.monotonic() + self.status("POST", path) + self.assertLess(time.monotonic() - t0, 1.5) # the status() helper itself pauses 0.5 s + + def test_a_host_the_server_does_not_answer_to(self): + self.assertEqual(self.status("POST", "/v1/chat/completions", {"Host": "rebind.example.com"}), + "HTTP/1.0 403 Forbidden") + + def test_a_method_with_no_handler(self): + self.assertEqual(self.status("PUT", "/v1/chat/completions"), "HTTP/1.0 501 Unsupported method ('PUT')") + + +class PromptProgressBatch(unittest.TestCase): + """#837: under --batch the engine's progress is one global line: prompt_progress() says nothing.""" + + def test_nothing_under_batch(self): + from serve.server import prompt_progress + engine = SimpleNamespace(progress=(512, 4096), progress_ms=900, reused=0, batch=0) + svc = SimpleNamespace(engine=engine) + self.assertEqual(prompt_progress(svc), {"total": 4096, "cache": 0, "processed": 512, "time_ms": 900}) + engine.batch = 2 + self.assertIsNone(prompt_progress(svc)) + + +class VisionArgs(unittest.TestCase): + """#767: vision.min_tokens reaches the encoder as --min-tokens (mtmd's image_min_tokens).""" + + def args_for(self, cfg): + import serve.server as server + seen = [] + + class Proc: + stdout = io.StringIO("READY 4096\n") + stdin = io.StringIO() + + def poll(self): + return None + + def popen(args, **kw): + seen.append(args) + return Proc() + + with mock.patch.object(server.subprocess, "Popen", popen), mock.patch.object(server, "contain"): + server.Vision({"exe": "strata-vision", "mmproj": "m.gguf", "model": "t.gguf", **cfg}) + return seen[0] + + def test_min_tokens_is_passed_only_when_set(self): + base = self.args_for({"max_tokens": 300}) + self.assertNotIn("--min-tokens", base) + self.assertEqual(self.args_for({"max_tokens": 1024, "min_tokens": 768})[-4:], + ["--max-tokens", "1024", "--min-tokens", "768"]) + + if __name__ == "__main__": unittest.main() diff --git a/serve/test_structured.py b/serve/test_structured.py index cc157a76..6b66cf8b 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -103,8 +103,11 @@ class Structured(unittest.TestCase): def test_object_mode_strict_json_and_truncation(self): fmt = {"type": "json_object"} self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) - for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', '```json\n{}\n```'): + for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', 'no json at all', '{"x":'): self.assertEqual(self.chat(script, response_format=fmt)[0], 502) + # #762: the JSON object is taken out of a code fence or the prose around it (the object itself stays strict) + for script in ('```json\n{}\n```', 'Here it is: {"answer":4} - done'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 200, script) self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502) # Plain text callers retain normal streaming, without a JSON validation gate. self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) @@ -154,6 +157,50 @@ class Structured(unittest.TestCase): self.assertEqual(reply["error"]["code"], "structured_output_failed") self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200) + def test_root_unions_of_object_shapes_are_accepted(self): + # A root anyOf of object shapes (sent by apps written against llama.cpp's grammar path) still means + # "one JSON object", so it is accepted; a non-object answer is still refused. + claim = {"type": "object", "additionalProperties": False, "required": ["claim_text"], + "properties": {"claim_text": {"type": "string", "minLength": 1}}} + empty = {"type": "object", "additionalProperties": False, "required": ["outcome"], + "properties": {"outcome": {"type": "string", "enum": ["no_substantive_content"]}}} + schemas = [ + {"anyOf": [claim, empty]}, + {"oneOf": [claim, empty]}, + {"allOf": [claim, {"required": ["claim_text"]}]}, + {"$ref": "#/$defs/claim", "$defs": {"claim": claim}}, + {"anyOf": [{"$ref": "#/$defs/claim"}, {"anyOf": [empty]}], "$defs": {"claim": claim}}, + ] + for schema in schemas: + fmt = {"type": "json_schema", "json_schema": {"name": "union", "strict": True, "schema": schema}} + with self.subTest(schema=schema): + self.assertEqual(self.chat('{"claim_text":"The term is 12 months."}', response_format=fmt)[0], 200) + self.assertEqual(self.chat("[1, 2]", response_format=fmt)[0], 502) + + def test_schemas_that_allow_non_objects_are_still_rejected(self): + obj = {"type": "object"} + schemas = [ + {"type": "array", "items": obj}, + {"type": "string"}, + {"type": ["object", "null"]}, + {"anyOf": [obj, {"type": "string"}]}, + {"anyOf": []}, + {"oneOf": [obj, {"type": "array"}]}, + {"allOf": [{"type": "string"}]}, + {"properties": {"x": {"type": "string"}}}, # no type: any JSON value validates + {"$ref": "#/$defs/a", "$defs": {"a": {"$ref": "#/$defs/a"}}}, # reference cycle + {"$ref": "#/$defs/missing", "$defs": {}}, + {"$ref": "#/$defs/s", "$defs": {"s": {"type": "string"}}}, + ] + with mock.patch.object(self.svc, "load") as load: + for schema in schemas: + fmt = {"type": "json_schema", "json_schema": {"name": "bad", "schema": schema}} + with self.subTest(schema=schema): + code, reply = self.chat(response_format=fmt) + self.assertEqual(code, 400) + self.assertIn("only JSON objects", reply["error"]["message"]) + load.assert_not_called() + def test_the_server_does_not_import_jsonschema_at_start(self): import subprocess import sys diff --git a/setup.py b/setup.py index 1368f940..96864095 100644 --- a/setup.py +++ b/setup.py @@ -4187,6 +4187,9 @@ def main() -> int: else: download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") ok(f"vision encoder: {mmproj}") + if vision == "cpu" and "BF16" in mmproj.name: # a tip only (recommend, never force; #625) + say(" tip: on the CPU a Q8_0 copy of this encoder is a third smaller and about as exact (embedding " + "cosine 0.999 vs BF16); see 'A Q8_0 encoder' in docs/DETAILS.md") # ---- 6. the pack and the MTP draft layer step(6, "preparing the model for Strata") diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index bd388c8a..b5cacb35 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -312,7 +312,7 @@ __device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vb // Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the // Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0, // gopinath87607), which agree with llama.cpp and with each other. -constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2; +constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q4_1 = 2, VDR_Q4_0 = 2, VDR_Q8_0 = 2; __device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u, const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, @@ -452,6 +452,46 @@ __device__ __forceinline__ float vec_dot_q5_0_q8_1(const void* __restrict__ vbq, const float s8 = __high2float(bq8_1->ds); return d5 * (sumi * d8 - (16.0f * VDR_Q5_0 / QI5_0) * s8); } +// Q4_0 (plain llama-quantize Q4_0 files, e.g. bartowski's: gate/up and most down projections): the codes are centred +// (q - 8 as signed bytes) before the dot, the exact integer form ggml-cpu's q4_0 x q8_0 dot uses, rather than +// llama.cpp's CUDA chain (uncentred codes minus 8 x the q8_1 block's float sum `ds.y`). On a real Q4_0 expert +// (2560 x 640) the CUDA chain measured 1.4e-2 relative error against the float product, the centred form 5.3e-3; +// with the CUDA chain native_expert_parity failed its 3e-2 limit on two layers of a Q4_0 Flash-Next file. The +// centring is the same idea as the Q5_1 min term above: the offset is applied to the activations' own int8 codes. +__device__ __forceinline__ int q4_0_centred(const int v) { + const int b = v ^ 0x08080808; // per byte: 0..15 -> (q - 8) as a 4-bit two's complement value + return b | ((b & 0x08080808) * 0x1E); // sign-extend each nibble into its byte (0x08 * 0x1E = 0xF0) +} +__device__ __forceinline__ float vec_dot_q4_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q4_0* bq4 = (const block_q4_0*) vbq + kbx; + int sumi = 0; +#pragma unroll + for (int i = 0; i < VDR_Q4_0; ++i) { + const int v = get_int_b2(bq4->qs, iqs + i); + sumi = ggml_cuda_dp4a(q4_0_centred((v >> 0) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i), sumi); + sumi = ggml_cuda_dp4a(q4_0_centred((v >> 4) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i + QI4_0), sumi); + } + return __half2float(bq4->d) * __low2float(bq8_1->ds) * sumi; +} +// Q4_1 (llama-quantize puts it on a few down projections of its Q4_0 files): the Q5_1 chain above without the fifth +// bit, the same min-term choice (the activations' own int8 codes): sumi * (d4 * d8) + sumu * (m4 * d8). +__device__ __forceinline__ float vec_dot_q4_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q4_1* bq4_1 = (const block_q4_1*) vbq + kbx; + int sumi = 0, sumu = 0; +#pragma unroll + for (int i = 0; i < VDR_Q4_1; ++i) { + const int v = get_int_b4(bq4_1->qs, iqs + i); + const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI4_1); + sumi = ggml_cuda_dp4a((v >> 0) & 0x0F0F0F0F, u0, sumi); + sumi = ggml_cuda_dp4a((v >> 4) & 0x0F0F0F0F, u1, sumi); + sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu)); + } + const float2 dm4 = __half22float2(bq4_1->dm); + const float d8 = __low2float(bq8_1->ds); + return sumi * (dm4.x * d8) + sumu * (dm4.y * d8); +} __device__ __forceinline__ float vec_dot_q5_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx, const int& iqs) { const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx; @@ -517,6 +557,10 @@ template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_ __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<2> { static constexpr int qk = 32, ipb = QI4_0 / VDR_Q4_0, step = VDR_Q4_0; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_0_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<3> { static constexpr int qk = 32, ipb = QI4_1 / VDR_Q4_1, step = VDR_Q4_1; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_1_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0; @@ -524,9 +568,9 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, // The formats of each role, one list each so a type cannot be in one switch and missing from another. Every // entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. -#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(8) -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8) -#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(8) +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) +#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) __device__ __forceinline__ float warp_sum(float v) { #pragma unroll @@ -1608,6 +1652,30 @@ __device__ void dq_q5_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { } } template +__device__ void dq_q4_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q4_0* x = (const block_q4_0*) vx + ibs * (QK_K / QK4_0); + const int ib = tid % 8, il = tid / 8; + const float d = __half2float(x[ib].d); + dst_t* y = yy + 32 * ib; + for (int j = 0; j < 4; ++j) { + const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_0 for value pairs iqs, iqs + 16 + y[iqs] = cvt(((float) (x[ib].qs[iqs] & 0xf) - 8.0f) * d); + y[iqs + 16] = cvt(((float) (x[ib].qs[iqs] >> 4) - 8.0f) * d); + } +} +template +__device__ void dq_q4_1(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q4_1* x = (const block_q4_1*) vx + ibs * (QK_K / QK4_1); + const int ib = tid % 8, il = tid / 8; + const float2 dm = __half22float2(x[ib].dm); + dst_t* y = yy + 32 * ib; + for (int j = 0; j < 4; ++j) { + const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_1 for value pairs iqs, iqs + 16 + y[iqs] = cvt((float) (x[ib].qs[iqs] & 0xf) * dm.x + dm.y); + y[iqs + 16] = cvt((float) (x[ib].qs[iqs] >> 4) * dm.x + dm.y); + } +} +template __device__ void dq_q5_1(const void* vx, int64_t ibs, dst_t* yy, int tid) { const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1); const int ib = tid % 8, il = tid / 8; @@ -1658,6 +1726,8 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 13: dq_q5_k(vx, ibs, y, tid); break; case 7: dq_q5_1(vx, ibs, y, tid); break; case 6: dq_q5_0(vx, ibs, y, tid); break; + case 2: dq_q4_0(vx, ibs, y, tid); break; + case 3: dq_q4_1(vx, ibs, y, tid); break; case 8: dq_q8_0(vx, ibs, y, tid); break; case 30: dq_bf16(vx, ibs, y, tid); break; default: break; @@ -1682,7 +1752,7 @@ __global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const v // the types dq_dispatch dequantizes bool is_iq(int t) { return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || - t == 12 || t == 13 || t == 7 || t == 6 || t == 8; + t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8; } // values per block of the types the grouped expert kernels take (0 = none) int gu_qk(int t) { @@ -2456,6 +2526,8 @@ size_t iq_row_bytes(int t, int64_t n) noexcept { case 13: return (size_t) (n / 256) * sizeof(block_q5_K); case 7: return (size_t) (n / 32) * sizeof(block_q5_1); case 6: return (size_t) (n / 32) * sizeof(block_q5_0); + case 2: return (size_t) (n / 32) * sizeof(block_q4_0); + case 3: return (size_t) (n / 32) * sizeof(block_q4_1); case 8: return (size_t) (n / 32) * sizeof(block_q8_0); case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32) default: return 0; diff --git a/src/kernels/dequant_bf16_test.cpp b/src/kernels/dequant_bf16_test.cpp index 80d3d53e..28a75ba1 100644 --- a/src/kernels/dequant_bf16_test.cpp +++ b/src/kernels/dequant_bf16_test.cpp @@ -25,6 +25,7 @@ bool cpu_block(int type, const uint8_t* b, float* out) { switch (type) { case 2: dequantize_q4_0(b, out); return true; case 6: dequantize_q5_0(b, out); return true; + case 7: dequantize_q5_1(b, out); return true; case 8: dequantize_q8_0(b, out); return true; case 11: dequantize_q3_K(b, out); return true; case 12: dequantize_q4_K(b, out); return true; diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 7292dd96..406213c3 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -11,9 +11,13 @@ #include #include #include +#include #if !defined(_WIN32) #include #endif +#include +#include +#include #include #include @@ -134,12 +138,71 @@ void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) { for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale; } +void bf16_dequant_row(const uint8_t* row, float* out160) { + // bfloat16 IS the top 16 bits of a float32, so widening is exact for every value, normal or not - no rounding, + // no clamp, no scale. Bytes are assembled little-endian explicitly rather than reinterpreted, so this is the + // same on a big-endian host. + for (int j = 0; j < PLE_HEAD_DIM; ++j) { + const uint32_t bits = (uint32_t) row[2 * j] | ((uint32_t) row[2 * j + 1] << 8); + const uint32_t wide = bits << 16; + float v; + std::memcpy(&v, &wide, sizeof v); + out160[j] = v; + } +} + // --------------------------------------------------------------------------------------------------- +// THE FORMAT TABLE (see PleFormatInfo). One entry per table type; the block formats decode 5 blocks of 32. +namespace { +template +void dequant_blocks(const uint8_t* row, float /*scale*/, float* out160) { + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) Block(row + (size_t) b * BlockBytes, out160 + b * 32); +} +void dequant_iq4_nl(const uint8_t* row, float, float* out160) { iq4nl_dequant_row(row, out160); } +void dequant_fp8(const uint8_t* row, float scale, float* out160) { fp8_e4m3_dequant_row(row, scale, out160); } +void dequant_bf16(const uint8_t* row, float, float* out160) { bf16_dequant_row(row, out160); } + +const PleFormatInfo kPleFormats[] = { + {PleFormat::IQ4_NL, "IQ4_NL", "IQ4_NL", PLE_ROW_BYTES, false, dequant_iq4_nl}, + {PleFormat::Q5_0, "Q5_0", "Q5_0", (PLE_HEAD_DIM / 32) * 22, false, dequant_blocks}, + {PleFormat::F8_E4M3, "F8_E4M3", "I8", PLE_ROW_BYTES_FP8, true, dequant_fp8}, + // Ordinary GGUFs ship the table in other types: Unsloth's UD-Q6_K_XL and Swift-1.5 Q4_K_L as Q8_0, a Q5_K_M finetune as Q5_1 + {PleFormat::Q5_1, "Q5_1", "Q5_1", PLE_ROW_BYTES_Q5_1, false, dequant_blocks}, + {PleFormat::Q8_0, "Q8_0", "Q8_0", PLE_ROW_BYTES_Q8_0, false, dequant_blocks}, + // Q4_0 (plain llama-quantize Q4_0 files, #599): 90-byte rows like IQ4_NL (18-byte blocks), a linear 4-bit grid + {PleFormat::Q4_0, "Q4_0", "Q4_0", PLE_ROW_BYTES, false, dequant_blocks}, + // BF16 (#586): the checkpoint's own table at full precision, 320-byte rows; self-describing, so no scale and no + // metadata to trust (tools/ple_fp8_pack.py writes the FP8 form of the same table) + {PleFormat::BF16, "BF16", "BF16", PLE_ROW_BYTES_BF16, false, dequant_bf16}, +}; +constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]); +} // namespace + +const PleFormatInfo* ple_formats() { return kPleFormats; } +int ple_format_count() { return kPleFormatCount; } +const PleFormatInfo& ple_format_info(PleFormat f) { return kPleFormats[(int) f]; } +const PleFormatInfo* ple_format_for_type(const char* gguf_type_name) { + for (const PleFormatInfo& f : kPleFormats) + if (std::strcmp(f.gguf_type, gguf_type_name) == 0) return &f; + return nullptr; +} +std::string ple_format_list() { + std::string out; + for (int i = 0; i < kPleFormatCount; ++i) { + const PleFormatInfo& f = kPleFormats[i]; + if (i > 0) out += i + 1 == kPleFormatCount ? " or " : ", "; + out += std::strcmp(f.gguf_type, "I8") == 0 ? "FP8 (I8)" : f.name; + } + return out; +} + +static_assert(PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES && PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES_FP8, "row buffers too small"); + struct PleTable::Impl { GgufFile* file = nullptr; const uint8_t* data = nullptr; uint64_t n_rows = 0; - bool q5_0 = false; // #296: Q5_0 rows (110 B), the mapped reader only + const PleFormatInfo* fmt = &ple_format_info(PleFormat::IQ4_NL); // the table's format (#296: Q5_0 is one of them) mutable uint64_t bytes_read = 0; // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes // from an unbuffered SSD read into `raw`. @@ -155,15 +218,9 @@ struct PleTable::Impl { strata::ngram::PleReader::Ticket prefetch_tickets[kMaxPrefetch] = {}; uint32_t prefetch_keys[kMaxPrefetch][PLE_N_HEADS] = {}; uint8_t prefetch_raw[kMaxPrefetch][PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; - bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL float scale = 1.0f; // the FP8 table's one scale uint32_t rb = PLE_ROW_BYTES; // bytes per row - void decode(const uint8_t* row, float* out160) const { - if (fp8) fp8_e4m3_dequant_row(row, scale, out160); - else if (q5_0) - for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) strata::dequantize_q5_0(row + (size_t) b * 22, out160 + b * 32); - else iq4nl_dequant_row(row, out160); - } + void decode(const uint8_t* row, float* out160) const { fmt->dequant(row, scale, out160); } }; PleTable::PleTable() : impl_(new Impl) {} @@ -193,12 +250,16 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - // IQ4_NL (ISTA-DASLab's shard 2, the original's own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as - // shipped: I8 bytes marked strata.ple.format = f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) - impl_->fp8 = false; - impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0; - impl_->rb = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; - if (std::strcmp(t->type_name(), "I8") == 0) { + // The table's type is looked up in the format list (ple_formats()): IQ4_NL (ISTA-DASLab's shard 2, the original's + // own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as shipped: I8 bytes marked strata.ple.format = + // f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) + const PleFormatInfo* fmt = ple_format_for_type(t->type_name()); + if (fmt == nullptr) { + err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not " + ple_format_list(); + close(); + return false; + } + if (fmt->needs_scale) { const MetaValue* f = impl_->file->get("strata.ple.format"); const MetaValue* s = impl_->file->get("strata.ple.scale"); if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) { @@ -206,19 +267,14 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - impl_->fp8 = true; impl_->scale = (float) s->num(); - impl_->rb = PLE_ROW_BYTES_FP8; - } else if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { - err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL, Q5_0 or FP8 (I8)"; - close(); - return false; } + impl_->fmt = fmt; + impl_->rb = fmt->row_bytes; // PleReader's row_bytes has been a runtime parameter since the FP8 table (160 B rows) needed it; Q5_0's // 110 B rows go through the exact same generic path (ple_reader_test --selftest covers both 90 and 110 B // rows: straddling, caching, in-flight tickets, keep-alive). This refusal was stale. impl_->n_rows = t->shape[1]; - impl_->data = impl_->file->tensor_data(*t); // THE CHECK THAT MAKES THE OFFSET FALSIFIABLE. The manifest's `shard2_tensor.offset` is 0, but that is // the offset within the GGUF's DATA SECTION: the file's first 192 bytes are a header, and reading at 0 @@ -228,10 +284,18 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // assumed. A wrong data offset would leave a different remainder. // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. + // The size arithmetic is checked before it is used (#865): a header that claims enough rows to wrap the 64-bit + // product, or a data section that starts past the end of the file, must be refused, not compared after wrapping. + if (impl_->n_rows > std::numeric_limits::max() / impl_->rb || + impl_->file->data_start() > impl_->file->file_size()) { + err = "PLE table size overflow or invalid data offset in " + gguf_path; + close(); + return false; + } const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb; const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); const bool alone = impl_->file->tensors().size() == 1; - if (alone ? need != have : t->offset + need > have) { + if (t->offset > have || need > have - t->offset || (alone && (t->offset != 0 || need != have))) { char buf[256]; std::snprintf(buf, sizeof buf, "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " @@ -243,6 +307,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } + impl_->data = impl_->file->tensor_data(*t); // only a table that fits the file is mapped if (io.mode == PleIo::Direct) { // The parse above is the validated source of the offset; the mapping itself is not kept, so no page of // the table can enter this process's working set or the file cache through it. @@ -265,14 +330,30 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1); const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need; madvise((void*) a0, a1 - a0, MADV_WILLNEED); + // Fault the table in with several threads first: mlock (and a single toucher) brings it in one page at a time + // from one thread, ~0.5 GB/s from a cold file - 106 s for a 54 GB Q8_0 table. The pages are then resident + // and mlock only pins them. + { + constexpr uintptr_t kPiece = 64ull << 20; + const uintptr_t pieces = (a1 - a0 + kPiece - 1) / kPiece; + const unsigned threads = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + std::atomic next{0}; + auto touch = [&] { + volatile uint8_t sink = 0; + for (uintptr_t i; (i = next.fetch_add(1)) < pieces;) + for (uintptr_t p = a0 + i * kPiece, e = std::min(a1, p + kPiece); p < e; p += page) + sink = sink + *(const volatile uint8_t*) p; + (void) sink; + }; + std::vector pool; + for (unsigned t = 0; t < threads; ++t) pool.emplace_back(touch); + for (auto& t : pool) t.join(); + } if (mlock((const void*) a0, a1 - a0) == 0) { impl_->locked = true; } else { - std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): touching its pages instead\n", - std::strerror(errno)); - volatile uint8_t sink = 0; - for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p; - (void) sink; + std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): its pages stay faulted in " + "but may be reclaimed\n", std::strerror(errno)); } #endif } @@ -323,13 +404,14 @@ void PleTable::close() { impl_->data = nullptr; impl_->n_rows = 0; impl_->rb = PLE_ROW_BYTES; - impl_->q5_0 = false; - impl_->fp8 = false; + impl_->fmt = &ple_format_info(PleFormat::IQ4_NL); + impl_->scale = 1.0f; + impl_->bytes_read = 0; } bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } bool PleTable::locked() const { return impl_->locked; } -const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } +const char* PleTable::format() const { return impl_->fmt->name; } PleIo PleTable::mode() const { return impl_->mode; } uint64_t PleTable::rows() const { return impl_->n_rows; } uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } diff --git a/src/kernels/ple_q5_parity.cpp b/src/kernels/ple_q5_parity.cpp index cd387a8e..29dc47e9 100644 --- a/src/kernels/ple_q5_parity.cpp +++ b/src/kernels/ple_q5_parity.cpp @@ -1,4 +1,5 @@ -// Real-artifact Q5_0 PLE rows against ggml's reference dequantizer. +// Real-artifact Q5_0 / Q5_1 / Q8_0 PLE rows against ggml's reference dequantizer, through both readers (the mapped +// one and the direct SSD reader). #define NOMINMAX #include "strata/artifact/gguf_reader.hpp" #include "strata/kernels/ngram.hpp" @@ -10,33 +11,28 @@ #include #include -int main(int argc, char** argv) { - if (argc != 2) { - std::fprintf(stderr, "usage: ple_q5_parity \n"); - return 2; - } - strata::GgufFile gguf(argv[1]); - const auto* tensor = gguf.find("per_layer_token_embd.weight"); - if (!tensor || tensor->type != 6 || tensor->shape.size() != 2 || tensor->shape[0] != 160) { - std::fprintf(stderr, "expected Q5_0 PLE [160, N]\n"); - return 2; - } +namespace { + +// Largest absolute difference between the table's rows and ggml's dequantization of the same bytes, single rows +// and one 16-row batch; -1 when the table cannot be opened or read. +double check(const char* path, strata::kernels::PleIo mode, const uint8_t* bytes, size_t row_bytes, + const ggml_type_traits* traits, std::string& format, size_t& n_rows) { strata::kernels::PleIoOptions options; - options.mode = strata::kernels::PleIo::Mmap; + options.mode = mode; strata::kernels::PleTable table; std::string err; - if (!table.open(argv[1], err, options)) { - std::fprintf(stderr, "%s\n", err.c_str()); - return 1; + if (!table.open(path, err, options)) { + std::fprintf(stderr, "open: %s\n", err.c_str()); + return -1.0; } - const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_0); - const uint8_t* bytes = gguf.tensor_data(*tensor); + format = table.format(); + n_rows = (size_t) table.rows(); const uint32_t probes[] = {0, 1, 12345, 20000003, (uint32_t) (table.rows() - 1)}; double max_abs = 0.0; for (uint32_t row : probes) { float got[160], want[160]; table.read_row(row, got); - traits->to_float(bytes + (size_t) row * 110, want, 160); + traits->to_float(bytes + (size_t) row * row_bytes, want, 160); for (int i = 0; i < 160; ++i) max_abs = std::max(max_abs, (double) std::fabs(got[i] - want[i])); } @@ -45,15 +41,46 @@ int main(int argc, char** argv) { float batch[16 * 160]; if (!table.issue(rows) || !table.collect(batch, err)) { std::fprintf(stderr, "collect: %s\n", err.c_str()); - return 1; + return -1.0; } for (int h = 0; h < 16; ++h) { float want[160]; - traits->to_float(bytes + (size_t) rows[h] * 110, want, 160); + traits->to_float(bytes + (size_t) rows[h] * row_bytes, want, 160); for (int i = 0; i < 160; ++i) max_abs = std::max(max_abs, (double) std::fabs(batch[h * 160 + i] - want[i])); } - std::printf("Q5_0 PLE: %zu rows, max_abs %.3e %s\n", (size_t) table.rows(), max_abs, - max_abs <= 1e-6 ? "PASS" : "FAIL"); - return max_abs <= 1e-6 ? 0 : 1; + return max_abs; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: ple_q5_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* tensor = gguf.find("per_layer_token_embd.weight"); + // Q5_0 (#296: OrcaRouter's Q4_K_S), Q5_1 (a Q5_K_M GGUF), Q8_0 (UD-Q6_K_XL, Swift-1.5 Q4_K_L): 5 blocks of + // 32 per row + if (!tensor || (tensor->type != GGML_TYPE_Q5_0 && tensor->type != GGML_TYPE_Q5_1 && tensor->type != GGML_TYPE_Q8_0) || + tensor->shape.size() != 2 || tensor->shape[0] != 160) { + std::fprintf(stderr, "expected a Q5_0, Q5_1 or Q8_0 PLE [160, N]\n"); + return 2; + } + const auto type = (ggml_type) tensor->type; + const size_t row_bytes = type == GGML_TYPE_Q5_0 ? 110 : type == GGML_TYPE_Q5_1 ? 120 : 170; + const auto* traits = ggml_get_type_traits(type); + const uint8_t* bytes = gguf.tensor_data(*tensor); + bool ok = true; + for (auto mode : {strata::kernels::PleIo::Mmap, strata::kernels::PleIo::Direct}) { + std::string format; + size_t n_rows = 0; + const double max_abs = check(argv[1], mode, bytes, row_bytes, traits, format, n_rows); + const bool pass = max_abs >= 0.0 && max_abs <= 1e-6; + std::printf("%s PLE, %s reader: %zu rows, max_abs %.3e %s\n", format.c_str(), + mode == strata::kernels::PleIo::Mmap ? "mapped" : "direct", n_rows, max_abs, pass ? "PASS" : "FAIL"); + ok = ok && pass; + } + return ok ? 0 : 1; } diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index 87270fdc..92084708 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -75,6 +75,170 @@ bool check_rows(ng::PleReader& rd, const std::vector& rows, uint32_t n return true; } +/// THE BF16 TABLE, and the claim it rests on. A bfloat16 is literally the top half of a float32, so widening +/// one is a shift: exact for every value, normal or not, with no rounding to hide behind. These patterns are +/// the ones a lossy path would break on - the subnormals and the NaN/inf encodings a saturating cast to FP8 +/// would collapse - so a table that came back through the FP8 route would not reproduce all of them. +void bf16_widening_is_exact() { + const uint16_t bits[] = {0x0000, 0x8000, 0x3f80, 0xbf80, 0x7f7f, 0xff7f, // 0, -0, 1, -1, max, -max + 0x0001, 0x8001, 0x007f, 0x7f80, 0xff80, // smallest subnormals, +-inf + 0x7fc0, 0x7f81, 0x4049, 0xc249, 0x3c75}; // NaN, signalling NaN, 3.14, -3.14 + for (uint16_t b : bits) { + uint8_t row[2 * k::PLE_HEAD_DIM]; + std::memset(row, 0, sizeof row); + row[0] = (uint8_t) b; // little-endian: the low byte first + row[1] = (uint8_t) (b >> 8); + float out[k::PLE_HEAD_DIM]; + k::bf16_dequant_row(row, out); + uint32_t want = (uint32_t) b << 16, got; + std::memcpy(&got, &out[0], sizeof got); + CHECK(got == want, "bf16 0x%04x widened to 0x%08x, not 0x%08x", b, got, want); + bool tail_zero = true; // one element under test must not have shifted the rest + for (int j = 1; j < k::PLE_HEAD_DIM; ++j) tail_zero = tail_zero && out[j] == 0.0f; + CHECK(tail_zero, "bf16 0x%04x: the rest of the row is not zero", b); + } +} + +/// EVERY FORMAT OF THE TABLE, END TO END (table-driven: one entry in `k::ple_formats()` is one run here). A minimal +/// PLE-only GGUF holds `rows` rows of that format's row size, each filled with bytes that encode the row, and both I/O +/// modes must return exactly what the format's own dequantizer makes of those bytes - so the row width, the offset +/// and the type lookup all have to be right for every format, not only for IQ4_NL. +uint32_t gguf_type_id(const char* name) { + static const struct { const char* name; uint32_t id; } ids[] = { + {"IQ4_NL", 20}, {"Q4_0", 2}, {"Q4_1", 3}, {"Q5_0", 6}, {"Q5_1", 7}, {"Q8_0", 8}, {"BF16", 30}, {"F8_E4M3", 24}}; + for (const auto& e : ids) + if (std::strcmp(e.name, name) == 0) return e.id; + return 0xFFFFFFFFu; +} + +// `claimed_rows` is the row count the header states; `rows` rows are actually written (equal unless a test lies) +std::string write_format_table(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows, uint64_t claimed_rows = 0) { + const std::string path = dir + "/ple_format_selftest.gguf"; + std::ofstream out(path, std::ios::binary); + if (!out) { std::fprintf(stderr, "cannot write %s\n", path.c_str()); return {}; } + const auto le = [](auto value, int bytes) { + std::string s((size_t) bytes, '\0'); + for (int i = 0; i < bytes; ++i) s[(size_t) i] = (char) ((value >> (8 * i)) & 0xff); + return s; + }; + const auto str = [&](const char* s) { return le((uint64_t) std::strlen(s), 8) + std::string(s); }; + const uint64_t n_kv = f.needs_scale ? 3 : 1; + std::string head = "GGUF" + le(3u, 4) + le(1ull, 8) + le(n_kv, 8); + head += str("general.architecture") + le(8u, 4) + str("strata-ple"); + if (f.needs_scale) { + const float scale = 0.75f; + uint32_t sb; + std::memcpy(&sb, &scale, 4); + head += str("strata.ple.format") + le(8u, 4) + str("f8_e4m3"); + head += str("strata.ple.scale") + le(6u, 4) + le(sb, 4); // 6 = FLOAT32 + } + head += str("per_layer_token_embd.weight") + le(2u, 4); + head += le((uint64_t) k::PLE_HEAD_DIM, 8) + le(claimed_rows != 0 ? claimed_rows : (uint64_t) rows, 8); + head += le(gguf_type_id(f.name), 4) + le(0ull, 8); + while (head.size() % 32) head += '\0'; + out.write(head.data(), (std::streamsize) head.size()); + std::vector r(f.row_bytes); + for (uint32_t i = 0; i < rows; ++i) { + expected_row(i, f.row_bytes, r.data()); + out.write((const char*) r.data(), (std::streamsize) f.row_bytes); + } + out.close(); + return out ? path : std::string(); +} + +void format_round_trip(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows) { + CHECK(gguf_type_id(f.name) != 0xFFFFFFFFu, "%s: no GGUF type id in this test", f.name); + CHECK(f.row_bytes > 0 && f.row_bytes <= (uint32_t) k::PLE_ROW_BYTES_MAX, "%s: row_bytes %u out of range", f.name, f.row_bytes); + const std::string path = write_format_table(dir, f, rows); + if (path.empty()) { CHECK(false, "%s: no table was written", f.name); return; } + std::mt19937 rng(13); + std::vector want(rows); + for (uint32_t i = 0; i < rows; ++i) want[i] = rng() % rows; + want[0] = 0; + want[1] = rows - 1; + for (k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { + const char* name = mode == k::PleIo::Direct ? "direct" : "mmap"; + k::PleTable t; + std::string err; + k::PleIoOptions io; + io.mode = mode; + io.max_inflight = 8; + io.cache_rows = 0; + CHECK(t.open(path, err, io), "%s: open in %s mode: %s", f.name, name, err.c_str()); + if (g_fail) break; + CHECK(std::strcmp(t.format(), f.name) == 0, "%s: format() says \"%s\"", f.name, t.format()); + CHECK(t.rows() == rows, "%s: rows %llu, not %u", f.name, (unsigned long long) t.rows(), rows); + std::vector raw(f.row_bytes); + float got[k::PLE_HEAD_DIM], ref[k::PLE_HEAD_DIM]; + for (uint32_t r : want) { + t.read_row(r, got); + expected_row(r, f.row_bytes, raw.data()); + f.dequant(raw.data(), f.needs_scale ? 0.75f : 1.0f, ref); + if (std::memcmp(got, ref, sizeof got) != 0) { + CHECK(false, "%s: %s: row %u differs from the format's own dequantizer", f.name, name, r); + break; + } + } + // the 16-row path a token takes, one batch + float tok[16 * k::PLE_HEAD_DIM]; + uint32_t rows16[16]; + for (int h = 0; h < 16; ++h) rows16[h] = want[(size_t) h + 2]; + t.gather(rows16, tok); + for (int h = 0; h < 16; ++h) { + expected_row(rows16[h], f.row_bytes, raw.data()); + f.dequant(raw.data(), f.needs_scale ? 0.75f : 1.0f, ref); + CHECK(std::memcmp(tok + (size_t) h * k::PLE_HEAD_DIM, ref, sizeof ref) == 0, "%s: %s: gather head %d differs", f.name, name, h); + } + } + std::filesystem::remove(path); +} + +/// A table whose header does not match the file is refused with a message, never read past its end (#865): one row +/// short, one row long (a single-tensor shard must be filled exactly), and a row count that wraps the 64-bit size. +void bad_sizes_are_refused(const std::string& dir) { + for (int i = 0; i < k::ple_format_count(); ++i) { + const k::PleFormatInfo& f = k::ple_formats()[i]; + struct { const char* what; uint32_t rows; uint64_t claimed; } cases[] = { + {"claims one row more than the file holds", 500, 501}, + {"claims one row less than the file holds", 500, 499}, + {"claims a row count that wraps 2^64", 8, (uint64_t) 0x4000000000000000ull / 3 * 2}, + }; + for (const auto& c : cases) { + const std::string path = write_format_table(dir, f, c.rows, c.claimed); + if (path.empty()) { CHECK(false, "%s: no table was written", f.name); continue; } + for (k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { + k::PleTable t; + std::string err; + k::PleIoOptions io; + io.mode = mode; + io.cache_rows = 0; + CHECK(!t.open(path, err, io), "%s: a table that %s was accepted", f.name, c.what); + CHECK(!err.empty(), "%s: refused without a message (%s)", f.name, c.what); + CHECK(!t.is_open(), "%s: left open after refusing (%s)", f.name, c.what); + } + std::filesystem::remove(path); + } + } +} + +void all_formats_round_trip(const std::string& dir) { + bf16_widening_is_exact(); // BF16's own claim: a shift, exact for every pattern + bad_sizes_are_refused(dir); + CHECK(k::ple_format_count() > 0, "no formats"); + for (int i = 0; i < k::ple_format_count(); ++i) { + const k::PleFormatInfo& f = k::ple_formats()[i]; + CHECK((int) f.id == i, "%s: the table is not in PleFormat order", f.name); + CHECK(k::ple_format_for_type(f.gguf_type) == &f, "%s: type lookup", f.name); + format_round_trip(dir, f, 2000); + } + CHECK(k::ple_format_for_type("Q6_K") == nullptr, "Q6_K must not be a PLE format"); + if (g_fail == 0) { + std::printf("ple formats, both readers vs their dequantizers:"); + for (int i = 0; i < k::ple_format_count(); ++i) std::printf(" %s", k::ple_formats()[i].name); + std::printf(": OK\n"); + } +} + // row_bytes: ng::ROW_BYTES (90, IQ4_NL) is the production default; 110 (#296, OrcaRouter's Q5_0 PLE rows) is // run too, through the exact same generic row_bytes path -- nothing here is IQ4_NL-specific, so a second row // size run here is the correctness evidence for lifting ngram.cpp's "Q5_0 PLE requires --ple-io mmap" refusal. @@ -272,9 +436,12 @@ int main(int argc, char** argv) { bool direct_only = false; bool sync_submit = false; bool self = false; + std::string make_path, make_fmt, ram_path; // --make-table PATH FORMAT (uses --rows), --ram-time PATH for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; if (a == "--selftest") self = true; + else if (a == "--make-table" && i + 2 < argc) { make_path = argv[i + 1]; make_fmt = argv[i + 2]; i += 2; } + else if (a == "--ram-time" && i + 1 < argc) ram_path = argv[++i]; else if (a == "--dir" && i + 1 < argc) dir = argv[++i]; else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i]; else if (a == "--rows" && i + 1 < argc) rows = std::atoi(argv[++i]); @@ -288,10 +455,38 @@ int main(int argc, char** argv) { if (self) { // ng::ROW_BYTES (90, IQ4_NL, production default) and 110 (#296, OrcaRouter's Q5_0 PLE rows) through the // same generic row_bytes path -- see the comment on selftest(). + all_formats_round_trip(dir); // every format of k::ple_formats(), both readers, vs its dequantizer + if (g_fail != 0) return 1; const int r90 = selftest(dir, ng::ROW_BYTES); const int r110 = selftest(dir, 110); return r90 != 0 ? r90 : r110; } + if (!make_path.empty()) { // a big synthetic table, for timing --ple-io ram's fault-in + for (int i = 0; i < k::ple_format_count(); ++i) { + const k::PleFormatInfo& f = k::ple_formats()[i]; + if (make_fmt != f.name) continue; + const std::string tmp = write_format_table(std::filesystem::path(make_path).parent_path().string(), f, (uint32_t) rows); + if (tmp.empty()) return 1; + std::filesystem::rename(tmp, make_path); + std::printf("wrote %s: %s, %d rows, %.2f GiB\n", make_path.c_str(), f.name, rows, + (double) rows * f.row_bytes / (1024.0 * 1024.0 * 1024.0)); + return 0; + } + std::fprintf(stderr, "unknown format %s\n", make_fmt.c_str()); + return 2; + } + if (!ram_path.empty()) { // open mapped and locked (--ple-io ram): the seconds it takes + k::PleTable t; + k::PleIoOptions io; + io.mode = k::PleIo::Mmap; + io.lock = true; + std::string err; + const double t0 = now_us(); + const bool ok = t.open(ram_path, err, io); + std::printf("ram open: %s, format %s, locked %d, %.2f s\n", ok ? "ok" : err.c_str(), ok ? t.format() : "-", ok && t.locked(), + (now_us() - t0) / 1e6); + return ok ? 0 : 1; + } if (!gguf.empty()) return real(gguf, rows, tokens, inflight, direct_first, direct_only, sync_submit); std::fprintf(stderr, "nothing to do\n"); return 2; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9a001015..d37fdecb 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6388,6 +6388,11 @@ int main(int argc, char** argv) { float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; int req_penalty_last_n = 0; int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) + // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary + // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor + // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root + // when that reaches --prompt-cache-root. Absent = checkpointed as before. + int req_ckpt = 1; // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; @@ -6404,6 +6409,7 @@ int main(int argc, char** argv) { const std::string key = tok.substr(0, eq); const float fv = std::strtof(tok.c_str() + eq + 1, nullptr); if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); + else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0; else if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); @@ -6792,7 +6798,7 @@ int main(int argc, char** argv) { pp_from = read_from; pp_reached = read_from; pp_t0 = r0; - pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every; + pp_next_check = reread_to > 0 || !req_ckpt ? INT64_MAX : resume + o.prompt_cache_every; // ckpt=0: none { std::lock_guard lk(part_mu); part_at.clear(); @@ -7119,9 +7125,11 @@ int main(int argc, char** argv) { // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. // (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one // is cheaper to read again than the extra part costs (~0.3 s). + const int64_t last_turn = turn_at; // ckpt=0 drops the split there, the root is still looked for before it + if (!req_ckpt) turn_at = -1; int64_t root_at = -1; if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && (read_from == 0 || resumed_from0)) - for (int64_t i = 1; i < turn_at; ++i) + for (int64_t i = 1; i < last_turn; ++i) if (ids[(size_t) i] == o.turn_token) { if (i >= o.prompt_cache_root) root_at = i; break; @@ -7393,10 +7401,10 @@ int main(int argc, char** argv) { // (the checkpoints taken while reading it are still good) live.swap(consumed); live_imgs = imgs_below(req_imgs, (int64_t) live.size()); - live_ok = o.prompt_cache > 0; + live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830) } static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; - if (state_hash && live_ok) { + if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates) // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and // separately of what lies past them in the last KV page (stale cells, fine unless something reads them) if (cudaDeviceSynchronize() != cudaSuccess) { diff --git a/sycl/include/strata/core/session.hpp b/sycl/include/strata/core/session.hpp index af9cbfc7..3bb6e9d4 100644 --- a/sycl/include/strata/core/session.hpp +++ b/sycl/include/strata/core/session.hpp @@ -18,6 +18,7 @@ #include #include "strata/core/hit_hook.hpp" #include "strata/core/layer.hpp" +#include "strata/kernels/cpu/pool.hpp" #include #include @@ -375,7 +376,7 @@ struct SessionLoopScratch { float* y_miss = nullptr; ///< pinned host staging for the pool's answer, `parts_bytes` long size_t parts_bytes = 0; dpct::event_ptr probe = nullptr; - long long pinned_core = -1; ///< the affinity to restore, or -1 if the host was never pinned + strata::kernels::cpu::ThreadAffinity pinned_core{}; ///< affinity to restore, or invalid if the host was not pinned bool pinned = false; /// Allocates the buffers and pins the host thread. Call ONCE, at session setup. diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 0b1e2f05..9e615bc1 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -41,7 +41,8 @@ MOUNT = Path(os.environ.get("STRATA_SYCL_ROOT") or ROOT.parent) # what strata- # Battlemage / Alchemist PCI device ids -> (name, VRAM GB). lspci's database lags new cards (an Arc Pro B70 reads # "Intel Corporation Device [8086:e223]"), so the sysfs id is the reliable signal and the name table is ours. -INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e221": ("Arc Pro B60", 24.0), "e20b": ("Arc B580", 12.0), +INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e221": ("Arc Pro B60", 24.0), "e211": ("Arc Pro B60", 24.0), + "e20b": ("Arc B580", 12.0), "e20c": ("Arc B570", 10.0), "e212": ("Arc B50", 16.0), "56a0": ("Arc A770", 16.0), "56a1": ("Arc A750", 8.0), "56a2": ("Arc A580", 8.0), "56a5": ("Arc A380", 6.0), "56a6": ("Arc A310", 4.0), "5690": ("Arc A770M", 16.0)} diff --git a/sycl/src/core/native_dense.cpp b/sycl/src/core/native_dense.cpp index 4007db4b..af95caaf 100644 --- a/sycl/src/core/native_dense.cpp +++ b/sycl/src/core/native_dense.cpp @@ -86,7 +86,12 @@ NativeDense::~NativeDense() { bool NativeDense::load(const std::vector &shards, WeightTable &table, std::string &err, - bool include_ple_key) try { + bool include_ple_key, int64_t layer_lo, int64_t layer_hi) try { + auto outside = [&](const std::string &name) { // a blk.. tensor of another stage's layers + if (layer_hi < 0 || name.rfind("blk.", 0) != 0) return false; + const long l = std::strtol(name.c_str() + 4, nullptr, 10); + return l < layer_lo || l >= layer_hi; + }; if (scratch_ || !weights_.empty()) { err = "native dense: already loaded"; return false; } if (shards.empty()) { err = "native dense: at least one GGUF shard is required"; return false; } try { @@ -155,7 +160,7 @@ bool NativeDense::load(const std::vector &shards, } } for (const auto& tensor : gguf.tensors()) { - if (!eligible(tensor, include_ple_key)) continue; + if (!eligible(tensor, include_ple_key) || outside(tensor.name)) continue; if (!in_range(tensor.name) && tensor.name.find("ple") == std::string::npos) continue; if (!seen.insert(tensor.name).second) { err = "native dense: duplicate tensor " + tensor.name; return false; diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cpp index 2c75bde5..e3bc1167 100644 --- a/sycl/src/core/session.cpp +++ b/sycl/src/core/session.cpp @@ -784,7 +784,7 @@ bool SessionLoopScratch::init(size_t parts_bytes_in, std::string &err) try { const std::vector cores = strata::kernels::cpu::physical_cores(false); if (!cores.empty()) { pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]); - pinned = true; + pinned = pinned_core.valid; } return true; } @@ -800,7 +800,7 @@ void SessionLoopScratch::free() { if (pinned) { strata::kernels::cpu::restore_thread_affinity(pinned_core); pinned = false; - pinned_core = -1; + pinned_core = {}; } if (probe != nullptr) { dpct::destroy_event(probe); probe = nullptr; } if (y_miss != nullptr) { @@ -1367,7 +1367,10 @@ bool session_run_token(const ModelGeometry &g, int64_t pos, int32_t pos_base, // A slow ring: flush the submission queue once more, and notice a fault or a finished graph. last_flush = now; ++tg.flushes; - const dpct::err0 q = DPCT_CHECK_ERROR((cs->ext_oneapi_empty())); + // SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration + // (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as + // "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way. + const dpct::err0 q = cs->ext_oneapi_empty() ? 0 : 1; if (q != 1 && *seq < want) { err = "session_run_token: layer " + std::to_string(l) + " never rang (" + diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp index 038f4d43..27aa6fb4 100644 --- a/sycl/src/core/verify.cpp +++ b/sycl/src/core/verify.cpp @@ -1376,8 +1376,10 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool, const auto now = Clock::now(); if (now - last_flush > std::chrono::microseconds(2000)) { last_flush = now; - const dpct::err0 q = - DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())); + // SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration + // (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as + // "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way. + const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1; if (q != 1 && *seq < want) { trace_ev("NEVER-RANG", k, l, (int64_t) q); trace_dump(stderr); diff --git a/sycl/tools/fixups.py b/sycl/tools/fixups.py index b07d6a0e..26d942c9 100644 --- a/sycl/tools/fixups.py +++ b/sycl/tools/fixups.py @@ -53,6 +53,10 @@ for rel in all_sources(): edit(rel, sub(r"__nanosleep\(\d+\);", "/* spin (no __nanosleep on SYCL) */;")) # 7. `__fadd_rn(a, b ? c : d)` lost its parentheses. edit(rel, sub(r"= (\w+) \+ (\w+) \? (\w+\[\w+\]) : 0\.0f;", r"= \1 + (\2 ? \3 : 0.0f);")) + # 8. cudaStreamQuery(s): dpct writes `DPCT_CHECK_ERROR(s->ext_oneapi_empty())`, which is 0 whenever the call does not + # throw, so the ring waits' `q != 1` guard (1 = still running) was always true and any wait over 2 ms "never rang". + edit(rel, sub(r"(const dpct::err0 q =)\s*DPCT_CHECK_ERROR\(\(+(\w+)\)*->ext_oneapi_empty\(\)\)+;", + r"\1 \2->ext_oneapi_empty() ? 0 : 1;")) # 2b. every `(dpct::queue_ptr) stream` cast goes through strata::q_of(), which maps CUDA's null stream to the # default in-order queue instead of dereferencing a null sycl::queue* (include/strata/sycl_queue.hpp). diff --git a/tests/core/dequant_q5_1_test.cpp b/tests/core/dequant_q5_1_test.cpp new file mode 100644 index 00000000..6cd17f76 --- /dev/null +++ b/tests/core/dequant_q5_1_test.cpp @@ -0,0 +1,40 @@ +// dequantize_q5_1 (strata/artifact/dequant.hpp: the PLE table of a Q5_1 GGUF) against ggml's dequantize_row_q5_1, +// on synthetic blocks: random codes, high bits and scales, plus the edge codes 0 and 31 and a negative minimum. +// No model, no GPU. +#include "strata/artifact/dequant.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include +#include + +int main() { + constexpr int kBlocks = 4096; + constexpr int kBlockBytes = 24; + std::mt19937 rng(20261002); + std::uniform_int_distribution byte(0, 255); + std::uniform_real_distribution scale(-0.05f, 0.05f); + std::vector blocks((size_t) kBlocks * kBlockBytes); + for (int b = 0; b < kBlocks; ++b) { + uint8_t* blk = blocks.data() + (size_t) b * kBlockBytes; + const ggml_fp16_t d = ggml_fp32_to_fp16(scale(rng)); + const ggml_fp16_t m = ggml_fp32_to_fp16(b == 1 ? -1.5f : scale(rng) * 20.0f); + std::memcpy(blk, &d, 2); + std::memcpy(blk + 2, &m, 2); + for (int i = 4; i < kBlockBytes; ++i) blk[i] = (uint8_t) byte(rng); + if (b == 0) std::memset(blk + 4, 0x00, 20); // every code 0: the value is m + if (b == 1) std::memset(blk + 4, 0xFF, 20); // every code 31 (all high bits set) + } + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1); + std::vector want((size_t) kBlocks * 32), got((size_t) kBlocks * 32); + traits->to_float(blocks.data(), want.data(), (int64_t) want.size()); + for (int b = 0; b < kBlocks; ++b) strata::dequantize_q5_1(blocks.data() + (size_t) b * kBlockBytes, got.data() + b * 32); + double max_abs = 0.0; + for (size_t i = 0; i < want.size(); ++i) max_abs = std::fmax(max_abs, std::fabs((double) got[i] - want[i])); + const bool ok = max_abs <= 1e-6; + std::printf("Q5_1 dequant: %d blocks, max_abs %.3e %s\n", kBlocks, max_abs, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/tools/test_setup_sycl.py b/tools/test_setup_sycl.py index 2ff02b64..49badcab 100644 --- a/tools/test_setup_sycl.py +++ b/tools/test_setup_sycl.py @@ -71,5 +71,26 @@ class CMakeOption(unittest.TestCase): self.assertIn("add_subdirectory(sycl)", src) +class IntelIds(unittest.TestCase): + """sycl/setup_intel.py names a card by its PCI device id. The Arc Pro B60s measured on 2x B60 (`lspci -nn` 8086:e211, + bmg-g21) must not fall through to "Intel GPU e211 (xe)" with a guessed VRAM size.""" + + @staticmethod + def table(): + import importlib.util + spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod.INTEL_ARC + + def test_b60_e211_is_named_with_its_vram(self): + self.assertEqual(self.table()["e211"], ("Arc Pro B60", 24.0)) + + def test_the_ids_that_were_listed_before_are_kept(self): + t = self.table() + self.assertEqual(t["e223"][0], "Arc Pro B70") + self.assertEqual(t["e221"][0], "Arc Pro B60") + + if __name__ == "__main__": unittest.main() diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index 6be3f44b..99e51f35 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -5,7 +5,7 @@ // rows at the image's pad tokens and gives them their 2-D M-RoPE positions (see --serve GENI in generate.cpp). // // strata-vision --mmproj --model [--gpu] [--threads N] -// [--max-tokens N] [--flash-attn on|off|auto] +// [--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto] // // Resident: prints "READY ", then per stdin line // ENC -> "OK " or "ERR " @@ -51,7 +51,7 @@ bool parse_enc(const std::string& line, std::string& img, std::string& out) { int main(int argc, char** argv) { std::string mmproj, model; bool gpu = false; - int threads = 0, max_tokens = 0; + int threads = 0, max_tokens = 0, min_tokens = 0; llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -64,6 +64,7 @@ int main(int argc, char** argv) { else if (a == "--gpu") gpu = true; else if (a == "--threads") threads = std::atoi(next().c_str()); else if (a == "--max-tokens") max_tokens = std::atoi(next().c_str()); + else if (a == "--min-tokens") min_tokens = std::atoi(next().c_str()); // mtmd image_min_tokens (#767) else if (a == "--flash-attn") { // FA keeps K and V in FP16; off = the attention in FP32 const std::string v = next(); fa = v == "on" ? LLAMA_FLASH_ATTN_TYPE_ENABLED : v == "off" ? LLAMA_FLASH_ATTN_TYPE_DISABLED @@ -73,7 +74,7 @@ int main(int argc, char** argv) { } if (mmproj.empty() || model.empty()) { std::fprintf(stderr, "usage: strata-vision --mmproj --model [--gpu] [--threads N] " - "[--max-tokens N] [--flash-attn on|off|auto]\n"); + "[--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto]\n"); return 2; } // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM, @@ -103,6 +104,7 @@ int main(int argc, char** argv) { if (threads <= 0 && !gpu) threads = std::max(1u, std::thread::hardware_concurrency() / 2); if (threads > 0) cp.n_threads = threads; if (max_tokens > 0) cp.image_max_tokens = max_tokens; + if (min_tokens > 0) cp.image_min_tokens = min_tokens; mtmd_context* ctx = mtmd_init_from_file(mmproj.c_str(), text, cp); if (!ctx || !mtmd_support_vision(ctx)) { std::printf("ERR cannot load the vision encoder %s\n", mmproj.c_str());