Merge branch 'f-140' into f-140-j
This commit is contained in:
commit
0fff115dfd
52 files changed
+3698
-183
No files matched your search
+9
-1
@@ -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)
|
||||
|
||||
@@ -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 <json> --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: `<data root>` is the directory with the models, packs and MTP layer, `<strata checkout>` the Strata source tree.
|
||||
@@ -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: <data root>/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 <data root>/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 <data root>/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=<the toolkit>, 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 <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 2-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 3-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 4-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 5-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 6-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
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
|
||||
@@ -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("<strata checkout>/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("<strata checkout>/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])
|
||||
@@ -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}}
|
||||
@@ -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]
|
||||
```
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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: <data root>/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 <data root>/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 <data root>/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=<the toolkit>, 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 <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 6-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 4-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 4-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 1-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 1-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 2-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 2-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
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 <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 5-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
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 <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 3-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
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
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"engine": "strata",
|
||||
"exe": "<data root>/strata-native.sh",
|
||||
"cwd": "<strata checkout>",
|
||||
"tokenizer": "<data root>/packs/coder-iq1_m/tokenizer",
|
||||
"model_name": "coder-iq1_m",
|
||||
"backend": "sycl",
|
||||
"log": "<data root>/logs/w2/coder2.engine.log",
|
||||
"args": [
|
||||
"--pack",
|
||||
"<data root>/packs/coder-iq1_m",
|
||||
"--native",
|
||||
"<data root>/models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf",
|
||||
"--ple-gguf",
|
||||
"<data root>/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",
|
||||
"<data root>/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"
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
```
|
||||
@@ -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:
|
||||
@@ -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)
|
||||
@@ -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: <data root>/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 <data root>/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 <data root>/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=<the toolkit>, 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 <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 6-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 4-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 4-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 1-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 1-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 3-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 3-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
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 <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 5-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
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 <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
strata verify: captured the 2-token window (upload <FIXME: Placeholder>, sync <FIXME: Placeholder>)
|
||||
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
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"engine": "strata",
|
||||
"exe": "<data root>/strata-native.sh",
|
||||
"cwd": "<strata checkout>",
|
||||
"tokenizer": "<data root>/packs/qwen-iq2_xs/tokenizer",
|
||||
"model_name": "qwen3.8-flash-next-iq2_xs",
|
||||
"backend": "sycl",
|
||||
"log": "<data root>/logs/w2/iq2b.engine.log",
|
||||
"args": [
|
||||
"--pack",
|
||||
"<data root>/packs/qwen-iq2_xs",
|
||||
"--native",
|
||||
"<data root>/models/qwen-iq2_xs/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf",
|
||||
"--ple-gguf",
|
||||
"<data root>/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",
|
||||
"<data root>/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"
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
+59
-8
@@ -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-<model>.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-<model>.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 `</think>`
|
||||
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-<model>.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-<model>.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-<model>.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-<model>.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-<pid>.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.
|
||||
|
||||
+3
-3
@@ -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.
|
||||
|
||||
+21
-2
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+34
-3
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
+151
-16
@@ -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 "</think>" 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 = {"<think>": "\U000F0E01", "</think>": "\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 "<think>" in v or "</think>" 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 <think> / </think> in their text swapped for THINK_TAGS' marks, and
|
||||
"""#537: (messages, tools) with every literal <think> / </think> (#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 <think>...</think> 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 = "</tool_call>"
|
||||
|
||||
|
||||
PARAM_END = "</parameter>"
|
||||
FUNC_START = "<function="
|
||||
FUNC_END = "</function>"
|
||||
|
||||
|
||||
@@ -428,6 +463,50 @@ def call_end(text: str) -> 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<function="
|
||||
if kind == "named" and name in names:
|
||||
return CALL_START + f"\n<function={name}>\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:
|
||||
"""`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> 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 `<tool_call>` 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 `<tool_` or `</thi`."""
|
||||
@@ -601,10 +683,46 @@ class OutputParser:
|
||||
self.buf += delta
|
||||
out: list[Event] = []
|
||||
while True:
|
||||
if self.state == "reasoning":
|
||||
if self.state == "rcall":
|
||||
# #804: a `<tool_call>` 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("<function="):].split(">", 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 `<tool_call>` and then (after whitespace) `<function=`; the tag with anything else after
|
||||
# it is prose that names the format ("I'll use a <tool_call> 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 = ""
|
||||
|
||||
@@ -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}]"
|
||||
|
||||
+530
-64
File diff suppressed because it is too large.
Load diff
+70
-3
@@ -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
|
||||
|
||||
@@ -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()<end:time.sleep(.01)
|
||||
self.assertFalse(e.alive(),'unrecoverable native ERR must invalidate health before a new request')
|
||||
def run_request(self,svc):
|
||||
return list(svc.run([1],False,[],8,{},threading.Event()))
|
||||
def test_fatal_error_is_not_a_success_and_next_request_reloads(self):
|
||||
e=self.engine();svc=self.service(e)
|
||||
with self.assertRaises(EngineDied):self.run_request(svc)
|
||||
self.wait_dead(e)
|
||||
self.assertIs(svc.engine,e,'the failed request must not be retried automatically')
|
||||
self.assertEqual(svc.history[-1]['finish'],'error')
|
||||
result=self.run_request(svc);self.addCleanup(svc.engine.close)
|
||||
self.assertTrue(svc.engine.alive())
|
||||
self.assertTrue(svc.loaded());self.assertEqual(result[-1][1]['completion_tokens'],1)
|
||||
def test_http_health_and_next_request_recovery(self):
|
||||
old=self.engine();svc=self.service(old);http=serve(svc,port=0)
|
||||
base=f'http://127.0.0.1:{http.server_address[1]}'
|
||||
body={'messages':[{'role':'user','content':'hi'}],'max_tokens':8,
|
||||
'chat_template_kwargs':{'enable_thinking':False},'stream':True}
|
||||
try:
|
||||
def post():
|
||||
req=urllib.request.Request(base+'/v1/chat/completions',data=json.dumps(body).encode(),headers={'Content-Type':'application/json'})
|
||||
with urllib.request.urlopen(req,timeout=5) as r:return r.read().decode()
|
||||
text=post()
|
||||
self.assertIn('"error"',text);self.assertTrue(text.rstrip().endswith('data: [DONE]'))
|
||||
with urllib.request.urlopen(base+'/health',timeout=5) as r:self.assertFalse(json.load(r)['loaded'])
|
||||
body['stream']=False
|
||||
self.assertEqual(json.loads(post())['usage']['completion_tokens'],1)
|
||||
with urllib.request.urlopen(base+'/health',timeout=5) as r:self.assertTrue(json.load(r)['loaded'])
|
||||
finally:
|
||||
http.shutdown();http.server_close();svc.engine.close()
|
||||
def test_batch_timeout_signature_also_invalidates_engine(self):
|
||||
e=self.engine('batch')
|
||||
with self.assertRaises(EngineDied):list(e.generate([1],8,{},threading.Event()))
|
||||
self.wait_dead(e)
|
||||
|
||||
def feed(self,e,lines,slots):
|
||||
import queue
|
||||
class P:
|
||||
stdout=iter(lines)
|
||||
terminated=False
|
||||
def terminate(self):self.terminated=True
|
||||
old=e.proc;e.proc=P();e.lines=queue.Queue();e.slot_q=[queue.Queue() for _ in range(slots)];e.ended=False
|
||||
e._pump()
|
||||
self.assertTrue(e.ended);self.assertTrue(e.proc.terminated)
|
||||
self.assertIsNone(e.lines.get_nowait());self.assertTrue(e.lines.empty()) # EOF, never the trailing DONE
|
||||
e.proc=old
|
||||
def test_fatal_lines_are_checked_before_batch_routing(self):
|
||||
e=self.engine('fatal')
|
||||
self.feed(e,['ERR verify batch: timed out at layer 3\n','BDONE 0 1 0 1 error\n'],2)
|
||||
self.assertTrue(all(q.get_nowait() is None and q.empty() for q in e.slot_q)) # only the EOF reached a slot, not the BDONE
|
||||
def test_an_earlier_window_never_finished_is_fatal(self):
|
||||
e=self.engine('fatal')
|
||||
self.feed(e,['ERR verify: an earlier window never finished on the GPU (#267); restart the engine\n','DONE 0 1 0 1 error\n'],0)
|
||||
self.feed(e,['ERR verify batch: an earlier window never finished on the GPU (#267)\n'],2)
|
||||
def test_generate_batched_refuses_a_dead_engine(self):
|
||||
e=self.engine('fatal');e.close()
|
||||
with self.assertRaises(EngineDied):list(e.generate_batched([1],8,{},threading.Event()))
|
||||
|
||||
def test_validation_error_does_not_kill_engine(self):
|
||||
e=self.engine('invalid')
|
||||
with self.assertRaises(ValueError):list(e.generate([1],8,{},threading.Event()))
|
||||
self.assertTrue(e.alive())
|
||||
self.assertEqual(list(e.generate([1],8,{},threading.Event())),[90])
|
||||
def test_closed_serial_engine_rejects_without_accessing_closed_pipe(self):
|
||||
e=self.engine();e.close()
|
||||
with self.assertRaises(EngineDied):list(e.generate([1],8,{},threading.Event()))
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Chat history normalization before rendering the model's prompt."""
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
from serve.frontend import ChatTemplate, anthropic_to_messages, openai_to_messages
|
||||
from serve.server import ByteTokenizer, MockEngine, Service
|
||||
|
||||
|
||||
class EmptyAssistantHistory(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.template = ChatTemplate(Path(__file__).with_name("chat_template.jinja"))
|
||||
tok = ByteTokenizer()
|
||||
self.service = Service(MockEngine(tok, "ok"), tok, self.template)
|
||||
|
||||
def test_openai_empty_replies_are_not_rendered(self):
|
||||
for content in (None, "", " \n\t", [], [{"type": "text", "text": ""}]):
|
||||
for preserve in (True, False):
|
||||
with self.subTest(content=content, preserve_thinking=preserve):
|
||||
history = []
|
||||
for _ in range(3):
|
||||
history.extend([{"role": "user", "content": "haz un ls"},
|
||||
{"role": "assistant", "content": content,
|
||||
"reasoning_content": "Let me run ls."}])
|
||||
history.append({"role": "user", "content": "haz un ls"})
|
||||
messages, tools, kwargs = openai_to_messages({"messages": history})
|
||||
kwargs["preserve_thinking"] = preserve
|
||||
clean = [m for m in messages if m["role"] == "user"]
|
||||
self.assertEqual(self.service.encode_prompt(messages, tools, kwargs),
|
||||
self.service.encode_prompt(clean, tools, kwargs))
|
||||
|
||||
def test_anthropic_thinking_only_replies_are_not_rendered(self):
|
||||
messages, tools, kwargs = anthropic_to_messages({"messages": [
|
||||
{"role": "user", "content": "haz un ls"},
|
||||
{"role": "assistant", "content": [{"type": "thinking", "thinking": "Let me run ls."}]},
|
||||
{"role": "user", "content": "haz un ls"},
|
||||
]})
|
||||
self.assertEqual(self.service.encode_prompt(messages, tools, kwargs),
|
||||
self.service.encode_prompt([messages[0], messages[2]], tools, kwargs))
|
||||
|
||||
def test_text_and_tool_calls_are_kept(self):
|
||||
messages, tools, kwargs = openai_to_messages({"messages": [
|
||||
{"role": "user", "content": "haz un ls"},
|
||||
{"role": "assistant", "content": [{"type": "text", "text": "Running ls."}]},
|
||||
{"role": "assistant", "content": None, "tool_calls": [
|
||||
{"type": "function", "function": {"name": "run", "arguments": '{"command":"ls"}'}},
|
||||
]},
|
||||
{"role": "tool", "content": "file.txt"},
|
||||
{"role": "user", "content": "thanks"},
|
||||
]})
|
||||
before = copy.deepcopy(messages)
|
||||
prompt = self.template.render(messages, tools=tools, **kwargs)
|
||||
self.assertIn("Running ls.", prompt)
|
||||
self.assertIn("<function=run>", 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("<tool_response>\n\n</tool_response>", 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("<function=a>\n"))
|
||||
self.assertTrue(forced_call("required", two).endswith("<function="))
|
||||
self.assertIsNone(forced_call("auto", one))
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Model discovery, on-demand loading and safe unloading over the actual HTTP API."""
|
||||
import json
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import unittest
|
||||
@@ -45,6 +46,41 @@ class ResidentEngine(StrataEngine):
|
||||
|
||||
|
||||
class Lifecycle(unittest.TestCase):
|
||||
def test_close_cleans_up_after_a_broken_stdin_pipe(self):
|
||||
for running in (False, True):
|
||||
with self.subTest(running=running):
|
||||
engine = StrataEngine("missing-executable", [], lazy=True)
|
||||
read_fd, write_fd = os.pipe()
|
||||
stdin = os.fdopen(write_fd, "w")
|
||||
self.addCleanup(stdin.close)
|
||||
os.close(read_fd) # the engine's end of the pipe is already gone
|
||||
stdin.write("pending") # buffered: flush() and close() will hit the broken pipe
|
||||
proc = mock.Mock(stdin=stdin, stdout=io.StringIO())
|
||||
self.addCleanup(proc.stdout.close)
|
||||
proc.poll.side_effect = [None if running else 0, 0]
|
||||
engine.proc, engine.pump, engine.log = proc, mock.Mock(), io.StringIO()
|
||||
self.addCleanup(engine.log.close)
|
||||
engine.ended, engine.progress, engine.last = False, (1, 2), {"generated": 1}
|
||||
|
||||
engine.close()
|
||||
|
||||
self.assertTrue(stdin.closed)
|
||||
self.assertTrue(proc.stdout.closed)
|
||||
self.assertTrue(engine.log.closed)
|
||||
engine.pump.join.assert_called_once_with(timeout=2)
|
||||
self.assertIsNone(engine.proc)
|
||||
self.assertTrue(engine.ended)
|
||||
self.assertIsNone(engine.progress)
|
||||
self.assertEqual(engine.last, {})
|
||||
if running:
|
||||
proc.terminate.assert_called_once()
|
||||
proc.wait.assert_called_once_with(timeout=20)
|
||||
else:
|
||||
proc.terminate.assert_not_called()
|
||||
proc.wait.assert_not_called()
|
||||
proc.kill.assert_not_called()
|
||||
engine.close() # repeated cleanup is harmless
|
||||
|
||||
def test_close_sends_eof_before_waiting_for_windows_reader(self):
|
||||
engine = StrataEngine("missing-executable", [], lazy=True)
|
||||
proc = mock.Mock()
|
||||
|
||||
@@ -234,6 +234,18 @@ class ParallelService(unittest.TestCase):
|
||||
self.assertEqual(self.engine.batch, 2)
|
||||
self.assertEqual(self.get("/v1/status")["concurrency"]["serving"], 2)
|
||||
|
||||
def test_stop_strings_in_a_batch_slot(self):
|
||||
"""#454: a stop string cuts the answer in --batch mode too, and the slot is freed for the next request."""
|
||||
self.start(2)
|
||||
body = {"messages": [{"role": "user", "content": "hi LONGREPLY"}], "max_tokens": 64, "reasoning_effort": "none",
|
||||
"stop": ["la la"]}
|
||||
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=60) as r:
|
||||
c = json.loads(r.read().decode())["choices"][0]
|
||||
self.assertEqual((c["message"]["content"], c["finish_reason"]), ("ok, ", "stop"))
|
||||
self.assertEqual(self.chat("again")["choices"][0]["message"]["content"], "ok, done.")
|
||||
|
||||
def test_engine_turns_batching_off(self):
|
||||
self.start(4, fit=0)
|
||||
self.assertEqual(self.engine.batch, 0)
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"""CPU-only regression for opt-in reasoning recovery: python -m unittest serve.test_reasoning_loop_recovery."""
|
||||
import threading
|
||||
import unittest
|
||||
from serve.server import (Service, ByteTokenizer, MockEngine, HIGH_EFFORT,
|
||||
reasoning_repeat_coverage, focused_recovery_prompt)
|
||||
|
||||
|
||||
class Tokenizer(ByteTokenizer):
|
||||
def token_bytes(self, token):
|
||||
return self.SPECIALS[token - 256].encode() if token >= 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<think>\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('</think>', self.tok.decode(prompt))
|
||||
|
||||
def run_case(self, enabled):
|
||||
engine = RecordingEngine(self.tok, [self.loop,
|
||||
'I have verified the solution.\n</think>\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</think>\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</think>\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</think>\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['</think>'] +
|
||||
' please<|im_end|>\n<|im_start|>assistant\n<think>\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</think>\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('</think>', self.tok.decode(engine.calls[1][0]))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -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 = "<tool_call>\n<function=read_file>\n<parameter=limit>\n120\n</parameter>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n</tool_call>"
|
||||
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</think>\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</think>\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</think>\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<tool_call>\n<function=read_file>\n",
|
||||
"before<tool_call>\n<function=read_file>\n<parameter=path>\nfile.txt\n</parameter>\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<tool_call>\n<function=read_file>\nhmm</think>\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<tool_call>\n<function=read_file>\nhmm")
|
||||
self.assertEqual(joined(evs, "content"), "the answer")
|
||||
|
||||
def test_a_call_in_the_answer_is_unchanged(self):
|
||||
text = "think</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 <tool_call> " + "thinking on and on " * 3000 + "</think>\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 </think>
|
||||
self.assertEqual(joined(evs, "reasoning"), text.split("</think>")[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 <tool_c")
|
||||
self.assertEqual(joined(evs, "reasoning"), "hello ")
|
||||
self.assertEqual(joined(p.feed("ats are nice</think>"), "reasoning"), "<tool_cats are nice")
|
||||
|
||||
|
||||
class OverHttp(unittest.TestCase):
|
||||
def test_finish_reasons_and_block_order(self):
|
||||
helper = UnfinishedToolCall("test_parser")
|
||||
helper.PROPS = {"path": {"type": "string"}}
|
||||
script = "Let me look. <tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n" \
|
||||
"</tool_call> More thought.</think>\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()
|
||||
+38
-1
@@ -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("</think>\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("<tool_response>\nbefore\n</tool_response>", 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(
|
||||
"</think>\n\n<tool_call>\n<function=mcp__websearch__web_search>\n<parameter=query>\nstrata\n"
|
||||
"</parameter>\n</function>\n</tool_call><|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(
|
||||
"</think>\n\n<tool_call>\n<function=multi_agent_v1.spawn_agent>\n<parameter=message>\nhi\n</parameter>\n"
|
||||
|
||||
+1000
-3
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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<typename dst_t>
|
||||
__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<dst_t>(((float) (x[ib].qs[iqs] & 0xf) - 8.0f) * d);
|
||||
y[iqs + 16] = cvt<dst_t>(((float) (x[ib].qs[iqs] >> 4) - 8.0f) * d);
|
||||
}
|
||||
}
|
||||
template<typename dst_t>
|
||||
__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<dst_t>((float) (x[ib].qs[iqs] & 0xf) * dm.x + dm.y);
|
||||
y[iqs + 16] = cvt<dst_t>((float) (x[ib].qs[iqs] >> 4) * dm.x + dm.y);
|
||||
}
|
||||
}
|
||||
template<typename dst_t>
|
||||
__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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+112
-30
@@ -11,9 +11,13 @@
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#if !defined(_WIN32)
|
||||
#include <sys/mman.h>
|
||||
#endif
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
|
||||
@@ -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 (*Block)(const uint8_t*, float*), int BlockBytes>
|
||||
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<strata::dequantize_q5_0, 22>},
|
||||
{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<strata::dequantize_q5_1, 24>},
|
||||
{PleFormat::Q8_0, "Q8_0", "Q8_0", PLE_ROW_BYTES_Q8_0, false, dequant_blocks<strata::dequantize_q8_0, 34>},
|
||||
// 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<strata::dequantize_q4_0, 18>},
|
||||
// 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<uint64_t>::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<uintptr_t> 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<std::thread> 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; }
|
||||
|
||||
@@ -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 <string>
|
||||
#include <vector>
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 2) {
|
||||
std::fprintf(stderr, "usage: ple_q5_parity <gguf-containing-ple>\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 <gguf-containing-ple>\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;
|
||||
}
|
||||
@@ -75,6 +75,170 @@ bool check_rows(ng::PleReader& rd, const std::vector<uint32_t>& 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<uint8_t> 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<uint32_t> 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<uint8_t> 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;
|
||||
|
||||
@@ -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<std::mutex> 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) {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <dpct/dpct.hpp>
|
||||
#include "strata/core/hit_hook.hpp"
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/kernels/cpu/pool.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
@@ -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.
|
||||
|
||||
+2
-1
@@ -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)}
|
||||
|
||||
@@ -86,7 +86,12 @@ NativeDense::~NativeDense() {
|
||||
|
||||
bool NativeDense::load(const std::vector<std::string> &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.<l>. 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<std::string> &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;
|
||||
|
||||
@@ -784,7 +784,7 @@ bool SessionLoopScratch::init(size_t parts_bytes_in, std::string &err) try {
|
||||
const std::vector<int> 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 (" +
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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 <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
int main() {
|
||||
constexpr int kBlocks = 4096;
|
||||
constexpr int kBlockBytes = 24;
|
||||
std::mt19937 rng(20261002);
|
||||
std::uniform_int_distribution<int> byte(0, 255);
|
||||
std::uniform_real_distribution<float> scale(-0.05f, 0.05f);
|
||||
std::vector<uint8_t> 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<float> 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;
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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 <mmproj.gguf> --model <text model .gguf, first split> [--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 <n_embd>", then per stdin line
|
||||
// ENC <image path> <output path> -> "OK <n_tokens> <nx> <ny> <ms>" or "ERR <message>"
|
||||
@@ -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 <mmproj.gguf> --model <model.gguf> [--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());
|
||||
|
||||
Reference in new issue
Block a user