diff --git a/CMakeLists.txt b/CMakeLists.txt index b7f6a8da..0f6426a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -99,6 +99,9 @@ endif() option(STRATA_BUILD_TESTS "Build the test suite" ${_strata_tests_default}) option(STRATA_BUILD_CONVERSATION_TESTS "Build standalone conversation cache tests" OFF) option(STRATA_WERROR "Treat compiler warnings as errors" OFF) +# #2027: defined here, before the GPU section reads it to register the native-expert tests (it was defined at the +# native-experts section far below, so a first configure registered four tests fewer than the second) +option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) if(STRATA_BUILD_CONVERSATION_TESTS) enable_testing() @@ -1207,7 +1210,6 @@ target_link_libraries(strata_kernels_cpu PUBLIC Threads::Threads) # The CPU computes a native expert with ggml-cpu's own dot products (`ggml_get_type_traits_cpu`), so an IQ # weight means exactly what it means in llama.cpp. ggml is built static from a llama.cpp checkout: a local one # with -DSTRATA_GGML_DIR=..., otherwise the pinned upstream commit (third_party/ggml/VERSION.txt). -option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: fetch the pinned commit)") if(STRATA_PREFILL_MMQ AND NOT STRATA_NATIVE_EXPERTS) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 66250f25..a8fe8834 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -216,6 +216,14 @@ of decode (one card 47.5 / 46.9 / 48.3 -> 50.5 / 48.5 / 51.3 tok/s with it on). `bench/results/2026-10-04-community-rx-6800-windows`): on was 12-22% slower. 4x R9700: fork off was 13-45% faster. Linux RX 6000 users can try `STRATA_SH_STREAM=1`; the output is identical either way. +**The draft's side stream (`STRATA_MTP_SIDE_STREAM`):** HIP does not use the MTP drafter's branch stream, and since +0.1.40.2 it does not create it (#1240: an R9700 lost prompt speed with it). gfx103x is the exception and creates it: on +an RX 6800 under Windows (`STRATA_HIP_PROMPT_F16=1`, IQ3_XXS, two runs each) a 7.9K-token prompt reads at 798-808 tok/s +with the stream and 584-596 without, and a 30.4K-token one at 855-863 against 553-600; `STRATA_PREFILL_TIMING=1` puts +the whole difference in the "wait copy" phase (3,081 -> 75 ms and 12,642 -> 288 ms). Decode and the output are the same. +`STRATA_MTP_SIDE_STREAM=0` turns it off on gfx103x, `=1` creates it on another HIP card. Measured on one card and one +OS; a Linux gfx103x number is welcome. + **Long prompts on a big card: check the lend-coverage line (#1389, measured by the reporter on an RX 7900 XTX, gfx1100, v0.1.40.2, 50 GB RAM).** With `--resident-experts` the prompt path borrows cache slots, and the experts of those slots must also sit in RAM. After the first request of a start the engine prints diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 7e79c05d..69e5e2f7 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -35,7 +35,7 @@ drafter's does). A window carries two rows per active slot (its token and its pr four slots are in one window; more slots (`--batch` up to what fits) rotate through. The windows run through the stages one after the other (`--batch-groups 1`): on 0.1.41 a layer split with `--batch` 2 or more pipelines the slots in groups by default, and the pipelined path does not run the slots' MTP drafts, so with `--batch-mtp` and no `--batch-groups` the -engine runs one group and says so; `--batch-groups G` (G above 1) or `--batch-groups auto` given on the command line +engine (0.1.43.1) pipelines and leaves `--batch-mtp` off, and says so (0.1.42/0.1.43 ran one serial group with it: 4 streams on 2x A4000 aggregated 63.9 tok/s against 91.8 pipelined, 85.8 pipelined without `--batch-mtp`; #2038). `--batch-groups 1` or `STRATA_BATCH_MTP_SERIAL=1` keeps `--batch-mtp` with serial windows, which is the better choice for about two streams as measured below; `--batch-groups G` (G above 1) or `--batch-groups auto` given on the command line keeps the pipeline and turns `--batch-mtp` off. Only a layer split of two stages on two GPUs has been run. Measured on a layer split of 2x RTX 3080 20 GB (220 W cap) with a Xeon E5-2696 v4, UD-Q4_K_XL, `"layer_split": "23"`, @@ -86,7 +86,7 @@ With a layer split, the engine options go into the config's `args`: | --- | --- | | `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | | `--batch-groups G` | with a layer split (default: auto, below): the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | -| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--batch-mtp` or `--adapt-async 1` and no `--batch-groups` the default is one group (the slots' MTP drafts and the adaptive tier between batch windows do not run in pipelined groups) and the log says so; `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off, and given with `--adapt-async 1` pipelines the groups and turns `--adapt-async` off (the pipelined path does not adapt). | +| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--adapt-async 1` and no `--batch-groups` the default is one group (the adaptive tier between batch windows does not run in pipelined groups) and the log says so; with `--batch-mtp` and no `--batch-groups` the pipeline wins and `--batch-mtp` is left off (`--batch-groups 1` or `STRATA_BATCH_MTP_SERIAL=1` keeps it); `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off, and given with `--adapt-async 1` pipelines the groups and turns `--adapt-async` off (the pipelined path does not adapt). | | `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by diff --git a/docs/DETAILS.md b/docs/DETAILS.md index dd088519..61f27890 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -643,6 +643,28 @@ with the fallback off it still starts and degrades instead of failing - the slac worth more than the extra slots, which is the same ordering measured above (enkynakamura, #781; one 256-token sample per step, so the upper rows are noisy). +**The free figure moves after startup.** The `... MiB of VRAM free with everything loaded` line is read before the +verify windows are captured (each captured window, and each `--batch` slot layout, takes some tens of MiB: 538 MiB at +that line was 395 MiB after the last capture in #2065, an RTX 4090 D with `--batch 2` at 262,144 context). Below about +a gigabyte on Windows the driver can page GPU memory to system RAM instead of failing: decode fell from 91 to 3 tok/s +at 70K tokens and then a window never finished, the watchdog stopping the engine after 60 s. From 0.1.43.1 each request +re-reads the free VRAM, says `WARNING: only N MiB of VRAM free at the start of this request` once it is under 1 GiB +(512 MiB elsewhere) with the `--vram-reserve-mib` that would leave room, and the stall report prints the figure. The +engine only says it; the fix is a larger `--vram-reserve-mib`, a smaller `--max-context` or `--batch`, or +`Prefer No Sysmem Fallback` for the engine. + +**A stall named "request" can be the OS paging the engine's own memory.** Before a request that switches +conversation, the engine parks the outgoing one in RAM: copies of its running checkpoints and K/V, which then sit in +ordinary memory until the conversation comes back. On a 64 GB PC with `--resident-budget-gib 40`, an 8 GiB conversation +cache and a 256K context, the working set was 8-30 GB of 56 GB committed and the engine took about 190 page faults +a second (under 1 MB/s if each is a pagefile read) in #2049: one silent step of more than 60 s, five times, on 0.1.41 +and 0.1.43 alike (thread dumps: the main thread inside the copy of the checkpoints, at the same instruction each time). The log's `verify window (last window, not the +current stage) ... host at layer step 48; the GPU rang 48` line in that report is the previous request's last window, +not the stalled one. From 0.1.43.1 the park is named in the stage (`request: parking the previous conversation`), its +copies report progress to the watchdog, and Windows counts page faults at 8 a unit instead of 64 when it decides +whether the file tier is busy. The cure for the slowness itself is memory: a smaller `--resident-budget-gib`, a smaller +`--conversation-cache-mib`, or the pagefile on an SSD. + --- ## Using it @@ -1698,14 +1720,18 @@ the pairs in which the switched arm won). They are here so you can try them on y -0.1% (5/6). Boxes that hold all experts in RAM never use the stage buffers. - **`STRATA_ADAPT_LAG=2`: the adaptive tier's copies are waited for one window later** (#764). Decode, 6 pairs: Tesla P100 (PCIe 3.0 x16) +3.5% (6/6 pairs faster), RTX 5070 +0.2% (4/6), RTX 3060 -1.3% (0/6), so it stays opt-in. -- **`STRATA_ADAPT_OVERLAP` (CUDA on Linux: on, `=0` turns it off; CUDA on Windows and HIP: `=1` turns it on, since an RTX 5070 on Windows decoded Q2_0 2.6% slower with it and IQ3_XXS no faster): the adaptive tier's copies land while the next +- **`STRATA_ADAPT_OVERLAP` (`=1` turns it on, on every backend; the startup log names the state and, when it cannot run, why): the adaptive tier's copies land while the next window runs, with the same tokens.** The window takes the swaps at the same moment as with #463's wait (so the same experts run on the GPU and the CPU in every window), but the copies go in layer order and the verify window holds a layer's plan back until that layer's copies have landed, instead of the whole window waiting for the round (about 10 ms every fourth window on an A4000, PCIe 3.0 x16). One GPU, the whole arena in RAM, no `--adapt-async`, `--pipeline-windows`, `STRATA_ADAPT_LAG`, - `STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`; otherwise the log says why it is off. RTX A4000, 6 interleaved pairs each, - decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%), - IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time. + `STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`. On by default on CUDA on Linux since 0.1.43, opt-in on Windows and HIP; + opt-in on every backend since #2010, after an RTX 5090 Laptop lost 21% decode with it. What it is worth per box: an RTX A4000 (6 + interleaved pairs each, decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), + IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%), IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time) and a Tesla P100 + (+4.4%) gain, but an RTX 5070 on Windows loses 2.6% on Q2_0 (IQ3_XXS no faster) and an RTX 5090 Laptop (WSL2, Core Ultra 9 + 275HX, native IQ3_XXS pack, `--expert-cache-per-layer`) loses 21%: 84.6 vs 106.6 tok/s medians of 5 generations of 256 + tokens from one build, the slowest of the fast run above the fastest of the slow one (#2010). - **`STRATA_ADAPT_CALLBACK_WARMUP` (Linux, on by default since 0.1.43.1; =0 turns it off): start the GPU host-callback thread before the CPU pool pins the host thread.** A callback thread created later can inherit the host's one-CPU affinity and compete with the verifier spinning for its signal (#1975). The warm-up runs and synchronizes one no-op host callback before @@ -1841,7 +1867,7 @@ 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). The engine reads the table + default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). A start-up probe warns when direct reads measure slow (under 15K rows/s) but never switches by itself (since 0.1.43.1; `STRATA_PLE_AUTO_MMAP=1` brings back the 0.1.42 switch to `--ple-io mmap`): the bar is calibrated for NVMe, a SATA SSD tops out at 10-14K rows/s with direct's 16 reads in flight, and on one (Linux, 77.8K-token prompt) mmap read 2.1K rows/s against direct's 14.4K (#2040), while on a Windows box with a slow mapped file mmap stalled prompts (#1984). 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 diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp index 1cb8af77..88a010b4 100644 --- a/include/strata/core/conversation_buffer.hpp +++ b/include/strata/core/conversation_buffer.hpp @@ -1,5 +1,7 @@ #pragma once +#include "strata/core/progress.hpp" + #include #include #include @@ -78,6 +80,7 @@ public: segment.resize(count, value); segments_.push_back(std::move(segment)); size_ += count; + progress_beat(); // #2049: zero-filling 16 MiB of fresh pages is slow when the host is paging } } else { while (!segments_.empty() && size_ - segments_.back().size() >= n) { diff --git a/include/strata/program/batch_groups.hpp b/include/strata/program/batch_groups.hpp index e0d87589..0abff1f8 100644 --- a/include/strata/program/batch_groups.hpp +++ b/include/strata/program/batch_groups.hpp @@ -3,9 +3,12 @@ // `--batch-groups N` pipelines N groups of slots through the stages of a layer split; `--batch-groups auto` picks the // most groups (at most one per stage) that divide the slots. Since 0.1.41 a layer split with `--batch` >= 2 and no // `--batch-groups` at all means `auto`. The pipelined path does not run `--batch-mtp`'s drafts or the batch -// adaptive tier (`--adapt-async 1` between batch windows), so when one of those is asked for and the number of groups -// was NOT given, `auto` resolves to one group (the serial windows they run in) and says why. A number or `auto` -// given on the command line is honoured as before. +// adaptive tier (`--adapt-async 1` between batch windows). `--adapt-async 1` with the number of groups NOT given still +// makes `auto` resolve to one group (and says why). `--batch-mtp` does not any more (0.1.43.1): on 2x A4000 and 2x RTX +// 3090 four concurrent streams lost 25-30% with the serial MTP windows against the pipelined default, so the default +// pipelines and `--batch-mtp` is left off there (said at start); STRATA_BATCH_MTP_SERIAL=1 or `--batch-groups 1` keeps +// the serial windows with the slots' drafts (the 0.1.42/0.1.43 behaviour). A number or `auto` given on the command line +// is honoured as before. // // Pure (no GPU, no environment read): generate.cpp passes in what it knows. #pragma once @@ -23,6 +26,7 @@ struct Input { int later_stages = 0; ///< the layer split's stages after CUDA0 (0: no layer split) bool batch_mtp = false; ///< --batch-mtp is on (it passed the gates that do not concern the groups) bool adapt_async = false; ///< --adapt-async 1 was asked for + bool mtp_serial = false; ///< STRATA_BATCH_MTP_SERIAL=1: --batch-mtp with no --batch-groups runs one serial group (0.1.43) }; struct Result { @@ -30,6 +34,7 @@ struct Result { bool from_auto = false; ///< the number came from `auto` (given or the 0.1.41 default) Serial serial = Serial::None; ///< `auto` would have pipelined, but this feature needs the serial windows int would_be = 1; ///< what `auto` would have picked without it (== groups unless `serial`) + bool mtp_dropped = false; ///< --batch-mtp met the default pipeline: the pipeline wins, --batch-mtp is off }; /// The most groups, at most one per stage of the layer split (`later_stages` + 1 GPUs), that divide `batch`. @@ -51,8 +56,9 @@ inline Result resolve(const Input& in) { r.would_be = auto_groups(in.later_stages, in.batch); r.groups = r.would_be; if (!in.set && r.would_be > 1) { // only the default gives way; `--batch-groups auto` asked for the pipeline - if (in.batch_mtp) r.serial = Serial::BatchMtp; + if (in.batch_mtp && in.mtp_serial) r.serial = Serial::BatchMtp; else if (in.adapt_async) r.serial = Serial::AdaptAsync; + r.mtp_dropped = in.batch_mtp && r.serial == Serial::None; if (r.serial != Serial::None) r.groups = 1; } return r; diff --git a/serve/frontend.py b/serve/frontend.py index 39fa317a..e8cc2335 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -242,7 +242,11 @@ THINK_TAGS = {"": "\U000F0E01", "": "\U000F0E02"} # 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} +# #2026: `` the same way. A user asking for the string verbatim handed the model the real end-of-call token +# (type 4, matched everywhere); it copied that token into its answer and the reply came back empty. An assistant +# message keeps its own: a client replaying the model's raw call text sends the tokens the model wrote. +TOOL_LITERAL_TAGS = {"": "\U000F0E07"} +LITERAL_TAGS = {**THINK_TAGS, **VISION_TAGS, **TOOL_LITERAL_TAGS} THINK_MARKS = {v: k for k, v in LITERAL_TAGS.items()} CONTROL_MARK0 = 0xF0E10 # the control tokens' marks start here, clear of the two sets above @@ -292,17 +296,19 @@ def mark_think_literals(messages: list[dict], tools: list[dict] | None, tags: di if not _has_tag(messages, tags) and not _has_tag(tools, tags): return messages, tools, False out = [] + own = {t: v for t, v in tags.items() if t not in TOOL_LITERAL_TAGS} # what an assistant message keeps as written for m in messages: m = dict(m) content = m.get("content") + mine = own if m.get("role") == "assistant" else tags for k, v in m.items(): if k != "role": - m[k] = _mark_deep(v, tags) + m[k] = _mark_deep(v, mine) if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("") \ and "" in content: i, j = content.index("") + len(""), content.index("") - m["content"] = (content[:i] + _mark(content[i:j], tags) + "" + - _mark(content[j + len(""):], tags)) + m["content"] = (content[:i] + _mark(content[i:j], own) + "" + + _mark(content[j + len(""):], own)) out.append(m) return out, _mark_deep(tools, tags), True @@ -716,9 +722,17 @@ def function_end(text: str) -> int: return -1 +_JSON_FENCE = re.compile(r"```[ \t]*(?:json)?[ \t]*\r?\n\s*", re.I) + + def json_tool_call(body: str, schemas: dict) -> ToolCall | None: """`{"name": N, "arguments": {...}}` (or "parameters", or the arguments as a JSON string) of a declared tool -> its - call; anything else -> None.""" + call; anything else -> None. #2037: the object may sit in a Markdown fence (```json ... ```).""" + body = body.strip() + m = _JSON_FENCE.match(body) + if m: + body = body[m.end():].rstrip() + body = body[:-3] if body.endswith("```") else body try: obj = json.loads(body) except ValueError: @@ -822,6 +836,15 @@ class OutputParser: return "param" if after[len(PARAM_START):gt] in self.schemas else "text" if after.startswith("{"): return "json" if self.schemas else "text" + if after.startswith("```") or (after and "```".startswith(after)): + # #2037: the JSON call inside a Markdown fence (```json ... ```) in the explicit wrapper + m = _JSON_FENCE.match(after) + if m: + rest = after[m.end():] + if rest.startswith("{"): + return "json" if self.schemas else "text" + return "wait" if not rest else "text" + return "wait" if "\n" not in after else "text" if not after or FUNC_START.startswith(after) or PARAM_START.startswith(after): return "wait" return "text" diff --git a/serve/server.py b/serve/server.py index 8e61c180..ff1b935c 100644 --- a/serve/server.py +++ b/serve/server.py @@ -305,6 +305,11 @@ class EngineStarting(RuntimeError): not a 400 about the prompt.""" +class ClientGone(Exception): + """#1999: the client hung up while its request was being prepared (an image URL downloading, a picture encoding or + waiting for its turn): nothing is left to answer.""" + + class ModelBusy(RuntimeError): """Explicit model controls must not interrupt active or queued requests.""" @@ -2229,12 +2234,14 @@ class Vision: im.save(out, format="PNG") return out.getvalue() - def encode_all(self, sources: list) -> list[tuple[Path, int]]: + def encode_all(self, sources: list, cancel=None) -> list[tuple[Path, int]]: """encode() for every image of one request: the files of this request's earlier images are never evicted to make room for a later one (#1072: with more than 64 unique images the first was deleted before the request - had read it).""" + had read it). `cancel` (#1999): a request whose client left does not encode its next pictures.""" out: list[tuple[Path, int]] = [] for src in sources: + if cancel is not None and cancel.is_set(): + raise ClientGone() out.append(self.encode(src, keep=[p for p, _ in out])) return out @@ -3538,7 +3545,22 @@ class Service: prompt, plain = unmark_think_literals(prompt, self.literals) return self.tok.encode(prompt, parse_special=True, plain=plain) - def _note_unreadable_tool_images(self, messages): + @contextlib.contextmanager + def _turn(self, cancel=None): + """The engine's single turn (self.fifo) for an image encode. #1999: a client that leaves while this request + waits for it gives its place up (ClientGone), as a queued generation does (#1619).""" + if cancel is None: + self.fifo.acquire() + else: + while not self.fifo.acquire(timeout=0.25): + if cancel.is_set(): + raise ClientGone() + try: + yield + finally: + self.fifo.release() + + def _note_unreadable_tool_images(self, messages, cancel=None): """A picture a tool returned (Claude Code's Read of an image file) that this server cannot read - it has no image encoder, or the encoder refuses that picture - becomes a short note in its place instead of a 400. Clients resend the whole history every turn, so one unreadable tool picture would fail every later request of @@ -3556,9 +3578,11 @@ class Service: if why is None: src = item["source"] try: + if cancel is not None and cancel.is_set(): + raise ClientGone() if src.startswith(("http://", "https://")): src = fetched[item["source"]] = Vision.download(src) # outside the FIFO, as in prepare() - with self.fifo: # the encoder takes its turn with the requests (see below) + with self._turn(cancel): # the encoder takes its turn with the requests (see below) self.vision.encode(src) except (ValueError, OSError) as e: why = str(e) @@ -3567,11 +3591,13 @@ class Service: content[n] = {"type": "text", "text": f"[image omitted: {why}]"} return fetched - def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None): + def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the prompt; with thinking, Service.run writes it once the thinking is over.""" - fetched = self._note_unreadable_tool_images(messages) + # `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop + # between pictures and raise ClientGone + fetched = self._note_unreadable_tool_images(messages, cancel) ids = self.encode_prompt(messages, tools, kwargs) if force and kwargs.get("enable_thinking", True) is False: ids = ids + self.tok.encode(force, parse_special=True) @@ -3585,14 +3611,18 @@ class Service: start = self.tok.encode(VISION_START, parse_special=True)[0] # An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request # for as long as urlopen waited. - images = [fetched[src] if src in fetched else Vision.download(src) if src.startswith(("http://", "https://")) - else src for src in images] + def fetch(src): + if cancel is not None and cancel.is_set(): + raise ClientGone() + return fetched[src] if src in fetched else Vision.download(src) \ + if src.startswith(("http://", "https://")) else src + images = [fetch(src) for src in images] # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not # run on the GPU at the same time - an encode during a running request left that request stuck at # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the # same FIFO as the requests. - with self.fifo: - encoded = (self.vision.encode_all(images) if hasattr(self.vision, "encode_all") + with self._turn(cancel): + encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all") else [self.vision.encode(src) for src in images]) # one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image # (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs, @@ -4401,7 +4431,11 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}), "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]}) messages += [{"role": "tool", "content": r} for r in results] - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req) + try: + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req, cancel=cancel) + except ClientGone: # #1999: the client left while a picture was prepared + done = {**done, "finish": "cancel"} + break yield "done", {**done, "completion_tokens": total, "prompt_tokens": len(ids)} @@ -5240,6 +5274,8 @@ def make_handler(svc: Service): except EngineStuck as e: # an unload or restart that could not end the engine self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + except ClientGone: # #1999: the client left while the request was prepared + self._note(outcome="disconnected") except OSError: self._note(outcome="disconnected") raise # as before #332: the server's own handling @@ -5483,10 +5519,10 @@ def make_handler(svc: Service): svc.reasoning_budget(req) # a bad value is a 400 before anything is sent stop_strings(req) # ... and so is a bad stop / stop_sequences check_request_sampling(req) # ... and a sampling field of the wrong type - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req) - _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() - self._watch_client(cancel) # #430 #431 + self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long) + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel) + _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, {t["name"] for t in extra}) if use_mcp else None chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force) @@ -5544,16 +5580,19 @@ def make_handler(svc: Service): return self._json(e.status, e.body()) if title is not None: return self._responses_ready(req, title) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long) try: - ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req) + ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req, cancel) + except ClientGone: + self._note(outcome="disconnected") + return except ResponsesError as e: return self._json(e.status, e.body()) except ModelBusy as e: return self._json(409, responses_error_body(str(e), "server_error", code="model_busy")) except (GpuBusy, EngineStarting, EngineStuck, EngineDied) as e: return self._json(503, responses_error_body(str(e), "server_error", code="server_error")) - cancel = threading.Event() - self._watch_client(cancel) # #430 #431 def check(text, finish): return validated_json(text, validator, finish) @@ -5626,7 +5665,7 @@ def make_handler(svc: Service): except OSError: pass - def _responses_prepare(self, req): + def _responses_prepare(self, req, cancel=None): responses_api.check_request(req) messages = responses_api.input_messages(req) tools, names, skipped = responses_api.request_tools(req) @@ -5664,12 +5703,14 @@ def make_handler(svc: Service): shown = responses_api.prompt_tools(req, tools) if svc.codex_compaction_cache else tools try: try: - ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req) + ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req, + cancel=cancel) except ValueError: if shown is tools: raise shown = tools # too long with the kept tools: the request as sent - ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req) + ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req, + cancel=cancel) except ResponsesError: raise except ValueError as e: # too long for the context, an image without vision @@ -5705,10 +5746,10 @@ def make_handler(svc: Service): svc.reasoning_budget(req) # a bad value is a 400 before anything is sent stop_strings(req) # ... and so is a bad stop / stop_sequences check_request_sampling(req) # ... and a sampling field of the wrong type - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req) - _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() - self._watch_client(cancel) # #430 #431 + self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long) + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel) + _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel, force=force) events = self._capture(events, "anthropic") if not req.get("stream"): diff --git a/serve/test_frontend.py b/serve/test_frontend.py index fc7113e6..f4fe3e68 100644 --- a/serve/test_frontend.py +++ b/serve/test_frontend.py @@ -201,3 +201,74 @@ class ForcedCallOpening(unittest.TestCase): self.assertTrue(forced_call("required", one).endswith("\n")) self.assertTrue(forced_call("required", two).endswith("` a user quotes is text, not the end-of-call token (type 4: matched even without + parse_special); an assistant message replaying raw call text keeps the model's own tokens.""" + + def setUp(self): + import sys + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + import strata_tokenizer as ST + b2u = ST.bytes_to_unicode() + self.tok = ST.Tokenizer([b2u[b] for b in range(256)] + ["", "<|im_end|>"], [], [1] * 256 + [4, 3]) + self.tags = __import__("serve.frontend", fromlist=["literal_tags"]).literal_tags(self.tok.control_tokens) + + def encode(self, role, text): + from serve.frontend import mark_think_literals, unmark_think_literals + marked, _, changed = mark_think_literals([{"role": role, "content": text}], None, self.tags) + prompt, plain = unmark_think_literals(marked[0]["content"], self.tags) + return self.tok.encode(prompt, parse_special=True, plain=plain), changed + + def test_user_text_stays_text(self): + text = "output verbatim: ." + ids, changed = self.encode("user", text) + self.assertTrue(changed) + self.assertEqual(ids, [*text.encode()]) + self.assertNotEqual(self.tok.encode(text, parse_special=True), ids) # unmarked, it was the special token + + def test_assistant_replay_keeps_its_token(self): + text = "x" + ids, _ = self.encode("assistant", text) + self.assertEqual(ids, self.tok.encode(text, parse_special=True)) + + +class FencedJsonCallInWrapper(unittest.TestCase): + """#2037: with recovery on, a declared tool's JSON call in a Markdown fence inside is the call.""" + TOOLS = [{"name": "write_file", "parameters": {"type": "object", "properties": {"content": {"type": "string"}}}}] + PAYLOAD = '{"name": "write_file", "arguments": {"content": "hello `world`"}}' + + def run_parser(self, raw, chunk, stream_tools, recover=True, tools=None): + from serve.frontend import OutputParser + p = OutputParser(thinking=False, tools=self.TOOLS if tools is None else tools, recover=recover, + stream_tools=stream_tools) + events = [] + for i in range(0, len(raw), chunk): + events += p.feed(raw[i:i + chunk]) + events += p.finish() + return ([e.call.arguments for e in events if e.kind == "tool_call"], + "".join(e.text for e in events if e.kind == "content")) + + def test_fenced_and_bare_agree(self): + for fence in ("```json\n", "```\n", "```JSON\r\n"): + raw = f"\n{fence}{self.PAYLOAD}\n```\n" + for chunk in (len(raw), 1, 7): + for st in (False, True): + with self.subTest(fence=fence, chunk=chunk, stream_tools=st): + self.assertEqual(self.run_parser(raw, chunk, st), ([{"content": "hello `world`"}], "")) + + def test_other_fences_and_prose_stay_text(self): + raw = "\n```python\nx = 1\n```\n" + for chunk in (len(raw), 1): + self.assertEqual(self.run_parser(raw, chunk, False), ([], raw)) + raw = f"Here:\n```json\n{self.PAYLOAD}\n```\n" # no wrapper: just text + self.assertEqual(self.run_parser(raw, len(raw), False), ([], raw)) + + def test_off_without_recovery_or_for_an_undeclared_tool(self): + raw = f"\n```json\n{self.PAYLOAD}\n```\n" + calls, text = self.run_parser(raw, len(raw), False, recover=False) + self.assertEqual((calls, text), ([], raw)) + other = [{"name": "other", "parameters": {}}] + calls, text = self.run_parser(raw, len(raw), False, tools=other) + self.assertEqual((calls, text), ([], raw)) diff --git a/serve/test_server.py b/serve/test_server.py index 8f5c7373..bbb176ad 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -5439,3 +5439,72 @@ class UntimedReads(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class PrepareCancelled(unittest.TestCase): + """#1999: a client that leaves while its pictures are prepared gives the turn up and encodes nothing more.""" + + def make(self, d, vision): + tok = ByteTokenizer() + return Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=vision(d)) + + @staticmethod + def msgs(n=2): + return [{"role": "user", "content": [{"type": "text", "text": "look"}] + + [{"type": "image", "source": f"{i}.png"} for i in range(n)]}] + + def test_cancel_before_the_encode_runs_none(self): + import tempfile + calls = [] + + class V(ImageMarkers.FakeVision): + def encode(self, source): + calls.append(source) + return self.rows, 3 + with tempfile.TemporaryDirectory() as d: + svc = self.make(d, V) + cancel = threading.Event() + cancel.set() + from serve.server import ClientGone + with self.assertRaises(ClientGone): + svc.prepare(self.msgs(), None, {}, cancel=cancel) + self.assertEqual(calls, []) + self.assertTrue(svc.fifo.acquire(blocking=False)) # the turn was not left held + svc.fifo.release() + + def test_cancel_while_waiting_for_the_turn(self): + import tempfile + from serve.server import ClientGone + with tempfile.TemporaryDirectory() as d: + svc = self.make(d, ImageMarkers.FakeVision) + cancel = threading.Event() + threading.Timer(0.3, cancel.set).start() + with svc.fifo: # another request holds the engine + t0 = time.perf_counter() + with self.assertRaises(ClientGone): + svc.prepare(self.msgs(1), None, {}, cancel=cancel) + self.assertLess(time.perf_counter() - t0, 3) + + def test_cancel_between_pictures_stops_the_next_encode(self): + import tempfile + from serve.server import ClientGone, Vision + cancel, seen = threading.Event(), [] + v = Vision.__new__(Vision) + + def encode(src, keep=()): + seen.append(src) + cancel.set() # the client leaves during the first encode + return Path("x"), 3 + v.encode = encode + with self.assertRaises(ClientGone): + v.encode_all([b"a", b"b", b"c"], cancel) + self.assertEqual(seen, [b"a"]) + + def test_without_cancel_nothing_changes(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + svc = self.make(d, ImageMarkers.FakeVision) + ids, _, _ = svc.prepare(self.msgs(), None, {}, cancel=threading.Event()) + self.assertEqual(ids.count(ByteTokenizer().encode("<|image_pad|>", parse_special=True)[0]), 6) + svc.embeddings.path.unlink(missing_ok=True) diff --git a/setup.py b/setup.py index 5fbe72c8..7d291e1c 100644 --- a/setup.py +++ b/setup.py @@ -2642,7 +2642,7 @@ def build_engine_hip(gpu, llama, vision="none") -> Path: has_archs = set(archs) <= set(meta.get("archs", [])) floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs and \ - (meta.get("isa_floor") or "") == floor + (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE) vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc) if engine_ok and vision_ok: ok("engine already built for this PC") @@ -2671,6 +2671,10 @@ def build_engine_hip(gpu, llama, vision="none") -> Path: "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}", f"-DSTRATA_GGML_DIR={llama}", *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "") + if stale_binary(ROOT / "build-hip" / EXE): # #2054: no stamp for a binary of another version + fail(f"the engine build finished without a new engine ({EXE} is version " + f"{binary_engine_version(ROOT / 'build-hip' / EXE)}, this source is {source_version()}): " + "the installed engine is left as it was", "delete the folder build-hip and run this again") shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE) meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none", "lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})} @@ -3108,7 +3112,7 @@ def update_installed_engine(url_base, toolkit=None) -> None: "starting the installed one") return if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed - if meta.get("src") != source_hash(ENGINE_SOURCES): + if meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE): try: usable = [x for x in amd_gpus() if amd_problem(x) is None] g = next((x for x in usable if x["arch"] in meta.get("archs", [])), usable[0] if usable else None) @@ -3125,7 +3129,7 @@ def update_installed_engine(url_base, toolkit=None) -> None: local = meta.get("source") == "local" vision = meta.get("vision") or "none" if local: # compiled here: is it older than the source (a git pull)? - if meta.get("src") == source_hash(ENGINE_SOURCES) and \ + if meta.get("src") == source_hash(ENGINE_SOURCES) and not stale_binary(eng / EXE) and \ (vision == "none" or meta.get("vision_src") == source_hash(VISION_SOURCES)): return elif ver >= MIN_ENGINE: @@ -3400,7 +3404,7 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path: new_arch = local and not set(archs) <= built floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch and \ - (meta.get("isa_floor") or "") == floor + (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE) vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc)) if engine_ok and vision_ok: ok("engine already built for this PC") @@ -3421,6 +3425,10 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path: *host_compiler_defs(True), *engine_defs(archs, toolkit), *isa_floor_defs(floor, bdir, meta)], vcvars, "build-strata-cuda12.bat" if t12 else "build-strata.bat") + if stale_binary(bdir / EXE): # #2054: the stamp below is written only for a binary of this source + fail(f"the engine build finished without a new engine ({EXE} is version {binary_engine_version(bdir / EXE)}, " + f"this source is {source_version()}): the installed engine and its stamp are left as they were", + "the build folder " + str(bdir) + " may be configured for something else: delete it and run this again") shutil.copy2(bdir / EXE, eng / EXE) if not vision_ok: say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ...")) @@ -4031,6 +4039,18 @@ def choices_from_config(cfg_path: Path) -> dict: vis is None or int(val("--vram-reserve-mib")) != VISION["gpu"]["reserve_mib"]) else None} +def calibration_targets(have: list, model: str | None, family: str | None) -> list: + """#2036: the installed configs `--calibrate --model X` (and/or --family) means; every config with neither.""" + if not (model or family): + return list(have) + out = [] + for c in have: + ch = choices_from_config(c) + if (not model or ch["model"] == model) and (not family or ch["family"] == family): + out.append(c) + return out + + def find_in(roots: list, rel: str): """The first of roots/rel that exists.""" for r in roots: @@ -4067,6 +4087,24 @@ def source_version() -> str: return m.group(1) if m else "0" +def binary_engine_version(exe) -> str | None: + """The version compiled into an engine binary (the `engine=X.Y.Z` line it prints at start; 0.1.13 and newer carry + it), read from the file without running it. None: unreadable, or a binary without it.""" + try: + m = re.search(rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n", Path(exe).read_bytes()) + except OSError: + return None + return m.group(1).decode() if m else None + + +def stale_binary(exe) -> bool: + """#2054: the engine binary is of another version than this source tree builds. A BUILD.json that carries the + source's hash and version cannot be trusted alone: a build that stopped (a host compiler the toolkit rejects) can + leave the old binary beside a stamp of the new source, and nothing would ever compile it again.""" + v = binary_engine_version(exe) + return v is not None and v != source_version() + + def engine_version(exe: Path) -> tuple: """The version in the engine folder's BUILD.json, or else the one compiled into the binary. A locally compiled engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept @@ -4955,7 +4993,17 @@ def main() -> int: # choice, and asked once when the PC has cards that could share the model run_gpu = start_gpus(a.gpus) or a.gpu port = a.port or 8080 # a new install's port (issue #32: --port for an existing one) - if have and a.calibrate and not (a.setup or a.model or a.family or a.check): + if a.calibrate and (a.setup or a.check or not have): # #2036: said, not dropped + why = ("--setup" if a.setup else "--check" if a.check else "no model is installed yet") + warn(f"--calibrate does nothing with {why}: it tunes a model that is already installed. Run setup first, " + "then " + ("START-HERE.bat" if WIN else "./setup.sh") + " --calibrate [--model NAME]") + if have and a.calibrate and not (a.setup or a.check): + targets = calibration_targets(have, a.model, a.family) + if not targets: # #2036: --model names a model that is not installed + names = ", ".join(sorted({choices_from_config(c)["model"] or c.stem for c in have})) + fail(f"--calibrate: {a.model or a.family} is not installed (installed: {names})", + "calibrate an installed model, or set this one up first without --calibrate") + have = targets if not a.build: update_installed_engine(a.prebuilt) pick_cfg = have[0] diff --git a/src/core/conversation_copy.hpp b/src/core/conversation_copy.hpp index e15b1197..0dea46a3 100644 --- a/src/core/conversation_copy.hpp +++ b/src/core/conversation_copy.hpp @@ -1,8 +1,15 @@ #pragma once +#include "strata/core/conversation_cache.hpp" +#include "strata/core/progress.hpp" + #include +#include +#include #include +#include +#include #include namespace strata::core::conversation_detail { @@ -26,7 +33,58 @@ inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes) { cudaStream_t s = streams[(size_t) dev]; e = cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDefault, s); if (e != cudaSuccess) return e; - return cudaStreamSynchronize(s); + e = cudaStreamSynchronize(s); + core::progress_beat(); // #2049: a parked conversation is many of these; each one that lands is progress + return e; +} + +/// #2049 #2065 #1971: a host-to-host copy that tells the watchdog it is moving. Parked state (the running +/// checkpoints, the K/V segments) sits in ordinary pageable memory for the whole session; when the OS has written +/// it to the pagefile, copying it back runs at the drive's page-in speed (measured in the reports: ~190 hard faults +/// a second, under 1 MB/s) and one memcpy of it stays silent past the 60 s limit, so the watchdog ended an engine +/// that was only slow. One beat per 1 MiB slice keeps a copy that moves alive and still lets a real stall show. +/// STRATA_TEST_SLOW_COPY_US=N (tests only): every 1 MiB slice of a checkpoint copy takes N microseconds more, as when +/// the OS has paged the checkpoints out and each slice is read back from the drive. Unset: no delay. +inline long test_slow_copy_us() { + static const long v = [] { const char* e = std::getenv("STRATA_TEST_SLOW_COPY_US"); return e ? std::atol(e) : 0L; }(); + return v; +} + +template +inline std::vector copy_beating(const std::vector& src) { + std::vector out; + out.reserve(src.size()); + const size_t step = std::max(1, ((size_t) 1 << 20) / sizeof(T)); + for (size_t at = 0; at < src.size(); at += step) { + out.insert(out.end(), src.begin() + (std::ptrdiff_t) at, + src.begin() + (std::ptrdiff_t) std::min(src.size(), at + step)); + if (const long us = test_slow_copy_us(); us > 0) std::this_thread::sleep_for(std::chrono::microseconds(us)); + core::progress_beat(); + } + return out; +} + +inline ConversationCheckpoint copy_checkpoint_beating(const ConversationCheckpoint& c) { + ConversationCheckpoint o; + o.ids = copy_beating(c.ids); + o.imgs = copy_beating(c.imgs); + o.gdn = copy_beating(c.gdn); + o.ple = copy_beating(c.ple); + o.tails = copy_beating(c.tails); + o.dead = copy_beating(c.dead); + o.block_pos = copy_beating(c.block_pos); + o.used = c.used; + o.pinned = c.pinned; + o.stage_parts.reserve(c.stage_parts.size()); + for (const auto& part : c.stage_parts) o.stage_parts.push_back(copy_checkpoint_beating(part)); + return o; +} + +inline std::vector copy_checkpoints_beating(const std::vector& cs) { + std::vector out; + out.reserve(cs.size()); + for (const auto& c : cs) out.push_back(copy_checkpoint_beating(c)); + return out; } } // namespace strata::core::conversation_detail diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 9c2342f8..4fbcf88b 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -257,7 +257,7 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView captured.geometry = geometry_key(g); captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; captured.live.ids = view.ids; captured.live.imgs = view.images; - captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; + captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints); const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; captured.kv = std::move(reuse.kv); const size_t layers = owned_qsa(ss); @@ -283,7 +283,7 @@ bool conversation_snapshot_sources(SavedConversation& meta, std::vector 75 ms); the two events + // change nothing. So gfx103x creates the stream and no other HIP card does. STRATA_MTP_SIDE_STREAM=1 / =0 forces + // either. + { + int dev = 0; + cudaDeviceProp prop{}; + bool on = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess && + std::strncmp(prop.gcnArchName, "gfx103", 6) == 0; + if (const char* v = std::getenv("STRATA_MTP_SIDE_STREAM"); v != nullptr && *v != 0) on = std::atoi(v) != 0; + if (on && cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess) { + err = "mtp: streams"; + return false; + } + } #endif const double files_s = std::chrono::duration(std::chrono::steady_clock::now() - t_files).count(); if (shared != nullptr) { @@ -1344,6 +1362,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* } (void) cudaStreamQuery(cs_); prefetch_ple(tokens[a]); + progress_at("mtp draft: waiting for the GPU"); // #2065 for (int j = 0; j + 1 < max_steps; ++j) { uint32_t spins = 0; while (((volatile int32_t*) h_out_)[j] < 0) { @@ -1372,6 +1391,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* } (void) cudaStreamQuery(cs_); prefetch_ple(tokens[a]); + progress_at("mtp draft: waiting for the GPU"); // #2065: a stall here read as "decode", the verify window before it auto wait_step = [&](int j) { uint32_t spins = 0; while (((volatile int32_t*) h_out_)[j] < 0) { diff --git a/src/program/batch_groups_test.cpp b/src/program/batch_groups_test.cpp index 19145638..ecc51929 100644 --- a/src/program/batch_groups_test.cpp +++ b/src/program/batch_groups_test.cpp @@ -49,9 +49,13 @@ int main() { { // the production shape: parallel 2 on a 2-GPU split with --batch-mtp bg::Input i = in(2, 1); i.batch_mtp = true; - const auto r = bg::resolve(i); - check(r.groups == 1 && r.from_auto && r.serial == bg::Serial::BatchMtp && r.would_be == 2, - "--batch-mtp, nothing given: one group, because of --batch-mtp"); + auto r = bg::resolve(i); + check(r.groups == 2 && r.from_auto && r.serial == bg::Serial::None && r.mtp_dropped, + "--batch-mtp, nothing given: the pipeline wins, --batch-mtp is dropped"); + i.mtp_serial = true; + r = bg::resolve(i); + check(r.groups == 1 && r.from_auto && r.serial == bg::Serial::BatchMtp && r.would_be == 2 && !r.mtp_dropped, + "STRATA_BATCH_MTP_SERIAL: one group, because of --batch-mtp"); check(bg::serial_what(r.serial)[0] == '-', "the reason names the feature"); } { @@ -64,7 +68,9 @@ int main() { bg::Input i = in(2, 1); i.batch_mtp = true; i.adapt_async = true; - check(bg::resolve(i).serial == bg::Serial::BatchMtp, "both: --batch-mtp is named"); + check(bg::resolve(i).serial == bg::Serial::AdaptAsync, "both: --adapt-async 1 still gives one group"); + i.mtp_serial = true; + check(bg::resolve(i).serial == bg::Serial::BatchMtp, "both with STRATA_BATCH_MTP_SERIAL: --batch-mtp is named"); } { // nothing to give way: the slots do not divide, so auto is one group anyway and there is nothing to say bg::Input i = in(3, 1); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index b1ffd943..7a93c0a3 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1157,12 +1157,14 @@ static uint64_t file_tier_activity() { return total; #elif defined(_WIN32) // #1984 #1971: Windows had no measure here, so a prompt waiting on mapped-file page-ins never got the I/O allowance. - // Bytes read (MiB) plus page faults / 64 (Windows counts soft faults too; a stuck engine makes almost none). + // Bytes read (MiB) plus page faults / 8 (Windows counts soft faults too; a stuck engine makes almost none). uint64_t total = 0; IO_COUNTERS io{}; if (GetProcessIoCounters(GetCurrentProcess(), &io)) total += io.ReadTransferCount >> 20; PROCESS_MEMORY_COUNTERS pmc{}; - if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) total += pmc.PageFaultCount >> 6; + // >> 3, not >> 6: a host that pages hard reads from the pagefile at ~200 faults a second (#2049: 190/s, one + // thread waiting on one page at a time), which at >> 6 is 3 a second and never counted as busy + if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) total += pmc.PageFaultCount >> 3; return total; #else return 0; @@ -1262,12 +1264,29 @@ bool launch_blocking() { #endif } +/// #2065: the VRAM free when the current request began (-1 before the first); the stall report prints it, because a +/// card this full is the one measured cause of a window that never finishes (the driver pages GPU memory). +std::atomic g_req_vram_free_mib{-1}; +constexpr int64_t kVramSafeMib = +#ifdef _WIN32 + 1024; // WDDM pages instead of failing (docs/DETAILS.md, the sysmem fallback): the line #2065 fell below +#else + 512; +#endif + void stall_report(std::FILE* f, uint64_t layers_during) { strata::core::Progress& p = strata::core::progress(); std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " "last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, stage_text().c_str(), (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000), (unsigned long long) layers_during); + if (const int64_t vf = g_req_vram_free_mib.load(); vf >= 0) { + std::fprintf(f, " VRAM free when this request began: %lld MiB%s\n", (long long) vf, + vf >= kVramSafeMib ? "" : " - LOW: a card this full can page GPU memory to system RAM (decode " + "falls to a few tok/s, then a window never finishes, #2065); a larger --vram-reserve-mib, a " + "smaller --max-context, or 'Prefer No Sysmem Fallback' for the engine in the NVIDIA control panel " + "(docs/DETAILS.md) leaves room"); + } for (int pass = 0; pass < 2; ++pass) { if (pass == 1) { std::this_thread::sleep_for(std::chrono::seconds(2)); @@ -1314,11 +1333,21 @@ void stall_report(std::FILE* f, uint64_t layers_during) { /// STRATA_TRACE=1: the VRAM left at a step of the startup (finds what fills the card after the cache is sized) void mem_mark(const char* where) { - static const bool on = std::getenv("STRATA_TRACE") != nullptr; - if (!on) return; + static const char* const env = std::getenv("STRATA_TRACE"); + if (env == nullptr) return; size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where); + // STRATA_TRACE=2: also wait for the device here and name the first step after which it reports an error. A + // "sticky" failure (#2013: unspecified launch failure surfacing in a later, unrelated call) is then pinned to + // the step that ran the faulting work. Only a diagnostic: it adds a synchronisation per mark. + if (env[0] == '2') { + const cudaError_t sync_e = cudaDeviceSynchronize(); + const cudaError_t last_e = cudaGetLastError(); + std::fprintf(stderr, "strata trace: device %s after %s (sync: %s, last error: %s)\n", + sync_e == cudaSuccess && last_e == cudaSuccess ? "ok" : "ERROR", where, cudaGetErrorString(sync_e), + cudaGetErrorString(last_e)); + } } /// #463's A/B: STRATA_ADAPT_NOWAIT=1 lets a verify window start before the adaptive tier's copies have landed (0.1.37) @@ -1337,21 +1366,21 @@ int adapt_lag() { return v; } -/// 0.1.43 STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next decode window already runs. The window +/// STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next decode window already runs. The window /// sees the swapped-in experts as resident from its first layer, exactly as after #463's wait (so the tokens are the same /// ones); what changes is only when the bytes arrive: the copies go in layer order and the verify window holds a layer's /// plan back until that layer's copies have landed (AdaptGate in strata/core/verify.hpp). The ~10 ms a 96-swap round -/// took at the next window's start (PCIe 3.0 x16, Q2_0) is then hidden behind the window. On for CUDA (=0 turns it off), opt-in on HIP. +/// took at the next window's start (PCIe 3.0 x16, Q2_0) is then hidden behind the window. Opt-in on every backend +/// (=1 turns it on); the startup log names the state, and why when it cannot run. bool adapt_overlap() { static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_OVERLAP"); -#if defined(STRATA_USE_HIP) - return e && e[0] == '1'; // HIP: not measured yet, opt-in -#elif defined(_WIN32) - return e && e[0] == '1'; // Windows CUDA: opt-in (RTX 5070, Q2_0: -2.6% story decode with it, IQ3_XXS neutral) -#else - return !(e && e[0] == '0'); // Linux CUDA: on since 0.1.43 (same tokens, +5.5..8.3% decode on an A4000, +4.4% P100); =0 turns it off -#endif + // Opt-in on every backend (#2010). Windows CUDA since 0.1.43: an RTX 5070 decoded Q2_0 2.6% slower with it + // (story decode, -2.1% code), IQ3_XXS no faster. Linux CUDA was on by default from 0.1.43 (same tokens, +5.5..8.3% + // decode on an A4000, +4.4% on a P100) until an RTX 5090 Laptop (WSL2, Core Ultra 9 275HX, native IQ3_XXS pack, + // --expert-cache-per-layer) decoded 21% slower with it: 84.6 vs 106.6 tok/s medians of 5 generations of 256 + // tokens from one build, the slowest of the fast run above the fastest of the slow one. + return e && e[0] == '1'; }(); return v; } @@ -3202,13 +3231,12 @@ int main(int argc, char** argv) { if (rps >= kSlowRowsPerS) std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps); if (rps > 0 && rps < kSlowRowsPerS) { - // #1984 #1971: on Windows the mapped reads stalled prompts (the first chunk waits for 16 serial page faults - // a token from a cold table with no progress mark), so there the switch is only made when asked for + // #1984 #1971 #2040: on no platform is the switch made on its own. Windows: the mapped reads stalled prompts (the first chunk waits for 16 serial page faults + // a token from a cold table with no progress mark). Linux SATA SSD: the 15K rows/s bar is NVMe-calibrated, a SATA SSD + // tops out at 10-14K with direct's 16 reads in flight and mapped reads were 7x slower. The switch is only made when asked for // (STRATA_PLE_AUTO_MMAP=1, the 0.1.42 behaviour); otherwise the slow probe warns and direct is kept. bool auto_mmap = !o.ple_io_explicit; -#if defined(_WIN32) if (const char* am = std::getenv("STRATA_PLE_AUTO_MMAP"); am == nullptr || std::atoi(am) == 0) auto_mmap = false; -#endif if (auto_mmap) { std::fprintf(stderr, "strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " "random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " @@ -3224,7 +3252,7 @@ int main(int argc, char** argv) { } else { std::fprintf(stderr, "strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " "MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " - "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on such drives; " + "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on some DRAM-less NVMe drives but 7x slower on a SATA SSD (#2040), so it is not chosen for you; " "--ple-io ram needs the RAM for the table%s\n", rps, rps * 4096.0 / 1e6, o.ple_io_explicit ? "" : " (kept direct: pass --ple-io mmap or --ple-io ram to change it)"); } @@ -4369,6 +4397,7 @@ int main(int argc, char** argv) { bin.later_stages = (int) stages.size(); bin.batch_mtp = mtp_on; bin.adapt_async = o.adapt_async != 0; + { const char* ms = std::getenv("STRATA_BATCH_MTP_SERIAL"); bin.mtp_serial = ms != nullptr && ms[0] != '\0' && ms[0] != '0'; } return strata::program::batch_groups::resolve(bin); }; const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP"); @@ -4381,7 +4410,12 @@ int main(int argc, char** argv) { : !o.serve ? "it needs --serve" : nullptr; // the groups it would run with (the default gives way to it: one group; a number or auto given pipelines) if (why == nullptr && !stages.empty() && batch_groups_for(true).groups > 1) - why = "it does not combine with --batch-groups (pipelined slot groups) yet"; + why = batch_groups_for(true).mtp_dropped + ? "a layer split with --batch pipelines the slots in groups by default and the pipelined groups run no slot " + "drafts (4 streams on 2 GPUs: 25-30% faster than the serial MTP windows); --batch-groups 1 or " + "STRATA_BATCH_MTP_SERIAL=1 keeps --batch-mtp with serial windows (fewer streams, or when prompts arrive " + "rarely, it can be the faster choice)" + : "it does not combine with --batch-groups (pipelined slot groups) yet"; // (a layer split with helper-GPU expert caches or --remote-expert-opt has not been run with slot drafters) if (why == nullptr && !stages.empty() && (remote_caches || o.remote_expert_opt)) why = "it is not run with helper expert caches on a layer split"; @@ -6297,7 +6331,9 @@ int main(int argc, char** argv) { total += b; if (srcp->pinned(l, e)) pinned += b; } - strata::prefill::Prefill::set_pinned_share(total ? (double) pinned / (double) total : 1.0); + double share = total ? (double) pinned / (double) total : 1.0; + if (const char* t = std::getenv("STRATA_TEST_PINNED_SHARE")) share = std::atof(t); // tests: the Windows-like ring rule + strata::prefill::Prefill::set_pinned_share(share); } // bytes -> slots for CUDA0's cache: exact when it knows its per-slot offsets (a native pack's blobs differ // per layer), otherwise max_blob each. @@ -7339,6 +7375,7 @@ int main(int argc, char** argv) { } } } + mem_mark("before the prompt path init"); for (;;) { const int r = init_prompt_paths(); if (r == 0) break; @@ -7902,6 +7939,14 @@ int main(int argc, char** argv) { // addresses change: all parked images live in ordinary host vectors. auto park_current_body = [&](size_t held) -> bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; + // #2049: parking copies the outgoing conversation's running checkpoints and K/V into host memory, which + // is a silent stretch of the "request" stage; when the OS has paged that memory out it takes minutes. + // Named, so a stall report says "parking"; its copies beat (conversation_copy.hpp), so the watchdog + // sees a park that moves and ends one that does not. + struct ParkStage { + ParkStage() { strata::core::progress_at("request: parking the previous conversation"); } + ~ParkStage() { strata::core::progress_at("request"); strata::core::progress_beat(); } + } park_stage; // --conversation-cache-min-tokens: a short conversation is not worth one of the slots. Parking is a // switch-time decision, so a client's small side requests would otherwise park themselves and, once the // cache is full, evict the long conversation they were interleaved with (oldest first) - the reuse it @@ -8395,8 +8440,10 @@ int main(int argc, char** argv) { bool aflipped = false; // the pending swaps are in the tables and their copies may still be landing bool aov = false; int64_t aov_flips = 0; - if (adapt_overlap()) { - const char* why = multi_gpu || !stages.empty() ? "not on a layer split" + // #2010: the overlap is opt-in on every backend now, so the off state is the default and has to be visible too. + // The predicates are side-effect free, so they are read in both states: they name why it could not run. + const bool aov_want = adapt_overlap(); + const char* aov_why = multi_gpu || !stages.empty() ? "not on a layer split" : peer.valid() ? "not with --peer-device" : remote_opt ? "not with --remote-expert-opt" : o.adapt_async ? "not with --adapt-async" @@ -8411,12 +8458,13 @@ int main(int argc, char** argv) { ? "not in the resident RAM mode unless STRATA_ADAPT_OVERLAP_RESIDENT=1" : drive.d.usage.empty() ? "the adaptive tier is off" : nullptr; - if (why == nullptr) { + if (aov_want) { + if (aov_why == nullptr) { agate.ticks.resize((size_t) g.n_layers + 1); for (int64_t l = 0; l <= g.n_layers; ++l) agate.ticks[(size_t) l] = {&agate, (int32_t) l}; agate.has.assign((size_t) g.n_layers, 0); - if (!ver.set_adapt_gate(&agate)) why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on"; - if (why == nullptr && !(std::getenv("STRATA_ADAPT_SIGNAL") && std::getenv("STRATA_ADAPT_SIGNAL")[0] == 'h')) { + if (!ver.set_adapt_gate(&agate)) aov_why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on"; + if (aov_why == nullptr && !(std::getenv("STRATA_ADAPT_SIGNAL") && std::getenv("STRATA_ADAPT_SIGNAL")[0] == 'h')) { // the landing of each layer's copies is told by a stream-ordered D2H copy of the layer number into pinned memory // (STRATA_ADAPT_SIGNAL=host: a host function instead). No callback thread has to be scheduled while the pool's workers spin on every other CPU int32_t* vals = nullptr; void* hp = nullptr; @@ -8432,13 +8480,15 @@ int main(int argc, char** argv) { } else { (void) cudaGetLastError(); } } } - aov = why == nullptr; + aov = aov_why == nullptr; if (aov) std::fprintf(stderr, "strata serve: adaptive overlap (STRATA_ADAPT_OVERLAP=0 turns it off): the adaptive tier's copies land while the next window runs " "(same tokens, a layer waits for its own copies)\n"); - else if (std::getenv("STRATA_ADAPT_OVERLAP") != nullptr) // quiet when it was only the default - std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", why); - } + else if (std::getenv("STRATA_ADAPT_OVERLAP") != nullptr) // the env var was set: say what stopped it + std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", aov_why); + } else + std::fprintf(stderr, "strata serve: adaptive overlap: off%s%s\n", + aov_why ? ": " : " (STRATA_ADAPT_OVERLAP=1 turns it on)", aov_why ? aov_why : ""); // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own auto res_upload = [&]() { if (d_res != nullptr) @@ -9903,6 +9953,24 @@ int main(int argc, char** argv) { strata::core::progress_at("idle"); } } busy_scope; + { // #2065: said, never changed - the free VRAM now (the verify windows' captures and the batch layouts + // eat into what startup reported), once per 128 MiB lower it gets + size_t vf_b = 0, vt_b = 0; + if (cudaMemGetInfo(&vf_b, &vt_b) == cudaSuccess) { + const int64_t vf = (int64_t) (vf_b >> 20); + g_req_vram_free_mib.store(vf); + static int64_t low_said_at = INT64_MAX; + if (vf < kVramSafeMib && vf + 128 <= low_said_at) { + low_said_at = vf; + std::fprintf(stderr, "strata serve: WARNING: only %lld MiB of VRAM free at the start of this request " + "(below %lld MiB): when the card is this full the driver can page GPU memory " + "to system RAM, decode falls to a few tok/s and a window may never finish " + "(#2065). Add --vram-reserve-mib %lld to the config's args, or lower " + "--max-context / --batch\n", (long long) vf, (long long) kVramSafeMib, + (long long) ((o.vram_reserve_mib + (kVramSafeMib - vf) + 63) / 64 * 64)); + } + } + } stop_req.store(false); // a STOP that arrived between requests is stale err.clear(); // Disk sessions: SAVE | RESTORE , between requests (the path runs to the end of the line, @@ -10939,9 +11007,32 @@ int main(int argc, char** argv) { if (!refill_one(p, e)) return false; } const strata::core::OnDevice on(p.dev); - const int32_t first = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, want))); - if (want != p.sp->chunk() || first != p.first_now) { - if (!p.sp->relayout(want, p.cache->device_slot(first), part_bytes(p, first), e)) return false; + // #2090: the loan a chunk needs is NOT monotonic in the chunk: a chunk above the scan's small_max + // lays out the byte-budget ring (199 slots at 5120), one at or below it 0.1.39's (384 at 4096), so + // a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The + // loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be + // lent even then is halved until it can, instead of ending the engine. + int64_t want_p = want; + int64_t need_p = part_slots(p, want_p); + while ((need_p <= 0 || need_p + 128 > p.cache->slots()) && want_p > 256) { + want_p = std::max(256, want_p / 2 / 256 * 256); + need_p = part_slots(p, want_p); + } + if (need_p <= 0 || need_p + 128 > p.cache->slots()) { + e = "prefill: no chunk of this request fits the slots that can be lent (#2090)"; + return false; + } + if (want_p != want) + std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " + "buffers do not fit the slots that can be lent (#2090)\n", (long long) want, + (long long) want_p); + if (need_p > p.cache->slots() - p.first) // the case that ended the engine before (#2090) + std::fprintf(stderr, "strata serve: the loan for a chunk of %lld tokens (%lld slots) is larger than the " + "auto chunk's (%lld slots): starting it earlier (#2090)\n", (long long) want_p, + (long long) need_p, (long long) (p.cache->slots() - p.first)); + const int32_t first = (int32_t) (p.cache->slots() - need_p); + if (want_p != p.sp->chunk() || first != p.first_now) { + if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e)) return false; p.first_now = first; } for (int64_t l = p.lb; l < p.le; ++l) // THIS participant's layers only @@ -10953,7 +11044,7 @@ int main(int argc, char** argv) { any = true; } } - p.lent_chunk = want; + p.lent_chunk = want_p; } if (any) res_upload(); if (trace) { diff --git a/sycl/include/strata/core/expert_source.hpp b/sycl/include/strata/core/expert_source.hpp index 2a8731ae..78870cf8 100644 --- a/sycl/include/strata/core/expert_source.hpp +++ b/sycl/include/strata/core/expert_source.hpp @@ -570,6 +570,11 @@ public: bool pcie_layer(int64_t layer) const override; bool transient(int64_t layer, int64_t expert) const override; bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override; + /// The blob read from the model file(s) only, never from the RAM copy or an exchange buffer (STRATA_CHECK_SWAPS). + bool copy_blob_from_file(int64_t layer, int64_t expert, uint8_t* dst) const { + return base_ != nullptr && dst != nullptr && layer >= 0 && expert >= 0 && layer < n_layers_ && expert < n_expert_ && + copy_from_files(layer, expert, dst); + } /// CS-T: advances the assembled blobs' age (see staged_blob). void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads. diff --git a/sycl/serve/server_intel.py b/sycl/serve/server_intel.py index 1b775c5d..baae26c2 100644 --- a/sycl/serve/server_intel.py +++ b/sycl/serve/server_intel.py @@ -5,7 +5,7 @@ Every argument is serve/server.py's. Nothing in serve/ is edited (the SYCL port keeps out of the shared files so upstream merges stay clean); this wrapper adds, at run time: - - the Monitor tab's GPU readings on an Intel Arc (sycl/serve/xe_telemetry.py) when no NVIDIA card answers; + - the Monitor tab's GPU readings on an Intel Arc (sycl/serve/xe_telemetry.py) (also on a PC with an NVIDIA card: the engine runs on the Intel one); - a model menu in the web app's header, for a host that swaps models on one GPU: the config names the RPC that does the swap as "model_switcher" (it takes {"mode": m} and answers {"mode", "up", "starting", "choices", "urls"}); the menu offers the models served on this server's port. Without that key nothing changes; @@ -35,15 +35,14 @@ from xe_telemetry import _XeGpu # noqa: E402 def install_xe_reader(): - """telemetry.gpu_reader -> the xe reader when NVML has no card and an Intel Arc is there.""" + """telemetry.gpu_reader -> the xe reader whenever an Intel Arc is there. #2001: this server runs the SYCL engine, + so the cards it reports are the Intel ones; before, an NVIDIA card in the same PC answered first and the Monitor + (and the benchmark report, which takes the card's name from it) showed the GeForce the engine never used.""" orig = T.gpu_reader def gpu_reader(index=0, amd=False): - g = orig(index, amd) - if g.ok(): - return g xe = _XeGpu(index) - return xe if xe.ok() else g + return xe if xe.ok() else orig(index, amd) T.gpu_reader = gpu_reader diff --git a/sycl/serve/xe_telemetry.py b/sycl/serve/xe_telemetry.py index 3eb3b61a..137667e9 100644 --- a/sycl/serve/xe_telemetry.py +++ b/sycl/serve/xe_telemetry.py @@ -12,6 +12,12 @@ import sys import time +# the cards sycl/setup_intel.py names by PCI id (INTEL_ARC) +ARC_NAMES = {"e223": "Arc Pro B70", "e221": "Arc Pro B60", "e211": "Arc Pro B60", "e20b": "Arc B580", "e20c": "Arc B570", + "e212": "Arc B50", "56a0": "Arc A770", "56a1": "Arc A750", "56a2": "Arc A580", "56a5": "Arc A380", + "56a6": "Arc A310", "5690": "Arc A770M"} + + class _XeGpu: """The Intel Arc readings in NVML's shape. Load and VRAM come from /run/gpustat.json (a root sampler: the only VRAM accounting xe exposes is per-client fdinfo, readable by root only); temperature, power and the PCIe link are @@ -21,13 +27,15 @@ class _XeGpu: def __init__(self, index=0): import glob self.dev = None + cards = [] # #2001: the Intel cards in sysfs order, as setup numbers them for d in sorted(glob.glob("/sys/class/drm/card[0-9]*/device")): try: if open(f"{d}/vendor").read().strip() == "0x8086" and os.path.isdir(f"{d}/tile0"): - self.dev = os.path.realpath(d) - break + cards.append(os.path.realpath(d)) except OSError: continue + if 0 <= index < len(cards): + self.dev = cards[index] self.hwmon = None for n in glob.glob(f"{self.dev}/hwmon/hwmon*/name") if self.dev else []: self.hwmon = os.path.dirname(n) @@ -38,7 +46,13 @@ class _XeGpu: def name(self): st = self._stat() - return (st or {}).get("name") or "Intel Arc GPU" + if (st or {}).get("name"): + return st["name"] + try: # the PCI id's name (setup_intel.INTEL_ARC), not a generic one + with open(f"{self.dev}/device") as f: + return "Intel " + ARC_NAMES.get(f.read().strip().lower().replace("0x", ""), "Arc GPU") + except (OSError, TypeError): + return "Intel Arc GPU" def _stat(self): try: diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index faf7e391..5d6f5866 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -333,13 +333,16 @@ bool resident_stage_swaps(strata::core::FileExpertSource &src, if (slot < 0) continue; const SwapHome home = locate(s.layer); const strata::core::OnDevice on(home.dev); - /* - DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. - While the origin API might be synchronous, it depends on the type of - operand memory, so you may need to call wait() on event return by memcpy - API to ensure synchronization behavior. - */ - + // the evicted expert's bytes go back into exchange buffer q BEFORE its slot is overwritten + // (CUDA: cudaMemcpyAsync D2H on the owning card's stream; the dpct migration had dropped the call) + try { + home.stream->memcpy(src.exchange_buffer(q), home.cache->device_slot(slot), + (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); + } catch (sycl::exception const& e) { + std::fprintf(stderr, "strata: copy back of layer %d slot %d (device %d) failed: %s\n", (int) s.layer, + (int) slot, home.dev, e.what()); + return false; + } bool seen = false; for (const SwapHome& u : used) seen = seen || u.stream == home.stream; if (!seen) used.push_back(home); @@ -349,6 +352,32 @@ bool resident_stage_swaps(strata::core::FileExpertSource &src, if (!staged.empty()) { for (const SwapHome& u : used) { const strata::core::OnDevice on(u.dev); + try { + u.stream->wait(); + } catch (sycl::exception const& e) { + std::fprintf(stderr, "strata: copy back sync (device %d) failed: %s\n", u.dev, e.what()); + return false; + } + } + // STRATA_CHECK_SWAPS=1 (a test aid): each evicted expert's exchange buffer must hold the model file's bytes + if (const char* chk = std::getenv("STRATA_CHECK_SWAPS"); chk != nullptr && chk[0] != '\0' && chk[0] != '0') { + static std::atomic n_ok{0}, n_bad{0}; + std::vector ref; + int64_t bad = 0; + for (const Staged& x : staged) { + ref.resize((size_t) strata::kernels::cpu::expert_layout().blob_bytes(x.layer)); + if (!src.copy_blob_from_file(x.layer, x.out, ref.data()) || + std::memcmp(ref.data(), src.exchange_buffer(x.q), ref.size()) != 0) { + ++bad; + std::fprintf(stderr, "strata: STRATA_CHECK_SWAPS: layer %d expert %d: the exchange buffer differs from the file\n", + (int) x.layer, (int) x.out); + } else { + ++n_ok; + } + } + n_bad += bad; + std::fprintf(stderr, "strata: STRATA_CHECK_SWAPS: %zu staged, %lld differ (total %lld ok, %lld differ)\n", + staged.size(), (long long) bad, (long long) n_ok.load(), (long long) n_bad.load()); } for (const Staged& x : staged) if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) { @@ -3003,13 +3032,12 @@ int main(int argc, char **argv) try { if (rps >= kSlowRowsPerS) std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps); if (rps > 0 && rps < kSlowRowsPerS) { - // #1984 #1971: on Windows the mapped reads stalled prompts (the first chunk waits for 16 serial page faults - // a token from a cold table with no progress mark), so there the switch is only made when asked for + // #1984 #1971 #2040: on no platform is the switch made on its own. Windows: the mapped reads stalled prompts (the first chunk waits for 16 serial page faults + // a token from a cold table with no progress mark). Linux SATA SSD: the 15K rows/s bar is NVMe-calibrated, a SATA SSD + // tops out at 10-14K with direct's 16 reads in flight and mapped reads were 7x slower. The switch is only made when asked for // (STRATA_PLE_AUTO_MMAP=1, the 0.1.42 behaviour); otherwise the slow probe warns and direct is kept. bool auto_mmap = !o.ple_io_explicit; -#if defined(_WIN32) if (const char* am = std::getenv("STRATA_PLE_AUTO_MMAP"); am == nullptr || std::atoi(am) == 0) auto_mmap = false; -#endif if (auto_mmap) { std::fprintf(stderr, "strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " "random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " @@ -3025,7 +3053,7 @@ int main(int argc, char **argv) try { } else { std::fprintf(stderr, "strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " "MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " - "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on such drives; " + "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on some DRAM-less NVMe drives but 7x slower on a SATA SSD (#2040), so it is not chosen for you; " "--ple-io ram needs the RAM for the table%s\n", rps, rps * 4096.0 / 1e6, o.ple_io_explicit ? "" : " (kept direct: pass --ple-io mmap or --ple-io ram to change it)"); } @@ -12606,6 +12634,31 @@ int main(int argc, char **argv) try { std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); + // STRATA_CHECK_SWAPS=1 (a test aid): after the run every expert must be held (the GPU cache or the RAM copy), + // and every RAM-copy blob must equal the model file's bytes (nothing lost, nothing stale after the swaps) + if (src.complement_ready()) + if (const char* chk = std::getenv("STRATA_CHECK_SWAPS"); chk != nullptr && chk[0] != '\0' && chk[0] != '0') { + int64_t held_ram = 0, held_gpu = 0, lost = 0, stale = 0; + std::vector ref; + for (int64_t l = 0; l < g.n_layers; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) { + const bool ram = src.has_resident(l, e); + const bool gpu = host_res[(size_t) l * (size_t) g.n_expert + (size_t) e] >= 0; + held_ram += ram; + held_gpu += gpu; + if (!ram && !gpu) { ++lost; continue; } + if (!ram) continue; + ref.resize((size_t) strata::kernels::cpu::expert_layout().blob_bytes(l)); + if (!src.copy_blob_from_file(l, e, ref.data()) || + std::memcmp(ref.data(), src.resident_blob(l, e), ref.size()) != 0) { + if (stale++ < 8) + std::fprintf(stderr, "strata: STRATA_CHECK_SWAPS: layer %d expert %d: the RAM copy differs from the file\n", + (int) l, (int) e); + } + } + std::printf("%-24s audit: %lld experts in RAM, %lld in the GPU cache, %lld held by neither, %lld RAM blobs differ from the file\n", + "STRATA_CHECK_SWAPS", (long long) held_ram, (long long) held_gpu, (long long) lost, (long long) stale); + } if (srcp == &src) { // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) const double fms = src.file_ms() - fms0, fmb = (double) (src.file_blob_bytes() - fbytes0) / 1e6; std::printf("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, " diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 557af920..67bd63a0 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -606,7 +606,14 @@ def collect_machine(base: str, key: str, cfg: dict | None, gpu_arg: str | None = gpu_names = [g["name"] for g in used] or ([static["gpu_name"]] if static.get("gpu_name") else []) m = status.get("machine") or {} vram_mib = (m.get("gpu") or {}).get("total_mib") or None - if used and used[0].get("vram_mib"): + # #2001: the server names the cards it reads (" + " between them). A name nvidia-smi does not list means the + # engine runs on another vendor's card (an Intel Arc beside a GeForce): the server's names are the right ones, and + # so is its VRAM total - the PC's NVIDIA cards were not used. + served = [n for n in (static.get("gpu_name") or "").split(" + ") if n and n != "?"] + if served and not all(n in {g["name"] for g in local["gpus"]} for n in served): + gpu_names, used = served, [] + local = {**local, "cuda": None} # the PC's CUDA belongs to cards the engine did not use + elif used and used[0].get("vram_mib"): vram_mib = sum(g.get("vram_mib") or 0 for g in used) n_ctx = None for d in models.get("data") or []: @@ -649,7 +656,35 @@ def is_strata(base: str, key: str) -> bool: return bool(h and h.get("service") == "strata") +def without_profile_save(cfg: dict) -> tuple[dict, bool]: + """#2088: the config without `--expert-profile-save FILE` (and its value) - the engine writes that profile when the + server quits, and a benchmark's short prompts must not replace the user's calibrated one. -> (config, removed).""" + args = list(cfg.get("args") or []) + out, i, removed = [], 0, False + while i < len(args): + if args[i] == "--expert-profile-save": + i, removed = i + 2, True + elif isinstance(args[i], str) and args[i].startswith("--expert-profile-save="): + i, removed = i + 1, True + else: + out.append(args[i]) + i += 1 + return ({**cfg, "args": out} if removed else cfg), removed + + def start_server(cfg_path: Path, port: int, gpu: str | None, log_path: Path): + try: + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + cfg = None + if isinstance(cfg, dict): + safe, removed = without_profile_save(cfg) + if removed: # a copy beside the log: the user's config file is not touched + print("Note: the bench starts this model without --expert-profile-save, so its short prompts do not " + "overwrite your saved expert profile.", file=sys.stderr) + tmp = log_path.with_suffix(".config.json") + tmp.write_text(json.dumps(safe), encoding="utf-8") + cfg_path = tmp cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port)] if gpu: cmd += ["--gpu", gpu] @@ -702,9 +737,19 @@ def gpu_slug(machine: dict) -> str: names = machine.get("gpu") or [] if not names: return "cpu" - n = re.sub(r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b", " ", names[0]) - s = slug(n, 30) - return s if len(names) == 1 else f"{len(names)}x-{s}" + # #2062: the cards one by one when they differ (rtx-5070-ti-plus-rtx-a4000), "2x-" only for identical ones + groups: list[list] = [] # [name, count], in the order the cards are listed + for name in names: + same = next((g for g in groups if g[0] == name), None) + if same: + same[1] += 1 + else: + groups.append([name, 1]) + parts = [] + for name, count in groups: + n = re.sub(r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b", " ", name) + parts.append(slug(n, 30) if count == 1 else f"{count}x-{slug(n, 30)}") + return "-plus-".join(parts)[:80].strip("-") def model_label(machine: dict) -> str: diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py index 124b7853..1d1fd992 100644 --- a/tools/test_setup_choices.py +++ b/tools/test_setup_choices.py @@ -614,3 +614,50 @@ class HostCompilers(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class CalibrateWithModel(unittest.TestCase): + """#2036: --calibrate --model X tunes model X (it used to fall through to a plain re-setup); a model that is not + installed is an error that says so; --calibrate with --setup or --check says it does nothing.""" + + def run_main(self, *argv, installed=("iq3_xxs", "q2_0")): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + cfgs = [] + for tag in installed: + p = Path(tmp.name) / f"strata-{tag}.json" + p.write_text(json.dumps({"exe": "x", "args": ["--max-context", "8192"], "model_name": tag})) + cfgs.append(p) + tuned = [] + with mock.patch.object(sys, "argv", ["setup.py", *argv]), \ + mock.patch.object(setup, "installed_configs", lambda: cfgs), \ + mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None), \ + mock.patch.object(setup, "calibrate_config", lambda c: tuned.append(c.name) or True), \ + mock.patch.object(setup, "start", lambda *a, **k: 0), \ + mock.patch.object(setup, "data_folder", lambda d: (Path(tmp.name), [])), \ + mock.patch.object(setup, "step", side_effect=SystemExit("reached the plain setup")): + try: + code, out = quiet(setup.main) + except SystemExit as e: + code, out = e.code, "" + return code, tuned + + def test_model_is_the_target(self): + code, tuned = self.run_main("--calibrate", "--model", "IQ3_XXS", "--yes", "--no-start") + self.assertEqual((code, tuned), (0, ["strata-iq3_xxs.json"])) + + def test_a_model_not_installed_is_an_error(self): + code, tuned = self.run_main("--calibrate", "--model", "IQ3_S", "--yes", "--no-start") + self.assertEqual((code, tuned), (1, [])) + + def test_targets(self): + with tempfile.TemporaryDirectory() as d: + ps = [] + for tag in ("iq3_xxs", "q2_0"): + p = Path(d) / f"strata-{tag}.json" + p.write_text(json.dumps({"args": []})) + ps.append(p) + self.assertEqual(setup.calibration_targets(ps, None, None), ps) + self.assertEqual(setup.calibration_targets(ps, "Q2_0", None), [ps[1]]) + self.assertEqual(setup.calibration_targets(ps, "Q2_0", "qwen"), [ps[1]]) + self.assertEqual(setup.calibration_targets(ps, "Q4_K_M", None), []) diff --git a/tools/test_setup_stale_stamp.py b/tools/test_setup_stale_stamp.py new file mode 100644 index 00000000..b282215d --- /dev/null +++ b/tools/test_setup_stale_stamp.py @@ -0,0 +1,144 @@ +"""#2054: BUILD.json is trusted only beside a binary of the source's version. + +A build that stopped (nvcc rejecting a newer host gcc) once left the old engine next to a stamp of the new source, and +every later update said "engine already built for this PC" for good. `stale_binary` reads the version compiled into the +binary; `build_engine` refuses to stamp or install a binary of another version and compiles again when the installed +one is stale. + + python -m unittest tools.test_setup_stale_stamp +""" +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + +GPU = {"arch": 86, "archs": [86], "name": "RTX 3060"} + + +def binary(version: str | None) -> bytes: + return b"\x7fELF....tail_role_token=0 vram_elastic=0 engine=" + version.encode() + b"\n...." if version else b"old binary" + + +class StaleBinary(unittest.TestCase): + def test_reads_the_compiled_in_version(self): + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43"): + exe = Path(d) / "strata" + exe.write_bytes(binary("0.1.42")) + self.assertEqual(setup.binary_engine_version(exe), "0.1.42") + self.assertTrue(setup.stale_binary(exe)) + exe.write_bytes(binary("0.1.43")) + self.assertFalse(setup.stale_binary(exe)) + + def test_four_part_version_and_unknowns(self): + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43.1"): + exe = Path(d) / "strata" + exe.write_bytes(binary("0.1.43.1")) + self.assertFalse(setup.stale_binary(exe)) + exe.write_bytes(binary("0.1.43")) + self.assertTrue(setup.stale_binary(exe)) + exe.write_bytes(binary(None)) # a binary that carries no version: not judged + self.assertFalse(setup.stale_binary(exe)) + self.assertFalse(setup.stale_binary(Path(d) / "missing")) + + +class BuildEngineStamp(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.eng = self.root / "engine" + self.eng.mkdir() + (self.eng / setup.EXE).write_bytes(binary("0.1.42")) + self.old_stamp = {"source": "local", "version": "0.1.42", "archs": [86], "vision": "none", + "cuda_dirs": [], "src": "oldhash", "vision_src": None} + (self.eng / "BUILD.json").write_text(json.dumps(self.old_stamp)) + self.built = binary("0.1.43") # what the fake compile leaves in the build folder + self.compiles = 0 + patches = [mock.patch.object(setup, "ROOT", self.root), + mock.patch.object(setup, "source_hash", lambda parts: "newhash"), + mock.patch.object(setup, "source_version", lambda: "0.1.43"), + mock.patch.object(setup, "install_build_tools", lambda gpu, yes: ("nvcc", None)), + mock.patch.object(setup, "toolkit_root_defs", lambda nvcc: []), + mock.patch.object(setup, "host_compiler_defs", lambda cuda: []), + mock.patch.object(setup, "engine_defs", lambda archs, tk=13: []), + mock.patch.object(setup, "isa_floor_defs", lambda *a: []), + mock.patch.object(setup, "cpu_floor", lambda avx2: ""), + mock.patch.object(setup, "cpu_info", lambda: ("cpu", True)), + mock.patch.object(setup, "cmake_build", self.fake_build), + mock.patch.object(setup, "say", lambda *a, **k: None), + mock.patch.object(setup, "ok", lambda *a, **k: None)] + for p in patches: + p.start() + self.addCleanup(p.stop) + + def fake_build(self, src, bdir, target, defs, vcvars, bat): + self.compiles += 1 + bdir.mkdir(parents=True, exist_ok=True) + (bdir / setup.EXE).write_bytes(self.built) + + def stamp(self): + return json.loads((self.eng / "BUILD.json").read_text()) + + def test_a_good_build_is_stamped(self): + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.compiles, 1) + self.assertEqual(self.stamp()["src"], "newhash") + self.assertEqual(self.stamp()["version"], "0.1.43") + self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built) + + def test_a_build_that_leaves_the_old_binary_is_not_stamped_or_installed(self): + self.built = binary("0.1.42") # the build "succeeded" without producing the new engine + with self.assertRaises(SystemExit): + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.stamp(), self.old_stamp) # still the old hash: the next update compiles again + self.assertEqual((self.eng / setup.EXE).read_bytes(), binary("0.1.42")) + + def test_a_poisoned_stamp_is_compiled_again(self): + """The state #2054 found: the new source hash and version in BUILD.json, the old binary beside it.""" + (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"})) + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.compiles, 1) + self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built) + + def test_a_healthy_install_is_left_alone(self): + (self.eng / setup.EXE).write_bytes(binary("0.1.43")) + (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"})) + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.compiles, 0) + + +class UpdateInstalledEngine(unittest.TestCase): + def test_a_poisoned_stamp_makes_the_update_compile(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + eng = root / "engine" + eng.mkdir() + (eng / setup.EXE).write_bytes(binary("0.1.42")) + (eng / "BUILD.json").write_text(json.dumps({"source": "local", "version": "0.1.43", "archs": [86], + "vision": "none", "src": "newhash"})) + built = [] + with mock.patch.object(setup, "ROOT", root), \ + mock.patch.object(setup, "source_hash", lambda parts: "newhash"), \ + mock.patch.object(setup, "source_version", lambda: "0.1.43"), \ + mock.patch.object(setup, "update_engine_gpu", lambda tk: dict(GPU)), \ + mock.patch.object(setup, "get_llama_cpp", lambda: Path("llama")), \ + mock.patch.object(setup, "build_engine", lambda *a, **k: built.append(a)), \ + mock.patch.object(setup, "say", lambda *a, **k: None): + setup.update_installed_engine("http://x", 13) + self.assertEqual(len(built), 1) + built.clear() + (eng / setup.EXE).write_bytes(binary("0.1.43")) + setup.update_installed_engine("http://x", 13) + self.assertEqual(built, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 80fc2d70..30d3978b 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -2,6 +2,8 @@ writing and the comparison. Light: no GPU, no Strata server, a few seconds.""" from __future__ import annotations +import contextlib +import io import json import os import sys @@ -276,6 +278,54 @@ class ReportTests(unittest.TestCase): self.assertEqual(B.gpu_selection({"gpu": "0,2"}), [0, 2]) self.assertEqual(B.gpu_selection({}, None), []) + def test_the_slug_names_mixed_cards_one_by_one(self): + """#2062: two different cards are not N copies of the first.""" + a, b = "NVIDIA GeForce RTX 5070 Ti", "NVIDIA RTX A4000" + self.assertEqual(B.gpu_slug({"gpu": [a]}), "rtx-5070-ti") + self.assertEqual(B.gpu_slug({"gpu": [a, b]}), "rtx-5070-ti-plus-rtx-a4000") + self.assertEqual(B.gpu_slug({"gpu": [b, a]}), "rtx-a4000-plus-rtx-5070-ti") + self.assertEqual(B.gpu_slug({"gpu": [b, b]}), "2x-rtx-a4000") + self.assertEqual(B.gpu_slug({"gpu": [b, a, b]}), "2x-rtx-a4000-plus-rtx-5070-ti") + + def test_a_card_the_pc_s_nvidia_smi_does_not_list_is_the_servers_own(self): + """#2001: the engine on an Intel Arc beside a GeForce: the report names the Arc (the name the server reads).""" + srv = FakeStrata() + self.addCleanup(srv.stop) + nv = {"gpus": [{"name": "NVIDIA GeForce RTX 3080 Ti", "vram_mib": 12288, "driver": "560.1"}], "cuda": "12.6"} + with mock.patch.object(B, "gpu_info_local", return_value=nv), mock.patch.object( + B, "try_json", side_effect=lambda base, path, *a, **k: ( + {"hardware_static": {"gpu_name": "Intel Arc Pro B70"}} if path == "/metrics" else {})): + m = B.collect_machine(srv.base, "", {"backend": "sycl"}) + self.assertEqual((m["gpu"], m["cuda"]), (["Intel Arc Pro B70"], None)) + + def test_a_bench_server_never_saves_over_the_users_profile(self): + """#2088: --expert-profile-save writes the profile at quit; the bench's own server runs without it.""" + cfg = {"args": ["--expert-profile", "p.bin", "--expert-profile-save", "p.bin", "--spec", "4"]} + safe, removed = B.without_profile_save(cfg) + self.assertTrue(removed) + self.assertEqual(safe["args"], ["--expert-profile", "p.bin", "--spec", "4"]) + self.assertEqual(cfg["args"][3], "p.bin") # the input is not changed + safe, removed = B.without_profile_save({"args": ["--expert-profile-save=p.bin", "--spec", "4"]}) + self.assertEqual((safe["args"], removed), (["--spec", "4"], True)) + same = {"args": ["--spec", "4"]} + self.assertEqual(B.without_profile_save(same), (same, False)) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as d: + c = Path(d) / "strata-x.json" + c.write_text(json.dumps(cfg)) + with mock.patch.object(B.subprocess, "Popen") as popen, contextlib.redirect_stderr(io.StringIO()): + B.start_server(c, 8080, None, Path(d) / "run.log") + used = Path(popen.call_args[0][0][popen.call_args[0][0].index("--config") + 1]) + self.assertNotIn("--expert-profile-save", json.loads(used.read_text())["args"]) + self.assertIn("--expert-profile-save", json.loads(c.read_text())["args"]) # the user's file is as it was + + def test_an_attached_server_is_not_stopped(self): + """#2088: with --url the bench only reads; the server it did not start keeps running.""" + srv = FakeStrata() + self.addCleanup(srv.stop) + with tempfile.TemporaryDirectory() as d, mock.patch.object(B, "stop_server") as stop: + self.assertEqual(self.run_main(srv, d), 0) + stop.assert_not_called() + def test_names(self): m = {"gpu": ["NVIDIA GeForce RTX 3060"], "model": "Qwen3.8 Flash-Next", "quant": "IQ3_XXS"} self.assertEqual(B.results_dir_name(m, "2026-10-10"), "2026-10-10-community-rtx-3060-qwen3-8-flash-next-iq3-xxs")