diff --git a/UPDATE.bat b/UPDATE.bat index b2d9da3f..198e1a99 100644 --- a/UPDATE.bat +++ b/UPDATE.bat @@ -32,7 +32,8 @@ rem All of it in one block: cmd reads a .bat file while it runs it, and the git if defined DIRTY ( echo You have local changes to tracked files here, so nothing was touched. To move to the new history echo yourself ^(your untracked files, models and settings stay where they are^): - echo git branch pre-cleanup-backup ^&^& git stash push + echo git branch pre-cleanup-backup + echo git stash push echo git checkout -B main origin/main echo then run UPDATE.bat again. pause diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index ddd67774..34a3b9b6 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -12,7 +12,7 @@ endif() # same wave32 / 64 KiB LDS / sudot4 family as gfx1100, on a unified-memory APU; experimental. set(_strata_hip_validated gfx1100 gfx1201) set(_strata_hip_community gfx1101 gfx1200) -set(_strata_hip_unvalidated gfx1010 gfx1011 gfx1012 gfx1102 gfx1103 gfx1030 gfx1031 gfx1034 gfx1150 gfx1151) # gfx1103: Radeon 780M iGPU, opt-in, portable kernels (no WMMA) +set(_strata_hip_unvalidated gfx1010 gfx1011 gfx1012 gfx1102 gfx1103 gfx1030 gfx1031 gfx1034 gfx1150 gfx1151 gfx1152) # gfx1103: Radeon 780M iGPU, opt-in, portable kernels (no WMMA); gfx1152: Krackan, Radeon 860M / 840M (#1625), builds with the portable kernels, no card report yet # CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use # spaces, which foreach(IN LISTS) would otherwise treat as one element. string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}") diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 2950a257..9df74204 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -6,6 +6,16 @@ set -e cd /opt/strata || exit 1 +# #1584: the engine in the image is built with AVX2 CPU kernels. A host CPU without AVX2 (Sandy / Ivy Bridge Xeons, +# Bulldozer) runs it into an illegal instruction. A warning, not a stop: recommend, never force (the flags file +# can be wrong in a VM, and a build made on that host may be fine). STRATA_CPUINFO is for the test. +cpuinfo="${STRATA_CPUINFO:-/proc/cpuinfo}" +if [ -r "$cpuinfo" ] && grep -q '^flags' "$cpuinfo" && ! grep -m1 '^flags' "$cpuinfo" | grep -qw avx2; then + echo "WARNING: this host CPU has no AVX2. The engine in this image is built for CPUs with AVX2, so it may stop" >&2 + echo " with 'illegal instruction' (exit 132). Build the image on this machine (docker build), which compiles the" >&2 + echo " engine for the CPU it runs on, and see docs/INSTALL.md (Older CPUs, experimental) for the older-CPU build." >&2 +fi + STRATA_DATA="${STRATA_DATA:-/data}" FAMILY="${FAMILY:-qwen}" MODEL="${MODEL:-IQ2_XS}" diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 8aea5ed3..692b667c 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -441,6 +441,10 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 [bench/results/2026-10-07-community-gfx1150](../bench/results/2026-10-07-community-gfx1150/README.md). Setup does not install for it yet (an integrated Radeon other than Strix Halo is named and not supported): build by hand with `-DCMAKE_HIP_ARCHITECTURES=gfx1150` and point `STRATA_HIPBLASLT_TUNING` at the table yourself. +- **gfx1152** (Radeon 860M / 840M, Ryzen AI 300 "Krackan", #1625): in CMake's unvalidated list like gfx1150, so + `-DCMAKE_HIP_ARCHITECTURES=gfx1152` builds with a warning. It runs the portable kernels (the matrix-core guards name + gfx1150 and gfx1151 only), no card has reported on it, and setup does not install for it (an integrated Radeon other + than Strix Halo is named and not supported). A report from a real 860M is welcome. - **Not validated:** gfx1032 (the same `dp4a` path, no hardware report), setup's own build path and the `gfx103X-all` wheels on gfx1030, images, answer-quality benchmarks. RDNA1 (gfx1012, RX 5500 XT) builds by hand: [OLDER_GPUS.md](OLDER_GPUS.md#amd-building-gfx906-and-gfx1012). diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d5a0c1fd..d8fd0db3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -932,6 +932,14 @@ If reserving space for growth would evict another conversation, parking uses a full capture instead. Oldest parked entries are evicted first. Oversized snapshots or host allocation failures fall back to ordinary prompt processing. +`--conversation-cache-min-tokens N` (default 0 = park every conversation) parks only conversations of at least N +tokens. A parked conversation costs one of the slots whatever its length, and parking is a switch-time decision, so a +client that interleaves short side requests with one long conversation spends the cache on the side requests and, once +it is full, evicts the long one oldest-first - exactly the reuse it wanted. Setting the minimum above the side +requests' length keeps the long conversation parked. The check runs before `make_room()`, so a skipped park evicts +nothing and stores nothing; the log line is `conversation cache: skip parking (N tokens, below the M minimum; +parked=P)`. 0 is the pre-flag behaviour and the flag leaves the answers untouched - it only decides which +conversations keep a slot. `--conversation-cache-min-free-mib N` (default 2560) additionally requires that physical-RAM headroom remain available: the engine checks before allocation and again after capture. Unknown telemetry or insufficient RAM skips parking. Windows diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 5659f97e..804adbdb 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -113,7 +113,8 @@ leaves out the ones every card's cache holds, not only the first card's, and whe the hottest by the expert profile over all the layers. An adaptive swap copies the evicted expert back into RAM from the card that owns its layer. Before, `--resident-experts` with a split ran as `--mmap-experts`, and setup recommended one card in the low-RAM mode; with an engine that has it (`RESIDENT_SPLIT_ENGINE` in setup.py), setup keeps the cards -together and the experts no card holds in RAM. Swift 1.5 IQ3_XXS at +together and the experts no card holds in RAM. The same copy, sized by a RAM budget (`--resident-budget-gib`, the +Unsloth UD-Q4_K_XL and UD-IQ4_XS configs), is kept on a split as well ([UNSLOTH_Q4.md](UNSLOTH_Q4.md)). Swift 1.5 IQ3_XXS at 160K (q4_0 KV, `--prefill 4096`, `--spec 4` with the stock draft layer), RTX 4060 Ti (layers 0-19) + RTX 5080 (20-47), i9-14900KF, 32 GB of RAM, Windows 11, four greedy prompts at a time, decode tok/s: diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.md index 5b3080a5..f6c2d263 100644 --- a/docs/UNSLOTH_Q4.md +++ b/docs/UNSLOTH_Q4.md @@ -26,9 +26,16 @@ What setup does differently for this model: engine 0.1.32 or newer (checked before anything is downloaded), and an NVIDIA GPU: it has not been run on AMD cards (its prompt kernels for the Q4_K / Q5_K experts are NVIDIA-only), so with `--backend hip` setup says so and asks before the download (#429; `--model UD-Q4_K_XL --yes` tries it). One GPU - by default: the RAM budget below has no layer split (the engine refuses `--resident-budget-gib` with one). No + by default (the tested setup); on several, see the next point. No experimental speed projection (not tested with it). Images (#967) are an option, with a warning that this file is untested with them (reported working, #971). -- Several GPUs (#498): when the RAM holds the GGUF files and 24 GB more (~135 GB of RAM) and two or more cards can +- Several GPUs, with an engine that keeps the resident RAM copy on a layer split (0.1.40 and newer, #642): the RAM + budget is kept on the split. Each card caches the experts of its own layers, and the budget holds the hottest of + the rest by the whole expert profile (the experts no card holds), so any RAM works as on one card. Setup asks (one + GPU stays the default; `--gpus 0,1`, "2" at setup or "y" when a start offers both cards takes the split), and a + start on several GPUs keeps `--resident-budget-gib`. Measured on an RTX 3090 (x16) + RTX 3080 Ti (x4), 91 GB of RAM, + budget 64 GiB, engine 0.1.41: decode 45 tok/s against 38 on the 3090 alone (the auto split gives the x4 card two + layers); 57.6 GiB of experts in RAM, no file reads per request. +- Several GPUs with an older engine (#498): when the RAM holds the GGUF files and 24 GB more (~135 GB of RAM) and two or more cards can share it, setup asks (one GPU stays the default; `--gpus 0,1` takes the split). The split runs **without** the RAM budget: all 77 GB of experts are loaded into RAM from the GGUFs at start, the files pass through the OS file cache while they load, and the config gets `"gpu": [0, 1]` and `"layer_split": "auto"`. Measured on 2x RTX 3090 with 165 GiB (#498): decode 31 tok/s on one card with the budget, @@ -243,7 +250,7 @@ PLE table, a Q6_K head) is UD-Q4_K_XL's. Three shards, 93.7 GB: Setup treats it like UD-Q4_K_XL (the list above): the same RAM budget (your RAM less 24 GB; at most all 55 GiB of its experts, so a PC with ~80 GB of RAM or more holds all of them), the pack with `--compat-bf16`, no `experts.bin`, one -GPU by default. It does not ask on AMD: its experts' formats have prompt kernels there too. Images are an option (asked, +GPU by default (several keep the budget, as above). It does not ask on AMD: its experts' formats have prompt kernels there too. Images are an option (asked, off by default; NVIDIA): the image path has no restriction for this pack, which uses the original model's image encoder; not yet run with images. diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index 298dc3bc..1be01432 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -455,7 +455,14 @@ private: if (a->u) align = a->u; alignment_ = align; data_start_ = (c.pos() + align - 1) / align * align; - if (data_start_ > size_) throw std::runtime_error("GGUF: data section starts past EOF"); + if (data_start_ > size_) { + // A file with tensors needs its data section. One without (a split model's metadata-only first + // shard) may end at its header, before the aligned start - unsloth's UD-Q5_K_XL shard 1 ends 6 bytes + // short, and llama.cpp's gguf-py reads it. Nothing is read there; the clamp keeps + // `file_size() - data_start()` (the payload checks downstream) at 0 instead of wrapping. + if (n_tensors != 0) throw std::runtime_error("GGUF: data section starts past EOF"); + data_start_ = size_; + } } std::string path_; diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 9938bb6f..56d0d774 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -196,8 +196,14 @@ public: bool live = false; }; - ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {} + ConversationCache(size_t budget, size_t slots, int64_t min_tokens = 0) + : budget_(budget), slots_(slots), min_tokens_(min_tokens) {} bool enabled() const { return budget_ != 0 && slots_ != 0; } + /// `--conversation-cache-min-tokens`: whether a conversation of this length is worth one of `slots`. Every + /// parked conversation costs a whole slot whatever its length, so a client that interleaves short side requests + /// with one long conversation spends the cache on the side requests and evicts the long one (oldest first) - + /// exactly the reuse it wanted. 0 parks every conversation, whatever its size. + bool wants(int64_t tokens) const { return min_tokens_ <= 0 || tokens >= min_tokens_; } size_t bytes() const { return bytes_ + reuse_.bytes(); } size_t size() const { return entries_.size(); } size_t evictions() const { return evictions_; } @@ -332,6 +338,7 @@ public: private: size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0, superseded_ = 0; + int64_t min_tokens_ = 0; // --conversation-cache-min-tokens: 0 parks every conversation, whatever its size std::deque entries_; // least recently active first ConversationKvReuse reuse_; }; diff --git a/serve/frontend.py b/serve/frontend.py index 1dccb91c..685b8d84 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -767,13 +767,44 @@ class OutputParser: p = self.buf.find(FUNC_START, p + 1) return -1, False + @property + def line(self) -> str: + """Materialize the current line only for a decision, newline, or state snapshot.""" + if self._line_blocks is not None: + self._line_blocks.extend(self._line_parts) + self._line_parts = ["".join(self._line_blocks)] + self._line_blocks = None + elif len(self._line_parts) > 1: + self._line_parts = ["".join(self._line_parts)] + return self._line_parts[0] if self._line_parts else "" + + @line.setter + def line(self, text: str): + self._line_parts = [text] if text else [] + self._line_blocks = None + def _track(self, text: str) -> str: """Follow the reasoning text that has gone out: the open code fence, the current line, and the backticks of the current paragraph. Returns the text.""" + # Most token fragments stay on the current line. Fence and paragraph + # bookkeeping happens only when a newline completes that line. + if "\n" not in text: + if text: + self._line_parts.append(text) + if len(self._line_parts) == 64: + # Release small fragment objects in bounded groups. Completed + # blocks are never recopied until the full line is requested. + if self._line_blocks is None: + self._line_blocks = [] + self._line_blocks.append("".join(self._line_parts)) + self._line_parts.clear() + return text parts = text.split("\n") for k, part in enumerate(parts): if k < len(parts) - 1: - line, self.line = self.line + part, "" + line = self.line + part if self._line_parts or self._line_blocks else part + self._line_parts.clear() + self._line_blocks = None s = line.lstrip() if self.fence: if s.startswith(self.fence * 3): @@ -785,7 +816,8 @@ class OutputParser: else: self.ticks += line.count("`") else: - self.line += part + if part: + self._line_parts.append(part) return text def _opener_ok(self) -> bool: @@ -797,6 +829,19 @@ class OutputParser: """The text so far leaves the next character inside a code fence or inline code.""" return bool(self.fence) or (self.ticks + self.line.count("`")) % 2 == 1 + def _quoted_think_end(self, i: int) -> bool | None: + """#537: the `` at self.buf[i] is the model quoting the tag while it thinks, not the end of the + thinking: written right after a quote or backtick and followed by anything but a line break, as in `` + or "...". The end of the thinking is followed by a line break. None while the character after the + tag has not arrived.""" + before = self.buf[i - 1] if i else self.line[-1:] + if before not in ('"', "'", "`"): + return False + after = self.buf[i + len(THINK_END):] + if not after: + return None + return after[0] not in "\r\n" + def _release(self, deliver: bool) -> list[Event]: """Settle the calls waiting in self.pending: events for real calls, or all of it back as reasoning text.""" out = [] @@ -1005,6 +1050,16 @@ class OutputParser: out.append(Event("reasoning", self._track(self.buf[:len(self.buf) - keep]))) self.buf = self.buf[len(self.buf) - keep:] return out + quoted = self._quoted_think_end(i) + if quoted is None: # held like a partial tag until the character after it is here + if i: + out.append(Event("reasoning", self._track(self.buf[:i]))) + self.buf = self.buf[i:] + return out + if quoted: # #537: a quoted `` is reasoning text + out.append(Event("reasoning", self._track(self.buf[:i + len(THINK_END)]))) + self.buf = self.buf[i + len(THINK_END):] + continue if i: out.append(Event("reasoning", self._track(self.buf[:i]))) self.buf = self.buf[i + len(THINK_END):] @@ -1167,6 +1222,8 @@ class OutputParser: self.buf = "" self._reset_scan() return out + if self.state == "reasoning" and self.buf == THINK_END: # the output ends on a held ``: its end + self.buf, self.state = "", "content" if self.buf: # an unfinished call inside the reasoning (#804) is reasoning text, never a call kind = {"reasoning": "reasoning", "rcall": "reasoning", "content": "content"}.get(self.state, "content") diff --git a/serve/server.py b/serve/server.py index 986c5994..c950d251 100644 --- a/serve/server.py +++ b/serve/server.py @@ -54,7 +54,7 @@ from urllib.parse import parse_qs, urlsplit ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module -from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 +from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages, tool_choice_of, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 @@ -196,6 +196,7 @@ def focused_recovery_prompt(tok, ids, generated): LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1") +QUEUE_BEAT_S = 10.0 # a request waiting for the single turn sends a keep-alive this often (#1619) CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here # The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first # token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer. @@ -690,8 +691,10 @@ class StrataEngine: pass why = (f"the engine did not report READY within {ENGINE_READY_S:.0f} s" if timed_out else "the engine exited before it was ready") - raise RuntimeError(why + (f" (see {log})" if log else "") + - start_failure_hint(log, log_start) + start_log_tail(log, log_start)) + # EngineDied, not bare RuntimeError: a request waiting on this load must end with a 503 + # through the request path's handler - a RuntimeError there left the turn with no answer (#1527) + raise EngineDied(why + (f" (see {log})" if log else "") + + start_failure_hint(log, log_start) + start_log_tail(log, log_start)) self.known_ctx = self.max_context # survives a failed restart: requests keep their limit and restart it # (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that # report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones @@ -878,8 +881,10 @@ class StrataEngine: time.sleep(self.RESTART_RETRY_S) finally: self.starting = False - with self.slot_cv: # #1012: wake the requests that waited through it: they go on with the - self.slot_cv.notify_all() # new engine, or (it did not start) end with a clean EngineDied + # a lazy first start never reached the post-READY __init__ where slot_cv is made (#1527) + if "slot_cv" in self.__dict__: + with self.slot_cv: # #1012: wake the requests that waited through it: they go on with the + self.slot_cv.notify_all() # new engine, or (it did not start) end with a clean EngineDied self.info = {**info, **self.info} def _parse_done(self, line): @@ -3365,12 +3370,14 @@ class Service: room = ctx - CTX_SLACK - len(ids) if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1): if room < 1: - raise ValueError(f"prompt ({len(ids)} tokens) leaves no room to answer in the context " + raise ValueError("request exceeds the context window: " + f"prompt ({len(ids)} tokens) leaves no room to answer in the context " f"({ctx}); requests are never truncated") max_new = room elif max_new > room: if not self.fit_max_tokens: - raise ValueError(f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context " + raise ValueError("request exceeds the context window: " + f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context " f"({ctx}); requests are never truncated. Send a smaller " f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the " "model's strata-.json to shorten it to the room left (#545)") @@ -3564,7 +3571,32 @@ class Service: self.status["queued"] += 1 try: # --batch: the engine runs several requests at once (StrataEngine.generate_batched orders them) - with (contextlib.nullcontext() if getattr(self.engine, "batch", 0) else self.fifo): + turn = contextlib.ExitStack() + if not getattr(self.engine, "batch", 0): + # #1619: a request waiting for the single turn sends a keep-alive every QUEUE_BEAT_S, so a client with + # a stream idle timeout does not abort a healthy queued request (and its retry read the prompt again); + # a client that left while queued gives its place up instead of taking the turn only to cancel there + got = False + try: + while not got: + got = self.fifo.acquire(timeout=QUEUE_BEAT_S) + if got: + turn.callback(self.fifo.release) + elif cancel.is_set(): + break + else: + yield "ping", None + except BaseException: # the consumer closed us at a ping: no longer queued + with self.status_lock: + self.status["queued"] -= 1 + raise + if not got: # cancelled while queued + with self.status_lock: + self.status["queued"] -= 1 + yield "done", {"finish": "cancel", "completion_tokens": 0, "reused": 0, "timings": None, + "reasoning_tokens": 0, "reasoning_recoveries": 0} + return + with turn: try: with self.status_lock: if trace is not None: @@ -3622,6 +3654,9 @@ class Service: with self.status_lock: trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3) if t in self.stop_ids: + if force and parser.state == "reasoning" and parser.buf == THINK_END: + opens = True # #537: the held was the end: the call opens there + break finish = "stop" raw_ids.append(t) break @@ -3718,6 +3753,7 @@ class Service: continue if (self.reasoning_close_retry and thinking and finish == "stop" and not close_retried and not answered and not wrap and not opens and parser.state == "reasoning" + and parser.buf != THINK_END # #537: not after a held , the end and (stops is None or stops.hit is None) and not cancel.is_set()): # #1053: the model wrote its reasoning and stopped before : the client would get # an empty answer. Close the thinking once and let it answer. @@ -4362,10 +4398,13 @@ def make_handler(svc: Service): if size < 0: raise BadBody(400, "malformed chunk size in the request body") if size == 0: - for _ in range(64): # the trailers, up to the blank line - if self.rfile.readline(8193).strip() == b"": - break - return b"".join(parts) + for _ in range(64): # the trailers, including the final blank line + trailer = self.rfile.readline(8193) + if trailer == b"\r\n": + return b"".join(parts) + if not trailer.endswith(b"\r\n"): + raise BadBody(400, "malformed or incomplete chunked request trailers") + raise BadBody(400, "too many chunked request trailers") total += size if total > limit: self.close_connection = True diff --git a/serve/telemetry.py b/serve/telemetry.py index 8a629e04..497ac9ad 100644 --- a/serve/telemetry.py +++ b/serve/telemetry.py @@ -307,6 +307,8 @@ class Telemetry: c = self.ps.disk_io_counters() except (OSError, RuntimeError): return None, None + if c is None: # psutil found no disk (a gVisor container, Windows with its disk counters off) + return None, None t = time.time() prev, self._disk_prev = self._disk_prev, (t, c.read_bytes, c.write_bytes) if prev is None or t <= prev[0]: diff --git a/serve/test_chunked_body.py b/serve/test_chunked_body.py index 45428a94..1686352e 100644 --- a/serve/test_chunked_body.py +++ b/serve/test_chunked_body.py @@ -1,5 +1,6 @@ """#893 / #894: a request body sent as Transfer-Encoding: chunked (a relay or proxy) is decoded, on every route that -reads a body; a malformed or oversized one is a 400 / 413, not an empty body. +reads a body; a malformed or oversized one is a 400 / 413, not an empty body. Incomplete chunked framing must not +apply an otherwise valid JSON body. python -m unittest serve.test_chunked_body -v """ @@ -100,6 +101,48 @@ class ChunkedBody(unittest.TestCase): status, got = self.send(head, chunked(body)) self.assertEqual(status, 200, got) + def assert_settings_body_rejected(self, extra: bytes, body: bytes): + previous = dict(self.svc.shared) + self.addCleanup(self.svc.set_shared, previous) + before = self.svc.set_shared({"temperature": 0.7}) + head = b"/settings HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF + extra + status, got = self.send(head, body) + self.assertEqual((status, self.svc.shared), (400, before), got) + + def test_incomplete_chunked_trailers_do_not_change_settings(self): + body = json.dumps({"defaults": {"temperature": 0.5}}).encode() + prefix = chunked(body)[:-len(CRLF)] # the zero chunk, without the terminating blank line + for tail in (b"", b"X-Trailer: 1", b"X-Trailer: 1" + CRLF, b"\r", b"\n", b" " + CRLF): + with self.subTest(tail=tail): + self.assert_settings_body_rejected(b"Transfer-Encoding: chunked" + CRLF, prefix + tail) + + def test_chunked_trailer_limit_does_not_change_settings(self): + body = json.dumps({"defaults": {"temperature": 0.5}}).encode() + prefix = chunked(body)[:-len(CRLF)] + for end in (b"", CRLF): + with self.subTest(end=end): + trailers = (b"X-Trailer: 1" + CRLF) * 64 + end + self.assert_settings_body_rejected(b"Transfer-Encoding: chunked" + CRLF, prefix + trailers) + + def test_an_overlong_chunked_trailer_does_not_change_settings(self): + body = json.dumps({"defaults": {"temperature": 0.5}}).encode() + trailers = b"X-Trailer: " + b"x" * 8193 + CRLF + self.assert_settings_body_rejected(b"Transfer-Encoding: chunked" + CRLF, chunked(body, trailers=trailers)) + + def test_complete_settings_bodies_still_apply(self): + previous = dict(self.svc.shared) + self.addCleanup(self.svc.set_shared, previous) + body = json.dumps({"defaults": {"temperature": 0.5}}).encode() + for extra, framed in ((b"Content-Length: %d" % len(body) + CRLF, body), + (b"Transfer-Encoding: chunked" + CRLF, chunked(body)), + (b"Transfer-Encoding: chunked" + CRLF, + chunked(body, trailers=(b"X-Trailer: 1" + CRLF) * 63))): + with self.subTest(extra=extra, size=len(framed)): + self.svc.set_shared({"temperature": 0.7}) + head = b"/settings HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF + extra + status, got = self.send(head, framed) + self.assertEqual((status, self.svc.shared), (200, {"temperature": 0.5}), got) + def test_a_chunked_control_body_is_consumed(self): head = (b"/unload HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF + b"Transfer-Encoding: chunked" + CRLF) diff --git a/serve/test_context_overflow.py b/serve/test_context_overflow.py new file mode 100644 index 00000000..8c68b77e --- /dev/null +++ b/serve/test_context_overflow.py @@ -0,0 +1,117 @@ +"""#1615: recognizable context-overflow errors over HTTP, without a GPU or model pack. + + python -m unittest serve.test_context_overflow -v +""" +import http.client +import json +import unittest +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import CTX_SLACK, ByteTokenizer, MockEngine, Service, serve + +ROOT = Path(__file__).resolve().parents[1] +CTX = 131072 +APIS = (("/v1/chat/completions", "max_tokens"), + ("/v1/messages", "max_tokens"), + ("/v1/responses", "max_output_tokens")) + + +class ContextOverflow(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = MockEngine(tok, "ok", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.port = cls.httpd.server_address[1] + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def setUp(self): + self.svc.fit_max_tokens = False + + def post(self, path, budget_key, prompt_tokens, max_tokens=None, stream=False): + body = {"input": "hi"} if path == "/v1/responses" else { + "messages": [{"role": "user", "content": "hi"}]} + body["stream"] = stream + if max_tokens is not None: + body[budget_key] = max_tokens + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) + try: + with mock.patch.object(self.svc, "encode_prompt", return_value=[ord("x")] * prompt_tokens): + c.request("POST", path, json.dumps(body), {"Content-Type": "application/json"}) + r = c.getresponse() + return r.status, r.getheader("Content-Type"), json.loads(r.read()) + finally: + c.close() + + def test_both_overflow_errors_are_recognizable_before_streaming(self): + # The full prompt case reproduces #1615. fit_max_tokens cannot rescue it. + cases = ((150722, None, False, "no room to answer"), + (150722, 16, True, "no room to answer"), + (150722, 16, False, "+ max tokens (16)"), + (1024, CTX, False, f"+ max tokens ({CTX})")) + for path, key in APIS: + for stream in (False, True): + for prompt, budget, fit, detail in cases: + with self.subTest(path=path, stream=stream, prompt=prompt, budget=budget, fit=fit): + self.svc.fit_max_tokens = fit + with mock.patch.object(self.engine, "generate") as generate: + status, content_type, body = self.post(path, key, prompt, budget, stream) + generate.assert_not_called() + self.assertEqual(status, 400, body) + self.assertIn("application/json", content_type) + error = body["error"] + self.assertEqual(error["type"], "invalid_request_error") + message = error["message"] + # OpenAI's established wording, recognized by client overflow classifiers. + self.assertIn("exceeds the context window", message) + self.assertIn(f"prompt ({prompt} tokens)", message) + self.assertIn(detail, message) + self.assertIn(f"({CTX})", message) + self.assertIn("requests are never truncated", message) + if "+ max tokens" in detail: + room = max(0, CTX - CTX_SLACK - prompt) + self.assertIn(f"max_tokens (at most {room} here)", message) + self.assertIn('"fit_max_tokens": true', message) + if path == "/v1/responses": + self.assertEqual(error["code"], "context_length_exceeded") + self.assertEqual(error["param"], "input") + else: + self.assertEqual(set(error), {"type", "message"}) + + def test_one_token_of_room_still_answers_but_zero_is_rejected(self): + for path, key in APIS: + for fit in (False, True): + with self.subTest(path=path, fit=fit): + self.svc.fit_max_tokens = fit + status, _, body = self.post(path, key, CTX - CTX_SLACK - 1, 1) + self.assertEqual(status, 200, body) + status, _, body = self.post(path, key, CTX - CTX_SLACK, 1) + self.assertEqual(status, 400, body) + self.assertIn("exceeds the context window", body["error"]["message"]) + + def test_prepare_preserves_prompt_and_budget_limits(self): + ids = [ord("x")] * 1024 + room = CTX - CTX_SLACK - len(ids) + for fit in (False, True): + self.svc.fit_max_tokens = fit + for budget in (None, 0, -1, 1, room, room + 1): + with self.subTest(fit=fit, budget=budget), \ + mock.patch.object(self.svc, "encode_prompt", return_value=ids): + if budget == room + 1 and not fit: + with self.assertRaises(ValueError): + self.svc.prepare([], None, {}, budget) + else: + prepared, _, maximum = self.svc.prepare([], None, {}, budget) + self.assertEqual(prepared, ids) + self.assertEqual(maximum, 1 if budget == 1 else room) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_parser_track.py b/serve/test_parser_track.py new file mode 100644 index 00000000..53f7ef76 --- /dev/null +++ b/serve/test_parser_track.py @@ -0,0 +1,126 @@ +"""Tracking state must be identical at every streamed fragment, not just at the end.""" +import itertools +import random +import unittest + +from serve.frontend import OutputParser + + +class ReferenceParser(OutputParser): + # Keep the original string storage as well as the original tracking algorithm. + line = "" + + def _track(self, text): + parts = text.split("\n") + for k, part in enumerate(parts): + if k < len(parts) - 1: + line, self.line = self.line + part, "" + s = line.lstrip() + if self.fence: + if s.startswith(self.fence * 3): + self.fence = "" + elif s[:3] in ("```", "~~~") and (s[0] * 3) not in s[3:]: + self.fence = s[0] + elif not s: + self.ticks = 0 + else: + self.ticks += line.count("`") + else: + self.line += part + return text + + +class TrackTests(unittest.TestCase): + def assert_state(self, actual, expected): + self.assertEqual((actual.line, actual.fence, actual.ticks), + (expected.line, expected.fence, expected.ticks)) + self.assertEqual(actual._opener_ok(), expected._opener_ok()) + self.assertEqual(actual._in_code(), expected._in_code()) + + def test_fragment_state_from_varied_initial_states(self): + fragments = ("", "a", "é🙂", "`", "``", "```", "~~~", "\r", "\n", "\r\n", + "\n\n", " ```python\n", "```quoted```\n", "~\ntext", "\t\nrest") + for fence, line, ticks, text in itertools.product(("", "`", "~"), + ("", " ", "``", "code `"), + (0, 1, 2, 3), fragments): + actual, expected = OutputParser(), ReferenceParser() + for parser in (actual, expected): + parser.fence, parser.line, parser.ticks = fence, line, ticks + self.assertEqual(actual._track(text), expected._track(text)) + self.assert_state(actual, expected) + + def test_random_streaming_boundaries(self): + text = ("Reasoning `inline` café 🙂\n\n ```python\nquoted\n```\n" + "~~~xml\r\n\n~~~\n\nAnswer\n" * 8) + rng = random.Random(1029) + for _ in range(50): + actual, expected = OutputParser(), ReferenceParser() + pos = 0 + while pos < len(text): + end = pos + rng.randint(1, 17) + fragment = text[pos:end] + self.assertEqual(actual._track(fragment), expected._track(fragment)) + self.assert_state(actual, expected) + pos = end + + def test_long_line_snapshots_restore_and_append(self): + actual, expected = OutputParser(), ReferenceParser() + for parser in (actual, expected): + # Include Unicode and backticks: string materialization must preserve + # characters and the code decision, even after a restored snapshot. + for _ in range(4096): + parser._track("abc café 🙂 `") + self.assert_state(actual, expected) + for parser in (actual, expected): + saved = (parser.fence, parser.line, parser.ticks) + parser.buf = "\n```python\nignored" + parser._ok_at(len(parser.buf)) + self.assertEqual((parser.fence, parser.line, parser.ticks), saved) + parser._track("more text") + self.assertEqual(saved[1] + "more text", parser.line) + parser._track("\n~~~\ninside\n~~~\n") + self.assert_state(actual, expected) + + def test_feed_events_with_long_lines_and_quoted_tool_tags(self): + text = ("prefix " * 1024 + "``\n\n```xml\n" + "x" * 16384 + + "\n```\n" + + "ok\nDone") + for recover, stream in itertools.product((False, True), repeat=2): + kwargs = dict(thinking=False, tools=[{"name": "write"}], recover=recover, stream_tools=stream) + actual, expected = OutputParser(**kwargs), ReferenceParser(**kwargs) + def normalized(events): + return [(e.kind, e.text, (e.call.name, e.call.arguments) if e.call else None) for e in events] + for pos in range(0, len(text), 17): + delta = text[pos:pos + 17] + self.assertEqual(normalized(actual.feed(delta)), normalized(expected.feed(delta))) + self.assertEqual(normalized(actual.finish()), normalized(expected.finish())) + + def test_compaction_boundaries_reads_and_line_replacement(self): + for count in (63, 64, 65, 127, 128, 129, 1025): + actual, expected = OutputParser(), ReferenceParser() + for i in range(count): + text = f"{i}: café 🙂 `" + actual._track(text) + expected._track(text) + saved = actual.line + self.assert_state(actual, expected) + # Reading a joined line must not lose it when another block fills. + for i in range(129): + text = f"{i}: more" + actual._track(text) + expected._track(text) + self.assert_state(actual, expected) + # Replacing the line discards every old block, including a partial tail. + for parser in (actual, expected): + parser.line = saved + parser._track("\n```python\n") + for _ in range(count): + parser._track("code") + parser._track("\n```\n\n") + parser._track("new line") + self.assert_state(actual, expected) + self.assertEqual(actual.line, "new line") + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_queue_keepalive.py b/serve/test_queue_keepalive.py new file mode 100644 index 00000000..d7d35656 --- /dev/null +++ b/serve/test_queue_keepalive.py @@ -0,0 +1,77 @@ +"""#1619: a request waiting for the single request turn sends keep-alive comments (a client with a stream idle +timeout must not abort a healthy queued request), and one cancelled while queued leaves without taking the turn. + + python -m unittest serve.test_queue_keepalive -v +""" +import http.client +import json +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +import serve.server as server +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, serve + +ROOT = Path(__file__).resolve().parents[1] + + +class QueueKeepAlive(unittest.TestCase): + def setUp(self): + tok = ByteTokenizer() + self.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.addCleanup(self.httpd.server_close) + self.addCleanup(self.httpd.shutdown) + p = mock.patch.object(server, "QUEUE_BEAT_S", 0.1) + p.start() + self.addCleanup(p.stop) + + def test_a_queued_stream_gets_keep_alives_then_its_answer(self): + self.svc.fifo.acquire() # another request holds the turn + c = http.client.HTTPConnection("127.0.0.1", self.httpd.server_address[1], timeout=10) + self.addCleanup(c.close) + body = {"stream": True, "messages": [{"role": "user", "content": "hi"}]} + c.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"}) + r = c.getresponse() + seen = b"" + t0 = time.monotonic() + while seen.count(b": keep-alive") < 2 and time.monotonic() - t0 < 5: + seen += r.fp.readline() + self.assertGreaterEqual(seen.count(b": keep-alive"), 2, seen) + self.assertEqual(self.svc.status["queued"], 1) + self.svc.fifo.release() + rest = r.read() + self.assertIn(b"[DONE]", rest) + self.assertIn(b'"finish_reason": "stop"', rest) # the answer ran once the turn was free + self.assertEqual(self.svc.status["queued"], 0) + + def test_a_request_cancelled_while_queued_never_takes_the_turn(self): + self.svc.fifo.acquire() + self.addCleanup(self.svc.fifo.release) + cancel = threading.Event() + ids = self.svc.tok.encode("hi") + run = self.svc.run(ids, False, None, 8, {}, cancel) + first = next(run) + self.assertEqual(first, ("ping", None)) + self.assertEqual(self.svc.status["queued"], 1) + cancel.set() + rest = list(run) + self.assertEqual([k for k, _ in rest], ["done"]) + self.assertEqual(rest[0][1]["finish"], "cancel") + self.assertEqual(self.svc.status["queued"], 0) + self.assertTrue(self.svc.fifo.locked()) # still the other request's: we never held it + + def test_closing_a_queued_request_is_no_longer_queued(self): + self.svc.fifo.acquire() + self.addCleanup(self.svc.fifo.release) + run = self.svc.run(self.svc.tok.encode("hi"), False, None, 8, {}, threading.Event()) + next(run) + run.close() + self.assertEqual(self.svc.status["queued"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_ready_timeout.py b/serve/test_ready_timeout.py new file mode 100644 index 00000000..78ef33d0 --- /dev/null +++ b/serve/test_ready_timeout.py @@ -0,0 +1,108 @@ +"""#1527: the READY-read timeout (#1317) ends the engine, and the request that was loading it must end too - +a 503 with the reason, not a connection that never answers (or a misleading 400).""" +import os +from pathlib import Path +import sys +import tempfile +import threading +import time +import unittest +import json +import urllib.request +from unittest import mock +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import serve.server as server # noqa: E402 +from serve.server import StrataEngine, Service, ChatTemplate, ByteTokenizer, serve # noqa: E402 + +# never prints READY: the READY read times out and the process is killed +SILENT = r''' +import time +time.sleep(3600) +''' + +# first run answers READY + one request; after --hang is touched a restart stays silent forever +HANG_ON_RESTART = r''' +import sys, time +from pathlib import Path +hang = Path(sys.argv[sys.argv.index('--hang') + 1]) +if hang.exists(): + time.sleep(3600) +print('READY 4096 stop', flush=True) +for line in sys.stdin: + if line.startswith('QUIT'): + break + if line.startswith(('GEN', 'BGEN')): + print('T 90\nDONE 1 1 0 1 stop', flush=True) +''' + + +@unittest.skipIf(os.name == "nt", "the .cmd wrapper keeps the pipe open after the kill (only the wrapper dies), so the " + "close of its stdout waits for the sleeping child; a real engine is one process") +class ReadyTimeout(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self._patchers = [mock.patch.object(server, 'ENGINE_READY_S', 0.5), + mock.patch.object(StrataEngine, 'RESTART_RETRY_S', 0.0)] + for p in self._patchers: + p.start(); self.addCleanup(p.stop) + + def make_script(self, name, code): + py = self.root / (name + '.py') + if os.name == 'nt': + py.write_text(code); script = self.root / (name + '.cmd') + script.write_text(f'@"{sys.executable}" "{py}" %*\r\n') + else: + script = py; py.write_text('#!' + sys.executable + '\n' + code); py.chmod(0o700) + return str(script) + + def service(self, script, extra_args=()): + eng = StrataEngine(script, list(extra_args), lazy=True) + self.addCleanup(eng.close) + return Service(eng, ByteTokenizer(), ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + + def post(self, base): + body = {'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 8} + req = urllib.request.Request(base + '/v1/chat/completions', data=json.dumps(body).encode(), + headers={'Content-Type': 'application/json'}) + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.read() + + def assert503(self, base): + t0 = time.monotonic() + try: + self.post(base) + self.fail('a request on an engine that never reports READY must not succeed') + except urllib.error.HTTPError as e: + self.assertEqual(e.code, 503) + body = e.read().decode() + self.assertIn('did not report READY', body) + self.assertIn('next request restarts it', body) + self.assertLess(time.monotonic() - t0, 60) + + def test_ready_timeout_on_lazy_load_answers_the_request(self): + # lazy start: restart()'s own bookkeeping must not crash on the missing slot_cv either (#1527) + svc = self.service(self.make_script('silent', SILENT)) + httpd = serve(svc, port=0) + self.addCleanup(httpd.shutdown); self.addCleanup(httpd.server_close) + base = f'http://127.0.0.1:{httpd.server_address[1]}' + self.assert503(base) + self.assertFalse(svc.engine.starting) + + def test_ready_timeout_on_restart_answers_the_request(self): + # the reporter's case: the engine had answered once, then a restart hangs on the READY read + hang = self.root / 'hang' + svc = self.service(self.make_script('hang_on_restart', HANG_ON_RESTART), ('--hang', str(hang))) + httpd = serve(svc, port=0) + self.addCleanup(httpd.shutdown); self.addCleanup(httpd.server_close) + base = f'http://127.0.0.1:{httpd.server_address[1]}' + status, _ = self.post(base) # first request: the engine works + self.assertEqual(status, 200) + svc.engine.proc.kill(); svc.engine.proc.wait(10) # it dies between requests + hang.touch() # and its restart never reports READY + self.assert503(base) + self.assertFalse(svc.engine.starting) + + +if __name__ == '__main__': + unittest.main() diff --git a/serve/test_reasoning_tools.py b/serve/test_reasoning_tools.py index a34171e4..46ef8fc0 100644 --- a/serve/test_reasoning_tools.py +++ b/serve/test_reasoning_tools.py @@ -111,6 +111,47 @@ class Parser(unittest.TestCase): self.assertEqual(joined(p.feed("ats are nice"), "reasoning"), "` the model quotes while it thinks - right after a quote or backtick, with no line break after + it - is reasoning text; the end of the thinking is still a `` with a line break after it.""" + + def test_a_quoted_tag_stays_reasoning(self): + for quote in ("in rcall, `` could arrive inside the held body", + 'the mock engine returns "\\n\\n2", no tool call', + '```python\ntext = ("\\n\\nI will use the tag now.")\n```', + "split it on '' first"): + text = "plan\n" + quote + "\ndone\n\n\nanswer" + for width in (1, 7, 100_000): + with self.subTest(quote=quote[:24], width=width): + evs = run(text, width) + self.assertEqual(joined(evs, "reasoning"), "plan\n" + quote + "\ndone\n") + self.assertEqual(joined(evs, "content"), "answer") + + def test_a_call_quoted_after_it_is_not_run(self): + text = ('it returns "\\n\\n2" here.\nThe call looks like this:\n' + CALL + " in the answer.\n" + "\n\n" + CALL) + for width in (1, 7, 100_000): + with self.subTest(width=width): + evs = run(text, width) + self.assertEqual(len([e for e in evs if e.kind == "tool_call"]), 1) # the answer's own call + self.assertIn(CALL + " in the answer.", joined(evs, "reasoning")) + self.assertEqual(joined(evs, "content"), "") + + def test_the_end_after_a_quote_still_ends_the_thinking(self): + for thought in ('she said "yes"', "it is `x`", "it is 'x'"): + for width in (1, 100_000): + with self.subTest(thought=thought, width=width): + evs = run(thought + "\n\nanswer", width) + self.assertEqual(joined(evs, "reasoning"), thought) + self.assertEqual(joined(evs, "content"), "answer") + + def test_an_output_that_ends_on_the_tag(self): + for width in (1, 100_000): + evs = run('say "', width) + self.assertEqual(joined(evs, "reasoning"), 'say "') + self.assertEqual(joined(evs, "content"), "") + + class OverHttp(unittest.TestCase): def test_finish_reasons_and_block_order(self): helper = UnfinishedToolCall("test_parser") diff --git a/serve/test_server.py b/serve/test_server.py index eb55dac7..0fba3fb7 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3243,6 +3243,15 @@ class ReasoningCloseRetry(unittest.TestCase): self.assertEqual(len(self.engine.prompts), 1) self.assertEqual(c["message"]["content"], "Fine.") + def test_a_reply_that_closed_its_thinking_right_after_a_quote_is_not_touched(self): + # #537: that waits for the character after it; the end of the turn makes it the end of the thinking + self.svc.reasoning_close_retry = True + self.engine.THOUGHT = 'two plus two is "4"' + c = self.chat() + self.assertEqual(len(self.engine.prompts), 1) + self.assertFalse(c["message"].get("content")) + self.assertEqual(c["message"]["reasoning_content"], 'two plus two is "4"') + class ThinkingBudget(unittest.TestCase): """#123: reasoning_budget_tokens (opt-in): at the budget the thinking is wrapped up and the model answers, @@ -3477,6 +3486,26 @@ class ForcedToolChoice(unittest.TestCase): # where the thinking ended, after the blank line the template puts before a call self.assertEqual(second, first + self.tok.encode(CallingEngine.THOUGHT + "\n\n" + opening)) + def test_a_thinking_that_ends_right_after_a_quote_opens_the_call(self): + # #537: that waits for the character after it; the end of the turn makes it the end of the thinking + thought, calling = 'I will search for "2+2"', self.engine.generate + + def generate(ids, max_new, sampling, cancel, embeddings=None): + if self.tok.decode(ids).endswith(("\n")): + yield from calling(ids, max_new, sampling, cancel) + return + self.engine.prompts.append(list(ids)) + yield from self.tok.encode(thought + "") + self.tok.encode("<|im_end|>", parse_special=True) + self.engine.generate = generate + for stream in (False, True): + with self.subTest(stream=stream): + self.engine.prompts = [] + code, b = self.openai(tool_choice="required", stream=stream) + finish, calls, reasoning = self.call_of(code, b, stream) + self.assertEqual((finish, calls, reasoning), ("tool_calls", [("search", {"q": "2+2"})], thought)) + first, second = self.engine.prompts + self.assertEqual(second, first + self.tok.encode(thought + "\n\n\n\n\n" + "y" * 40, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) svc.fifo = SlowRelease() @@ -3922,6 +3951,31 @@ class AmdTelemetry(unittest.TestCase): self.assertEqual(svc.free_vram_mib(), 26 << 10) +class TelemetryNoDisks(unittest.TestCase): + """psutil.disk_io_counters() returns None where it finds no disk (a gVisor container; Windows with its disk counters + off): the sampler goes on without a disk reading instead of its thread ending at the first sample, which left + /metrics' hardware empty and the frozen-engine check's GPU reading at 0.""" + + def test_sampler_runs_without_disk_counters(self): + from serve import telemetry + vm = SimpleNamespace(total=64 * 2**30, available=40 * 2**30) + fake = SimpleNamespace(cpu_count=lambda logical=True: 8, cpu_percent=lambda interval=None: 12.5, + virtual_memory=lambda: vm, disk_io_counters=lambda: None) + with mock.patch.dict(sys.modules, {"psutil": fake}): + t = telemetry.Telemetry(extra=lambda: {"tok_s": 1.5}) + try: + deadline = time.monotonic() + 5.0 + while not t.snapshot()["now"] and time.monotonic() < deadline: + time.sleep(0.05) + now = t.snapshot()["now"] + self.assertEqual(now.get("tok_s"), 1.5) + self.assertEqual(now.get("ram_used"), 24 * 2**30) + self.assertIsNone(now.get("disk_read_mb")) + self.assertIsNone(t.sample()["disk_write_mb"]) + finally: + t.close() + + class SilentEngine(unittest.TestCase): """#481: an engine that prints nothing for engine_silence_s during a request (or never acknowledges a STOP) has lost step with the server: it is ended and the request fails with EngineDied, instead of waiting forever.""" diff --git a/setup.py b/setup.py index 5bbd1452..c4daa67e 100644 --- a/setup.py +++ b/setup.py @@ -1013,11 +1013,16 @@ def start_gpus(text): are the ones Strata can use, AMD cards as setup lists them ("all": every supported AMD card).""" if not text: return None - if str(text).strip().lower() == "all" and not WIN and not together_ok(gpus()): + found = gpus() + if str(text).strip().lower() == "all" and not WIN and not together_ok(found): amd = amd_gpus() if len([g for g in amd if amd_problem(g) is None]) >= 2: return [g["index"] for g in amd_parse_gpus("all", amd)] - return parse_gpus(text, gpus()) + if not found and not WIN: # #1594: no NVIDIA card, AMD ones: "1,0" names those, as setup lists them + amd = amd_gpus() + if amd: + return [g["index"] for g in amd_parse_gpus(text, amd)] + return parse_gpus(text, found) def choose_gpus(a, found) -> list: @@ -1100,13 +1105,15 @@ def unsloth_split_need_gb(model="UD-Q4_K_XL") -> float: def split_budget(cfg: dict, yes: bool = False, explicit: bool = False) -> bool: - """#498: a UD-Q4_K_XL config (its RAM budget, --resident-budget-gib) started on several GPUs. The engine refuses + """#498: a UD-Q4_K_XL config (its RAM budget, --resident-budget-gib) started on several GPUs. The engine refused the budget with a layer split (it exited with code 2), so the split runs without it - all the experts loaded into RAM at start - where the RAM holds the GGUFs and 24 GB more; else setup says so and asks (#737: a recommendation, not a wall - 128 GB ran it fine): a "no" stops, before the config is saved; `explicit` (--gpus) with --yes goes on. - True when the config changed.""" + #642: the engines from RESIDENT_SPLIT_ENGINE keep the resident RAM copy on a split - every card's cache left out + of it, the rest ranked by the whole expert profile - and the budget is that copy's size, so it is kept, as + split_mmap keeps --resident-experts. True when the config changed.""" a = cfg.get("args", []) - if "--resident-budget-gib" not in a: + if "--resident-budget-gib" not in a or resident_split(): return False model = budget_model(cfg) need, ram = unsloth_split_need_gb(model), ram_gb() @@ -1174,9 +1181,11 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: can = together_ok(found) if not can: return cfg - # #498: UD-Q4_K_XL's RAM budget has no layer split; without it the RAM must hold the GGUFs and 24 GB more + # #498: UD-Q4_K_XL's RAM budget had no layer split; without it the RAM must hold the GGUFs and 24 GB more. #642: + # the engines from RESIDENT_SPLIT_ENGINE keep the budget on both cards, so any RAM is offered them (one GPU stays + # the recommendation, the tested setup) budget = "--resident-budget-gib" in cfg.get("args", []) - if budget and ram_gb() < unsloth_split_need_gb(budget_model(cfg)): + if budget and not resident_split() and ram_gb() < unsloth_split_need_gb(budget_model(cfg)): return cfg pair = can[:2] cfg["gpus_asked"] = True @@ -1190,7 +1199,11 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: say(" This model runs in the low-RAM mode with its experts kept in RAM, on one GPU (recommended: steady RAM") say(" use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in") say(" two reports (#364, #384), but RAM can fill up to 0 free during long prompts.") - if budget: + if budget and resident_split(): + say(f" This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested") + say(" setup). On both it keeps the budget: each card caches the experts of its own layers, and the RAM holds") + say(" the hottest of the rest (#642).") + elif budget: say(f" This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested") say(" setup). On both it has no budget: all its experts are loaded into RAM at start, which this PC's RAM") say(" holds - about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s).") @@ -1285,10 +1298,15 @@ def find_vcvars(cuda_v=None): def find_tool(name): - """A tool on PATH, or the one pip installed next to this Python (cmake, ninja).""" + """A tool on PATH, or the one pip installed next to this Python (cmake, ninja). A PATH copy that does not run + (a pip launcher whose Python is gone) is skipped for the one next to this Python.""" p = shutil.which(name) if p: - return p + try: + if subprocess.run([p, "--version"], capture_output=True, timeout=30).returncode == 0: + return p + except (OSError, subprocess.SubprocessError): + pass for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent, Path.home() / ".local" / "bin"): c = d / (name + (".exe" if WIN else "")) @@ -2892,6 +2910,30 @@ def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | No return eng +def update_engine_gpu(toolkit=13): + """#1485: the card an engine update is for. Not simply the one with the most VRAM: a Tesla V100 (32 GB) beside two + RTX 4090s was taken, and CUDA 13 cannot compile for it. The cards the installed models are set up for come + first (their "gpu"); for the CUDA 13 engine a card it cannot compile for is left out when another can. An + explicit --gpu (GPU_PICK) still wins. None when there is no NVIDIA GPU.""" + if GPU_PICK is not None: + return gpu_info() + found = gpus() + if not found: + return None + named = set() + for c in installed_configs(): + try: + g = json.loads(c.read_text(encoding="utf-8-sig")).get("gpu") + except (OSError, ValueError): + continue + named.update(i for i in (g if isinstance(g, list) else [g]) if isinstance(i, int) and not isinstance(i, bool)) + pool = [g for g in found if g["index"] in named] or found + if int(toolkit) != 12: + pool = [g for g in pool if int(g["arch"]) >= CUDA13_MIN_ARCH] or pool + g = max(pool, key=lambda x: (round(x["vram_gb"]), -x["index"])) + return {**g, "count": len(found)} + + def update_installed_engine(url_base, toolkit=None) -> None: """An installed ready-made engine older than MIN_ENGINE is replaced before the model starts, so a plain START-HERE.bat on an existing install picks up a new release. If that cannot happen (no internet, the model @@ -2954,7 +2996,7 @@ def update_installed_engine(url_base, toolkit=None) -> None: except OSError: warn(f"engine {meta.get('version') or ''} is in use: close the model window and run this again to update it") return - gpu = gpu_info() + gpu = update_engine_gpu(toolkit) if local: try: # a failed compile must not stop the model from starting if gpu is None: @@ -3386,8 +3428,27 @@ def unsloth_together(a, model, ram, gpu, chosen) -> bool: split runs without it: all its experts loaded into RAM from the GGUFs at start, as with the 2-3-bit models - only where the RAM holds the GGUF files and 24 GB more (unsloth_split_need_gb; 165 GiB, 2x RTX 3090: 31 -> 64-78 tok/s). An explicit --gpus is honoured there; otherwise asked, one GPU by default (--yes: one GPU, as before); an - explicit --resident-budget-gib keeps one GPU. True: all of them.""" + explicit --resident-budget-gib keeps one GPU. #642: the engines from RESIDENT_SPLIT_ENGINE keep the budget on a + split (the experts no card holds, the hottest by the whole profile), so there the cards go together with it, at + any RAM: --gpus, or "2" when asked; one GPU stays the recommendation (--yes alone: one GPU, as before). True: all + of them.""" names = " + ".join(gpu_name(g) for g in chosen) + if resident_split(): + note = "with its RAM budget (each card caches its own layers' experts, the RAM the hottest of the rest; #642)" + if a.gpus: + ok(f"{model} on {names}, as you chose (--gpus), {note}") + return True + if not a.yes: + say() + say(f" {model} runs with a RAM budget of its experts, on one GPU or on {names} together:") + say(f" 1) {gpu_name(gpu)} only (recommended: the tested setup)") + say(f" 2) {names} together: each card caches the experts of its own layers (#642)") + if ask(f"{model}: which GPUs?", ["1", "2"], "1", a.yes) == "2": + ok(f"{model} on {names}, {note}") + return True + warn(f"{model} runs on one GPU: using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) + + f" shares it across {names}, with its RAM budget)") + return False need = unsloth_split_need_gb(model) if ram < need: note = (f"{model} on several GPUs has no RAM budget and needs ~{need:.0f} GB of RAM (its GGUF files and " @@ -4594,7 +4655,7 @@ def main() -> int: help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") ap.add_argument("--port", type=int, help="the server's port (default: the one the install was set up with, 8080 for a new one)") - ap.add_argument("--gpu", help="one GPU, numbered as nvidia-smi numbers them (default: asked when several can be " + ap.add_argument("--gpu", help="one GPU, numbered as nvidia-smi numbers them (AMD: as setup lists them) (default: asked when several can be " "used; with --setup it is saved, when starting it is for that start only)") ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " "them): \"0,2\", or \"all\" (every card that can); the first is the main one. " @@ -4990,8 +5051,9 @@ def main() -> int: budget, q4_split = None, False if MODELS[model].get("budget"): # Unsloth's UD-Q4_K_XL: a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM mode (no - # experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode has no layer split) unless - # the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498) + # experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode had no layer split) unless + # the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498). #642: from + # RESIDENT_SPLIT_ENGINE several GPUs, when asked for, keep the budget (unsloth_together) if MODELS[model].get("experimental"): warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md): most of its experts are read from the SSD while it " "answers, so it is several times slower than the 2-3-bit models; quality checked against llama.cpp") @@ -5014,7 +5076,7 @@ def main() -> int: budget = budget_choice(model, ram, a.resident_budget_gib) if multi and not unsloth_together(a, model, ram, gpu, chosen): multi, sel, chosen = [], [gpu["index"]], [gpu] - q4_split = bool(multi) # #498: on several GPUs without the RAM budget + q4_split = bool(multi) and not resident_split() # #498: on several GPUs without the RAM budget (#642: kept) if not q4_split: ok(f"RAM budget: {budget:g} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD") if a.low_ram not in ("auto", "off"): @@ -5411,7 +5473,7 @@ def main() -> int: elif a.kv_streaming == "on": warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off") if budget is not None and not q4_split: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N - args += ["--resident-budget-gib", f"{budget:g}"] # GiB kept in RAM (#498: a layer split has no budget) + args += ["--resident-budget-gib", f"{budget:g}"] # GiB kept in RAM (#498: a layer split had no budget) if vision != "none": args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])] if vision == "gpu" and a.vram_reserve_mib is None and 0 < gpu.get("vram_gb", 0.0) <= 12.5: diff --git a/src/artifact/gguf_reader_test.cpp b/src/artifact/gguf_reader_test.cpp index 70f1bc2c..aab0003d 100644 --- a/src/artifact/gguf_reader_test.cpp +++ b/src/artifact/gguf_reader_test.cpp @@ -5,6 +5,11 @@ // 2. the same name twice: refused at open, and the error names the tensor and the file - GGUF has no // index to say which of the two a name means, and find() is first-match, so the alternative is a // lookup that silently picks by position. +// 3. no tensors, and the file ends at its header, before the 32-byte-aligned data start: the file opens, +// with data_start() clamped to the file size. A split model's first shard can hold metadata only and +// end unpadded (unsloth's UD-Q5_K_XL shard 1 ends 6 bytes before its aligned data start; llama.cpp's +// gguf-py reads it); nothing is ever read from its data section. +// 4. one tensor, and the file ends at its header: still refused at open ("data section starts past EOF"). // // The fixture is a minimal GGUF v3 written here (header, no metadata, two F32[8] tensors, 32-byte // alignment), so the test needs neither gguf-py nor a shard. The file is closed before it is removed: @@ -37,7 +42,8 @@ void put_str(std::vector& b, const std::string& s) { } // A GGUF v3 file of F32[8] tensors named `names`, laid out 32 bytes apart from a 32-byte-aligned data start. -std::filesystem::path write_gguf(const std::vector& names) { +// `header_only`: the file ends right after the tensor directory - no alignment padding, no data. +std::filesystem::path write_gguf(const std::vector& names, bool header_only = false) { std::vector b; put(b, 0x46554747u); // "GGUF" put(b, 3); @@ -50,7 +56,7 @@ std::filesystem::path write_gguf(const std::vector& names) { put(b, 0); // F32 put(b, 32 * i); // offset from data_start } - b.resize((b.size() + 31) / 32 * 32 + 32 * names.size(), 0); + if (!header_only) b.resize((b.size() + 31) / 32 * 32 + 32 * names.size(), 0); const auto path = std::filesystem::temp_directory_path() / "strata_gguf_reader_test.gguf"; std::ofstream(path, std::ios::binary).write(reinterpret_cast(b.data()), (std::streamsize)b.size()); return path; @@ -88,6 +94,36 @@ int main() { check(err.find(path.filename().string()) != std::string::npos, " the error names the file"); if (!err.empty()) std::printf(" (%s)\n", err.c_str()); } + { + const auto path = write_gguf({}, true); // 24 bytes: the aligned data start (32) is past EOF + std::string err; + uint64_t size = 0, start = 1; + size_t n = 1; + try { + strata::GgufFile g(path.string()); + size = g.file_size(); + start = g.data_start(); + n = g.tensors().size(); + } catch (const std::exception& e) { + err = e.what(); + } + std::filesystem::remove(path); + check(err.empty() && n == 0, "no tensors, ends before the aligned data start: the file opens"); + check(err.empty() && start == size, " data_start() is the file size (nothing to read past it)"); + if (!err.empty()) std::printf(" (%s)\n", err.c_str()); + } + { + const auto path = write_gguf({"blk.0.attn_q.weight"}, true); + std::string err; + try { + strata::GgufFile g(path.string()); + } catch (const std::exception& e) { + err = e.what(); + } + std::filesystem::remove(path); + check(err.find("data section starts past EOF") != std::string::npos, + "one tensor, ends before the aligned data start: refused at open"); + } std::printf(g_fail ? "gguf_reader_test: %d FAILED\n" : "gguf_reader_test: all passed\n", g_fail); return g_fail ? 1 : 0; } diff --git a/src/core/arch_defaults_test.cpp b/src/core/arch_defaults_test.cpp index f4ce0098..2fb6d0e3 100644 --- a/src/core/arch_defaults_test.cpp +++ b/src/core/arch_defaults_test.cpp @@ -30,6 +30,7 @@ int main() { CHECK(arch_default_env("gfx1100").empty()); CHECK(arch_default_env("gfx1201:sramecc-:xnack-").empty()); CHECK(arch_default_env("gfx1150").empty()); + CHECK(arch_default_env("gfx1152").empty()); CHECK(arch_default_env("gfx11510").empty()); // not a prefix match CHECK(arch_default_env("").empty()); CHECK(arch_default_env(nullptr).empty()); diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp index d31bf635..3750d119 100644 --- a/src/core/conversation_cache_test.cpp +++ b/src/core/conversation_cache_test.cpp @@ -241,6 +241,23 @@ int main() { check(!disabled.put(image({1,2,3})) && !no_slots.put(image({1,2,3})), "disabled cache stores nothing"); check(disabled.best(a,{},true).tokens == 0, "disabled cache has no matches"); } + { + // --conversation-cache-min-tokens: a conversation shorter than the minimum is not worth one of the slots. + // Parking is a switch-time decision, so without this a client's short side requests park themselves and, + // once the cache is full, evict the long conversation they were interleaved with (oldest first). + ConversationCache any(1024, 4, 0), floor(1024, 4, 12288); + check(any.enabled() && floor.enabled(), "the minimum does not disable the cache"); + check(any.wants(0) && any.wants(1) && any.wants(1 << 20), "0 parks every length, as before the flag"); + check(!floor.wants(0) && !floor.wants(1) && !floor.wants(12287), "below the minimum is not parked"); + check(floor.wants(12288) && floor.wants(12289), "the minimum itself and above are parked"); + // the CLI rejects a negative, but the predicate must not invert for one that reaches it another way + ConversationCache negative(1024, 4, -1); + check(negative.wants(0) && negative.wants(1), "a negative minimum parks everything, like 0"); + // wants() answers for the length alone; the gate is enabled() && wants(), so a disabled cache parks + // nothing whatever the length - keep the two independent rather than folding one into the other + ConversationCache disabled_min(0, 4, 12288); + check(!disabled_min.enabled() && disabled_min.wants(1 << 20), "a disabled cache still answers for length"); + } { // layer-split parking: checkpoints moved apart into stage parts and put back, no running state copied auto running = [](std::initializer_list ids, uint8_t salt, size_t parts) { diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index a81c0d83..7f9cff97 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -1708,9 +1708,10 @@ __device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { for (int j = 0; j < 8; ++j) { const int i = part * 8 + j; const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3; -#if defined(__HIPCC__) && ((defined(__gfx1012__) && HIP_VERSION_MAJOR < 7) || defined(__gfx1151__)) - // HIP 5.7 on RDNA1 and the HIP compiler on gfx1151 (PR #895, ROCm 7.13) fold the half path's negative scale - // times +0 to +0. Preserve the scale's sign, as the FP32/CPU paths do. +#if defined(__HIPCC__) && ((defined(__gfx1012__) && HIP_VERSION_MAJOR < 7) || defined(__gfx1151__) || \ + defined(__gfx1200__) || defined(__gfx1201__)) + // HIP 5.7 on RDNA1, the HIP compiler on gfx1151 (PR #895, ROCm 7.13) and on RDNA4 gfx1200/gfx1201 (ROCm + // 7.10, #1474) fold the half path's negative scale times +0 to +0. Preserve the scale's sign, as the FP32/CPU paths do. if constexpr (std::is_same_v) { if (code == 1) { yy[b * 64 + i] = __ushort_as_half(__half_as_ushort(x[b].d) & 0x8000u); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 4e03dc8b..7a92b58c 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1,5 +1,9 @@ // src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. #include "strata/prefill/prefill.hpp" +#include +#if defined(__cpp_lib_atomic_wait) +#define STRATA_ATOMIC_WAIT 1 // #1488: std::atomic::wait / notify_all are a GCC 11 library feature; GCC 10 spins instead +#endif #include "mmq_resident_sort.hpp" #include "wmma_gemm.h" #include "strata/core/mtp.hpp" @@ -477,9 +481,11 @@ struct Stager { // (atomic wait, and a blocking-sync event below), not a yield spin - 32 spinners took every core // (Linux; see stager_sleep for Windows). if (i >= kRing) { // job i - kRing's DMA from this buffer is queued +#if defined(STRATA_ATOMIC_WAIT) if (stager_sleep()) for (int x; (x = issued.load(std::memory_order_acquire)) <= i - kRing;) issued.wait(x); else +#endif while (issued.load(std::memory_order_acquire) <= i - kRing) std::this_thread::yield(); } // and done - for a generation's first kRing jobs that is the previous generation's last DMA from @@ -541,13 +547,17 @@ struct Stager { void issued_one(int j, cudaStream_t copy) { cudaEventRecord(dma_done[j % kRing], copy); issued.store(j + 1, std::memory_order_release); +#if defined(STRATA_ATOMIC_WAIT) issued.notify_all(); +#endif } /// No job is running after this (the end of a layer, or an early return in the middle of one). void finish() { head.store((uint64_t) gen << 32, std::memory_order_release); // n = 0: nothing more to claim issued.store(1 << 30, std::memory_order_release); +#if defined(STRATA_ATOMIC_WAIT) issued.notify_all(); +#endif while (active.load(std::memory_order_acquire) != 0) std::this_thread::yield(); } }; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d7024970..9c03606c 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -596,6 +596,10 @@ struct Options { int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations int conversation_cache_slots = 4; int64_t conversation_cache_min_free_mib = 2560; + /// --serve: park only conversations of at least this many tokens. Every parked conversation costs one of + /// conversation_cache_slots whatever its length, so without it a client that interleaves short side requests + /// with one long conversation evicts the long one (oldest first). 0 = park every conversation. + int64_t conversation_cache_min_tokens = 0; /// --serve SAVE: disk space a session file must leave free where it is written (MiB; 0 = no check) int64_t session_min_free_mib = 4096; /// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary) @@ -740,6 +744,8 @@ void usage() { " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n" " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking or restoring a\n" " session file (default 2560)\n" + " --conversation-cache-min-tokens N --serve: park only conversations of at least N tokens, so\n" + " short side requests do not take the slots a long one needs (default 0 = park any)\n" " --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n" " --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n" " default 512), so the command `VRAM ` (the server's POST /v1/vram) can\n" @@ -1835,17 +1841,20 @@ int main(int argc, char** argv) { else if (a == "--vision") o.vision = true; else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache"))); else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" || - a == "--conversation-cache-min-free-mib" || a == "--session-min-free-mib") { + a == "--conversation-cache-min-free-mib" || a == "--conversation-cache-min-tokens" || + a == "--session-min-free-mib") { const std::string value = next(a.c_str()); int64_t number = 0; const auto result = std::from_chars(value.data(), value.data() + value.size(), number); - const int64_t limit = a == "--conversation-cache-slots" ? INT32_MAX : INT64_MAX / (1024 * 1024); + const int64_t limit = (a == "--conversation-cache-slots" || a == "--conversation-cache-min-tokens") + ? INT32_MAX : INT64_MAX / (1024 * 1024); if (result.ec != std::errc{} || result.ptr != value.data() + value.size() || number < 0 || number > limit) { std::fprintf(stderr, "%s needs a nonnegative integer within range\n", a.c_str()); return 2; } if (a == "--conversation-cache-mib") o.conversation_cache_mib = number; else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number; + else if (a == "--conversation-cache-min-tokens") o.conversation_cache_min_tokens = number; else if (a == "--session-min-free-mib") o.session_min_free_mib = number; else o.conversation_cache_slots = (int) number; } @@ -7050,7 +7059,7 @@ int main(int argc, char** argv) { // (the snapshots accept a null draft) strata::core::ConversationCache conversations( o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0, - (size_t) o.conversation_cache_slots); + (size_t) o.conversation_cache_slots, o.conversation_cache_min_tokens); // Disk sessions: what a session file is bound to. The model fingerprint samples every model input this // engine loaded, by role (conversation_file.hpp), once; the config fingerprint covers the RESOLVED settings // that change what the saved bytes mean - the rope (K is cached post-RoPE), the loaded control vector, the @@ -7129,6 +7138,16 @@ int main(int argc, char** argv) { // addresses change: all parked images live in ordinary host vectors. auto park_current_body = [&](size_t held) -> bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; + // --conversation-cache-min-tokens: a short conversation is not worth one of the slots. Parking is a + // switch-time decision, so a client's small side requests would otherwise park themselves and, once the + // cache is full, evict the long conversation they were interleaved with (oldest first) - the reuse it + // wanted. Returning true is the same non-error skip the byte-budget and RAM-floor paths below take. + if (!conversations.wants((int64_t) live.size())) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (%zu tokens, below the %lld " + "minimum; parked=%zu)\n", + live.size(), (long long) o.conversation_cache_min_tokens, conversations.size()); + return true; + } // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold // nothing the outgoing chain does not, apart from the tail this conversation rewrote) if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached)) @@ -8127,7 +8146,8 @@ int main(int argc, char** argv) { "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " - "conversation_cache_min_free_mib=%lld tail_role_token=%lld vram_elastic=%d%s engine=" STRATA_VERSION "\n", + "conversation_cache_min_free_mib=%lld conversation_cache_min_tokens=%lld " + "tail_role_token=%lld vram_elastic=%d%s engine=" STRATA_VERSION "\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), @@ -8138,7 +8158,8 @@ int main(int argc, char** argv) { (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), pool.workers(), o.pcie_frac, o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, - (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token, xcache.segmented() ? 1 : 0, + (long long) o.conversation_cache_min_free_mib, (long long) o.conversation_cache_min_tokens, + (long long) o.tail_role_token, xcache.segmented() ? 1 : 0, o.batch > 0 ? (" batch_slots=" + std::to_string(o.batch) + " slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0) + " batch_groups=" + std::to_string(o.batch_groups)).c_str() : ""); diff --git a/tests/core/expert_cache_segmented_test.cpp b/tests/core/expert_cache_segmented_test.cpp index cabf24a4..9867e541 100644 --- a/tests/core/expert_cache_segmented_test.cpp +++ b/tests/core/expert_cache_segmented_test.cpp @@ -58,7 +58,9 @@ int main() { const bool ok = sized ? c.open_sized(std::vector(kSlots, kBlob), 4, 64, err) : c.open(kSlots, 4, 64, kBlob, err); if (!ok) { - if (err.find("virtual memory management") != std::string::npos) { + // #1475: a HIP build has no segmented cache ("--vram-elastic ... is CUDA-only for now"): a skip, not a failure + if (err.find("virtual memory management") != std::string::npos || + err.find("CUDA-only") != std::string::npos) { std::printf("%s: skipped\n", err.c_str()); return 77; } diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py index 4b6afb7b..c9e84ee7 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -111,6 +111,10 @@ class Tokenizer: # token containing regex metacharacters (several do: `<|`, `[`, `(`) is matched literally. self._always_re = self._alt(always) self._special_re = self._alt(list(self.special_tokens)) + # Initialize once, rather than allocating a default dict and looking it up + # through __dict__.setdefault on each encoded segment or decoded token. + self._piece_ids: dict[str, list[int]] = {} + self._bytes_cache: dict[int, bytes] = {} @staticmethod def _alt(literals: list[str]): @@ -214,7 +218,7 @@ class Tokenizer: out: list[int] = [] # A piece's ids depend on the piece alone, so repeated pieces (most of a resent conversation) are looked up # instead of merged again. The ids are the ones _bpe gives: this only skips the work. - cache = self.__dict__.setdefault("_piece_ids", {}) + cache = self._piece_ids for piece in self._re.findall(text): got = cache.get(piece) if got is None: @@ -242,11 +246,27 @@ class Tokenizer: return self._encode_plain(text) out: list[int] = [] pos = 0 + # Matches arrive in text order. For reusable span sequences, consume each + # span once instead of scanning the entire list for every literal match. + # Sorting a copy handles unsorted/overlapping input without mutating it. + # Other iterables keep the original consumption semantics below. + span_sequence = isinstance(plain, (list, tuple)) and bool(plain) + if span_sequence: + spans = iter(sorted(plain)) + upcoming = next(spans, None) + plain_end = 0 for m in pat.finditer(text): - if plain and any(a <= m.start() < b for a, b in plain): + start = m.start() + if span_sequence: + while upcoming is not None and upcoming[0] <= start: + plain_end = max(plain_end, upcoming[1]) + upcoming = next(spans, None) + if start < plain_end: + continue + elif plain and any(a <= start < b for a, b in plain): continue - if m.start() > pos: - out.extend(self._encode_plain(text[pos:m.start()])) + if start > pos: + out.extend(self._encode_plain(text[pos:start])) out.append(self.special_tokens[m.group(0)]) pos = m.end() if pos < len(text): @@ -265,7 +285,7 @@ class Tokenizer: def token_bytes(self, i: int) -> bytes: """The raw bytes of one token (a multi-byte character can be split across tokens).""" - cache = self.__dict__.setdefault("_bytes_cache", {}) + cache = self._bytes_cache b = cache.get(i) if b is None: if i < 0 or i >= len(self.tokens): diff --git a/tools/test_docker_entrypoint.py b/tools/test_docker_entrypoint.py index 4953265b..582415ff 100644 --- a/tools/test_docker_entrypoint.py +++ b/tools/test_docker_entrypoint.py @@ -95,6 +95,23 @@ class Entrypoint(unittest.TestCase): self.assertIn("by-model", out) self.assertIn(f"Config: {self.data}/config/strata-iq3_s.json", out) + def warning_for(self, flags): + info = self.tmp / "cpuinfo" + info.write_text(f"processor\t: 0\nflags\t\t: {flags}\n") + (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["x"]}\n') + env = dict(os.environ, STRATA_DATA=str(self.data), MODEL="IQ3_S", REINSTALL="0", STRATA_CPUINFO=str(info)) + r = subprocess.run([SH, str(self.script)], env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(r.returncode, 0, r.stderr) # a warning, never a stop (#1584) + return r.stderr + + def test_a_cpu_without_avx2_is_warned_not_stopped(self): + err = self.warning_for("fpu sse4_2 avx aes") + self.assertIn("no AVX2", err) + self.assertIn("docker build", err) + + def test_a_cpu_with_avx2_gets_no_warning(self): + self.assertEqual(self.warning_for("fpu sse4_2 avx avx2 fma"), "") + if __name__ == "__main__": unittest.main() diff --git a/tools/test_setup_start_gpus_amd.py b/tools/test_setup_start_gpus_amd.py new file mode 100644 index 00000000..d428fe8c --- /dev/null +++ b/tools/test_setup_start_gpus_amd.py @@ -0,0 +1,40 @@ +"""#1594: --gpus when starting an installed model on a PC with AMD cards and no NVIDIA ones names the AMD cards (as +setup lists them) instead of failing for want of an NVIDIA GPU. + + python -m unittest tools.test_setup_start_gpus_amd -v +""" +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import setup # noqa: E402 + + +def amd(index, arch="gfx1201"): + return {"index": index, "name": f"Radeon {index}", "arch": arch, "vram_gb": 32.0} + + +class StartGpusAmd(unittest.TestCase): + def run_start_gpus(self, text, cards, nvidia=()): + with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "gpus", return_value=list(nvidia)), \ + mock.patch.object(setup, "amd_gpus", return_value=cards): + return setup.start_gpus(text) + + def test_amd_numbers_are_taken_as_setup_lists_them(self): + self.assertEqual(self.run_start_gpus("1,0", [amd(0), amd(1)]), [1, 0]) + + def test_all_still_means_every_supported_amd_card(self): + self.assertEqual(sorted(self.run_start_gpus("all", [amd(0), amd(1)])), [0, 1]) + + def test_a_card_that_cannot_be_used_is_named(self): + with self.assertRaises(SystemExit): + self.run_start_gpus("1,0", [amd(0), amd(1, "gfx1010")]) + + def test_nothing_named_is_none(self): + self.assertIsNone(self.run_start_gpus("", [amd(0)])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index fc31e278..b9ba0536 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -335,7 +335,7 @@ class Main(Base): """#967: images are allowed with UD-Q4_K_XL, said to be untested.""" code, out, cfg = self.main(["--context", "8192", "--vision", "yes", "--low-ram", "on"], n_gpus=2) self.assertEqual(code, 0, out) - self.assertIn("(NVIDIA GeForce RTX 5070, 12 GB) only (--gpus 0,1 uses them together anyway)", out) + self.assertIn("(NVIDIA GeForce RTX 5070, 12 GB) only (--gpus 0,1 shares it across", out) self.assertNotIn("images are not available", out) self.assertIn("images: on", out) self.assertIn("images with UD-Q4_K_XL are untested", out) @@ -346,6 +346,7 @@ class Main(Base): self.assertNotIn("--mmap-experts", cfg["args"]) self.assertFalse(any("--experts-bin" in r for r in self.runs)) + @mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split def test_split_when_the_ram_holds_it(self): # #498: 165 GiB and --gpus 0,1: the split without the RAM budget (the engine refuses the pair) code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1"], n_gpus=2, ram=165.0) @@ -358,6 +359,7 @@ class Main(Base): self.assertIn("OS file cache", out) self.assertNotIn("RAM budget: ", out) + @mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split def test_split_without_the_ram_is_a_warning_not_a_wall(self): # #737: below the worst-case estimate (a 128 GB PC ran it) the split is still the user's call need = setup.unsloth_split_need_gb() @@ -374,6 +376,7 @@ class Main(Base): self.assertEqual(cfg["gpu"], [0, 1]) self.assertNotIn("--resident-budget-gib", cfg["args"]) + @mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split def test_an_explicit_budget_keeps_one_gpu(self): code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--resident-budget-gib", "60"], n_gpus=2, ram=165.0) @@ -382,6 +385,38 @@ class Main(Base): self.assertNotIn("layer_split", cfg) self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "60") + def test_split_keeps_the_budget(self): + """#642: with a resident-split engine the cards asked for keep the RAM budget, at any RAM.""" + with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): + code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1"], n_gpus=2) # 64 GB: no 135 GB asked + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["layer_split"], "auto") + self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "40") + for flag in ("--mmap-experts", "--resident-experts"): + self.assertNotIn(flag, cfg["args"]) + self.assertIn("as you chose (--gpus), with its RAM budget", out) + self.assertIn("RAM budget: 40 GiB", out) + self.assertNotIn("worst case", out) + code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--resident-budget-gib", "30"], n_gpus=2) + self.assertEqual(code, 0, out) # an explicit budget too + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "30") + self.assertNotIn("has no layer split", out) + + def test_asked_with_the_budget_one_gpu_by_default(self): + """#642: asked as before (one GPU recommended); "2" takes both cards with the budget.""" + with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): + code, out, cfg = self.main(["--context", "8192"], n_gpus=2, answers={}) # Enter: one GPU + self.assertEqual(code, 0, out) + self.assertTrue(any(f"{M}: which GPUs?" in q and "[1]" in q for q in self.asked), self.asked) + self.assertNotIn("layer_split", cfg) + self.assertIn("--resident-budget-gib", cfg["args"]) + code, out, cfg = self.main(["--context", "8192"], n_gpus=2, answers={"which GPUs?": "2"}) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--resident-budget-gib", cfg["args"]) + def test_yes_alone_keeps_one_gpu(self): code, out, cfg = self.main(["--context", "8192"], n_gpus=2, ram=165.0) self.assertEqual(code, 0, out) @@ -523,9 +558,15 @@ class IQ4XS(Base): class LayerSplit(unittest.TestCase): """#498: UD-Q4_K_XL across GPUs - asked at setup (one GPU by default), and a start with --gpus no longer keeps - the RAM budget the engine refuses with a split (it exited with code 2).""" + the RAM budget the engine refused with a split (it exited with code 2). #642: from RESIDENT_SPLIT_ENGINE the + budget is kept on the split.""" def setUp(self): + # the behaviour before RESIDENT_SPLIT_ENGINE (an engine from before 0.1.40); the tests of the newer engine + # patch MIN_ENGINE themselves + p = mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) + p.start() + self.addCleanup(p.stop) sys.path.insert(0, str(ROOT / "tools")) from test_setup_golden import card self.found = [card(i, "NVIDIA GeForce RTX 3090", 24.0, "86") for i in range(2)] @@ -601,6 +642,26 @@ class LayerSplit(unittest.TestCase): self.assertEqual(cfg["gpu"], 0) self.assertNotIn("Use both", out) + def test_resident_split_engine_keeps_the_budget(self): + """#642: a start with --gpus keeps the budget at any RAM; offered both cards (Enter: one, as before).""" + with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): + for ram in (165.0, 63.7): + code, out, cfg, started = self.start(ram) + self.assertIsNone(code, out) + self.assertTrue(started) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["args"], ["--pack", "p", "--resident-budget-gib", "40", "--kv", "int8"]) + self.assertNotIn("no RAM budget", out) + self.assertNotIn("cannot share its RAM budget", out) + code, out, cfg, _ = self.start(63.7, gpu=None, offered="") # offered at 64 GB too; Enter: one GPU + self.assertIsNone(code, out) + self.assertIn("On both it keeps the budget", out) + self.assertIn("staying on one GPU", out) + self.assertEqual(cfg["gpu"], 0) + code, out, cfg, _ = self.start(63.7, gpu=None, offered="y") + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--resident-budget-gib", cfg["args"]) + if __name__ == "__main__": unittest.main() diff --git a/tools/test_setup_update_gpu.py b/tools/test_setup_update_gpu.py new file mode 100644 index 00000000..52a75392 --- /dev/null +++ b/tools/test_setup_update_gpu.py @@ -0,0 +1,53 @@ +"""#1485: the card an engine update compiles for is one the installed models use (and CUDA 13 can compile for), not +the card with the most VRAM - a Tesla V100 beside two RTX 4090s made ./update.sh build for sm_70 with CUDA 13. + + python -m unittest tools.test_setup_update_gpu -v +""" +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import setup # noqa: E402 + +V100 = {"index": 1, "name": "Tesla V100-PCIE-32GB", "vram_gb": 32.0, "arch": "70", "driver": "580"} +R4090 = lambda i: {"index": i, "name": "RTX 4090", "vram_gb": 24.0, "arch": "89", "driver": "580"} # noqa: E731 + + +class UpdateEngineGpu(unittest.TestCase): + def pick(self, found, configs, toolkit=13, pinned=None): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + paths = [] + for n, cfg in enumerate(configs): + p = Path(tmp.name) / f"strata-{n}.json" + p.write_text(json.dumps(cfg)) + paths.append(p) + with mock.patch.object(setup, "gpus", return_value=found), \ + mock.patch.object(setup, "installed_configs", return_value=paths), \ + mock.patch.object(setup, "GPU_PICK", pinned): + return setup.update_engine_gpu(toolkit) + + def test_the_models_cards_not_the_biggest_one(self): + g = self.pick([R4090(0), V100, R4090(2)], [{"exe": "x", "args": [], "gpu": [0, 2]}]) + self.assertEqual(g["arch"], "89") + self.assertEqual(g["count"], 3) + + def test_a_card_cuda_13_cannot_compile_for_is_left_out_without_a_config(self): + self.assertEqual(self.pick([R4090(0), V100], [])["index"], 0) + + def test_the_cuda_12_engine_may_take_the_volta(self): + self.assertEqual(self.pick([R4090(0), V100], [], toolkit=12)["index"], 1) + + def test_only_a_volta_is_still_taken(self): + self.assertEqual(self.pick([V100], [])["index"], 1) + + def test_no_nvidia_card(self): + self.assertIsNone(self.pick([], [])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_strata_tokenizer.py b/tools/test_strata_tokenizer.py index 6b2f9009..17c3f698 100644 --- a/tools/test_strata_tokenizer.py +++ b/tools/test_strata_tokenizer.py @@ -48,5 +48,52 @@ class PieceCache(unittest.TestCase): self.assertLessEqual(len(t._piece_ids), 5) +class ByteCache(unittest.TestCase): + def test_decode_before_encode_cold_and_warm(self): + t = toy() + text = "café 日本語 🙂\r\n\x00" + ids = list(text.encode("utf-8")) # toy's first 256 token IDs are the raw bytes + self.assertEqual(t.decode(ids, errors="strict"), text) + self.assertEqual(t.decode(ids, errors="strict"), text) + self.assertEqual(t.decode([]), "") + for i in range(256): + self.assertEqual(t.token_bytes(i), bytes([i])) + + def test_invalid_ids_before_and_after_cache_use(self): + t = toy() + for _ in range(2): + for i in (-1, len(t.tokens), len(t.tokens) + 100): + with self.assertRaises(IndexError): + t.token_bytes(i) + self.assertEqual(t.token_bytes(65), b"A") + + def test_instances_with_different_vocabularies_stay_independent(self): + tokens = [ST.BYTE_TO_UNICODE[b] for b in range(256)] + a, b = ST.Tokenizer(tokens, []), ST.Tokenizer(tokens[::-1], []) + text = "the café 日本語 🙂\n" + for t in (a, b, a, b): + expected = [t.ids[ST.BYTE_TO_UNICODE[byte]] for byte in text.encode("utf-8")] + self.assertEqual(t.encode(text), expected) + self.assertEqual(t.decode(expected, errors="strict"), text) + self.assertEqual(a.token_bytes(0), b"\x00") + self.assertEqual(b.token_bytes(0), b"\xff") + + def test_shared_tokenizer_concurrent_first_decode(self): + import threading + from concurrent.futures import ThreadPoolExecutor + t = toy() + texts = ["café", "日本語", "🙂\r\n", "\x00plain"] + barrier = threading.Barrier(len(texts)) + def decode(text): + ids = list(text.encode("utf-8")) + barrier.wait(timeout=5) + for _ in range(100): + if t.decode(ids, errors="strict") != text: + raise AssertionError("concurrent decode changed the text") + return text + with ThreadPoolExecutor(len(texts)) as pool: + self.assertEqual(list(pool.map(decode, texts)), texts) + + if __name__ == "__main__": unittest.main() diff --git a/tools/test_tokenizer_plain_spans.py b/tools/test_tokenizer_plain_spans.py new file mode 100644 index 00000000..1e601707 --- /dev/null +++ b/tools/test_tokenizer_plain_spans.py @@ -0,0 +1,97 @@ +"""Exact token-ID parity for protected literals, including general caller span inputs.""" +import random +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import strata_tokenizer as ST + + +class ReferenceTokenizer(ST.Tokenizer): + def _encode_matching(self, text, pat, plain=()): + if pat is None: + return self._encode_plain(text) + out, pos = [], 0 + for m in pat.finditer(text): + if plain and any(a <= m.start() < b for a, b in plain): + continue + if m.start() > pos: + out.extend(self._encode_plain(text[pos:m.start()])) + out.append(self.special_tokens[m.group(0)]) + pos = m.end() + if pos < len(text): + out.extend(self._encode_plain(text[pos:])) + return out + + +def tokenizer(cls=ST.Tokenizer, specials=True, merges=False): + tokens = [ST.BYTE_TO_UNICODE[b] for b in range(256)] + types = [1] * 256 + rules = ["t h", "th i", "thi n", "thin k", "p l", "pl a", "pla i", "plai n", "< /"] if merges else [] + for rule in rules: + left, right = rule.split(" ") + tokens.append(left + right) + types.append(1) + if specials: + tokens += ["", "", "<|im_start|>", "<|im_end|>"] + types += [4, 4, 3, 3] + return cls(tokens, rules, types) + + +class PlainSpans(unittest.TestCase): + def test_boundaries_overlaps_order_and_no_input_mutation(self): + text = "🙂 aliteral b<|im_start|>x<|im_end|>z" + first = text.index("") + spans_cases = [[], [(first, first + 1)], [(first + 1, first + 7)], + [(0, first)], [(0, first + 1)], [(0, len(text))], + [(first + 2, first + 9), (first, first + 2)], + [(first, first + 20), (first + 1, first + 2)], + [(first, first), (first + 20, first)], + [(-10, 0), (len(text) + 1, len(text) + 20)]] + actual, reference = tokenizer(), tokenizer(ReferenceTokenizer) + for spans in spans_cases: + saved = list(spans) + for seq in (spans, tuple(spans)): + for parse_special in (False, True): + self.assertEqual(actual.encode(text, parse_special, plain=seq), + reference.encode(text, parse_special, plain=seq)) + self.assertEqual(spans, saved) + + def test_whole_protected_text_is_literal_bytes(self): + t = tokenizer() + text = "日本語🙂<|im_start|>" + expected = [t.ids[ST.BYTE_TO_UNICODE[b]] for b in text.encode("utf-8")] + for parse_special in (False, True): + self.assertEqual(t.encode(text, parse_special, plain=[(0, len(text))]), expected) + self.assertIn(t.special_tokens[""], t.encode(text)) + + def test_randomized_spans_match_reference(self): + rng = random.Random(1031) + actual, reference = tokenizer(merges=True), tokenizer(ReferenceTokenizer, merges=True) + pieces = ["", "", "<|im_start|>", "<|im_end|>", "plain", " café🙂 ", "\n"] + for _ in range(200): + text = "".join(rng.choice(pieces) for _ in range(30)) + spans = [(rng.randrange(-5, len(text) + 5), rng.randrange(-5, len(text) + 5)) + for _ in range(rng.randrange(50))] + for parse_special in (False, True): + self.assertEqual(actual.encode(text, parse_special, plain=spans), + reference.encode(text, parse_special, plain=spans)) + + def test_one_shot_iterables_preserve_consumption_behavior(self): + text = "a<|im_start|>b<|im_end|>" + spans = [(10, 30), (0, 7), (8, 12)] + actual, reference = tokenizer(), tokenizer(ReferenceTokenizer) + for parse_special in (False, True): + self.assertEqual(actual.encode(text, parse_special, plain=iter(spans)), + reference.encode(text, parse_special, plain=iter(spans))) + + def test_no_special_pattern_and_empty_text(self): + t = tokenizer(specials=False) + text = "café " + self.assertEqual(t.encode(text, True, plain=[(0, len(text))]), t.encode(text)) + self.assertEqual(tokenizer().encode("", True, plain=[(-1, 100)]), []) + + +if __name__ == "__main__": + unittest.main()