From 70f4240728242dc8c64909826efb4fc1e2b772d2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 00:08:41 +0200 Subject: [PATCH 1/4] Fix #3441, #3075: a drifted tool-call opener is read as the call; a call for a tool the request did not declare stays text A whose opener drops the word function (<=NAME>, , ) is read as when NAME is a declared tool. The answer follows the rule the reasoning already had (#804): a call counts only for a declared tool. Chat Completions and /v1/messages requests that declared no tools get the text back; the Responses route keeps its Codex compaction behaviour. Blocks that open like a call but do not read as one are counted in the server window. --- docs/DETAILS.md | 6 ++ serve/frontend.py | 71 +++++++++++++++++- serve/server.py | 21 ++++-- serve/test_mcp.py | 5 +- serve/test_server.py | 35 +++++++++ serve/test_tool_call_envelope.py | 121 +++++++++++++++++++++++++++++++ 6 files changed, 250 insertions(+), 9 deletions(-) create mode 100644 serve/test_tool_call_envelope.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 1432c709..dbcf4e43 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -991,6 +991,12 @@ print(r.choices[0].message.content) long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every 15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing the connection or pressing stop in your app really stops the model, so the next request starts at once. +- **Which tool calls come back as calls.** A call counts only when it names a tool the request declared. A call for + another name, or any call in a Chat Completions or Anthropic request that declared no tools, is returned as the + text it was written as, so a client never runs a tool it did not offer (the Responses route keeps its own rule + for Codex's compaction requests). A call whose envelope drifted by a token, `<=NAME>`, `` or `` + instead of ``, is read as the call when NAME is a declared tool. A `` block that still + does not read as a call is counted in the server window. - **Tool calls in other forms (opt-in).** `"tool_call_recovery": true` in `strata-.json` reads a call of a tool the request declared also when the model writes it as `` instead of ``, as JSON (`{"name": ..., "arguments": ...}`) inside ``, as a `` block at the start of a line diff --git a/serve/frontend.py b/serve/frontend.py index 3fda9c56..4cf0b4fa 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -682,6 +682,10 @@ CALL_END = "" PARAM_END = "" FUNC_START = "` (the word `function` dropped), ``, ``, or the bare `` +_LOOSE_OPEN = re.compile(r"<\s*(?:function\s*[=:]\s*|=\s*)?([A-Za-z0-9_.\-]+)\s*>") +_LOOSE_PART = re.compile(r"<\s*(?:function[ \t]*[=:]?\s*|=\s*)?[A-Za-z0-9_.\-]*\s*$") def param_end(text: str, final: bool = False) -> int: @@ -880,11 +884,19 @@ class OutputParser: until it is complete, so clients never see `` blocks that opened like a call and were returned as text # stream_tools: a tool call is also reported while it is being written - "tool_start" (its name and id) as # soon as the name is known, then "tool_args" pieces of its JSON arguments (string parameters character by # character; other types whole, once complete) - before the final "tool_call". Without it, a client sees @@ -913,6 +925,30 @@ class OutputParser: self.fence, self.line, self.ticks = snap return ok + def _callable(self, name: str) -> bool: + """#3075: may a call for `name` be a call? A tool the request declared (or its Responses spelling); with + none declared, only where `declared_only` is off.""" + if not self.schemas: + return not self.declared_only + return name in self.schemas or name in self._alias + + def _loose_open(self, after: str): + """#3441: `after` (text after a ``, whitespace dropped) opens a call in a drifted form that names a + declared tool -> (name, length of the opener); "wait" while it may still become one; None otherwise.""" + m = _LOOSE_OPEN.match(after) + if m: + name = m.group(1) + return (name, m.end()) if self._callable(name) else None + if ">" in after or "\n" in after or not after.startswith("<"): + return None + if _LOOSE_PART.match(after): + bare = after[1:].strip().lstrip("=").strip() + if after[1:].lstrip().startswith(("=", "function")): + return "wait" + if any(k.startswith(bare) for k in list(self.schemas) + list(self._alias) if isinstance(k, str)): + return "wait" + return None + def _follower(self, after: str) -> str: """recover: what a `` followed (after whitespace) by `after` opens: "call" (``), "json" (`{`), "wait" (not decided yet) or "text".""" @@ -1327,7 +1363,24 @@ class OutputParser: # it is prose that names the format ("I'll use a block") - content, not a malformed call # that ends the request. Until its follower has arrived it is held, like a partial tag. after = self.buf[i + len(CALL_START):].lstrip() + if self.schemas and not after.startswith(FUNC_START): + loose = self._loose_open(after) + if loose == "wait": # may still become one: held like a partial tag + j = i + while j > 0 and self.buf[j - 1] == "\n": + j -= 1 + if j > 0: + out.append(Event("content", self._track(self.buf[:j]))) + self.buf = self.buf[j:] + return out + if loose: # #3441: `<=NAME>` etc. is `` + at = len(self.buf) - len(after) + self.buf = self.buf[:at] + FUNC_START + loose[0] + ">" + after[loose[1]:] + continue kind = self._follower(after) if self.recover else None + if (after.startswith("<") and kind is None and not FUNC_START.startswith(after) + and not after.startswith(FUNC_START)): + self.unread += 1 if kind in ("param", "json"): if i and self.buf[:i].strip(): out.append(Event("content", self._track(self.buf[:i].rstrip("\n")))) @@ -1352,6 +1405,22 @@ class OutputParser: out.append(Event("content", self._track(self.buf[:j]))) self.buf = self.buf[j:] return out + if self.schemas or self.declared_only: + # #3075: a call counts only for a declared tool; the name must be complete to tell + gt = after.find(">") + nl = after.find("\n") + if gt < 0 and nl < 0: + j = i + while j > 0 and self.buf[j - 1] == "\n": + j -= 1 + if j > 0: + out.append(Event("content", self._track(self.buf[:j]))) + self.buf = self.buf[j:] + return out + if gt >= 0 and (nl < 0 or gt < nl) and not self._callable(after[len(FUNC_START):gt].strip()): + out.append(Event("content", self._track(self.buf[:i + len(CALL_START)]))) + self.buf = self.buf[i + len(CALL_START):] + continue if i and self.buf[:i].strip(): out.append(Event("content", self._track(self.buf[:i].rstrip("\n")))) self.buf = self.buf[i + len(CALL_START):] diff --git a/serve/server.py b/serve/server.py index 96965110..31409aec 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4763,18 +4763,20 @@ class Service: f"{el:.0f} s", flush=True) return now - def run(self, ids, thinking, tools, max_new, sampling, cancel, force=None) -> Iterator[tuple[str, object]]: + def run(self, ids, thinking, tools, max_new, sampling, cancel, force=None, + declared_only=False) -> Iterator[tuple[str, object]]: """The request's events (see _run); with "prevent_sleep" in the config, the PC stays awake while it runs or waits.""" ka = self.keep_awake if ka is not None: ka.acquire() try: - yield from self._run(ids, thinking, tools, max_new, sampling, cancel, force) + yield from self._run(ids, thinking, tools, max_new, sampling, cancel, force, declared_only) finally: if ka is not None: ka.release() - def _run(self, ids, thinking, tools, max_new, sampling, cancel, force=None) -> Iterator[tuple[str, object]]: + def _run(self, ids, thinking, tools, max_new, sampling, cancel, force=None, + declared_only=False) -> Iterator[tuple[str, object]]: """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}). `force` (forced_call): the opening of the call the reply must make - see prepare().""" # the model card's sampling for this thinking state, then the config's block, then the Chat settings shared with @@ -4802,7 +4804,8 @@ class Service: print(f"[strata] thinking capped at {max_new - reserve} of max_tokens {max_new} to leave room for " f"the answer (budget {budget})", flush=True) budget = max(1, max_new - reserve) - parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True, recover=self.tool_call_recovery) + parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True, recover=self.tool_call_recovery, + declared_only=declared_only) detok, n, finish = Detokenizer(self.tok), 0, "length" run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) @@ -5284,6 +5287,10 @@ class Service: self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as " f"reasoning (quoted, or the turn did not end on a stop)", flush=True) + if parser.unread: + print(f"[strata] {parser.unread} block(s) in the answer did not read as a call of a declared " + "tool and went back as text (a name the request did not declare, or a form the template does " + "not use)", flush=True) if stops is not None and stops.hit is None and stops.held: yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), @@ -5412,7 +5419,7 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, messages = list(messages) while True: text, reasoning, calls, own_calls = [], [], [], 0 - for kind, x in svc.run(ids, thinking, tools, max_new, sampling, cancel): + for kind, x in svc.run(ids, thinking, tools, max_new, sampling, cancel, declared_only=True): if kind == "done": done = x continue @@ -5533,7 +5540,7 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel calls = 0 streamed = {} # tool call id -> index, for calls sent piece by piece finished = set() # ... and the ones whose final tool_call came (#211) - for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force): + for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force, declared_only=True): if kind == "ping": # a PP line: the prompt is being read and there is nothing to say yet. It used to be only the SSE comment; # now it carries the progress when the client asked, and stays the comment when there is nothing to report. @@ -5659,7 +5666,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can return ("content_block_stop", {"type": "content_block_stop", "index": index}) streamed, finished = set(), set() # calls sent piece by piece; those whose final tool_call came (#211) - for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel, force=force): + for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel, force=force, declared_only=True): if kind == "ping": yield None continue diff --git a/serve/test_mcp.py b/serve/test_mcp.py index c80c5d01..2c414ef0 100644 --- a/serve/test_mcp.py +++ b/serve/test_mcp.py @@ -326,7 +326,10 @@ class ToolLoop(unittest.TestCase): self.assertNotIn("fake__echo", self.engine.prompt_text(0)) cs = self.chunks(text) self.assertFalse([c for c in cs if "strata_mcp" in c]) - self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "tool_calls") # returned to the client as always + # #3075: a request that declared no tools gets no tool call back; the call is the text it was written as + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop") + self.assertFalse([tc for c in cs for tc in c["choices"][0]["delta"].get("tool_calls") or []]) + self.assertIn("", "".join(c["choices"][0]["delta"].get("content") or "" for c in cs)) self.assertEqual(len(self.engine.prompts), 1) self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran for req in ({"strata_mcp": "yes"}, {"strata_mcp": 1}): # only a real true opts in diff --git a/serve/test_server.py b/serve/test_server.py index 4249585d..233f9e36 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -4411,6 +4411,41 @@ class ForcedToolChoice(unittest.TestCase): finish = c["choices"][0]["finish_reason"] or finish return finish, [(names[i], json.loads(args[i])) for i in sorted(names)], reasoning + def says(self, answer): + """The engine answers `answer` after an empty thought.""" + def generate(ids, max_new, sampling, cancel, embeddings=None): + self.engine.prompts.append(list(ids)) + yield from self.tok.encode("\n\n" + answer) + self.tok.encode("<|im_end|>", parse_special=True) + self.engine.generate = generate + + def test_a_call_the_request_never_offered_stays_text(self): + """#3075: the model goes on writing the format it was shown; a request that offered no such tool gets text.""" + from serve.frontend import CALL_END, CALL_START + answer = ("I will check that.\n" + CALL_START + "\n\n\n2+2\n\n" + "\n" + CALL_END + "\nHere is the report.") + self.says(answer) + for label, extra in {"nothing declared": {"tools": []}, "tool_choice none": {"tool_choice": "none"}, + "other tools": {}}.items(): + for stream in (False, True): + with self.subTest(case=label, stream=stream): + code, b = self.openai(stream=stream, **extra) + finish, calls, _ = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("stop", []), b) + if not stream: + content = b["choices"][0]["message"]["content"] or "" + self.assertIn("Here is the report.", content) + self.assertIn("", content) + + def test_a_call_with_a_dropped_function_keyword_is_still_the_call(self): + """#3441: `<=search>` for ``, as a model under a large tool surface writes it.""" + from serve.frontend import CALL_END, CALL_START + self.says(CALL_START + "\n<=search>\n\n2+2\n\n\n" + CALL_END) + for stream in (False, True): + with self.subTest(stream=stream): + code, b = self.openai(stream=stream) + finish, calls, _ = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})]), b) + def test_required_and_named_after_the_thinking(self): for choice in ("required", self.NAMED): for stream in (False, True): diff --git a/serve/test_tool_call_envelope.py b/serve/test_tool_call_envelope.py new file mode 100644 index 00000000..75ec2ad2 --- /dev/null +++ b/serve/test_tool_call_envelope.py @@ -0,0 +1,121 @@ +"""#3441 (a call whose envelope drifted by a token) and #3075 (a call for a tool the request never declared).""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import frontend # noqa: E402 + +TOOLS = [{"name": "functions.exec", "parameters": {"properties": {"input": {"type": "string"}}}}, + {"name": "shell", "parameters": {"properties": {"cmd": {"type": "string"}}}}, + {"name": "ns.web_search", "parameters": {"properties": {"q": {"type": "string"}}}}] + + +def body(opener, param="input", value="1+1", name=None): + return f"\n{opener}\n\n{value}\n\n\n" + + +def run(text, width=0, **kw): + """-> (events, parser); `width` 0 feeds the text whole, else that many characters at a time.""" + p = frontend.OutputParser(thinking=False, stream_tools=True, **kw) + evs = [] + if width: + for k in range(0, len(text), width): + evs += p.feed(text[k:k + width]) + else: + evs += p.feed(text) + evs += p.finish() + return evs, p + + +def calls(evs): + return [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"] + + +def text(evs): + return "".join(e.text or "" for e in evs if e.kind == "content") + + +class DriftedEnvelope(unittest.TestCase): + def test_a_dropped_function_keyword_is_still_the_call(self): + for opener in ("<=functions.exec>", "", "", + "", "<= functions.exec >"): + for width in (0, 1, 2, 3, 7): + with self.subTest(opener=opener, width=width): + evs, p = run(body(opener), width, tools=TOOLS) + self.assertEqual(calls(evs), [("functions.exec", {"input": "1+1"})]) + self.assertEqual(text(evs), "") + self.assertEqual(p.unread, 0) + + def test_the_template_form_is_unchanged(self): + evs, p = run(body(""), 0, tools=TOOLS) + self.assertEqual(calls(evs), [("functions.exec", {"input": "1+1"})]) + + def test_an_undeclared_name_in_a_drifted_opener_stays_text(self): + for width in (0, 1, 4): + with self.subTest(width=width): + raw = body("<=missing>") + evs, p = run(raw, width, tools=TOOLS) + self.assertEqual(calls(evs), []) + self.assertEqual(text(evs), raw) + self.assertEqual(p.unread, 1) + self.assertFalse([e for e in evs if e.kind == "tool_start"]) + + def test_prose_about_the_tag_is_not_a_drift(self): + for raw in ("Use a block for that.", " then the name"): + evs, p = run(raw, 3, tools=TOOLS) + self.assertEqual(calls(evs), []) + self.assertEqual(text(evs), raw) + self.assertEqual(p.unread, 0) + + def test_streamed_and_whole_agree(self): + raw = "Let me run it.\n" + body("<=shell>", "cmd", "ls") + "\nDone." + whole, _ = run(raw, 0, tools=TOOLS) + for width in (1, 2, 5, 11): + streamed, _ = run(raw, width, tools=TOOLS) + self.assertEqual(calls(streamed), calls(whole)) + self.assertEqual(text(streamed), text(whole)) + self.assertEqual(calls(whole), [("shell", {"cmd": "ls"})]) + self.assertEqual(text(whole), "Let me run it.Done.") + + +class OnlyDeclaredTools(unittest.TestCase): + def test_a_call_for_another_tool_stays_text(self): + raw = body("", "symbol", "600076") + for width in (0, 1, 3, 9): + with self.subTest(width=width): + evs, p = run("I will check.\n" + raw, width, tools=TOOLS) + self.assertEqual(calls(evs), []) + self.assertFalse([e for e in evs if e.kind in ("tool_start", "tool_args")]) + self.assertEqual(text(evs), "I will check.\n" + raw) + + def test_a_declared_call_after_an_undeclared_one_is_still_a_call(self): + raw = body("") + "\n" + body("", "cmd", "ls") + evs, p = run(raw, 5, tools=TOOLS) + self.assertEqual(calls(evs), [("shell", {"cmd": "ls"})]) + self.assertIn("get_indicators", text(evs)) + + def test_the_responses_spelling_of_a_namespace_tool_counts(self): + evs, p = run(body("", "q", "x"), 4, tools=TOOLS) + self.assertEqual(calls(evs), [("ns__web_search", {"q": "x"})]) + + def test_no_tools_declared(self): + raw = body("", "q", "2+2") + evs, p = run(raw, 3, tools=None, declared_only=True) + self.assertEqual((calls(evs), text(evs)), ([], raw)) + evs, p = run(raw, 3, tools=[], declared_only=True) + self.assertEqual((calls(evs), text(evs)), ([], raw)) + # without the flag (the Responses route: a Codex compaction request keeps its tools in the prompt only) + evs, p = run(raw, 3, tools=None) + self.assertEqual(calls(evs), [("search", {"q": "2+2"})]) + + def test_the_reasoning_state_is_as_before(self): + p = frontend.OutputParser(thinking=True, tools=TOOLS, stream_tools=True) + evs = p.feed("think " + body("", "cmd", "ls") + "\n\nok") + p.finish() + self.assertEqual(calls(evs), []) + + +if __name__ == "__main__": + unittest.main() From 366c8dbaaef6ba286fd7d9be7dc82ca1d3a30ed4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 00:13:14 +0200 Subject: [PATCH 2/4] Fix #3503: the Linux cuda12 engine package carries sm_60/61/70; the source Dockerfile builds it packaging/build_cuda_linux.sh is the recipe for the Linux cuda13 and cuda12 packages (cuda12: CUDA 12.9, 60;61;70;75;80;86;89, STRATA_EXPERIMENTAL_SM60=ON, driver 575.51). package_engine.py refuses a cuda12 package without sm_60, sm_61 or sm_70, so the 0.2.1 mistake (sm_75/86/89 only, a P100 container in a restart loop) cannot ship again. The root Dockerfile takes the CUDA image from CUDA_IMAGE: the CUDA 12 case turns on the Pascal/Volta build when an architecture below 75 is listed, names the package cuda12 with the matching driver, and the terminal stage has git (package_terminal.py calls it). --- Dockerfile | 12 ++++-- docs/DOCKER.md | 5 ++- packaging/ENGINE-COMPONENT.md | 3 +- packaging/build_cuda_linux.sh | 53 ++++++++++++++++++++++++++ packaging/package_engine.py | 5 +++ tests/terminal/test_engine_manifest.py | 11 +++++- 6 files changed, 83 insertions(+), 6 deletions(-) create mode 100644 packaging/build_cuda_linux.sh diff --git a/Dockerfile b/Dockerfile index 33cf7679..f6560ee1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,6 +5,8 @@ # # docker build -t strata:src . # RTX 20/30/40/50 (compiles for each, ~25 min) # docker build -t strata:src --build-arg CUDA_ARCHITECTURES=86 . # one card only (faster); 86 = RTX 30, 89 = RTX 40, 120 = RTX 50 +# docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 \ +# --build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 . # GTX 10 / P100 / V100 (driver 575+) # docker run --rm --gpus all -p 127.0.0.1:8080:8080 --ulimit memlock=-1 --shm-size 2g --stop-timeout 120 \ # -v strata-data:/data -e MODEL=IQ3_XXS -e API_KEY=change-me-please-123 strata:src # @@ -35,7 +37,9 @@ RUN /venv/bin/python -c "import setup; print(setup.get_llama_cpp())" RUN set -e; \ real=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do real="$real;${a}-real"; done; real=${real#;}; \ last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ + sm60=OFF; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do if [ "$a" -lt 75 ]; then sm60=ON; fi; done; \ /venv/bin/cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \ + -DSTRATA_EXPERIMENTAL_SM60=$sm60 \ -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_MMQ_KQUANTS=ON \ "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" -DSTRATA_GGML_DIR=/src/third_party/llama.cpp; \ /venv/bin/cmake --build build --target strata strata_kq -j "$(nproc)"; \ @@ -50,19 +54,21 @@ RUN set -e; \ [ -f build/libstrata_kq.so ] && cp build/libstrata_kq.so /stage/ || true; \ [ -f build-vision/bin/strata-vision ] && cp build-vision/bin/strata-vision /stage/ || true; \ ver="${ENGINE_VERSION:-$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1)}"; \ - echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"13.0\", \"portable\": true}" > /stage/BUILD.json; \ + cudafull=$(nvcc --version | sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1); cudamajor=${cudafull%%.*}; \ + if [ "$cudamajor" = 13 ]; then mindriver=580.65; else mindriver=575.51; fi; \ + echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"$cudafull\", \"portable\": true}" > /stage/BUILD.json; \ python3 packaging/collect_libs.py --binary build/strata --search /usr/local/cuda/lib64 --out /stage --also 'libcublasLt.so*'; \ archs=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do archs="$archs --arch sm_$a"; done; \ last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ python3 packaging/package_engine.py --src /stage --backend cuda --version "$ver" --out /engine $archs --arch "compute_$last" \ - --min-driver nvidia=580.65 --variant cuda13 --platform linux-x86_64 --build-id "docker-source-${ver}-cuda13.0" --include SYSTEM-LIBS.txt --include 'libstrata_kq*' \ + --min-driver nvidia=$mindriver --variant cuda$cudamajor --platform linux-x86_64 --build-id "docker-source-${ver}-cuda${cudafull}" --include SYSTEM-LIBS.txt --include 'libstrata_kq*' \ --include strata-vision; \ for d in /engine/*/; do python3 packaging/package_engine.py --verify "$d"; python3 packaging/binary_deps.py "$d"; done # ---- 2. the Terminal (the release archive, built here) FROM ${RUNTIME_BASE} AS terminal ENV DEBIAN_FRONTEND=noninteractive -RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates && rm -rf /var/lib/apt/lists/* +RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates git && rm -rf /var/lib/apt/lists/* COPY . /src/ RUN python3 /src/packaging/package_terminal.py --out /out --cache /cache \ && mkdir -p /opt/strata \ diff --git a/docs/DOCKER.md b/docs/DOCKER.md index f4b5ee62..7b22aa84 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -297,7 +297,10 @@ library inside the finished image. A package that fails any of these stops the b `docker/smoke-test.sh` runs the checks we ran on real cards (serves, key, chat, tool call, monitor, clean stop, memory freed, restart); see its first lines for the variables. **From source.** `docker build -t strata:src .` in the repository compiles the CUDA 13 engine inside Docker, makes the package -and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, much faster). For AMD and Intel +and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, much faster). For a GTX 10, P100 or +V100 build the CUDA 12 variant: `docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 +--build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 .` (the build turns on the Pascal / Volta code by itself +when an architecture below 75 is listed, and names the package `cuda12` with driver 575.51). For AMD and Intel builds from source see [AMD_HIP.md](AMD_HIP.md) and [INTEL.md](INTEL.md); then package the result with `packaging/package_engine.py` and use `docker/build.sh`. diff --git a/packaging/ENGINE-COMPONENT.md b/packaging/ENGINE-COMPONENT.md index db7c1221..3a633e0d 100644 --- a/packaging/ENGINE-COMPONENT.md +++ b/packaging/ENGINE-COMPONENT.md @@ -99,7 +99,8 @@ the manifest file (which holds every file's hash), used as the package's digest | `windows-x86_64` cuda, variant `cuda13` | the owner PC, the same cmake line as the release zips (CUDA 13.0, `75;86;89;120` real + `120` PTX, `STRATA_PORTABLE=ON`) | `strata.exe`, `strata_kq.dll`, `strata-vision.exe` (reused, unchanged since 0.1.44), `BUILD.json` | `min_driver` nvidia 580.65 | | `windows-x86_64` cuda, variant `cuda12` | the owner PC (CUDA 12.9, `60;61;70;75;80;86;89` real + `89` PTX, `STRATA_EXPERIMENTAL_SM60=ON`) | the same four files | experimental, `min_driver` nvidia 575.51; the CUDA 13 build wins when both fit | | `windows-x86_64` hip | the owner PC, `tools/hip/build_windows.bat` (ROCm 10.2 nightly wheels) then `tools/hip/package_windows.py` | `strata.exe`, `strata-device.exe`, the ROCm DLLs and the rocBLAS/hipBLASLt kernels of the zip (`--tree`) | no Windows AMD test machine yet; with `STRATA_NO_VISION` unset it also builds the two picture readers (`strata-vision.exe` on the CPU, `strata-vision-hip.exe` on the GPU) | -| `linux-x86_64` cuda | a Linux box with the CUDA toolkit | `strata`, `libstrata_kq.so`, `libcudart/libcublas/libcublasLt` (13.x) | the GPU driver's `libcuda` stays the PC's | +| `linux-x86_64` cuda, variant `cuda13` | a Linux box with the CUDA 13 toolkit, `VARIANT=cuda13 packaging/build_cuda_linux.sh` | `strata`, `libstrata_kq.so`, `libcudart/libcublas/libcublasLt` (13.x) | the GPU driver's `libcuda` stays the PC's | +| `linux-x86_64` cuda, variant `cuda12` | a Linux box with CUDA 12.9, `VARIANT=cuda12 packaging/build_cuda_linux.sh` (`60;61;70;75;80;86;89` real + `89` PTX, `STRATA_EXPERIMENTAL_SM60=ON`) | the same files with the 12.x libraries | experimental, `min_driver` nvidia 575.51; the Pascal and Volta package (the 0.2.1 one lacked sm_60 / 61 / 70, #3503); `package_engine.py` refuses a cuda12 package without them | | `linux-x86_64` hip | a box with ROCm (the Python wheels are enough) | `strata`, the HIP runtime, hipBLAS/hipBLASLt/rocBLAS, comgr + libLLVM, `rocblas/library` and `hipblaslt/library` for the listed gfx archs; `packaging/build_hip_linux.sh` builds it with both picture readers | | `linux-x86_64` hip, variant `rx6000` (RX 6000, gfx1030 / gfx1031) | `VARIANT=rx6000 packaging/build_hip_linux.sh` in the jammy chroot, ROCm 7.13.0a20260515 `gfx103X-all` wheels | the same set as the other HIP packages, with `rocblas/library` for gfx1030 / gfx1031; no `hipblaslt/library` kernels exist for them and no `tuning/` table | built, not tested on a real RX 6000 card (the manifest notes say so). `windows-x86_64` hip, variant `rdna2`: the same archs from `tools/hip/build_windows.bat` with `STRATA_HIP_ARCHS=gfx1030;gfx1031`, packaged with `--variant rdna2`. A PC with an RX 7000 / 9000 card beside an RX 6000 one never takes it (`engine_component.hip_preference`) | | `linux-x86_64` hip, gfx1103 (Radeon 780M / Phoenix iGPU) | `packaging/build_hip_gfx1103.sh` on the mini PC (TheRock gfx110X-all SDK) | the same set as the gfx1200/1201 package, with `rocblas/library` and `hipblaslt/library` for gfx1103 (600 MiB) | experimental, unvalidated: the iGPU resets now and then (MES REMOVE_QUEUE); never kill the engine mid-request; run configs set `STRATA_NO_ARENA_THP=1`. `engine_component.resolve` picks a HIP package only when its `archs` list a gfx target the Linux kfd topology reports | diff --git a/packaging/build_cuda_linux.sh b/packaging/build_cuda_linux.sh new file mode 100644 index 00000000..6c07a5ba --- /dev/null +++ b/packaging/build_cuda_linux.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# Build the Linux CUDA engine package for the release feed. +# +# VARIANT=cuda12 packaging/build_cuda_linux.sh # CUDA 12.9: GTX 10 (Pascal), Tesla P100, V100, and the newer cards up to sm_89 +# VARIANT=cuda13 packaging/build_cuda_linux.sh # CUDA 13: RTX 20 and newer (sm_75 .. sm_120) +# +# Run it on a Linux x86_64 box with the CUDA toolkit of that variant on PATH (nvcc), a Python 3 venv with requirements.txt and +# requirements-build.txt, and the pinned llama.cpp in third_party/llama.cpp (python -c "import setup; setup.get_llama_cpp()"). +# The package lands in $OUT (default ./out-engine-). Nothing is uploaded. +# +# The cuda12 package is the one the feed and docs/DOCKER.md offer to Pascal and Volta cards, so it needs machine code for sm_60, +# sm_61 and sm_70 and the -DSTRATA_EXPERIMENTAL_SM60=ON build (#3503: the 0.2.1 package had sm_75 / 86 / 89 only, and a P100 +# container restarted in a loop with "this PC's GPU is sm_60"). packaging/package_engine.py refuses a cuda12 package without them. +set -eu +variant=${VARIANT:-cuda13} +repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P) +case "$variant" in + cuda12) archs=${ARCHS:-60;61;70;75;80;86;89}; mindriver=575.51; sm60=ON ;; + cuda13) archs=${ARCHS:-75;86;89;120}; mindriver=580.65; sm60=OFF ;; + *) echo "build_cuda_linux.sh: VARIANT must be cuda12 or cuda13" >&2; exit 2 ;; +esac +out=${OUT:-$repo/out-engine-$variant} +build=${BUILD:-$repo/build-$variant} +py=${PYTHON:-python3} +cudafull=$(nvcc --version | sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1) +case "$variant:$cudafull" in + cuda12:12.*|cuda13:13.*) ;; + *) echo "build_cuda_linux.sh: $variant needs the matching CUDA toolkit; nvcc here is ${cudafull:-missing}" >&2; exit 2 ;; +esac + +real=""; for a in $(echo "$archs" | tr ';,' ' '); do real="$real;${a}-real"; done; real=${real#;} +last=$(echo "$archs" | tr ';,' ' ' | awk '{print $NF}') +cd "$repo" +cmake -G Ninja -S . -B "$build" -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \ + -DSTRATA_EXPERIMENTAL_SM60=$sm60 -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_MMQ_KQUANTS=ON \ + "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" -DSTRATA_GGML_DIR="$repo/third_party/llama.cpp" +cmake --build "$build" --target strata strata_kq -j "$(nproc)" + +ver=$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1) +stage=$(mktemp -d "${TMPDIR:-/tmp}/strata-engine-stage.XXXXXX") +trap 'rm -rf "$stage"' EXIT +cp "$build/strata" "$stage/" +[ -f "$build/libstrata_kq.so" ] && cp "$build/libstrata_kq.so" "$stage/" +echo "{\"version\": \"$ver\", \"source\": \"packaging/build_cuda_linux.sh\", \"archs\": \"$archs\", \"cuda\": \"$cudafull\", \"portable\": true}" > "$stage/BUILD.json" +"$py" packaging/collect_libs.py --binary "$build/strata" --search /usr/local/cuda/lib64 --out "$stage" --also 'libcublasLt.so*' +arch_args=""; for a in $(echo "$archs" | tr ';,' ' '); do arch_args="$arch_args --arch sm_$a"; done +mkdir -p "$out" +# shellcheck disable=SC2086 +"$py" packaging/package_engine.py --src "$stage" --backend cuda --version "$ver" --out "$out" $arch_args --arch "compute_$last" \ + --min-driver nvidia=$mindriver --variant "$variant" --platform linux-x86_64 --build-id "release-${ver}-${variant}-${cudafull}" \ + --include SYSTEM-LIBS.txt --include 'libstrata_kq*' +for d in "$out"/*/; do "$py" packaging/package_engine.py --verify "$d"; "$py" packaging/binary_deps.py "$d"; done +echo "built: $out" diff --git a/packaging/package_engine.py b/packaging/package_engine.py index 2c7c570a..86e58368 100644 --- a/packaging/package_engine.py +++ b/packaging/package_engine.py @@ -95,6 +95,11 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr raise SystemExit(f"unknown backend {backend!r}") if backend != "cpu" and not archs: raise SystemExit(f"a {backend} package needs at least one --arch (sm_86, gfx1201, ...)") + if backend == "cuda" and variant == "cuda12" and not any(a in ("sm_60", "sm_61", "sm_70") for a in archs): + # #3503: the cuda12 package is what the feed and docs/DOCKER.md offer to GTX 10 / P100 / V100; one built for + # sm_75 and up starts a restart loop on those cards ("this PC's GPU is sm_60") + raise SystemExit("refusing to package the cuda12 engine without sm_60, sm_61 or sm_70: it is the Pascal and Volta build " + "(CUDA 12.9, -DSTRATA_EXPERIMENTAL_SM60=ON, --arch sm_60 --arch sm_61 --arch sm_70 ...; see packaging/build_cuda_linux.sh)") if backend == "hip": from strata_control import hipblaslt_tuning problems = hipblaslt_tuning.check_stage(src, archs) diff --git a/tests/terminal/test_engine_manifest.py b/tests/terminal/test_engine_manifest.py index 2e388b49..a6652967 100644 --- a/tests/terminal/test_engine_manifest.py +++ b/tests/terminal/test_engine_manifest.py @@ -225,13 +225,22 @@ class Start(unittest.TestCase): def test_two_builds_of_one_version_prefer_the_newer_driver_when_both_fit(self): other = make_source(self.root / "src3") - old = package_engine.build(other, "cuda", "0.1.45", HERE, self.out, archs=("sm_86",), + old = package_engine.build(other, "cuda", "0.1.45", HERE, self.out, archs=("sm_60", "sm_86"), min_driver={"nvidia": "575.51"}, build_id="b-12", variant="cuda12") self.assertEqual(old.name, f"0.1.45-{HERE}-cuda-cuda12") self.assertEqual(ec.read_manifest(old).variant, "cuda12") self.assertEqual(Path(self.start(driver="610.0")).parent.resolve(), self.folder.resolve()) # 580.65 build wins self.assertEqual(Path(self.start(driver="576.0")).parent.resolve(), old.resolve()) # only the CUDA 12 one fits + def test_a_cuda12_package_without_pascal_or_volta_code_is_refused(self): + """#3503: the Linux cuda12 package shipped with 0.2.1 had sm_75/86/89 only; P100 containers restarted in a loop.""" + other = make_source(self.root / "src4") + with self.assertRaises(SystemExit) as caught: + package_engine.build(other, "cuda", "0.1.45", HERE, self.out, archs=("sm_75", "sm_86", "sm_89", "compute_89"), + min_driver={"nvidia": "575.51"}, build_id="b-12", variant="cuda12") + self.assertIn("sm_60", str(caught.exception)) + package_engine.build(other, "cuda", "0.1.45", HERE, self.out, archs=("sm_70", "sm_86"), build_id="b-13", variant="cuda12") + def test_a_good_package_does_not_hide_a_tampered_one(self): newer = package_engine.build(make_source(self.root / "src2"), "cuda", "0.1.46", HERE, self.out, archs=("sm_86",), build_id="b2") From f05725c3325760cf288fa245106e21662fc6fb51 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 00:37:50 +0200 Subject: [PATCH 3/4] Fix #3480: the HIP queue priming stands aside when GPU_MAX_HW_QUEUES is 1 or 2 With the runtime capped to two hardware queues the two primed queues are all of them, and the high-priority draft stream and the draft side stream share them: a 4K prompt on an RX 9060 XT read 681-753 tok/s primed and 1188-1238 unprimed. Primed only when the cap is 3 or more or unset; STRATA_HIP_QUEUE_PRIME=nn still forces it. HIP code only (gfx12, Linux). --- src/program/generate.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3cef8621..ab1e4480 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2233,7 +2233,7 @@ static double ple_direct_rows_per_s(strata::kernels::PleTable& t) { // it is the fast one). Streams are destroyed again; the runtime keeps the queues. // Two queues are enough (R9700, "nn": 0 slow of 32 fresh starts, unprimed 10 of 32); five (nnnnh) fixed the starts too but cost // decode 2 to 3.6% and two expert slots, four normal ones did not even fix the starts. -// STRATA_HIP_QUEUE_PRIME unset: gfx1200 / gfx1201 on Linux only, "nn"; "0": off; any other string is a spec +// STRATA_HIP_QUEUE_PRIME unset: gfx1200 / gfx1201 on Linux only, "nn" (not when GPU_MAX_HW_QUEUES is 1 or 2, #3480); "0": off; any other string is a spec // ('n' = a stream at the default priority, 'h' = at the highest) for experiments on other cards. static void prime_hw_queues() { const char* env = std::getenv("STRATA_HIP_QUEUE_PRIME"); @@ -2252,6 +2252,16 @@ static void prime_hw_queues() { (void) cudaGetLastError(); return; } + // #3480: with the runtime capped to two hardware queues (GPU_MAX_HW_QUEUES=1 or 2, the user's own setting) the two + // primed queues are all of them: the high-priority draft stream and the side stream share them and a 4K prompt + // reads 39% slower (RX 9060 XT, 681-753 against 1188-1238 tok/s). Not primed then; a spec in + // STRATA_HIP_QUEUE_PRIME still is. + const char* cap = std::getenv("GPU_MAX_HW_QUEUES"); + if (cap != nullptr && std::atoi(cap) >= 1 && std::atoi(cap) <= 2) { + std::fprintf(stderr, "strata generate: GPU queues not primed: GPU_MAX_HW_QUEUES=%s leaves none for the draft stream " + "(STRATA_HIP_QUEUE_PRIME=nn primes them anyway)\n", cap); + return; + } spec = "nn"; #endif } From 894f133b7d492382513cbe9673012d6c8e937bb8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 00:52:29 +0200 Subject: [PATCH 4/4] Fix #3465: after non-finite logits in a prompt window the retry reads the whole prompt batched The reporter's prompts ended in non-finite logits in the window that reads the prompt's last few tokens (after the last turn boundary), every time and on every retry, and passed with --short-read 0. The cause on their machine (a Windows VM, sm_89, a Broadwell AVX2 CPU, IQ3_S) was not reproduced on a P100 with a Broadwell Xeon, an RTX 3060 or a Core Ultra. The engine now reads the request that follows such a window with --short-read 0 for that one request, so the server's transparent retry succeeds instead of failing the same way. Nothing changes until a prompt window reports non-finite logits. STRATA_NAN_INJECT=1 exercises it. --- docs/DETAILS.md | 5 ++++- src/program/generate.cpp | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index dbcf4e43..2b8e9659 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -943,7 +943,10 @@ print(r.choices[0].message.content) conversation and every idle slot (a slot still running finishes its reply and is not kept after it) and reads its prompt from token 0. The server retries a request that had sent nothing yet once, transparently; a reply that had started ends as `"length"` with a line in the server window; a second fire on the retry ends the request with an - error (503 before an answer, an error event in a stream). With replicas, the server forgets what that replica held. + error (503 before an answer, an error event in a stream). When the flagged window was one that reads the prompt's + last few tokens (the part after the last turn boundary, read through the verify windows, `--short-read`), the retry + reads its whole prompt through the batched path instead (#3465: a reporter's prompts failed in that tail every time and + passed with `--short-read 0`); the engine prints a line saying so. With replicas, the server forgets what that replica held. `repeat_stop_tokens` stays as the backstop. The kernel writes only its flags and the host only reads them, so an answer without a NaN is the one the engine gives with `STRATA_NAN_GUARD=0`, which records no kernel: on an RTX 3080 with the RVN IQ3_S config at fixed expert sets (a chat replay of 8 turns on a 16K-token system prompt), the diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ab1e4480..8ab33cef 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -9199,6 +9199,10 @@ int main(int argc, char** argv) { bool live_ok = false; // #879: a window met non-finite logits: the next request drops every cached state first and reads from token 0 bool nan_flush = false; + // #3465: the non-finite logits came in a window that reads the PROMPT's tail (the last few tokens, read through + // the verify windows after the batched part). The retry reads that tail batched (--short-read 0 for one request): + // a reporter's prompts failed there every time and passed with --short-read 0. + bool nf_prompt_windows = false, short_read_off_once = false; std::vector checks; // STRATA_CKPT_POOL: the dropped checkpoints' storage, reused. STRATA_SLOT_CKPT_MOVE turns it on too: a moved // checkpoint frees nothing at the next prune, so every save would fault in fresh pages (17 -> 40-60 ms) @@ -9485,6 +9489,7 @@ int main(int argc, char** argv) { std::fflush(stderr); nf_hit = true; nan_flush = true; + if (std::strcmp(what, "prompt") == 0) nf_prompt_windows = true; return true; }; auto imgs_below = [&](const std::vector& all, int64_t L) { @@ -12363,6 +12368,10 @@ int main(int argc, char** argv) { // conversation and every idle batch slot go, and this prompt is read from token 0 (resume == 0 below) if (nan_flush) { nan_flush = false; + if (nf_prompt_windows) { + nf_prompt_windows = false; + short_read_off_once = o.short_read > 0; + } const size_t n_checks = checks.size(); live_ok = false; checks.clear(); @@ -12871,6 +12880,12 @@ int main(int argc, char** argv) { // STRATA_CKPT_REREAD compares a restored checkpoint with a batched re-read, so it keeps every read batched. static const bool no_short = std::getenv("STRATA_CKPT_REREAD") != nullptr; int64_t req_short_read = o.short_read; // STRATA_PIPELINE_SWITCH may set it per request (short_read=) + if (short_read_off_once) { // #3465: the request after non-finite logits in a prompt window + short_read_off_once = false; + req_short_read = 0; + std::fprintf(stderr, "strata serve: after non-finite logits in a prompt window (#3465): this request reads its " + "whole prompt through the batched path, none of it through the verify windows\n"); + } auto windows_ok = [&](int64_t a, int64_t b) -> bool { if (no_short || b - a > req_short_read) return false; if (sp.embd_rows != nullptr)