diff --git a/CMakeLists.txt b/CMakeLists.txt index 80e278b4..ddaecc42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -213,9 +213,16 @@ elseif(STRATA_ENABLE_CUDA) "CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal sm_60 or Volta sm_70 build is " "-DSTRATA_EXPERIMENTAL_SM60=ON; upstream does not support it.)") endif() - if(_base LESS 60) + if(_base LESS 52) message(FATAL_ERROR "CMAKE_CUDA_ARCHITECTURES '${CMAKE_CUDA_ARCHITECTURES}': even the experimental build " - "needs compute capability 6.0 (sm_60) or newer") + "needs compute capability 5.2 (sm_52, Maxwell) or newer") + endif() + # Maxwell (sm_52, #3218): one reporter built and ran this on two Quadro M6000 (CUDA 12.x, Qwen3.8-Flash-Next + # IQ1, about 22 t/s). It has no native half-precision arithmetic, so it is slower per byte than Pascal; only + # this opt-in build gets the floor. Warn, do not refuse. + if(_base LESS 60) + message(WARNING "Building for sm_${_base} (Maxwell): community-tested on one reporter's Quadro M6000 only, " + "no native half-precision arithmetic, CUDA 12.x toolkit required (docs/OLDER_GPUS.md).") endif() # #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not) if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 22bd4b65..45547388 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -502,7 +502,11 @@ applies at the next start. Network, key, MCP and program keys are not editable t decoding, with one generation per request. `jsonschema` is used when installed (`python -m pip install "jsonschema>=4.23,<5"`); without it the answer is only checked to be one JSON object. Malformed output returns **502** with `error.code: structured_output_failed`, an invalid schema **400**. JSON formats combined with tools or MCP are refused. - Streaming buffers the answer and emits content only after validation. + Streaming buffers the answer and emits content only after validation. Math answers often hold LaTeX such as `\alpha`, which is + not a valid JSON escape. Add `"repair_latex_escapes": true` to the `response_format` (or to `text.format` on `/v1/responses`) and, + only after the strict parse failed, the server doubles the backslashes that are not valid escapes and checks the answer again. + Valid output is never touched. `\b`, `\f`, `\n`, `\r`, `\t` and `\uXXXX` are valid JSON, so they stay: a `\beta` beside a `\alpha` + comes back with a backspace. Off by default. - `logit_bias` and token/bias pair lists work on CUDA and HIP engines without continuous batching ([LOGIT_BIAS.md](LOGIT_BIAS.md)). - Stop strings (`stop`, `stop_sequences`), `temperature`, `top_p`, `top_k`, `min_p` and `seed` are honored per request. `top_k` keeps at most 64 candidates. Penalties (`presence_penalty`, `frequency_penalty`, `repetition_penalty`, @@ -517,6 +521,21 @@ applies at the next start. Network, key, MCP and program keys are not editable t `STRATA_SPEC_GUMBEL=1` raise the accepted-draft rate on some machines; `STRATA_SPEC_PROB=1` is speculative rejection sampling. `STRATA_SPEC_DEPTH=1` prints acceptance by draft depth and `STRATA_SPEC_MIN_TEMP=0.9` limits sampled drafting to hotter requests. Try them on your own card before relying on them. +- **logprobs: how likely each token was (CUDA/HIP).** `"logprobs": true` with `"top_logprobs": 0..20` on + `/v1/chat/completions`, streamed or not, adds `choices[0].logprobs.content[]` to the reply (`token`, `logprob`, + `bytes`, `top_logprobs`); with thinking on, the thinking's entries come under `reasoning_content` instead. The + tokens, joined, spell the reply exactly (a character split across two tokens lands in the one that finishes it). + A reply is bounded by `max_tokens` -- or by the rest of the context when it is not sent -- and by no cap of our + own, as on OpenAI and vLLM, neither of which ties a length limit to logprobs. A reply that is not streamed, or + that answers a `json_schema` (buffered to be validated), does hold every entry until it ends, so a long one holds + a lot of them; a streamed reply hands each entry out with its chunk and keeps none. `"allowed_token_ids": [ids]` + keeps only those ids in `top_logprobs`, most likely first, renormalised to sum to 1; the chosen token is one of + them when it was named (vLLM's field, but vLLM masks generation with it, while here it filters what is reported, + so a token outside the named ids keeps its own `logprob` and an empty list). An id past the model's vocabulary is + a 400. A token whose probability could not be read gets no entry, and the reply goes on. On a server started with + `--parallel`, only a `max_tokens` 1 request gets them: it is the one a batch slot decodes through the single-token + path, which writes an LP line. A longer reply there is a 400, since the slot's `BT` lines carry none -- entries for + a prefix only, which a client cannot tell from the model's own answer. - **Non-finite logits end the request and drop the cached state (on by default).** If a verify window's logits are NaN, the window emits no tokens, the request ends, and the next request drops the live session, checkpoints and parked conversations and reads its prompt from token 0. The server retries a request that had sent nothing once, transparently. @@ -713,10 +732,13 @@ endpoints are refused with an error that says so. | `tools` | `function`, `namespace` and `custom` tools. Hosted tools (`web_search`, `file_search`, ...) are left out because the model cannot run them | | `tool_choice` | `"none"` hides the tools; anything else lets the model choose (it cannot be forced) | | `reasoning.effort` | `none`/`minimal`, `low`, `medium`, `high`/`xhigh`; without it the config's `reasoning_effort`, else the model's default | -| `max_output_tokens` | The output cap, thinking included. Running out ends the response `incomplete` | +| `max_output_tokens` | The output cap, thinking included. Running out ends the response `incomplete`. `0` and `-1` (or leaving it out) mean no cap, as for `max_tokens`; anything below `-1` is a 400 | | `text.format` | `json_schema` and `json_object` use the JSON formats above (checked, not constrained) | | `client_metadata["x-codex-turn-metadata"]` thread-title request | Opt-in `"codex_thread_titles": true`: answered without the engine as `{"title": ""}` so the conversation keeps the prompt cache | +The final event (`response.completed` or `response.incomplete`) and a non-streaming reply carry the same top-level `timings` object as +`/v1/chat/completions`. + The thinking comes back as a `reasoning` output item with `reasoning_text` content. The model writes no summaries, so `summary` is empty. With `"include": ["reasoning.encrypted_content"]` the item also carries an opaque string (base64, not encrypted). Send reasoning items back with the conversation, as Codex does, so the prompt matches and the cache is reused. Streaming diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 92c26f9c..080d9ee7 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -21,6 +21,7 @@ unchanged. Numbers are the reporters' own, on one machine each, unless the text | Cards | Compute capability | How it runs | What is different on it | | --- | --- | --- | --- | +| Quadro M6000, GTX 900 series (Maxwell) | 5.2 | a source build with CUDA 12.x | Opt-in, one reporter, [below](#maxwell-sm_52). No native half-precision arithmetic. Not in the ready-made CUDA 12 engine | | Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32; seven scheduling switches on by default ([below](#tesla-p100-sm_60)); opt-in `STRATA_Q8_SM60=1` ([below](#pascal-gp100-a-q8_0-decode-kernel-opt-in)) | | Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there); dense weights dequantized by a wide kernel; expert mode 8 and its own interleaved-matvec table; opt-in `STRATA_DENSE_F32=1` ([below](#tesla-p40-sm_61-what-was-measured-and-changed)) | | Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores; prompt attention on `mma.m8n8k4`; a leaner attention kernel. See [NVIDIA_V100.md](NVIDIA_V100.md) | @@ -41,6 +42,23 @@ too and cannot hold any of the model. | Radeon PRO V520 / Pro 5600M (RDNA1) | gfx1011 | built by hand: `-DCMAKE_HIP_ARCHITECTURES=gfx1011`; builds with 0 errors, untested on hardware | | Instinct MI50 / MI60, Radeon VII | gfx906 (wave64) | built by hand: `-DSTRATA_HIP_GFX906=ON` | +### Maxwell (sm_52) + +One reporter ran Strata v0.1.44.1 on two Quadro M6000 24 GB (Ubuntu, driver 580) with Qwen3.8-Flash-Next at IQ1 and saw about +22 tokens a second. Nobody has checked the answer text on these cards yet, and Maxwell has no native half-precision arithmetic, +so treat it as a test. The ready-made CUDA 12 engine holds no sm_52 code; build from source with a CUDA 12.x toolkit (CUDA 13 +cannot compile for Maxwell): + +``` +cmake -B build -G Ninja -DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52 +cmake --build build -j +``` + +CMake prints a warning for sm_52 and goes on. A release build still needs sm_75 or newer, and without `STRATA_EXPERIMENTAL_SM60=ON` +the build stops as before. `setup.py` does not install an engine for a Maxwell card, because none of the ready-made engines holds +code for it. On a PC with only Maxwell cards it lists the card as not supported, prints this recipe as a warning and stops. If you +try the build, please post a short chat and one code answer from the card. + ## NVIDIA: the CUDA 12 engine CUDA 13 dropped Pascal and Volta and cannot compile for them. Setup therefore keeps a second engine, built with CUDA 12.9 and diff --git a/serve/responses.py b/serve/responses.py index 8b7241b9..d5ea4cd0 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -420,11 +420,12 @@ def text_format(req: dict): kind = fmt.get("type") if kind in (None, "text"): return None + extra = {"repair_latex_escapes": True} if fmt.get("repair_latex_escapes") is True else {} # #2893, opt-in if kind == "json_object": - return {"type": "json_object"} + return {"type": "json_object", **extra} if kind == "json_schema": spec = {k: fmt[k] for k in ("name", "schema", "strict", "description") if k in fmt} - return {"type": "json_schema", "json_schema": spec} + return {"type": "json_schema", "json_schema": spec, **extra} raise ResponsesError("text.format.type must be text, json_object or json_schema", "text.format.type") @@ -443,8 +444,10 @@ def check_request(req: dict) -> None: raise ResponsesError("stored prompt templates are not supported: send instructions and input", "prompt", "unsupported_parameter") n = req.get("max_output_tokens") - if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < 1): - raise ResponsesError("max_output_tokens must be a positive whole number", "max_output_tokens") + # -1 and 0 mean no cap, as max_tokens does on the chat path (docs/DETAILS.md); anything lower is a mistake + if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < -1): + raise ResponsesError("max_output_tokens must be a whole number, 1 or more, or -1 or 0 for no cap", + "max_output_tokens") reasoning = req.get("reasoning") if reasoning is not None and not isinstance(reasoning, dict): raise ResponsesError("reasoning must be an object", "reasoning") @@ -662,10 +665,17 @@ class Assembler: if length: self.response["status"] = "incomplete" self.response["incomplete_details"] = {"reason": "max_output_tokens"} - return out + [self.event("response.incomplete", response=self.snapshot())] + return out + [self._with_timings(self.event("response.incomplete", response=self.snapshot()), done)] self.response["status"] = "completed" self.response["completed_at"] = int(time.time()) - return out + [self.event("response.completed", response=self.snapshot())] + return out + [self._with_timings(self.event("response.completed", response=self.snapshot()), done)] + + @staticmethod + def _with_timings(event: dict, done: dict) -> dict: + """Top-level `timings` on the final event, as /v1/chat/completions has them (#107).""" + if done.get("timings"): + event["timings"] = done["timings"] + return event def failed(self, message: str, code: str = "server_error") -> dict: """response.failed: an error after the stream started (the HTTP status is already sent).""" @@ -683,4 +693,6 @@ def collect(events) -> dict: for e in events: if e is not None: last = e + if last.get("timings"): # as on a whole /v1/chat/completions reply (#107) + return {**last["response"], "timings": last["timings"]} return last["response"] diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..7a268a46 100644 --- a/serve/server.py +++ b/serve/server.py @@ -80,7 +80,7 @@ from serve import owner_guard # noqa: E402 from serve import launch_identity # noqa: E402 from serve import logit_bias as bias_api # noqa: E402 from serve import lifeline # noqa: E402 -from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 +from serve.structured import StructuredOutputError, prepare_format, validated_json, extract_json # noqa: E402 from serve import responses as responses_api # noqa: E402 from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402 from serve import images as images_api # noqa: E402 @@ -1456,6 +1456,15 @@ class StrataEngine: pn = prefix.get("tokens") if isinstance(pn, int) and not isinstance(pn, bool) and pn > 0: keys += f" pin={pn}" + # logprobs: the engine writes an `LP` line after each `T` line (an engine without them ignores + # the key, so an older engine answers exactly as it did). Absent = no LP lines at all. + k = top_logprobs(sampling) + if k is not None: + keys += f" logprobs={k}" + ids = allowed_ids(sampling) + if ids: + # only these ids are printed; the engine's comma-separated list, renormalised below + keys += " allowed=" + ",".join(str(i) for i in ids) return keys + StrataEngine.projection_key(sampling) + bias_api.engine_key(sampling.get("logit_bias")) @staticmethod @@ -1474,35 +1483,56 @@ class StrataEngine: except (OSError, AttributeError): # the pipe is gone (or a restart's close() took the process): raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None - def _control(self, cancel, on_token, stop_when=None, on_quiet=None): + def _control(self, cancel, on_token, stop_when=None, on_quiet=None, want_lp=False): """Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats. Calls on_token(id) for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE). `stop_when()` true sends STOP once (the request is then read to its DONE). `on_quiet()` runs whenever the engine has been - quiet for half a second: between two PP lines of a read whose chunks take longer than that.""" + quiet for half a second: between two PP lines of a read whose chunks take longer than that. + + `want_lp`: a batch admission's token is the only one this reader ever sees with an `LP` line after it (a + slot's `BT` lines carry none), so a request asking for logprobs there is a `max_tokens` 1 one: read the + line here, for the request itself (its own lines: the engine's is shared by the slots' readers).""" stopped = False beat = time.monotonic() + held = NO_LINE # a line read while looking for a token's LP line while True: - try: - # A client can leave before the first PP/token. Poll its Event as often as _take_control does; - # the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine. - line = self.lines.get(timeout=0.5) - except queue.Empty: - if cancel.is_set() and not stopped: - self._send("STOP") - stopped = True - if on_quiet is not None: - on_quiet() - if time.monotonic() - beat >= 10.0: - beat = time.monotonic() - yield None - continue + if held is not NO_LINE: + line, held = held, NO_LINE + else: + try: + # A client can leave before the first PP/token. Poll its Event as often as _take_control does; + # the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine. + line = self.lines.get(timeout=0.5) + except queue.Empty: + if cancel.is_set() and not stopped: + self._send("STOP") + stopped = True + if on_quiet is not None: + on_quiet() + if time.monotonic() - beat >= 10.0: + beat = time.monotonic() + yield None + continue beat = time.monotonic() if line is None: raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") if not line.startswith(("PP ", "INFO")): btrace("ctl<", self._ctl_mode, line.strip()[:60]) if line.startswith("T "): - on_token(int(line[2:])) + t = int(line[2:]) + if want_lp: + # the engine writes the token and its LP line in one flush: the next line is that one, or a + # line this reader must still see (held for the next turn, as generate() does) + try: + held = self.lines.get(timeout=0.5) + except queue.Empty: + held = NO_LINE + if isinstance(held, str) and held.startswith("LP "): + own = getattr(cancel, "_strata_lp_lines", None) + if own is not None: + own.append((t, held)) + held = NO_LINE + on_token(t) if not stopped and (cancel.is_set() or (stop_when is not None and stop_when())): self._send("STOP") stopped = True @@ -1779,6 +1809,12 @@ class StrataEngine: self.progress, self.progress_ms, self.reused = None, 0, 0 born = self.gen # the engine process this request is sent to keys = self.sampling_keys(sampling or {}) + # logprobs: only an admission's token can have an LP line here (the slot's "BT" lines carry none), so the + # server refuses these requests unless max_tokens is 1. The lines go to the request itself, through its + # cancel Event: several requests read control lines at once, and the engine's lp_lines is one attribute. + want_lp = top_logprobs(sampling or {}) is not None + if want_lp: + cancel._strata_lp_lines = LPLines(cancel) out: list[int] = [] pending: list[int] = [] prompt, left = list(ids), int(max_new) @@ -1833,7 +1869,8 @@ class StrataEngine: self.slot_claims.add(reserved) if reserved is not None: self._send(f"BYIELD {reserved}") - for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way): + for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way, + want_lp=want_lp): while pending: t = pending.pop(0) out.append(t) @@ -1961,7 +1998,8 @@ class StrataEngine: if self.progress and live["state"] == "reading": live["prompt_read"] = self.progress[0] try: - for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress())): + for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress()), + want_lp=want_lp): while pending: t = pending.pop(0) out.append(t) @@ -2195,6 +2233,12 @@ class StrataEngine: return self.progress, self.progress_ms, self.reused = None, 0, 0 self.prefill_tok_s_mean = None + # logprobs: the engine writes "LP [id:logprob ...]" right after each "T " (the same + # flush), read here before the token is yielded, so whoever takes the token finds its line in + # lp_lines. Not asked for = the deque stays empty and nothing on this path changes. + want_lp = top_logprobs(sampling or {}) is not None + self.lp_lines = LPLines(cancel) + carry = NO_LINE # a line read for a token's LP line, held until it is used # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}" @@ -2222,7 +2266,10 @@ class StrataEngine: raise self._silent(f"the engine said nothing for {time.monotonic() - heard:.0f} s during " "the request") try: - line = self.lines.get(timeout=min(wait, 0.5)) + if carry is not NO_LINE: # the line read after a token for its LP line + line, carry = carry, NO_LINE + else: + line = self.lines.get(timeout=min(wait, 0.5)) except queue.Empty: if cancel.is_set(): return @@ -2249,7 +2296,18 @@ class StrataEngine: allow = silence if cancel.is_set(): return - yield int(line[2:]) + t = int(line[2:]) + if want_lp: + # the engine writes the token and its `LP` line in one flush, so the line is + # here now; an engine without logprobs leaves the next line a normal one + try: + carry = self.lines.get(timeout=0.5) + except queue.Empty: + carry = NO_LINE + if isinstance(carry, str) and carry.startswith("LP "): + self.lp_lines.append((t, carry)) + carry = NO_LINE + yield t elif line.startswith("PP "): f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): @@ -2292,9 +2350,12 @@ class StrataEngine: while True: left = allow - (time.monotonic() - heard) if allow > 0 else None try: - if left is not None and left <= 0: + if carry is not NO_LINE: # read already, after the last token + line, carry = carry, NO_LINE + elif left is not None and left <= 0: raise queue.Empty - line = self.lines.get(timeout=left) + else: + line = self.lines.get(timeout=left) except queue.Empty: raise self._silent("the engine did not finish the request after it was stopped (STOP) " f"within {allow:.0f} s") from None @@ -3720,6 +3781,40 @@ class Detokenizer: OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop` +def top_logprobs(req: dict): + """The K for the engine's logprobs=K, or None when the request did not ask. + + OpenAI: "logprobs": true with "top_logprobs" 0..20; the legacy completions form, + "logprobs": N, is taken as N.""" + lp = req.get("logprobs") + if lp is True: + k = req.get("top_logprobs") + return max(0, min(20, k)) if isinstance(k, int) and not isinstance(k, bool) else 0 + if isinstance(lp, int) and not isinstance(lp, bool) and lp >= 0: + return min(20, lp) + return None + + +def allowed_ids(req: dict) -> list: + """`allowed_token_ids`: the ids a caller named, or [] (vLLM's semantics, see LogprobEntries).""" + ids = req.get("allowed_token_ids") + if not isinstance(ids, (list, tuple)): + return [] + return [x for x in ids if isinstance(x, int) and not isinstance(x, bool) and x >= 0] + + +def batch_slots_on(engine) -> bool: + """Does this engine run requests in batch slots ("parallel", whose `BT` lines carry no LP lines)? + + Asked of each engine behind a ReplicaEngine: its own `batch` is how many requests it can run at once, so it + counts a replica without slots as one (serve/replicas.py) -- a server with `--replicas 2` and no `--parallel` + has none, and reads every reply by the GEN path, which does write them.""" + return any(int(getattr(e, "batch", 0) or 0) for e in (getattr(engine, "engines", None) or [engine])) + + +NO_LINE = object() # StrataEngine.generate: no line held after a token + + def stop_strings(req: dict) -> list[str]: """The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences` (a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated.""" @@ -5814,6 +5909,141 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, PP_DONE_TAIL = 64 + +class LPLines(collections.deque): + """One request's LP lines, tagged with its cancel Event (one per request, handed unchanged from the handler + through Service.run to Engine.generate). The last events of a request - the parser's and the stop strings' + tail - come after it has left the queue, when the next request may already have replaced the engine's lp_lines + with its own: LogprobEntries reads only the lines tagged with its own request's Event.""" + + def __init__(self, owner=None): + super().__init__() + self.owner = owner + + +class LogprobEntries: + """The engine's LP lines as OpenAI's logprobs.content entries. + + Each token's "token" is the text it completes (an incremental UTF-8 decode, as the reply's + text is made), so a character split across tokens lands in the token that finishes it and + the tokens, joined, spell the reply. "bytes" are the token's own bytes. The stop token + ends the reply and is not listed (OpenAI does not list it either). Tokens that make no + text of the reply are left out, because spell() gives each piece of text the tokens that + spell it. + + `allowed_token_ids`: only those ids are kept, and the logprobs are renormalised over them, + so a caller asking about specific candidates gets a distribution over exactly those instead + of a top-K list it has to hope contains them. vLLM, which named the field, masks generation + with these ids instead (every other logit -inf before sampling) and reports the unmasked + distribution; here they filter what is reported, so the chosen token can be outside them. + + On `--parallel`: only a `max_tokens` 1 request gets entries (an admission, decoded through the single-token path + that writes an LP line); the slot's `BT` lines carry none, so a longer reply is refused (400) before it starts. + """ + + def __init__(self, svc, allowed=(), owner=None): + self.tok, self.stop_ids = svc.tok, svc.stop_ids + self.allowed = [i for i in allowed] + self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") + self.pending = [] # entries read but not yet given to a piece of text + self.owner = owner # the request's cancel Event (LPLines) + self.lines = None # this request's current LPLines, kept once seen + + def spell(self, eng, text: str) -> list: + """The entries whose tokens spell `text`, the next piece of the reply.""" + self.pending += self.take(eng) + at = [0] + for e in self.pending: + at.append(at[-1] + len(e["token"])) + joined = "".join(e["token"] for e in self.pending) + i = joined.find(text) + while i >= 0 and text: + if i in at: + a = at.index(i) # the first token there + end = i + len(text) + b = next((j for j in range(a + 1, len(at)) if at[j] == end), None) + if b is not None: + out, self.pending = self.pending[a:b], self.pending[b:] + return out + i = joined.find(text, i + 1) + out, self.pending = self.pending, [] + return out + + def raw(self, t): + if hasattr(self.tok, "token_bytes"): + return self.tok.token_bytes(t) + return self.tok.decode([t]).encode("utf-8") + + def take(self, eng) -> list: + # the engine's current lines are this request's only when they carry its Event (a later generate pass + # of the same request makes new ones: the old ones are read to the end first); another request's never are. + # A batch admission keeps its own lines on the request's cancel Event: the engine's is one attribute, and + # the next request to read control lines may already have replaced it. + own = getattr(self.owner, "_strata_lp_lines", None) + cur, old = (own if own is not None else getattr(eng, "lp_lines", None)), None + if cur is not self.lines and getattr(cur, "owner", None) is self.owner: + old, self.lines = self.lines, cur + out = [] + for lines in (old, self.lines): + while lines: + t, line = lines.popleft() + if t in self.stop_ids: + continue + f = line.split() + if len(f) < 2: + continue + try: # "nan" (no head logits for that window row), "-nan(ind)" + lp = float(f[1]) # (MSVC) or a cut line: no entry for that token + alts = [(int(i), float(v)) for i, _, v in (x.partition(":") for x in f[2:])] + except ValueError: + continue + if not math.isfinite(lp) or not all(math.isfinite(v) for _, v in alts): + continue + b = self.raw(t) + e = {"token": self.inc.decode(b), "logprob": lp, "bytes": list(b), + "top_logprobs": []} + if self.allowed: + alts = [(i, v) for i, v in alts if i in self.allowed] + for i, v in alts: + alt = self.raw(i) + e["top_logprobs"].append({"token": alt.decode("utf-8", "replace"), + "logprob": v, "bytes": list(alt)}) + if self.allowed: + e = self._renormalise(e, t, lp) + out.append(e) + return out + + def _renormalise(self, e, t, lp): + """Keep only the named ids and normalise over them, so they sum to 1. + + The line carries the chosen token's own logprob on its head and the named ids after it, and never + repeats the chosen one among them. So the chosen token is put back when the caller named it: with + `allowed_token_ids` naming only the token the model chose, that token is then the whole distribution, + at 1 (logprob 0), which is what vLLM's mask gives -- here it used to leave nothing to normalise over, + which returned None, the entry was appended all the same, and the reply failed on e["token"]. A line + that carries none of the named ids has nothing to normalise over either: the entry keeps the chosen + token and its own logprob, with no alternatives. It is never None and never dropped, because the + reply's tokens have to keep spelling its text. + """ + cand = e["top_logprobs"] + own = None + if t in self.allowed: # named, and not repeated on the line: it is a candidate + b = self.raw(t) + own = {"token": b.decode("utf-8", "replace"), "logprob": lp, "bytes": list(b)} + cand = [own] + cand + if not cand: + return e # no named id observed for this token: its own logprob, no top + mx = max(x["logprob"] for x in cand) + se = sum(math.exp(x["logprob"] - mx) for x in cand) + lse = mx + math.log(se) + for x in cand: + x["logprob"] -= lse + cand.sort(key=lambda x: -x["logprob"]) # most likely first, as the unfiltered top-k already is + e["top_logprobs"] = cand + if own is not None: # the chosen token is in the distribution: report its own value + e["logprob"] = own["logprob"] # (it used to copy the first alternative's, another token's) + return e + def prompt_progress(svc: Service): """The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a @@ -5847,6 +6077,13 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} yield chunk({"role": "assistant", "content": ""}) + lp = LogprobEntries(svc, allowed_ids(req), cancel) if top_logprobs(req) is not None else None + + def with_lp(c, key): + got = lp.spell(svc.engine, c["choices"][0]["delta"][key]) if lp is not None else None + if got: + c["choices"][0]["logprobs"] = {key: got} + return c calls = 0 streamed = {} # tool call id -> index, for calls sent piece by piece finished = set() # ... and the ones whose final tool_call came (#211) @@ -5863,9 +6100,9 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel elif kind == "event": ev: Event = x if ev.kind == "reasoning" and ev.text: - yield chunk({"reasoning_content": ev.text}) + yield with_lp(chunk({"reasoning_content": ev.text}), "reasoning_content") elif ev.kind == "content" and ev.text: - yield chunk({"content": ev.text}) + yield with_lp(chunk({"content": ev.text}), "content") elif ev.kind == "tool_start": streamed[ev.call.id] = calls calls += 1 @@ -5905,11 +6142,14 @@ def _is_json(text: str) -> bool: def openai_collect(chunks) -> dict: content, reasoning, by_index, last, mcp = [], [], {}, None, [] + lps = {} # "content" / "reasoning_content" -> logprob entries for c in chunks: if c is None: # a heartbeat continue if c.get("strata_mcp"): mcp.append(c["strata_mcp"]) + for k, v in (c["choices"][0].get("logprobs") or {}).items(): + lps.setdefault(k, []).extend(v) d = c["choices"][0]["delta"] content.append(d.get("content") or "") reasoning.append(d.get("reasoning_content") or "") @@ -5936,11 +6176,80 @@ def openai_collect(chunks) -> dict: out = {"id": last["id"], "object": "chat.completion", "created": last["created"], "model": last["model"], "choices": [{"index": 0, "message": msg, "finish_reason": last["choices"][0]["finish_reason"]}], "usage": last["usage"]} + if lps: + out["choices"][0]["logprobs"] = {"content": lps.get("content", []), "refusal": None, **( + {"reasoning_content": lps["reasoning_content"]} if lps.get("reasoning_content") else {})} if last.get("timings"): out["timings"] = last["timings"] return out +def logprob_span(text: str, part: str, entries: list): + """The entries whose tokens spell `part`, a piece of `text`, or None when the tokens do not + spell `text` or no token boundary falls at both ends of `part`.""" + if "".join(e["token"] for e in entries) != text: + return None + start = text.find(part) + if start < 0: + return None + at, first = 0, None + for i, e in enumerate(entries): + if at == start and first is None: + first = i + if at == start + len(part) and first is not None: + return entries[first:i] + at += len(e["token"]) + return entries[first:] if first is not None and at == start + len(part) else None + + +def _same_json(a: str, b: str) -> bool: + """Are two strings the same JSON value (whitespace and key order aside)? No -> False.""" + try: + return json.loads(a) == json.loads(b) + except Exception: + return False + + +def _structured_logprobs(choice: dict, content: str): + """`content`'s logprobs, and the content the tokens actually spell. + + Returns `(content, logprobs)`: on failure `(the content as validated, None)`. + + `structured_chunks` returns the canonical JSON the validator produced, which the model never + generated, so its tokens do not spell it. Two honest outcomes: + + 1. a run of tokens spells what is being returned -> use it as it is; + 2. the tokens spell the model's own JSON, which is the same JSON value (the fenced-with-spaces + case, the common one) -> return the model's form, so `''.join(token) == content` again. + + Neither holds (a rearranged key order, or a reply that is not that JSON at all) and there are no + logprobs: a caller that joins the tokens must not silently get something that does not match. + """ + lps = choice.get("logprobs") + if not lps or not lps.get("content"): + return content, None + raw = choice["message"]["content"] or "" + entries = lps["content"] + if raw == content: # not rewritten: the entries are already its + return content, _with_reasoning(lps, entries) + span = logprob_span(raw, content, entries) + if span is not None: + return content, _with_reasoning(lps, span) + inner = extract_json(raw) + if inner and _same_json(inner, content): + span = logprob_span(raw, inner, entries) + if span is not None: + return inner, _with_reasoning(lps, span) # the model's own form: the tokens spell it + return content, None + + +def _with_reasoning(lps: dict, entries: list) -> dict: + out = {"content": entries} + if lps.get("reasoning_content"): + out["reasoning_content"] = lps["reasoning_content"] + return out + + def structured_chunks(chunks, validator): """Buffer structured streams so a client never receives unvalidated content.""" buffered = [] @@ -5956,12 +6265,23 @@ def structured_chunks(chunks, validator): result = openai_collect(buffered) choice = result["choices"][0] content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) + # logprobs: the entries spell what the model wrote, which this function replaces with the + # canonical JSON. `_structured_logprobs` gives back the form the tokens spell, or None. + content, logprobs = _structured_logprobs(choice, content) yield buffered[0] delta = {"content": content} if choice["message"].get("reasoning_content"): delta["reasoning_content"] = choice["message"]["reasoning_content"] - yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]} - yield buffered[-1] + piece = {"index": 0, "delta": delta, "finish_reason": None} + if logprobs: + piece["logprobs"] = logprobs + yield {**buffered[0], "choices": [piece]} + end = buffered[-1] + if end["choices"][0].get("logprobs"): + # those entries went out in the piece above (or were dropped with it): the closing + # chunk must not carry a second copy + end = {**end, "choices": [{k: v for k, v in end["choices"][0].items() if k != "logprobs"}]} + yield end finally: chunks.close() @@ -7146,6 +7466,25 @@ def make_handler(svc: Service): raise ValueError("structured response_format with tools/MCP is not supported") svc.load() max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest + # No cap of our own on the reply's length when logprobs are asked for: the reply is already bounded by + # max_tokens (by the rest of the context when it is not sent), which is the only bound OpenAI and vLLM + # put on it either. A reply that is not streamed does hold every entry (its token, bytes and up to 20 + # alternatives) until it ends, so a long one holds a lot: streaming hands each entry out with its chunk. + if top_logprobs(req) is not None and batch_slots_on(svc.engine) and max_req != 1: + # --parallel/--batch: a slot's "BT " lines carry no LP line, and the batched loop never + # calls emit_lp_line (src/program/generate.cpp); an admission -- a max_tokens 1 request -- is read + # as GEN 1, which does write them. Past that one token a reply would hold entries for a prefix + # only, which a client cannot tell from the model's own answer, so the longer one is refused. + raise ValueError('logprobs is available with "parallel" (batch slots) only for max_tokens 1; ' + 'run the server without "--parallel" for longer replies') + n_vocab = len(getattr(svc.tok, "tokens", ())) or None + if top_logprobs(req) is not None and n_vocab: + # emit_lp_line indexes the logits row with each named id as given, so an id past the vocabulary + # would read out of bounds: refused here, before anything is sent + bad = [i for i in allowed_ids(req) if i >= n_vocab] + if bad: + raise ValueError(f"allowed_token_ids: {bad[0]} is outside the vocabulary " + f"(0..{n_vocab - 1})") bias_api.validate_request(req, svc.engine, len(getattr(svc.tok, "tokens", ())) or None) use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) own = {t.get("name") for t in tools or [] if isinstance(t, dict)} # #592: a second line of defence diff --git a/serve/structured.py b/serve/structured.py index 9bed5348..1809a0c3 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -28,6 +28,46 @@ class _ObjectError: message = "the answer is not a JSON object" +class _Repairing: + """A validator that also tells validated_json to retry once, after a strict parse failed, with the backslashes that + are not valid JSON escapes doubled (response_format "repair_latex_escapes": true, #2893).""" + repair_escapes = True + + def __init__(self, inner): + self.inner = inner + + def iter_errors(self, value): + return self.inner.iter_errors(value) + + +_HEX = "0123456789abcdefABCDEF" + + +def repair_latex_escapes(text: str) -> str: + r"""Double every backslash that does not start a valid JSON escape, so \alpha and \gamma read as text. + The valid escapes (\b \f \n \r \t \/ \" and a well-formed \uXXXX) stay as they are: a model cannot be told + from LaTeX there, so a \beta next to a \alpha comes back with a backspace. Pairs of backslashes are skipped.""" + out = [] + i, n = 0, len(text) + while i < n: + ch = text[i] + if ch != "\\": + out.append(ch) + i += 1 + continue + nxt = text[i + 1] if i + 1 < n else "" + if nxt in ("\\", '"', "/", "b", "f", "n", "r", "t"): + out.append(ch + nxt) + i += 2 + elif nxt == "u" and len(text) >= i + 6 and all(c in _HEX for c in text[i + 2:i + 6]): + out.append(text[i:i + 6]) + i += 6 + else: + out.append("\\\\") + i += 1 + return "".join(out) + + _jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed _jsonschema_lock = threading.Lock() @@ -140,6 +180,8 @@ def prepare_format(response_format, messages, with_tools=False): # /v1/responses (#782): the schema is for the final answer; a turn that calls a tool is not an answer directive += ("\nThis applies only to your final answer. To use a tool, call it as usual; the JSON object is " "what you write once you are done with the tools.") + if response_format.get("repair_latex_escapes") is True: + validator = _Repairing(validator) messages = [dict(message) for message in messages] if messages and messages[0].get("role") == "system": content = messages[0].get("content") or "" @@ -152,7 +194,10 @@ def prepare_format(response_format, messages, with_tools=False): return messages, validator -def _extract_json(text: str) -> str: +def extract_json(text: str) -> str: + """The first JSON object in `text`: a ```-fenced block's inside when there is one, else the text + from its first `{`. Empty when there is nothing to take. The server's json_schema logprobs + alignment reads the model's own JSON form with it.""" s = (text or "").strip() if not s: return "" @@ -204,10 +249,20 @@ def validated_json(text, validator, finish): if finish != "stop": raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") try: - value = json.loads(_extract_json(text), object_pairs_hook=pairs, parse_constant=constant) + value = json.loads(extract_json(text), object_pairs_hook=pairs, parse_constant=constant) canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) except (ValueError, TypeError) as exc: - raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc + value = None + if getattr(validator, "repair_escapes", False): # opt-in (#2893); only after the strict parse failed + try: + value = json.loads(repair_latex_escapes(extract_json(text)), object_pairs_hook=pairs, + parse_constant=constant) + canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + print("[strata] structured output: repaired backslashes that were not valid JSON escapes", flush=True) + except (ValueError, TypeError): + value = None + if value is None: + raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc try: error = next(validator.iter_errors(value), None) except Exception as exc: diff --git a/serve/test_logprobs.py b/serve/test_logprobs.py new file mode 100644 index 00000000..a21237db --- /dev/null +++ b/serve/test_logprobs.py @@ -0,0 +1,541 @@ +"""OpenAI logprobs on /v1/chat/completions, from the engine's LP lines: python -m unittest serve.test_logprobs. + +The engine (src/program/generate.cpp) writes an `LP [id:logprob ...]` line right after +each `T ` when the request carries `logprobs=K`; this is the server half that turns those +lines into OpenAI's logprobs, and the parts that are easy to get wrong: + + - `allowed_token_ids`: only the named ids, renormalised over them (vLLM's semantics). + - `response_format: json_schema` rewrites the content, so the tokens no longer spell what is + returned; the entries are re-aligned or dropped, never returned wrong. +""" +from __future__ import annotations + +import json +import math +import queue +import threading +import unittest +import urllib.request +from pathlib import Path +from types import SimpleNamespace + +from serve.frontend import ChatTemplate +from serve.server import (ByteTokenizer, LogprobEntries, LPLines, MockEngine, Service, StrataEngine, batch_slots_on, + logprob_span, serve, top_logprobs, allowed_ids) + +ROOT = Path(__file__).resolve().parent.parent +TEMPLATE = ChatTemplate(ROOT / "serve" / "chat_template.jinja") + + +class Tokenizer(ByteTokenizer): + def token_bytes(self, token): + return self.SPECIALS[token - 256].encode() if token >= 256 else bytes([token]) + + +class ThinkTokenizer(Tokenizer): + # two extra special tokens that decode as the thinking marks; ALWAYS so the byte-level + # encode() maps them wherever they appear ("" would loop forever in startswith, so they + # are real strings, like the engine's own think tokens are) + SPECIALS = ByteTokenizer.SPECIALS + ["", ""] + ALWAYS = ("", "") + + +class LpEngine(MockEngine): + """MockEngine with the LP line of each token on lp_lines before the token is yielded, as the + engine leaves it; token i has the log-probability -(i + 1) / 100 and four named alternatives.""" + + def __init__(self, tok, script, lines=True): + super().__init__(tok, script, max_context=16384) + self.with_lines, self.sampling = lines, None + + def line(self, i, t): + """The LP line of token t, the i-th of the reply: the same four ids whatever was asked.""" + return (f"LP {-(i + 1) / 100:.6f} 65:-0.500000 72:-1.250000 " + f"88:-3.000000 91:-4.200000\n") + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.sampling, self.lp_lines = dict(sampling or {}), LPLines(cancel) + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if self.with_lines: + self.lp_lines.append((t, self.line(i, t))) + yield t + + +class NamedEngine(LpEngine): + """LpEngine that prints the request's own `allowed_token_ids`, as the engine's emit_lp_line does: + `LP : ...`, the chosen id left out (it is on the head).""" + + def line(self, i, t): + named = [int(x) for x in (self.sampling or {}).get("allowed_token_ids") or [] if int(x) != t] + alts = "".join(f" {x}:{-0.700000 - 0.010000 * j:.6f}" for j, x in enumerate(named)) + return f"LP {-(i + 1) / 100:.6f}{alts}\n" + + +class NextEngine(LpEngine): + """LpEngine for two requests: the second one stops after its first token (its LP line is in lp_lines) + until the first request's reply has been read.""" + + def __init__(self, tok, scripts, first_out): + super().__init__(tok, scripts) + self.first_out, self.calls = first_out, 0 + self.first_in, self.first_generated, self.second_started = (threading.Event(), threading.Event(), + threading.Event()) + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.calls += 1 + mine = self.calls + if mine == 1: + self.first_in.set() + try: + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if mine == 2 and i == 0: + self.second_started.set() + self.first_out.wait(10) + yield t + finally: + if mine == 1: + self.first_generated.set() + + +class HandOver: + """Service.fifo that, once the first request has generated, lets its turn go and then waits until the + next request is generating before the first one goes on.""" + + def __init__(self, engine): + self.lock, self.engine, self.waited = threading.Lock(), engine, False + + def acquire(self, *a, **k): + return self.lock.acquire(*a, **k) + + def release(self): + self.lock.release() + if self.engine.first_generated.is_set() and not self.waited: + self.waited = True + self.engine.second_started.wait(10) + + def locked(self): + return self.lock.locked() + + def __enter__(self): + self.acquire() + return self + + def __exit__(self, *exc): + self.release() + + +SCHEMA = {"type": "json_schema", "json_schema": {"name": "a", "strict": True, "schema": { + "type": "object", "properties": {"rent": {"type": "string"}, "quote": {"type": "string"}}, + "required": ["rent", "quote"], "additionalProperties": False}}} + + +class Keys(unittest.TestCase): + """What the request asks for, and what reaches the engine line.""" + + def test_what_the_request_asks(self): + self.assertEqual(top_logprobs({"logprobs": True}), 0) + self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 3}), 3) + self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 50}), 20) + self.assertEqual(top_logprobs({"logprobs": 2}), 2) # the legacy completions form + for req in ({}, {"logprobs": False}, {"logprobs": None}, {"top_logprobs": 3}): + self.assertIsNone(top_logprobs(req)) + + def test_allowed_ids(self): + self.assertEqual(allowed_ids({"allowed_token_ids": [1, 2, 3]}), [1, 2, 3]) + for req in ({}, {"allowed_token_ids": "1,2"}, {"allowed_token_ids": [True]}, {"allowed_token_ids": [-1]}): + self.assertEqual(allowed_ids(req), []) + + def test_the_engine_key_only_when_asked(self): + self.assertIn(" logprobs=0", StrataEngine.sampling_keys({"logprobs": True})) + self.assertIn(" logprobs=5", StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 5})) + self.assertNotIn("logprobs", StrataEngine.sampling_keys({})) + self.assertNotIn("logprobs", StrataEngine.sampling_keys({"logprobs": False, "temperature": 0})) + + def test_allowed_reaches_the_engine_line(self): + keys = StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 2, + "allowed_token_ids": [7, 8, 9]}) + self.assertIn(" logprobs=2 ", keys) + self.assertIn(" allowed=7,8,9", keys) + + def test_unreadable_lines_give_no_entry(self): + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + for line in ("LP nan", "LP -nan(ind)", "LP inf", "LP -0.1 65:x", "LP -0.1 65:-inf", "LP -0.1 65", + "LP -0.200000 65:-1.0"): + eng.lp_lines.append((72, line)) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), owner=a).take(eng) + self.assertEqual([e["logprob"] for e in got], [-0.2]) + + def test_a_filtered_line_with_nothing_left_keeps_its_token(self): + # none of the named ids on the line: the entry keeps the chosen token and its own logprob, and no + # alternatives. It used to be None, appended all the same, and the reply failed on e["token"]. + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + eng.lp_lines.append((72, "LP -0.300000 65:-0.500000")) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [70], a).take(eng) + self.assertEqual([(e["token"], e["logprob"], e["top_logprobs"]) for e in got], [("H", -0.3, [])]) + + def test_a_named_token_the_line_does_not_repeat_is_its_own_distribution(self): + # the engine prints the chosen token's logprob on the head and the named ids after it, never repeating + # the chosen one: naming only that id leaves it alone in the distribution, at 1 (logprob 0) + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + eng.lp_lines.append((72, "LP -0.300000 65:-0.500000")) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [72], a).take(eng) + self.assertEqual(got[0]["top_logprobs"], [{"token": "H", "logprob": 0.0, "bytes": [72]}]) + self.assertEqual(got[0]["logprob"], 0.0) + + +class Generate(unittest.TestCase): + """The token's LP line is read next to it, and only when it was asked for.""" + + def engine(self, *lines): + e = StrataEngine.__new__(StrataEngine) + e.proc = __import__("types").SimpleNamespace( + stdin=__import__("io").StringIO(), poll=lambda: None) + e.lines, e.can_stop, e.max_context, e.silence_s = queue.Queue(), False, 262144, 0 + for line in lines: + e.lines.put(line) + return e + + def test_a_token_is_yielded_with_its_lp_line_read(self): + e = self.engine("PP 3 3", "T 72", "LP -0.100000 72:-0.1 65:-2.5", "T 105", + "LP -0.200000 105:-0.2 65:-3", "T 257", "LP -0.010000", + "DONE 3 3 0 3 stop 0 0 0") + seen = [] + for t in e.generate([1, 2, 3], 8, {"logprobs": True, "top_logprobs": 2}, threading.Event()): + if t is not None: + seen.append((t, [x[0] for x in e.lp_lines])) + self.assertEqual(seen, [(72, [72]), (105, [72, 105]), (257, [72, 105, 257])]) + self.assertIn(" logprobs=2 ", e.proc.stdin.getvalue()) + self.assertEqual(e.lp_lines[1][1], "LP -0.200000 105:-0.2 65:-3") + + def test_an_engine_without_lp_lines(self): + e = self.engine("T 72", "T 105", "DONE 3 3 0 2 stop 0 0 0") + toks = [t for t in e.generate([1], 8, {"logprobs": True}, threading.Event()) if t is not None] + self.assertEqual(toks, [72, 105]) + self.assertEqual(list(e.lp_lines), []) + self.assertEqual(e.last["finish"], "stop") + + def test_not_asked_reads_as_before(self): + e = self.engine("T 72", "LP -0.1", "T 105", "DONE 3 3 0 2 stop 0 0 0") + toks = [t for t in e.generate([1], 8, {}, threading.Event()) if t is not None] + self.assertEqual(toks, [72, 105]) + self.assertEqual(list(e.lp_lines), []) + + def test_a_consumer_that_stops_early_does_not_lose_the_done_read_after_the_token(self): + # the DONE line was read while looking for the token's LP line: the drain must take it, + # not wait for another + e = self.engine("T 72", "DONE 3 3 0 1 length 0 0 0", None) + gen = e.generate([1], 1, {"logprobs": True}, threading.Event()) + self.assertEqual(next(gen), 72) + gen.close() + self.assertEqual(e.last["finish"], "length") + + +class Api(unittest.TestCase): + def setUp(self): + self.tok = Tokenizer() + self.engine = LpEngine(self.tok, "Café costs €5.") + self.svc = Service(self.engine, self.tok, TEMPLATE) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def post(self, body, stream=False): + body = {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 200, + "chat_template_kwargs": {"enable_thinking": False}, **body} + if stream: + body["stream"] = True + req = urllib.request.Request(self.base + "/v1/chat/completions", json.dumps(body).encode(), + {"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + if not stream: + return json.loads(raw) + return [json.loads(x[6:]) for x in raw.splitlines() if x.startswith("data: {")] + + def test_the_tokens_spell_the_content(self): + out = self.post({"logprobs": True, "top_logprobs": 1}) + choice = out["choices"][0] + content = choice["message"]["content"] + lps = choice["logprobs"]["content"] + self.assertEqual(content, "Café costs €5.") + self.assertEqual("".join(e["token"] for e in lps), content) + self.assertEqual(len(lps), len(content.encode())) # one per byte token; no stop token + self.assertEqual(b"".join(bytes(e["bytes"]) for e in lps), content.encode()) + e_acute = [e for e in lps if len(e["bytes"]) == 1 and e["bytes"][0] >= 0x80] + self.assertEqual([e["token"] for e in e_acute[:2]], ["", "é"]) # split across two tokens + self.assertEqual(lps[0]["logprob"], -0.01) + self.assertEqual(lps[0]["top_logprobs"][0]["token"], "A") + self.assertEqual(self.engine.sampling.get("logprobs"), True) + + def test_a_request_reads_only_its_own_lines(self): + # A's last "." is held by its stop string and sent after A has left the queue, when B is + # already generating on the same engine: each reply's tokens must spell that reply + first_out = threading.Event() + engine = NextEngine(self.tok, ["Café costs €5.", "Bonjour!"], first_out) + svc = Service(engine, self.tok, TEMPLATE) + svc.fifo = HandOver(engine) + httpd = serve(svc, port=0) + got = {} + try: + self.base = f"http://127.0.0.1:{httpd.server_address[1]}" + a = threading.Thread(target=lambda: got.update(a=self.post({"logprobs": True, "stop": [".!"]}))) + b = threading.Thread(target=lambda: got.update(b=self.post({"logprobs": True}))) + a.start() + self.assertTrue(engine.first_in.wait(10)) + b.start() + a.join(30) + first_out.set() + b.join(30) + finally: + first_out.set() + httpd.shutdown() + httpd.server_close() + for key, text in (("a", "Café costs €5."), ("b", "Bonjour!")): + choice = got[key]["choices"][0] + self.assertEqual(choice["message"]["content"], text) + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), text, key) + + def test_logprobs_take_any_max_tokens(self): + # No cap of our own: the reply is already bounded by max_tokens (the rest of the context when it is not + # sent), which is the only bound OpenAI and vLLM put on it too -- openai-node's max_tokens is optional + # and vLLM's defaults to 16 or None, neither tying it to logprobs. + for max_tokens in (200, 5000, 0, -1, None): # 0 / -1: "the rest of the context"; None: not sent + choice = self.post({"logprobs": True, "top_logprobs": 1, "max_tokens": max_tokens})["choices"][0] + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), + "Café costs €5.", max_tokens) + self.assertNotIn("logprobs", self.post({"max_tokens": 0})["choices"][0]) # not asked: as before + + def test_a_streamed_reply_needs_no_bound(self): + # A streamed reply hands each entry out with its chunk and keeps none, so it is bounded by the reply's own + # length. OpenAI itself bounds a reply only by the model's context, and its SDKs send no max_tokens by + # default. 5000 and "the rest of the context" must both be answered, as they are without logprobs. + for max_tokens in (5000, 0, None): # None: the field is not sent at all + chunks = self.post({"logprobs": True, "max_tokens": max_tokens}, stream=True) + text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(text, "Café costs €5.", max_tokens) + self.assertEqual("".join(toks), text, max_tokens) # an entry for every token, streamed or not + + def test_a_json_schema_reply_takes_any_max_tokens(self): + # structured_chunks buffers the reply to validate it, logprobs included: it holds the entries until the + # end, as a reply that is not streamed does. That memory is bounded by max_tokens, not by a cap of ours. + written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' + self.engine = self.svc.engine = LpEngine(self.tok, written) + content = '{"rent": "$1,250", "quote": "x"}' + for max_tokens in (200, 0, 5000): + choice = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA})["choices"][0] + self.assertEqual(choice["message"]["content"], content, max_tokens) + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content, max_tokens) + chunks = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA}, stream=True) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), content, (max_tokens, "streamed")) + + def test_logprobs_are_refused_on_the_batch_path(self): + # --parallel/--batch: the engine's batched loop prints "BT " and never calls emit_lp_line + # (src/program/generate.cpp), so no LP line reaches the server and the field would simply be absent. + # Refused up front instead, before anything is generated; a request that does not ask is untouched. + self.engine.batch = 2 + with self.assertRaises(urllib.error.HTTPError) as cm: + self.post({"logprobs": True}) + self.assertEqual(cm.exception.code, 400) + self.assertIn("--parallel", cm.exception.read().decode()) + self.engine.batch = 0 + self.assertIn("logprobs", self.post({"logprobs": True})["choices"][0]) + + def test_allowed_token_ids_outside_the_vocabulary_is_a_400(self): + # emit_lp_line indexes its logits row with each named id, so an id past the vocabulary would read out of + # bounds; the request is refused before anything is generated + self.tok.tokens = [str(i) for i in range(300)] # a tokenizer that knows its vocabulary + with self.assertRaises(urllib.error.HTTPError) as cm: + self.post({"logprobs": True, "top_logprobs": 1, "allowed_token_ids": [300]}) + self.assertEqual(cm.exception.code, 400) + self.assertIn("allowed_token_ids", cm.exception.read().decode()) + self.assertIn("logprobs", self.post({"logprobs": True, "top_logprobs": 1, + "allowed_token_ids": [299]})["choices"][0]) + + def test_streamed(self): + chunks = self.post({"logprobs": True}, stream=True) + content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(content, "Café costs €5.") + self.assertEqual("".join(toks), content) + + def test_with_thinking_each_part_is_spelled_by_its_tokens(self): + tok = ThinkTokenizer() + svc = Service(LpEngine(tok, "Two times three.\n\nSix."), tok, + TEMPLATE) + httpd = serve(svc, port=0) + try: + self.base = f"http://127.0.0.1:{httpd.server_address[1]}" + for stream in (False, True): + out = self.post({"logprobs": True, "chat_template_kwargs": {"enable_thinking": True}}, + stream) + chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"], + "logprobs": out["choices"][0]["logprobs"]}]}] + for key in ("content", "reasoning_content"): + text = "".join(c["choices"][0]["delta"].get(key) or "" for c in chunks if c.get("choices")) + toks = "".join(e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get(key, [])) + self.assertTrue(text) + self.assertEqual(toks, text, (key, stream)) + self.assertNotIn("think>", toks) + finally: + httpd.shutdown() + httpd.server_close() + + def test_not_asked_no_logprobs(self): + out = self.post({}) + self.assertNotIn("logprobs", out["choices"][0]) + + def test_an_engine_without_lp_lines_gives_none(self): + self.engine.with_lines = False + out = self.post({"logprobs": True}) + self.assertEqual(out["choices"][0]["message"]["content"], "Café costs €5.") + self.assertNotIn("logprobs", out["choices"][0]) + + def test_allowed_token_ids_are_renormalised_over_the_named_ids(self): + out = self.post({"logprobs": True, "allowed_token_ids": [65, 72]}) + lps = out["choices"][0]["logprobs"]["content"] + self.assertTrue(lps) + for e in lps: + ids = [t["token"] for t in e["top_logprobs"]] + self.assertEqual(ids, ["A", "H"]) # only the named ones + import math + total = sum(math.exp(t["logprob"]) for t in lps[0]["top_logprobs"]) + self.assertAlmostEqual(total, 1.0, places=6) # renormalised: they sum to 1 + + def test_allowed_token_ids_with_nothing_to_renormalise(self): + # the mock's alternatives are 65/72/88/91: naming another id leaves every line with no survivor. Each + # token keeps its own logprob and an empty candidate list, and the reply still comes back whole (this + # used to be a 400 on the unstreamed path and a reply cut after the role chunk when streamed). + for body in ({"logprobs": True, "allowed_token_ids": [66]}, + {"logprobs": True, "allowed_token_ids": [66, 70, 71]}): + choice = self.post(body)["choices"][0] + lps = choice["logprobs"]["content"] + self.assertEqual(choice["message"]["content"], "Café costs €5.") + self.assertEqual("".join(e["token"] for e in lps), "Café costs €5.") + self.assertEqual([e["top_logprobs"] for e in lps], [[]] * len(lps)) + self.assertEqual(lps[0]["logprob"], -0.01) # the token's own, as the engine reported it + streamed = self.post(body, stream=True) + toks = [e["token"] for c in streamed if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), "Café costs €5.") + + def test_a_named_token_the_model_chose_is_in_its_distribution(self): + # 46 is the reply's final ".": the engine does not repeat the chosen token among the named ids, so + # naming only it used to leave nothing to normalise over. It is the whole distribution now, at 0. + lps = self.post({"logprobs": True, "allowed_token_ids": [46]})["choices"][0]["logprobs"]["content"] + dot = [e for e in lps if e["token"] == "."] + self.assertEqual(len(dot), 1) + self.assertEqual(dot[0]["top_logprobs"], [{"token": ".", "logprob": 0.0, "bytes": [46]}]) + self.assertEqual(dot[0]["logprob"], 0.0) + self.assertEqual([e["top_logprobs"] for e in lps if e["token"] != "."], [[]] * (len(lps) - 1)) + + def test_a_choice_of_ten_that_only_the_ended_reply_settles(self): + # ten named ids, and a reply that is two of them: "1" alone is already one of the choices, so which + # one was picked is only known when the reply ends. Here "11": each token's entries cover the ten + # named ids (the chosen one included, because the engine never repeats it), and they sum to 1. + self.engine = self.svc.engine = NamedEngine(self.tok, "11") + digits = [ord(c) for c in "0123456789"] + for stream in (False, True): + out = self.post({"logprobs": True, "top_logprobs": 10, "allowed_token_ids": digits}, stream) + chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"], + "logprobs": out["choices"][0]["logprobs"]}]}] + content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + lps = [e for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(content, "11") + self.assertEqual([e["token"] for e in lps], ["1", "1"]) # the first token alone is a choice too + self.assertEqual("".join(e["token"] for e in lps), content) + for e in lps: + ids = [t["token"] for t in e["top_logprobs"]] + self.assertEqual(sorted(ids), sorted("0123456789")) # the ten named ids, and only them + self.assertIn(e["token"], ids) # the chosen one is one of them + self.assertEqual(ids[0], e["token"]) # ... and the most likely, here + self.assertEqual([t["logprob"] for t in e["top_logprobs"]], + sorted((t["logprob"] for t in e["top_logprobs"]), reverse=True)) + self.assertAlmostEqual(sum(math.exp(t["logprob"]) for t in e["top_logprobs"]), 1.0, places=6) + + def test_a_held_tail_of_more_than_one_token(self): + # "5." is the start of the stop string, so the parser holds two tokens and sends them as one piece + # after the request has left the queue: both entries come from this request's own lines all the same + chunks = self.post({"logprobs": True, "stop": ["5.!"]}, stream=True) + content = [c for c in chunks if c.get("choices") and c["choices"][0]["delta"].get("content")] + self.assertEqual(content[-1]["choices"][0]["delta"]["content"], "5.") # held, then flushed whole + self.assertEqual([e["token"] for e in content[-1]["choices"][0]["logprobs"]["content"]], ["5", "."]) + text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + self.assertEqual(text, "Café costs €5.") + self.assertEqual("".join(e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])), text) + choice = self.post({"logprobs": True, "stop": ["5.!"]})["choices"][0] # and not streamed + self.assertEqual(choice["message"]["content"], "Café costs €5.") + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), "Café costs €5.") + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"][-2:]), "5.") + + def test_json_schema_answer_as_written_with_its_logprobs(self): + # MockEngine appends the stop token to the script it is built with, and reports + # finish_reason=length when it runs out -- so the engine is rebuilt with this answer + # rather than re-pointed at a raw token list (which would drop the stop token). + written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' + self.engine = self.svc.engine = LpEngine(self.tok, written) + out = self.post({"logprobs": True, "temperature": 0, "response_format": SCHEMA}) + choice = out["choices"][0] + content = choice["message"]["content"] + self.assertEqual(content, '{"rent": "$1,250", "quote": "x"}') # the JSON as written + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content) + streamed = self.post({"logprobs": True, "response_format": SCHEMA}, stream=True) + toks = [e["token"] for c in streamed if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), content) + plain = self.post({"temperature": 0, "response_format": SCHEMA}) # not asked: as before + self.assertEqual(plain["choices"][0]["message"]["content"], + '{"rent":"$1,250","quote":"x"}') + self.assertNotIn("logprobs", plain["choices"][0]) + + +class Replicas(unittest.TestCase): + """`--replicas`: a ReplicaEngine's own `batch` is how many requests its engines run at once and counts a replica + without slots as one, so asking it "does this engine use batch slots" refused logprobs on a server that has + none -- one that reads every reply by the GEN path, which does write LP lines.""" + + @staticmethod + def replica(*batches): + from serve.replicas import ReplicaEngine + return ReplicaEngine([SimpleNamespace(gen=1, batch=b) for b in batches]) + + def test_no_slots_behind_replicas(self): + self.assertFalse(batch_slots_on(self.replica(0, 0))) + self.assertFalse(batch_slots_on(SimpleNamespace(batch=0))) # no replicas: the engine's own figure + + def test_slots_behind_replicas(self): + self.assertTrue(batch_slots_on(self.replica(2, 3))) # every one of them + self.assertTrue(batch_slots_on(self.replica(0, 2))) # one is enough + self.assertTrue(batch_slots_on(SimpleNamespace(batch=4))) + + +class Span(unittest.TestCase): + def entries(self, *toks): + return [{"token": t} for t in toks] + + def test_span(self): + es = self.entries("```", "json", "\n", "{", "}", "\n", "```") + self.assertEqual([e["token"] for e in logprob_span("```json\n{}\n```", "{}", es)], ["{", "}"]) + self.assertEqual(len(logprob_span("{}", "{}", self.entries("{", "}"))), 2) + + def test_no_span(self): + self.assertIsNone(logprob_span("x{}", "{}", self.entries("x{", "}"))) # no boundary at the start + self.assertIsNone(logprob_span("{}x", "{}", self.entries("{", "}x"))) # none at the end + self.assertIsNone(logprob_span("{}", "{}", self.entries("{"))) # do not spell it + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_logprobs_parallel.py b/serve/test_logprobs_parallel.py new file mode 100644 index 00000000..cc494aa3 --- /dev/null +++ b/serve/test_logprobs_parallel.py @@ -0,0 +1,117 @@ +"""Logprobs with "parallel" (batch slots): python -m unittest serve.test_logprobs_parallel. + +The fake engine of serve/test_parallel.py behind the real StrataEngine and Service, writing an LP line after each +T line when the GEN / BGEN line asks for logprobs. A typed decision (max_tokens 1) is read on the control lines +(an admission: BGEN, one T, DONE, BADM 0) and gets its logprobs; longer replies are refused with a 400, since the +slot's BT lines carry none. +""" +import json +import threading +import unittest +import urllib.error +import urllib.request +from unittest import mock + +import serve.test_parallel as tp + +# LP after each T when asked: the token's log-probability is -(prompt length) / 1000 (so two requests can be told +# apart) and "A" (65) is its one alternative at -1.5 -- or the named ids themselves, at -1, when the line carries +# `allowed=` (the engine's own branch: it prints those and no top-K) +_T_LINE = ' print(f"T {t}", flush=True)\n' +assert tp.FAKE_BATCH.count(_T_LINE) == 1 +FAKE_LP = tp.FAKE_BATCH.replace(_T_LINE, _T_LINE + ( + ' if " logprobs=" in line:\n' + ' al = [x[8:] for x in line.split() if x.startswith("allowed=")]\n' + ' cs = (" " + " ".join(i + ":-1.000000" for i in al[0].split(","))) if al else " 65:-1.500000"\n' + ' print(f"LP {-len(ids) / 1000:.6f}" + cs, flush=True)\n')) + + +class LogprobsWithBatchSlots(unittest.TestCase): + start, tearDown, get = tp.ParallelService.start, tp.ParallelService.tearDown, tp.ParallelService.get + + def start_lp(self, fake=FAKE_LP, slots=2): + with mock.patch.object(tp, "FAKE_BATCH", fake): + self.start(slots) + + def chat(self, text, max_tokens=1, logprobs=True, allowed=None): + body = {"messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, + "reasoning_effort": "none"} + if logprobs: + body |= {"logprobs": True, "top_logprobs": 1} + if allowed: + body["allowed_token_ids"] = allowed + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + return json.loads(r.read().decode()) + + @staticmethod + def entries(reply): + return ((reply["choices"][0].get("logprobs") or {}).get("content")) or [] + + def test_a_decision_gets_its_logprobs(self): + self.start_lp() + r = self.chat("Is it A or B?") + self.assertEqual(r["choices"][0]["message"]["content"], "o") + e = self.entries(r) + self.assertEqual(len(e), 1) + self.assertEqual(e[0]["token"], "o") + self.assertLess(e[0]["logprob"], 0) + self.assertEqual(e[0]["top_logprobs"], [{"token": "A", "logprob": -1.5, "bytes": [65]}]) + self.assertTrue(any(x.startswith("BGEN") for x in self.log.read_text().splitlines())) # an admission + + def test_the_named_ids_reach_the_slot_and_are_what_is_reported(self): + # allowed_token_ids travels in the same BGEN keys as logprobs, so the engine's own branch answers with + # exactly those ids: the admission path carries the whole feature, not just the top-K one + self.start_lp() + e = self.entries(self.chat("Is it A or B?", allowed=[65])) + self.assertEqual(len(e), 1) + self.assertEqual([x["token"] for x in e[0]["top_logprobs"]], ["A"]) + self.assertEqual(e[0]["top_logprobs"][0]["logprob"], 0) # the whole distribution: just that id + + def test_two_at_once_each_get_their_own(self): + self.start_lp() + short, long_ = "A or B?", "A or B? " + "x" * 300 + alone = {t: self.entries(self.chat(t))[0]["logprob"] for t in (short, long_)} + self.assertNotEqual(alone[short], alone[long_]) + for _ in range(5): + got, errs = {}, [] + + def run(t): + try: + got[t] = self.entries(self.chat(t))[0]["logprob"] + except Exception as exc: # noqa: BLE001 - reported below + errs.append(repr(exc)) + th = [threading.Thread(target=run, args=(t,)) for t in (short, long_, short, long_)] + for x in th: + x.start() + for x in th: + x.join(60) + self.assertEqual(errs, []) + self.assertEqual(got, alone) + + def test_not_asked_nothing_changes(self): + self.start_lp() + r = self.chat("Is it A or B?", logprobs=False) + self.assertEqual(r["choices"][0]["message"]["content"], "o") + self.assertIsNone(r["choices"][0].get("logprobs")) + + def test_longer_replies_are_refused_with_batch_slots(self): + self.start_lp() + with self.assertRaises(urllib.error.HTTPError) as cm: + self.chat("Is it A or B?", max_tokens=8) + self.assertEqual(cm.exception.code, 400) + self.assertIn("max_tokens 1", cm.exception.read().decode()) + # the server is still serving, and a reply that does not ask is untouched + self.assertEqual(self.chat("still serving?", max_tokens=16, logprobs=False)["choices"][0]["message"]["content"], + "ok, done.") + + def test_an_engine_without_lp_lines(self): + self.start_lp(fake=tp.FAKE_BATCH) # an older engine: the key is ignored, no LP line at all + r = self.chat("Is it A or B?") + self.assertEqual(r["choices"][0]["message"]["content"], "o") + self.assertEqual(self.entries(r), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_responses.py b/serve/test_responses.py index d6c4e857..866582c3 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -389,6 +389,21 @@ class OverHttp(Server): code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": 5, "stream": True}) self.assertEqual(events[-1]["type"], "response.incomplete") + def test_max_output_tokens_zero_and_minus_one_mean_no_cap(self): + # #4036: the documented "no cap" values; the answer is complete, not cut at the cap + for n in (0, -1): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n}) + self.assertEqual((code, r["status"]), (200, "completed"), (n, r)) + self.assertIsNone(r["incomplete_details"]) + code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": n, "stream": True}) + self.assertEqual((code, events[-1]["type"]), (200, "response.completed"), n) + + def test_max_output_tokens_bad_values_are_400(self): + for n in (-2, -100, 1.5, True, "5"): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n}) + self.assertEqual(code, 400, (n, r)) + self.assertEqual(r["error"]["param"], "max_output_tokens", n) + def test_effort_none_does_not_think(self): self.engine.scripts = [self.tok.encode("Hello.<|im_end|>", parse_special=True)] self.engine.script = self.engine.scripts[0] diff --git a/serve/test_server.py b/serve/test_server.py index 3e60dee4..935414f9 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3808,6 +3808,19 @@ class UsageAndStatus(unittest.TestCase): self.assertEqual(last["usage"]["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) self.assertEqual(last["timings"]["cache_n"], ClockedEngine.REUSED) + def test_responses(self): + # /v1/responses carries the same top-level timings as /v1/chat/completions + body = {"model": "x", "max_output_tokens": 20, "input": "hi"} + status, raw = self.request("/v1/responses", body) + self.assertEqual(status, 200) + r = json.loads(raw) + self.assertEqual(r["timings"]["cache_n"], ClockedEngine.REUSED) + self.assertEqual(r["timings"]["predicted_n"], r["usage"]["output_tokens"]) + status, raw = self.request("/v1/responses", {**body, "stream": True}) + last = [json.loads(line[6:]) for line in raw.decode().splitlines() if line.startswith("data: {")][-1] + self.assertIn(last["type"], ("response.completed", "response.incomplete")) + self.assertAlmostEqual(last["timings"]["predicted_per_second"], 50.0, delta=0.1) # 20 ms a token + def test_anthropic(self): u = self.chat("/v1/messages")["usage"] self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) diff --git a/serve/test_structured.py b/serve/test_structured.py index 6b66cf8b..f0e2c74a 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -112,6 +112,41 @@ class Structured(unittest.TestCase): # Plain text callers retain normal streaming, without a JSON validation gate. self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) + def test_latex_escape_repair_is_opt_in_and_only_after_a_strict_failure(self): + # #2893: \alpha is not a JSON escape. Off by default: still a 502. On: one retry after the strict parse failed. + bad = r'{"answer":"the angle \alpha and \gamma_0"}' + self.assertEqual(self.chat(bad, response_format={"type": "json_object"})[0], 502) + self.assertEqual(self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": False})[0], 502) + code, reply = self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": True}) + self.assertEqual(code, 200) + self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), + {"answer": "the angle \\alpha and \\gamma_0"}) + # streaming asks for the same check before any content leaves + _, raw = self.chat(bad, stream=True, response_format={"type": "json_object", "repair_latex_escapes": True}) + self.assertIn(r"\\alpha", raw) + # the repair does not hide what is wrong with the answer itself + fmt = {"type": "json_object", "repair_latex_escapes": True} + for script in ('[]', r'{"x":NaN}', r'{"a":"\alpha","a":2}', 'no json at all', r'{"x":"\alpha'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 502, script) + self.assertEqual(self.chat(r'{"answer":"\alpha"}', response_format=fmt, max_tokens=5)[0], 502) + + def test_latex_escape_repair_helper(self): + fix = structured.repair_latex_escapes + self.assertEqual(fix(r'{"a":"\alpha \gamma_0"}'), r'{"a":"\\alpha \\gamma_0"}') + for same in (r'{"a":"x\ny\t\"q\" \\ \/ \u00e9"}', '{"a": 1}', ''): + self.assertEqual(fix(same), same) + self.assertEqual(fix(r'{"a":"\u12"}'), r'{"a":"\\u12"}') # \u without four hex digits + self.assertEqual(fix(r'{"a":"\\alpha"}'), r'{"a":"\\alpha"}') # an escaped backslash is skipped as a pair + self.assertEqual(fix("\\"), "\\\\") # a lone trailing backslash + # \b is a valid escape: untouched, so it parses (as a backspace), as it does without the option + self.assertEqual(json.loads(fix(r'{"a":"\beta \alpha"}'))["a"], "\beta \\alpha") + + def test_the_repair_option_reaches_the_responses_format(self): + from serve.responses import text_format + self.assertEqual(text_format({"text": {"format": {"type": "json_object", "repair_latex_escapes": True}}}), + {"type": "json_object", "repair_latex_escapes": True}) + self.assertEqual(text_format({"text": {"format": {"type": "json_object"}}}), {"type": "json_object"}) + def test_rejected_schema_does_not_load_the_engine_or_retry(self): with mock.patch.object(self.svc, "load") as load: code, _ = self.chat(response_format={"type": "json_schema"}) diff --git a/setup.py b/setup.py index 55f8941f..7723eb59 100644 --- a/setup.py +++ b/setup.py @@ -1551,6 +1551,26 @@ def sm60_card(arch) -> bool: return 60 <= int(arch) <= 70 +def maxwell_card(arch) -> bool: + """#3218: Maxwell (5.x). No ready-made engine holds code for it; it is a source build (docs/OLDER_GPUS.md).""" + return 50 <= int(arch) < 60 + + +def maxwell_note(found) -> str: + """#3218: what to tell a PC whose only NVIDIA cards are Maxwell: setup cannot install an engine for it, and a + source build exists. Empty when there is no Maxwell card. A warning with the way forward, never a switch: setup + does not route a Maxwell card to an engine that holds no code for it.""" + cards = [g for g in found if maxwell_card(g["arch"])] + if not cards: + return "" + names = ", ".join(f"GPU {g['index']} ({g['name']})" for g in cards) + return (f"{names}: Maxwell (compute capability {cc(cards[0])}). No ready-made Strata engine holds code for it, so " + "setup cannot install one. One reporter built the engine from source for two Quadro M6000 with a CUDA 12.x " + "toolkit (cmake -B build -G Ninja -DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52) and saw about " + "22 tokens a second with a 1-bit Qwen3.8-Flash-Next; nobody has checked the answer text yet. Steps and " + "caveats: docs/OLDER_GPUS.md. A card of the RTX 20 series or newer runs the ready-made engine") + + def old_gpus_opt_in(found, named=(), cuda=None, other=False): """Why this run may use Pascal / Volta cards (the experimental CUDA 12 engine), or None. The cards are an opt-in: the user named one (`named`: --gpu / --gpus), asked for --cuda 12, set STRATA_EXPERIMENTAL_SM60=1, or the PC has @@ -1617,7 +1637,8 @@ def gpu_problem(g, together=False): if int(g["arch"]) < 75 and not (sm60_card(g["arch"]) and experimental_sm60()): return (f"not supported - older than the RTX 20 series (compute capability {cc(g)}; Strata needs 7.5 or " "newer" + ("; experimental: choose it with --gpu " + str(g["index"]) + " (the CUDA 12 engine, " - "docs/OLDER_GPUS.md)" if sm60_card(g["arch"]) else "") + ")") + "docs/OLDER_GPUS.md)" if sm60_card(g["arch"]) else + "; Maxwell only runs from a source build, docs/OLDER_GPUS.md" if maxwell_card(g["arch"]) else "") + ")") if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5: return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model " f"needs {SPLIT_MIN_VRAM_GB} GB or more)") @@ -8882,6 +8903,8 @@ def main() -> int: warn(f"older NVIDIA GPUs (Pascal / Volta) can be used ({OLD_GPUS}): experimental, through a second engine " "built with CUDA 12 (docs/OLDER_GPUS.md)") nv_ok = any(gpu_problem(g) is None for g in found) + if not nv_ok and not amd_ok and a.backend != "hip" and maxwell_note(found): # #3218: a warning with the way forward + warn(maxwell_note(found)) hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok)) if a.backend is None and nv_ok and amd_ok: # both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 5e97b8f5..a87e995d 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -2810,12 +2810,30 @@ void Verifier::accumulate_profile_inner(const unsigned long long* stamps) { bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) { const Clock::time_point t0 = Clock::now(); uint32_t spins = 0; + bool announced = false; // the watchdog's label is set only once the wait really starts: no cost when the copies landed while (adapt_gate_->reached() < layer) { + if (!announced) { + progress_at("verify window: waiting for the adaptive tier's copies of layer", layer); + announced = true; + } _mm_pause(); if ((++spins & 1023u) != 0) continue; if (Clock::now() - t0 > std::chrono::seconds(20)) { + // the release drains the window's own streams, never the tier's copy stream: say so, and hand out the + // gate's words and this window's GPU breadcrumbs (STRATA_VERIFY_TRACE) - the last landed layer is the + // exact place the stream stopped, which the released window's error line alone never told (#2188's class) + const int32_t reach = adapt_gate_->reached(), land = adapt_gate_->landed.load(); + const int32_t hl = adapt_gate_->hland != nullptr ? *adapt_gate_->hland : -2; + if (g_trace) trace_ev("GATE-TIMEOUT", -1, layer, reach); + std::fprintf(stderr, "strata verify: the adaptive gate waited %lld ms for layer %d: reached %d " + "(atomic %d, copy signal %d) - the tier's copy stream was not drained by the release\n", + (long long) ms_since(t0), (int) layer, (int) reach, (int) land, (int) hl); + if (g_trace) trace_dump(stderr); err = "verify: the adaptive tier's copies for layer " + std::to_string(layer) + " never landed" + - released_note(release_gpu_waits(5000)); + released_note(release_gpu_waits(5000)) + + " (the copy stream itself is not drained: reached " + std::to_string(reach) + " of " + + std::to_string(layer) + ", STRATA_VERIFY_TRACE=1 prints where the stream stopped)"; + std::fflush(stderr); return false; } } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0d4f4fc2..54d221cd 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -155,6 +155,51 @@ namespace strata::metal_engine { void set_model_shard(const char* shard1); } / #include #include +// logprobs=K / allowed=...: one `LP` line for the token just emitted, from `ver`'s head +// logits for the window row it came from (before sampling, penalties and temperature). +// Format matches the SYCL port's LP line so one server-side reader serves both. +// Called only when the request asked (`req_logprobs >= 0`): a request without logprobs never reaches it, so the +// default path does no work for this and prints exactly what it printed before. +static void emit_lp_line(const strata::core::Verifier& ver, int t, int32_t token, int k, + const std::vector& allowed) { + if (k < 0) return; + static std::vector row; + row.resize((size_t) ver.vocab()); + if (!ver.copy_logits(t, row.data()) || token < 0 || (size_t) token >= row.size()) { + std::printf("LP nan\n"); + return; + } + float mx = -INFINITY; + for (const float v : row) mx = std::max(mx, v); + double se = 0.0; + for (const float v : row) se += std::exp((double) v - (double) mx); + const double lse = (double) mx + std::log(se); + std::printf("LP %.6f", (double) row[(size_t) token] - lse); + if (!allowed.empty()) { + // Only the ids the caller named; the server renormalises over them, which is what allowed_token_ids means. + // The server refuses an id past the vocabulary with a 400 only when it can read the vocabulary size from the + // tokenizer. The engine's own vocab() is the authority: an id past it is left off the line, so the logits + // are never read out of bounds. + for (const int32_t id : allowed) { + if (id == token || id < 0 || (int64_t) id >= ver.vocab()) continue; + std::printf(" %d:%.6f", (int) id, (double) row[(size_t) id] - lse); + } + std::printf("\n"); + return; + } + if (k > 0) { + static std::vector ord; + ord.resize(row.size()); + for (size_t v = 0; v < row.size(); ++v) ord[v] = (int32_t) v; + const int kk = std::min(k, (int) row.size()); + std::partial_sort(ord.begin(), ord.begin() + kk, ord.end(), + [&](int32_t a, int32_t b) { return row[(size_t) a] > row[(size_t) b]; }); + for (int j = 0; j < kk; ++j) + std::printf(" %d:%.6f", ord[(size_t) j], (double) row[(size_t) ord[(size_t) j]] - lse); + } + std::printf("\n"); +} + namespace { // Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, // pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); @@ -12606,6 +12651,11 @@ int main(int argc, char** argv) { std::string req_bias_text; bool req_bias_present = false; int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) + // logprobs=K (0..20): after each "T id" an "LP logprob id:logprob ..." line. + // -1 (absent) = no LP lines, so a server that never asks sees today's output. + int req_logprobs = -1; + // allowed=a,b,c: with logprobs, print only these token ids (renormalized server-side). + std::vector req_allowed; // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root @@ -12645,6 +12695,18 @@ int main(int argc, char** argv) { else if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); + else if (key == "logprobs") req_logprobs = std::atoi(tok.c_str() + eq + 1); + else if (key == "allowed") { + const std::string csv = tok.substr(eq + 1); + size_t p = 0; + while (p < csv.size()) { + const size_t c = csv.find(",", p); + const std::string one = csv.substr(p, c == std::string::npos ? std::string::npos : c - p); + if (!one.empty()) req_allowed.push_back((int32_t) std::atoi(one.c_str())); + if (c == std::string::npos) break; + p = c + 1; + } + } else if (key == "min_p") req_min_p = fv; else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1); else if (key == "penalty_repeat") req_penalty_repeat = fv; @@ -15088,6 +15150,7 @@ int main(int argc, char** argv) { bool eos = false; for (int i = 0; !nf && i <= a && produced_n < max_new && !eos; ++i) { std::printf("T %d\n", (int) outp[(size_t) i]); + if (req_logprobs >= 0) emit_lp_line(V1(A), i, outp[(size_t) i], req_logprobs, req_allowed); strata::core::progress_beat(); ++produced_n; if (o.suffix_draft > 0) sfx.append(outp[(size_t) i]); @@ -15523,6 +15586,7 @@ int main(int argc, char** argv) { bool eos = false; for (int i = merged ? a : 0; i <= a && produced_n < max_new && !eos; ++i) { // (merged: row T-1 only) std::printf("T %d\n", (int) outv[(size_t) i]); + if (req_logprobs >= 0) emit_lp_line(ver, i, outv[(size_t) i], req_logprobs, req_allowed); strata::core::progress_beat(); ++produced_n; if (sfx_on) sfx.append(outv[(size_t) i]); diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 3e257771..93514fc8 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -9791,6 +9791,9 @@ int main(int argc, char **argv) try { // log-probability and the K most likely tokens', from the verify window's head logits (before sampling, // penalties and temperature). -1 (absent): no LP lines; a server that does not ask never sees one. int req_logprobs = -1; + // allowed=a,b,c: with logprobs, print only these token ids (the server renormalises over them; the same key + // the CUDA engine reads). Absent: the K most likely tokens, as before. + std::vector req_allowed; // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root @@ -9826,6 +9829,17 @@ int main(int argc, char **argv) try { else if (key == "penalty_present") req_penalty_present = fv; else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); else if (key == "logprobs") req_logprobs = std::clamp(std::atoi(tok.c_str() + eq + 1), -1, 20); + else if (key == "allowed") { + const std::string csv = tok.substr(eq + 1); + size_t p = 0; + while (p < csv.size()) { + const size_t c = csv.find(",", p); + const std::string one = csv.substr(p, c == std::string::npos ? std::string::npos : c - p); + if (!one.empty()) req_allowed.push_back((int32_t) std::atoi(one.c_str())); + if (c == std::string::npos) break; + p = c + 1; + } + } else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); else if (key == "img_keys") { @@ -11724,7 +11738,14 @@ int main(int argc, char **argv) try { for (const float v : lrow) se += std::exp((double) v - mx); const double lse = (double) mx + std::log(se); std::printf("LP %.6f", (double) lrow[(size_t) outv[(size_t) i]] - lse); - if (req_logprobs > 0) { + if (!req_allowed.empty()) { + // only the ids the caller named (never the chosen one, which the head carries, and never an id + // past the engine's own vocabulary); the server renormalises over them + for (const int32_t id : req_allowed) { + if (id == outv[(size_t) i] || id < 0 || (size_t) id >= lrow.size()) continue; + std::printf(" %d:%.6f", (int) id, (double) lrow[(size_t) id] - lse); + } + } else if (req_logprobs > 0) { lord.resize(lrow.size()); for (size_t v = 0; v < lrow.size(); ++v) lord[v] = (int32_t) v; std::partial_sort(lord.begin(), lord.begin() + req_logprobs, lord.end(), diff --git a/tests/terminal/test_pack_gguf_engram.py b/tests/terminal/test_pack_gguf_engram.py index 17848fa2..448d1c97 100644 --- a/tests/terminal/test_pack_gguf_engram.py +++ b/tests/terminal/test_pack_gguf_engram.py @@ -56,5 +56,51 @@ class EngramHeader(unittest.TestCase): self.assertFalse(PG.is_engram_file(PG.Gguf(tiny_gguf(Path(d) / "m.gguf", "deepseek41")))) +class LegacyModelMetadata(unittest.TestCase): + def test_legacy_engram_names_write_the_same_hash_table(self): + common = { + "general.architecture": "deepseek41", + "deepseek41.engram.max_ngram_size": 2, + "deepseek41.engram.head_count": 1, + "deepseek41.engram.token_map": [0, 1, 2], + "deepseek41.engram.multipliers": [3, 5], + "deepseek41.engram.primes": [7], + "deepseek41.engram.offsets": [0], + } + legacy = {**common, "deepseek41.engram.layer_ids": [1], + "deepseek41.engram.key_length": 256, "deepseek41.engram.pad_id": 2} + current = {**common, "deepseek41.engram.layers": [1], + "deepseek41.engram.head_dim": 256, "deepseek41.engram.pad_token_id": 2, + "deepseek41.engram.key_length": 999, "deepseek41.engram.pad_id": 999} + PG.int_tensors_to_engram([], legacy) + PG.int_tensors_to_engram([], current) + with tempfile.TemporaryDirectory() as d: + a, b = Path(d) / "legacy.bin", Path(d) / "current.bin" + PG.write_engram(a, legacy, 3) + PG.write_engram(b, current, 3) + self.assertEqual(a.read_bytes(), b.read_bytes()) + self.assertEqual(struct.unpack("<4s6i", a.read_bytes()[:28]), + (b"DSE1", 3, 1, 2, 1, 256, 2)) + + def test_source_config_restores_omitted_sparse_geometry(self): + kv = {"general.architecture": "deepseek41", "deepseek41.block_count": 40, + "deepseek41.embedding_length": 5120, "deepseek41.expert_count": 384} + cfg = {"text_config": {"num_hidden_layers": 40, "hidden_size": 5120, + "n_routed_experts": 384, "kv_source_layer_ids": [2, 8, 14, 20], + "index_source_layer_ids": [2, 8, 14, 20, 24, 28, 32, 36], + "candidate_source_layer_id": 20, "candidate_topk_blocks": 2048, + "candidate_block_size": 8}} + PG.apply_source_config(kv, cfg) + geometry = PG.geometry(kv, 129280) + self.assertEqual(geometry["kv_source_layer_ids"], [2, 8, 14, 20]) + self.assertEqual(geometry["index_source_layer_ids"], [2, 8, 14, 20, 24, 28, 32, 36]) + self.assertEqual(geometry["candidate_source_layer_id"], 20) + self.assertEqual(geometry["candidate_topk_blocks"], 2048) + self.assertEqual(geometry["candidate_block_size"], 8) + cfg["text_config"]["candidate_block_size"] = 16 + with self.assertRaisesRegex(SystemExit, "candidate_block_size"): + PG.apply_source_config(kv, cfg) + + if __name__ == "__main__": unittest.main() diff --git a/tools/calibrate.py b/tools/calibrate.py index 182c5a4d..5fbe48f4 100644 --- a/tools/calibrate.py +++ b/tools/calibrate.py @@ -361,7 +361,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke settings["--pcie-frac"] = f"{chosen[0]:.2f}" settings["--spec-min-p"] = f"{chosen[1]:.2f}" base_rate = statistics.median(confirm[chosen]) if confirm.get(chosen) else None - # 4. fewer CPU workers (a restart each), with the chosen settings + # 4. fewer CPU workers (a restart each), with the chosen settings. #1337's rule covers a death during a + # measurement too: an engine that exits mid-rate is that candidate losing; the measurements so far stay. if d_workers and len(worker_candidates(d_workers, extra_workers)) > 1: tuned = with_arg(with_arg(base_args, "--pcie-frac", f"{chosen[0]:.2f}"), "--spec-min-p", f"{chosen[1]:.2f}") by_workers = {} @@ -370,18 +371,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke for index, w in enumerate(workers, 1): _check_cancel(cancel_event) say(f" Measuring with {w} CPU workers (restarts the engine) ...") - e = restart(start_engine, with_arg(tuned, "--pool-workers", None if w == d_workers else str(w)), f"{w} workers", - say, report) - if e is None: - _progress(progress, "cpu_workers", index, len(workers)) - continue - try: - sw = Session(e, ids_list, cancel_event) - sw.warm_up(1) - by_workers[w] = [sw.rate(), sw.rate()] - say(f" {w} workers: {statistics.median(by_workers[w]):.1f} tok/s") - finally: - close(e) + measure_candidate(start_engine, with_arg(tuned, "--pool-workers", None if w == d_workers else str(w)), + f"{w} workers", say, report, by_workers, w, ids_list, cancel_event=cancel_event) _progress(progress, "cpu_workers", index, len(workers)) report["workers"] = {str(k): v for k, v in by_workers.items()} w_best = pick(by_workers, d_workers) if by_workers else d_workers @@ -392,7 +383,9 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke base_rate = statistics.median(by_workers[d_workers]) else: _progress(progress, "cpu_workers", 1, 1) - # 5. the adaptive expert tier (a restart each), with everything chosen so far + # 5. the adaptive expert tier (a restart each), with everything chosen so far. A candidate whose engine dies + # during its own measurement is dropped like a failed start (#1337); the other candidates and every earlier + # result survive. tuned = apply(base_args, settings) by_adapt = {} _progress(progress, "expert_tier", 0, len(ADAPT_CANDIDATES)) @@ -403,17 +396,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke for flag, v in zip(ADAPT_FLAGS, cand or (None,) * len(ADAPT_FLAGS)): args = with_arg(args, flag, v) say(f" Measuring the expert tier {'(the engine default)' if cand is None else 'every ' + cand[0] + ', ' + cand[1] + ' swaps, decay ' + cand[2]} (restarts the engine) ...") - e = restart(start_engine, args, "the expert tier " + key, say, report) - if e is None: - _progress(progress, "expert_tier", index, len(ADAPT_CANDIDATES)) - continue - try: - sa = Session(e, ids_list, cancel_event) - sa.warm_up(1) - by_adapt[key] = [sa.rate(max_new=TIER_MAX_NEW), sa.rate(max_new=TIER_MAX_NEW)] - say(f" {statistics.median(by_adapt[key]):.1f} tok/s") - finally: - close(e) + measure_candidate(start_engine, args, "the expert tier " + key, say, report, by_adapt, key, ids_list, + TIER_MAX_NEW, cancel_event=cancel_event) _progress(progress, "expert_tier", index, len(ADAPT_CANDIDATES)) a_best = pick(by_adapt, "default") if by_adapt else "default" report["adapt"] = by_adapt @@ -433,16 +417,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke _check_cancel(cancel_event) say(f" Measuring the shared expert {'on its own stream' if v == '1' else 'on the main stream (the AMD default)'}" " (restarts the engine) ...") - e = restart(lambda a: start_engine(a, {SH_STREAM: v}), tuned, f"{SH_STREAM}={v}", say, report) - if e is None: - continue - try: - sf = Session(e, ids_list, cancel_event) - sf.warm_up(1) - by_fork[v] = [sf.rate(), sf.rate()] - say(f" {statistics.median(by_fork[v]):.1f} tok/s") - finally: - close(e) + measure_candidate(lambda a: start_engine(a, {SH_STREAM: v}), tuned, f"{SH_STREAM}={v}", say, report, + by_fork, v, ids_list, cancel_event=cancel_event) report["sh_stream"] = by_fork if pick(by_fork, "0") == "1": env[SH_STREAM] = "1" @@ -455,6 +431,10 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke return {"settings": settings, "env": env, "report": report} +def first_line(exc: Exception) -> str: + return str(exc).strip().splitlines()[0][:300] if str(exc).strip() else type(exc).__name__ + + def restart(start_engine, args, what, say, report): """#1337: a later step's engine start that fails is a candidate that loses, not a failed run: what the earlier steps measured (and the settings they chose) must survive it. Returns the engine, or None after saying why and @@ -463,12 +443,36 @@ def restart(start_engine, args, what, say, report): try: return start_engine(args) except Exception as e: # noqa: BLE001 - whatever the start raised (RuntimeError, EngineDied, OSError ...) - why = str(e).strip().splitlines()[0][:300] if str(e).strip() else type(e).__name__ + why = first_line(e) say(f" the engine did not start for {what}: {why} - this candidate is dropped, the earlier results are kept") report.setdefault("failed_starts", {})[what] = why return None +def measure_candidate(start_engine, args, what, say, report, by: dict, key, ids_list, max_new: int | None = None, + cancel_event=None): + """One restart-and-measure candidate (#1337): a start that fails and an engine that exits mid-measurement are + both that candidate losing - `by[key]` gets its two rates, or report["failed_starts"] its reason. Everything + measured earlier and the other candidates survive. An operator cancel is not a candidate death: it raises.""" + e = restart(start_engine, args, what, say, report) + if e is None: + return + try: + s = Session(e, ids_list, cancel_event) + s.warm_up(1) + by[key] = [s.rate(max_new=max_new), s.rate(max_new=max_new)] + say(f" {what}: {statistics.median(by[key]):.1f} tok/s") + except CalibrationCancelled: + raise + except Exception as exc: # noqa: BLE001 - the engine died mid-measurement: this candidate loses (#1337) + why = first_line(exc) + say(f" the engine died while measuring {what}: {why} - this candidate is dropped, " + "the earlier results are kept") + report.setdefault("failed_starts", {})[what] = why + finally: + close(e) + + def close(eng): proc = getattr(eng, "proc", None) if proc is None: diff --git a/tools/dsv41/pack_gguf.py b/tools/dsv41/pack_gguf.py index b56838f5..4a44d1cc 100644 --- a/tools/dsv41/pack_gguf.py +++ b/tools/dsv41/pack_gguf.py @@ -20,6 +20,9 @@ from there when it is present. Nor a vision tower: vision_pack.py makes it from (--vision: another folder), and the pack takes it and its geometry (vision., image_token_id) from there when it is present; without it the engine reads text only. +For older GGUF converters that omit sparse-attention geometry, pass --config-json /path/to/the/source/model/config.json. +Existing metadata must agree with that configuration; the weights are never rewritten. + A quant that leaves the two Engram tables out (v1.1.16's Maya-S; Maya's quants hold them since) takes them from a set of GGUF files that holds them, beside it: --engram, else ../Engram/ (unsloth's MXFP8 shard of them, where setups before v1.1.17 put it) when it is whole. @@ -253,6 +256,29 @@ def ple_to_engram(kv: dict): kv["%s.engram.%s" % (a, k)] = v +def apply_source_config(kv: dict, config: dict): + """Fill sparse-attention geometry omitted by older converters from the model's own config.json.""" + a = kv["general.architecture"] + text = config.get("text_config", config) + fields = { + "embedding_length": "hidden_size", "block_count": "num_hidden_layers", + "expert_count": "n_routed_experts", "attention.compress_ratios": "compress_ratios", + "attention.kv_source_layers": "kv_source_layer_ids", + "attention.indexer.source_layers": "index_source_layer_ids", + "attention.indexer.candidate_source_layer": "candidate_source_layer_id", + "attention.indexer.candidate_top_k_blocks": "candidate_topk_blocks", + "attention.indexer.candidate_block_size": "candidate_block_size", + } + for name, source in fields.items(): + if source not in text: + continue + keys = ["%s.%s" % (a, k) for k in (name, *ALIASES.get(name, ()))] + for key in keys: + if key in kv and kv[key] != text[source]: + raise SystemExit("source config %s disagrees with GGUF %s" % (source, key)) + kv.setdefault(keys[0], text[source]) + + def int_tensors_to_engram(gs, kv: dict): """The IST-DAS sets carry the Engram's hash parameters as integer tensors of the first shard (engram_token_map I32, engram_primes / engram_offsets / engram_multipliers I64, one row a layer) instead of metadata: read them into the @@ -276,7 +302,8 @@ def int_tensors_to_engram(gs, kv: dict): # the IST-DAS spelling of the Engram's scalar keys -> the dotted ones this pack reads for dotted, theirs in (("engram.layers", "engram.layer_ids"), ("engram.max_ngram_size", "engram_max_ngram_size"), ("engram.head_count", "engram_n_heads"), ("engram.head_dim", "engram_head_dim"), - ("engram.pad_token_id", "engram_pad_token_id")): + ("engram.pad_token_id", "engram_pad_token_id"), + ("engram.head_dim", "engram.key_length"), ("engram.pad_token_id", "engram.pad_id")): if "%s.%s" % (a, dotted) not in kv and "%s.%s" % (a, theirs) in kv: kv["%s.%s" % (a, dotted)] = kv["%s.%s" % (a, theirs)] @@ -413,6 +440,7 @@ def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--model", required=True, help="the directory of the GGUF's shards") ap.add_argument("--out", help="default: /maya-ds4") + ap.add_argument("--config-json", help="the exact source model config.json, to fill sparse-attention geometry omitted by older GGUF converters") ap.add_argument("--vision", help="vision_pack.py's folder (default: /../vision; taken when it is there)") ap.add_argument("--dspark-gguf", help="unsloth's DSpark drafter GGUF (dspark-*-Q8_0.gguf, architecture dflash): its three " "blocks become mtp.0-2 beside the trunk's tensors (default: the first dspark-*.gguf " @@ -461,6 +489,8 @@ def main() -> int: if kv is None: arch = next((g.kv.get("general.architecture") for g in gs), None) raise SystemExit("%s: not a DeepSeek-V4.1 GGUF (architecture %r)" % (model, arch)) + if a.config_json: + apply_source_config(kv, json.loads(pathlib.Path(a.config_json).expanduser().read_text())) split = int(kv.get("split.count", 1)) if split != len(shards): counts = sorted({m.group(1) for m in (re.search(r"-of-(\d{5})\.gguf$", p.name) for p in shards) if m}) diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index 97e33597..7ffe1fb6 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -21,9 +21,10 @@ import calibrate as CAL # noqa: E402 class FakeEngine: - """Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`.""" + """Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`. + `dies`: setting values whose engine exits during its first generation (the #267 class, mid-measurement).""" - def __init__(self, args, speed, info_workers=6, starts=None, adapt=None, read=None, reads=None): + def __init__(self, args, speed, info_workers=6, starts=None, adapt=None, read=None, reads=None, dies=()): self.args = list(args) self.read, self.reads = read, reads # prompt read speed = read(prefill_pipe); the values it read with self.adapt_bonus = (adapt or {}).get(CAL.arg_value(args, "--adapt-swaps"), 1.0) @@ -33,10 +34,16 @@ class FakeEngine: self.speed = speed self.last = {} self.proc = None + self.dies = CAL.arg_value(args, "--adapt-swaps") in dies or CAL.arg_value(args, "--pool-workers") in dies + self.dead = False if starts is not None: starts.append(list(args)) def generate(self, ids, max_new, sampling, cancel): + if self.dies and not self.dead: + self.dead = True + raise RuntimeError("the engine exited: ERR verify: the adaptive tier's copies for layer 47 never landed" + " (the copy stream itself is not drained); restart the engine") tune = sampling.get("strata_tune") or {} rate = self.speed(tune.get("pcie_frac", 0.55), tune.get("spec_min_p", self.info["spec_min_p"]), self.workers) rate *= self.adapt_bonus @@ -54,9 +61,10 @@ BASE = ["--pack", "p", "--spec", "4", "--spec-min-p", "0.5", "--max-context", "8 class Calibrate(unittest.TestCase): - def run_with(self, speed, workers=6, base=BASE, adapt=None, read=None, reads=None): + def run_with(self, speed, workers=6, base=BASE, adapt=None, read=None, reads=None, dies=()): starts = [] - res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts, adapt, read, reads), + res = CAL.measure(base, [[1, 2, 3]] * 3, + lambda a: FakeEngine(a, speed, workers, starts, adapt, read, reads, dies), say=lambda *_: None, long_prompt=lambda i, n: [1] * n) return res, starts @@ -233,6 +241,22 @@ class Calibrate(unittest.TestCase): self.assertEqual(CAL.arg_value(a, "--adapt-swaps"), "160") self.assertIsNone(CAL.arg_value(CAL.apply(a, {}), "--adapt-swaps")) # an old calibration's tier goes + def test_engine_death_during_tier_measurement_drops_only_that_candidate(self): + # the 160-swap candidate's engine dies during its own measurement (the adaptive gate's #267 livelock): + # that candidate loses, 80 (10% faster) is still chosen, and the run returns with the earlier results + res, _ = self.run_with(lambda f, p, w: 50.0, adapt={"80": 1.10}, dies=("160",)) + self.assertEqual(res["settings"].get("--adapt-swaps"), "80") + self.assertEqual(list(res["report"]["adapt"]), ["default", "1/80/0.97"]) + self.assertIn("the expert tier 1/160/0.97", res["report"]["failed_starts"]) + + def test_engine_death_during_a_worker_measurement_keeps_the_run(self): + # 4 workers' engine dies mid-measurement: 3 and 2 are still measured, the default count stays, the tier runs + res, _ = self.run_with(lambda f, p, w: 50.0, workers=6, dies=("4",)) + self.assertNotIn("--pool-workers", res["settings"]) + self.assertEqual(sorted(int(k.split()[0]) for k in res["report"]["workers"]), [2, 3, 6]) + self.assertIn("4 workers", res["report"]["failed_starts"]) + self.assertEqual(list(res["report"]["adapt"]), ["default", "1/80/0.97", "1/160/0.97"]) + def test_old_calibration_is_the_baseline_reset(self): # a config tuned earlier: the measurement starts from the product defaults, not from those values base = CAL.apply(BASE, {"--pcie-frac": "0.20", "--pool-workers": "3", "--spec-min-p": "0.70"}) @@ -277,6 +301,18 @@ class Calibrate(unittest.TestCase): self.assertEqual(res["env"], {}) self.assertIn(f"{CAL.SH_STREAM}=1", res["report"]["failed_starts"]) + def test_engine_death_during_a_fork_measurement_keeps_the_run(self): + # the forked engine exits mid-measurement (#267's class): that candidate loses, the run returns + def start(args, env=None): + e = FakeEngine(args, lambda f, p, w: 50.0, 6) + if (env or {}).get(CAL.SH_STREAM) == "1": + e.dies = True + return e + res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=lambda *_: None, hip=True) + self.assertEqual(res["env"], {}) + self.assertEqual(list(res["report"]["sh_stream"]), ["0"]) + self.assertIn(f"{CAL.SH_STREAM}=1", res["report"]["failed_starts"]) + def test_apply_env(self): old = {"STRATA_ROCBLAS_TUNING": "tools/hip", CAL.SH_STREAM: "1"} self.assertEqual(CAL.apply_env(old, {}), {"STRATA_ROCBLAS_TUNING": "tools/hip"}) # an older choice goes diff --git a/tools/test_setup_older_gpus.py b/tools/test_setup_older_gpus.py index d11419e1..99ec6bcf 100644 --- a/tools/test_setup_older_gpus.py +++ b/tools/test_setup_older_gpus.py @@ -88,9 +88,33 @@ class OptIn(unittest.TestCase): self.assertIn("only kind", setup.old_gpus_opt_in([V100])) self.assertIsNone(setup.old_gpus_opt_in([V100], other=True)) # an AMD card it can use instead self.assertIsNone(setup.old_gpus_opt_in([card(0, "GTX 980", 4.0, "52")])) + # #3218: a Maxwell card is never routed to the CUDA 12 engine (it holds no sm_52 code), with or without a switch + m6000 = card(0, "Quadro M6000", 24.0, "52") + self.assertTrue(setup.sm60_card("60") and setup.sm60_card("70") and not setup.sm60_card("75")) + self.assertFalse(setup.sm60_card("52")) + self.assertIn("not supported", setup.gpu_problem(m6000)) + self.assertIn("Maxwell only runs from a source build", setup.gpu_problem(m6000)) + self.assertNotIn("experimental: choose it", setup.gpu_problem(m6000)) + self.assertIsNone(setup.old_gpus_opt_in([m6000])) + for env in ({"STRATA_EXPERIMENTAL_SM60": "1"}, {"STRATA_EXPERIMENTAL_SM52": "1"}): + with mock.patch.dict(os.environ, env): + self.assertFalse(setup.sm60_card("52")) + self.assertIn("not supported", setup.gpu_problem(m6000)) + self.assertIsNone(setup.old_gpus_opt_in([m6000])) + self.assertIsNone(setup.old_gpus_opt_in([m6000], named=[0], cuda="12")) # naming it does not admit it either with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): self.assertEqual(setup.old_gpus_opt_in([rtx, v100]), "STRATA_EXPERIMENTAL_SM60=1") + def test_maxwell_note_is_a_warning_with_the_recipe(self): + m6000 = card(0, "Quadro M6000", 24.0, "52") + note = setup.maxwell_note([m6000, {**m6000, "index": 1}]) + self.assertIn("GPU 0 (Quadro M6000), GPU 1 (Quadro M6000)", note) + self.assertIn("-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52", note) + self.assertIn("docs/OLDER_GPUS.md", note) + self.assertNotIn("STRATA_EXPERIMENTAL_SM52", note) # no switch the user has to set + self.assertEqual(setup.maxwell_note([V100, P40]), "") + self.assertEqual(setup.maxwell_note([]), "") + def test_named(self): self.assertEqual(setup.named_gpus(None, "0,2"), [0, 2]) self.assertEqual(setup.named_gpus(1, None), [1]) @@ -197,6 +221,26 @@ class Install(unittest.TestCase): self.assertIn("sm_70 is older than CUDA 13 supports", out) self.assertIn("experimental", out) + def test_a_maxwell_pc_is_warned_with_the_recipe_and_gets_no_engine(self): + """#3218: no ready-made engine holds sm_52 code, so none is installed; the way forward is printed, with or + without any switch (a user never has to set one).""" + m6000 = card(0, "Quadro M6000", 24.0, "52") + for env in (None, {"STRATA_EXPERIMENTAL_SM60": "1"}, {"STRATA_EXPERIMENTAL_SM52": "1"}): + with self.subTest(env=env): + code, out, cfg, calls, libs = self.run_setup(95.0, [m6000], argv_for("qwen", "IQ3_XXS"), env) + self.assertNotEqual(code, 0, out[-3000:]) + self.assertEqual((calls, libs), ([], [])) + self.assertIsNone(cfg) + self.assertIn("Maxwell (compute capability 5.2)", out) + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=52", out) + self.assertIn("docs/OLDER_GPUS.md", out) + + def test_a_maxwell_card_beside_a_newer_one_is_not_a_warning(self): + rtx = card(0, "NVIDIA GeForce RTX 3090", 24.0, "86") + code, out, cfg, calls, _ = self.run_setup(95.0, [rtx, card(1, "GTX 980", 4.0, "52")], argv_for("qwen", "IQ3_XXS")) + self.assertEqual((code, calls), (0, [13]), out[-3000:]) + self.assertNotIn("Maxwell (compute capability", out) + def test_a_p40_with_an_older_driver(self): code, out, cfg, calls, _ = self.run_setup(95.0, [P40], argv_for("qwen", "IQ3_XXS")) self.assertEqual(code, 0, out[-3000:]) # driver 535: enough for CUDA 12