okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""serve/server.py - plan v0.3 P8: OpenAI and Anthropic endpoints over any engine that maps token ids to tokens. 2 3python -m serve.server --engine mock --port 8095 (a scripted engine, for clients and tests) 4python -m serve.server --engine strata --config strata.json --port 8080 (the real engine, resident) 5 6Endpoints: POST /v1/chat/completions (OpenAI, stream and non-stream), POST /v1/messages (Anthropic, stream and 7non-stream), GET /v1/models, GET /models, GET /props, GET /slots, GET /health, GET /mcp. One sequence at a time behind a FIFO (plan: one resident sequence). 8Image generation (optional, when the config has an "images" section): POST /v1/images/generations (OpenAI's shape, 9plus seed and steps) runs stable-diffusion.cpp's sd-cli for Qwen-Image-2.1-Turbo, one job at a time on the GPU the 10text engine uses (serve/images.py). 11Tools from MCP servers (serve/mcp.py, `"mcp_servers"` in the config or --mcp-config) are offered only to requests that 12ask for them with `"strata_mcp": true` - the web app does; other clients see exactly the API they always saw. 13Images (optional, when the config has a "vision" entry): OpenAI image_url parts and Anthropic image blocks (base64 14data, http(s) URLs or local file paths) go through `strata-vision` (the model's mmproj file) and reach the engine as 15embeddings (`GENI`). JPEG/PNG/BMP/GIF go straight in; WebP, TIFF, AVIF, ... (agents like omp send WebP) are 16converted to PNG first with Pillow. 17A request whose prompt alone does not fit the engine's context is REJECTED with 400, never truncated. When the prompt 18fits but prompt plus max tokens does not (Claude Code asks for 32000, the Harness for 16384), max tokens is shortened to 19the room left (less CTX_SLACK) and the thinking budget follows it; `--no-fit-max-tokens` / `"fit_max_tokens": false` 20brings back the strict 400 of llama.cpp. 21An unset (or 0, or -1) max tokens means "unlimited": whatever the prompt leaves of the context. 22 23The engine boundary is `Engine.generate(prompt_ids, max_new, sampling, cancel) -> iterator of token ids`. 24`StrataEngine` keeps one `strata --serve` process resident (weights, expert arena and VRAM tier load once) and 25talks to it over stdin/stdout; `MockEngine` is a scripted stand-in that makes every API path testable without a GPU. 26""" 27from __future__import annotations 28 29import argparse 30import contextlib 31import collections 32import base64 33import hashlib 34import hmac 35import codecs 36import json 37import math 38import os 39import platform 40import queue 41import re 42import select 43import signal 44import socket 45import socketserver 46import struct 47import shutil 48import subprocess 49import sys 50import tempfile 51import threading 52import time 53import urllib .request 54import uuid 55from http .client import HTTPException 56from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 57from pathlib import Path 58from typing import Iterator ,Protocol 59from urllib .parse import parse_qs ,urlsplit 60 61ROOT = Path (__file__ ).resolve ().parents [1 ] 62sys .path .insert (0 ,str (ROOT / "tools" )) 63sys .path .insert (0 ,str (ROOT ))# run as a script (run-<model>.bat) as well as a module 64from serve .frontend import (THINK_END ,ChatTemplate ,Event ,OutputParser ,parser_for_template ,anthropic_to_messages ,anthropic_tools ,# noqa: E402 65forced_call ,images_of ,literal_tags ,mark_think_literals ,openai_to_messages ,require_messages , 66tool_choice_of ,unmark_think_literals ) 67from serve .mcp import McpCancelled ,hub_from_config # noqa: E402 68from serve import runconfig # noqa: E402 69from serve .webfiles import subtree_file as web_subtree_file # noqa: E402 70from strata_control import engine_component # noqa: E402 71from strata_control import tls # noqa: E402 72from strata_control .childenv import quiet_crash_env # noqa: E402 73from strata_control import reader_room # noqa: E402 74 75tls .install ()# #3722: image URLs and tool servers over HTTPS are checked against the operating system's certificates 76from strata_control import hipblaslt_tuning # noqa: E402 77from strata_control import vision_reader # noqa: E402 78from serve .ds_pictures import PICTURE_FORMATS ,DsPictures # noqa: E402 79from strata_control import draft_layer # noqa: E402 80from strata_control import drafting # noqa: E402 81from strata_control import vram_fit # noqa: E402 82from strata_control import user_args # noqa: E402 83from strata_control import gpu_roles # noqa: E402 84from serve import ready as ready_file # noqa: E402 85from serve import owner_guard # noqa: E402 86from serve import launch_identity # noqa: E402 87from serve import logit_bias as bias_api # noqa: E402 88from serve import lifeline # noqa: E402 89from serve .structured import StructuredOutputError ,prepare_format ,validated_json ,extract_json # noqa: E402 90from serve import responses as responses_api # noqa: E402 91from serve .responses import ResponsesError ,error_body as responses_error_body # noqa: E402 92from serve import images as images_api # noqa: E402 93from serve import ds4_vision # noqa: E402 94 95IM_END = "<|im_end|>" 96IMAGE_PAD = "<|image_pad|>" 97 98 99def popen (what :str ,args :list ,role :str = "engine" ,** kw ): 100"""#735: subprocess.Popen, but Windows' refusal to start a program (WinError 4551, or 1260 when a policy blocks it: 101Smart App Control on a clean Windows 11 blocks an exe that is not signed) is said in words instead of a bare 102OSError.""" 103try : 104return lifeline .popen (args ,role ,** kw )# a child that cannot outlive this server (serve/lifeline.py) 105except OSError as e : 106if getattr (e ,"winerror" ,None )in (4551 ,1260 ): 107raise OSError (f"Windows blocked { what } ( { args [ 0 ] } ): Smart App Control, or an application-control policy, does " 108"not let a program that is not signed run. Turn Smart App Control off (Windows Security > App " 109"& browser control > Smart App Control settings), or - for the image encoder only - run setup " 110"with --vision no (see docs/TROUBLESHOOTING.md)" )from e 111raise 112 113 114# How long close() gives the engine at each step of ending it (seconds). Module values so that a test can shorten them. 115ENGINE_QUIT_WAIT_S ,ENGINE_TERM_WAIT_S ,ENGINE_KILL_WAIT_S = 20 ,5 ,20 116 117 118def rttime_limit_note ()-> str : 119"""#3238: Linux only. A hard RLIMIT_RTTIME that is not unlimited (PipeWire's client module sets it to 0 when rtkit is 120missing; every program started from that desktop inherits it) makes the kernel SIGKILL a process as soon as it 121checks a thread with an armed CPU timer, with no OOM kill and no message. Returns one sentence naming the cause and 122the fix, or "" when the limit is unlimited, the platform has no such limit or it cannot be read.""" 123try : 124import resource 125soft ,hard = resource .getrlimit (resource .RLIMIT_RTTIME ) 126except (ImportError ,AttributeError ,OSError ,ValueError ): 127return "" 128if hard == resource .RLIM_INFINITY : 129return "" 130return (f"This session has a real-time CPU limit (RLIMIT_RTTIME hard limit { hard } ; the desktop's audio system sets " 131"it to 0 when rtkit is not installed). Linux can then end a program with signal 9 for no visible reason. " 132"Install rtkit, or start Strata outside the desktop session's limits, for example: " 133"systemd-run --user --collect -p LimitRTTIME=infinity -- strata serve ..." ) 134 135 136LEFTOVER_SETTLE_S = 120.0 # #4051: how long an engine ended at a start is waited for to give its memory back 137 138 139def end_leftover_engines (exe :str )-> None : 140"""Before an engine starts: end the ones a lost server left running (strata_control/procs.py). Only a process 141this install recorded whose starter is gone, or an orphan of exactly this executable running --serve, and only 142after its PID, start time and command line are checked again at the moment of the signal. Never raises. 143#4051: the new engine is not started while the old one still holds its memory (tens of GB take longer than the 14410 s this used to wait): a 40 GiB arena loaded beside 50 GiB the old engine had not returned put a 60 GiB PC into 145memory reclaim for good. One still there after LEFTOVER_SETTLE_S is said in plain words, and the start goes on 146(the engine waits for the RAM itself and warns; nothing is refused).""" 147if os .environ .get ("STRATA_KEEP_LEFTOVERS" )== "1" : 148return 149try : 150from strata_control import procs 151say = lambda text :text ,flush = True )# noqa: E731 152stuck = [r ["pid" ]for r in procs .end_leftovers (say = say ,settle = LEFTOVER_SETTLE_S )["stuck" ]] 153stuck += [r ["pid" ]for r in procs .end_orphans (exe ,say = say ,settle = LEFTOVER_SETTLE_S )if r ["outcome" ]== "stuck" ] 154if stuck : 155f"[strata] WARNING: the engine from an earlier run (process { ', ' . join ( map ( str , stuck )) } ) was told to stop " 156f"but still holds its memory after { LEFTOVER_SETTLE_S :.0f } s. Starting the next one now can leave this PC " 157"short of RAM and very slow: wait until that process is gone (it is shown by `ps`/Task Manager), " 158"or restart the PC if it does not go." ,flush = True ) 159except Exception as e :# noqa: BLE001 - a failed check must not stop a start 160f"[strata] could not check for engines left by an earlier run: { type ( e ). __name__ } " ,flush = True ) 161 162 163def listen_problem (host :str ,port :int ,e :OSError )-> str : 164"""#769: why the server cannot listen. Only an address that is taken says "already in use"; anything else (a port 165Windows keeps reserved, an address this PC does not have, no permission) says what the OS said.""" 166import errno 167code = getattr (e ,"winerror" ,None )or e .errno 168if code in (errno .EADDRINUSE ,10048 ): 169return (f"port { port } is already in use - is Strata (or another server) already running? " 170f"Close it, or start this one with a different --port" ) 171what = e .strerror or str (e ) 172if code in (10013 ,errno .EACCES ): 173if sys .platform == "win32" : 174hint = ("Windows may keep this port for itself (see `netsh int ipv4 show excludedportrange protocol=tcp`) " 175"or a firewall rule forbids it: start this one with a different --port" ) 176else : 177hint = ("This system does not allow it (on Linux and macOS, ports below 1024 need administrator rights): " 178"start this one with a different --port" ) 179elif code in (10049 ,errno .EADDRNOTAVAIL ): 180hint = f" { host } is not an address of this PC: check \"host\" in the model's strata-<model>.json or --host" 181else : 182hint = "check --host and --port" 183return f"cannot listen on { host } : { port } : { what } [ { code } ]. { hint } " 184 185 186def combined_embeddings_path (vision_dir :Path ,nbytes :int )-> Path : 187"""#874: where one request's combined image-embeddings file goes. Every request with images rewrites it (it is 188deleted after the request), which on a disk is steady heavy writing: on Linux it goes to /dev/shm when that has 189room (the engine reads it back at once), on Windows the file is opened short-lived (the cache is not forced out 190to the drive). Anywhere else, or when /dev/shm is too small (Docker's default is 64 MB), it stays in the encoder's 191own directory, as before.""" 192name = f"req- { uuid . uuid4 (). hex [: 12 ] } .sve" 193shm = Path ("/dev/shm" ) 194if os .name != "nt" and shm .is_dir ()and os .access (shm ,os .W_OK ): 195try : 196if shutil .disk_usage (shm ).free > 2 * nbytes + (16 << 20 ): 197return shm / f"strata-vision- { os . getpid () } - { name } " 198except OSError : 199pass 200return Path (vision_dir )/ name 201 202 203def write_temporary (path :Path ,parts :list )-> None : 204"""#874: write `parts` (files) one after the other into `path`; on Windows with FILE_ATTRIBUTE_TEMPORARY 205(os.O_SHORT_LIVED), so the file normally never reaches the drive before it is deleted.""" 206flags = os .O_WRONLY | os .O_CREAT | os .O_TRUNC | getattr (os ,"O_BINARY" ,0 )| getattr (os ,"O_SHORT_LIVED" ,0 ) 207with os .fdopen (os .open (path ,flags ,0o600 ),"wb" )as f : 208for part in parts : 209f .write (Path (part ).read_bytes ()) 210# #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the 211# template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top 212EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" 213EFFORT_TEXT = {"low" :"Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the " 214"conclusion without unnecessary elaboration." , 215"medium" :"Reasoning effort is set to medium. Think as much as the task needs, without unnecessary " 216"elaboration." , 217# the template's own xhigh sentence (chat_template.jinja), which #728's recovery swaps for the low one 218"xhigh" :"Reasoning effort is set to xhigh. Please think carefully through the task, validate key " 219"assumptions, consider plausible alternatives, and prioritize correctness, consistency, and " 220"clarity in the final answer." } 221VISION_START = "<|vision_start|>" 222# #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a 223# broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens" 224# sets it; 0 turns it off. 225REPEAT_STOP_TOKENS = 256 226ANSWER_ROOM_MIN_CAP = 1024 # 0.1.45: from this max_tokens on, thinking without a budget is closed early enough to leave room to answer 227DS41_DEFAULT_BUDGET = 32768 # DeepSeek-V4.1 only: the thinking budget when neither the request nor the config names one 228DS41_SMALL_CAP_MIN = 48 # DeepSeek-V4.1 only: from this max_tokens up to ANSWER_ROOM_MIN_CAP, thinking is capped at half of it 229ANSWER_RESERVE_MIN = 512 # #984: the tokens kept for the answer when a thinking budget is cut down to fit max_tokens 230# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) 231# #1053 (opt-in "reasoning_close_retry": true): a reply that ends on its stop token still inside <think>, with no answer 232# and no call, is continued once with the thinking closed (the same way the budget's wrap-up closes it) 233REASONING_CLOSE = "\n</think>\n\n" 234REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n" 235# The budget's pass to an engine that says "hold" in READY carries GEN hold=N:ID (N: the reasoning tokens left, ID: the one 236# token of </think>): the engine stops there with its session at exactly the tokens it sent, so the next pass (+ the wrap-up) 237# continues from the live session. Without it the engine ran a window or two past the cut, and the next pass read the 238# whole reasoning again from the checkpoint before it. The server's own key in `sampling`, never a client's. 239HOLD_KEY = "_strata_hold" 240# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see). 241# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the 242# low-effort instruction in place of the xhigh one. Both off by default. 243HIGH_EFFORT = EFFORT_TEXT ["xhigh" ] 244LOW_EFFORT = EFFORT_TEXT ["low" ] 245LOOP_CHECK_EVERY = 512 # output tokens between two looks at the reasoning (at a clean parser boundary) 246LOOP_COVERAGE = 0.25 # the share of the last 2,000 words inside 12-word passages seen three times 247LOOP_HISTORY_WORDS = 30000 # how far back the passages are counted (bounds the cost of a look) 248LOOP_TAIL_CHARS = 2048 # chars at the end of the reasoning also checked for a short period (#1753) 249LOOP_TAIL_PERIOD = 64 # a period at most this long in that tail reads as a fully repeated window 250 251 252def reasoning_repeat_coverage (text ): 253"""Coverage of recent words by 12-word passages seen at least three times. 254 255Only reasoning is supplied. The history (the last LOOP_HISTORY_WORDS words) detects repeated verification passes 256separated by long code drafts; the recent window excludes old repetitions. #1753: a loop can also be one long 257word (a 24k-digit string cycling an 11-digit pattern): the word split makes it a single word and no word count 258grows, and #606's token run never grows either (the tokenizer has no multi-digit tokens), so before the word 259count the last LOOP_TAIL_CHARS chars are checked for a period of at most LOOP_TAIL_PERIOD, and a periodic tail 260reads as full coverage: it is all of the recent output, repeated. 261""" 262tail = text [- LOOP_TAIL_CHARS :].lower () 263if len (tail )== LOOP_TAIL_CHARS and any (tail [p :]== tail [:- p ]for p in range (1 ,LOOP_TAIL_PERIOD + 1 )): 264return 1.0 265words = re .findall (r"\w+|[^\w\s]" ,text .lower ())[- LOOP_HISTORY_WORDS :] 266width ,window = 12 ,2000 267if len (words )< window : 268return 0.0 269grams = [tuple (words [i :i + width ])for i in range (len (words )- width + 1 )] 270counts = collections .Counter (grams ) 271start = max (0 ,len (words )- window ) 272covered = set () 273for i in range (start ,len (grams )): 274if counts [grams [i ]]>= 3 : 275covered .update (range (i ,i + width )) 276return len (covered )/ (len (words )- start ) 277 278 279def focused_recovery_prompt (tok ,ids ,generated ): 280"""The prompt's ids with the xhigh effort sentence of the first system message replaced by the low one, then 281every token generated so far. A splice of token ids: the prompt is never decoded and encoded again, so a literal 282`</think>` or vision marker in it (#537, #554) stays what it was. None when the sentence is not there as whole 283tokens in the first system message (a user's text never counts). No answer or end-of-thinking is inserted.""" 284end = tok .encode (IM_END ,parse_special = True ) 285if len (end )!= 1 or end [0 ]not in ids : 286return None 287head = ids [:ids .index (end [0 ])] 288if not tok .decode (head ).startswith ("<|im_start|>system\n" ): 289return None 290old ,new = tok .encode (HIGH_EFFORT ,parse_special = False ),tok .encode (LOW_EFFORT ,parse_special = False ) 291for i in range (len (head )- len (old )+ 1 ): 292if head [i :i + len (old )]== old : 293return ids [:i ]+ new + ids [i + len (old ):]+ list (generated ) 294return None 295 296 297LOOPBACK_NAMES = ("localhost" ,"127.0.0.1" ,"::1" ) 298QUEUE_BEAT_S = 10.0 # a request waiting for the single turn sends a keep-alive this often (#1619) 299KEEPALIVE_S = 10.0 # a held-back tool argument leaves the stream quiet: ping at least this often 300# Anthropic clients add /v1/messages to their base URL themselves. A base URL that already ends in /v1 (copied from an OpenAI-style 301# setup) makes them post /v1/v1/messages; these two paths mean the same as the real ones. Nothing else is aliased. 302V1_V1_ALIASES = {"/v1/v1/messages" :"/v1/messages" ,"/v1/v1/messages/count_tokens" :"/v1/messages/count_tokens" } 303CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here 304 305 306class ContextOverflow (ValueError ): 307"""A request that does not fit the context (a 400 on every API). It keeps the numbers, so /v1/messages can also say it the way Anthropic's API 308does: a client that decides from the wording (Claude Code compacts on "prompt is too long", and shortens max_tokens on "input length and 309`max_tokens` exceed context limit") then does what it does for Anthropic's own error (#4838).""" 310 311def __init__ (self ,text ,* ,prompt ,context ,max_new = None ): 312super ().__init__ (text ) 313self .prompt ,self .context ,self .max_new = prompt ,context ,max_new 314 315def anthropic_text (self )-> str : 316if self .max_new is None or self .prompt > self .context - CTX_SLACK - 1 :# the prompt alone leaves no room: the largest one that still leaves a token 317return f"prompt is too long: { self . prompt } tokens > { self . context - CTX_SLACK - 1 } maximum; { self } " 318return f"input length and `max_tokens` exceed context limit: { self . prompt } + { self . max_new } > { self . context - CTX_SLACK } ; { self } " 319# 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 320# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer. 321RATE_WINDOW_S = 2.0 322RATE_MIN_SPAN_S = 0.25 # younger than this there is no rate yet: the mean so far, with the span floored here 323# #481: a running request whose engine prints nothing (no T, PP or any other line) for this long has lost step with the 324# server (the engine's main thread waits, untimed, for its next command): the engine is ended and the request fails; 325# the next request starts it again. The config's "engine_silence_s" sets it (0: wait forever, as before). 326ENGINE_SILENCE_S = 300.0 327# #4271: a streaming client that stops reading (a hung process, a network that dropped) leaves the thread that writes to 328# it blocked once the socket buffers are full - and that thread holds the engine's turn. A write that makes no progress 329# for this long ends the request as a disconnect (the engine is stopped, the turn given back). 0: no limit, as before. 330STREAM_WRITE_TIMEOUT_S = float (os .environ .get ("STRATA_STREAM_WRITE_TIMEOUT_S" ,"60" )or 0 ) 331# Disk sessions: the longest allowance an engine may announce (`SWAIT <phase> <s>`) for one step that blocks in a 332# single call (a file flush, the host->device transfer); the engine's own bound is the same (session_phase_limit_s). 333SESSION_WAIT_MAX_S = 3600 334# ... except while a prompt is read: a PP line comes once per chunk (up to 32768 tokens with --prefill auto, issue 335# #282), and the slowest PCs read ~100 tok/s, so a first chunk can take minutes before the first line. Until the first 336# PP the wait adds the chunk's tokens at PP_FLOOR_TOK_S; after one, a chunk may take PP_SLACK x the last one's time. 337PP_CHUNK_MAX = 32768 338PP_FLOOR_TOK_S = 50.0 339PP_SLACK = 3.0 340# Reads that had no timeout (#1317). A blocking read of the image encoder's pipe or of the engine's READY line that 341# never returned held the request turn for good: the engine then sat idle in its command loop, so no watchdog could 342# fire and every later request queued behind it (the "lost step" class of #481). Generous on purpose: a cold model 343# load, a slow disk or a slow CPU encode is not a hang. Only a process that says nothing at all for this long is 344# ended; the next request starts it again. 345# STRATA_ENGINE_READY_S / STRATA_VISION_READY_S / STRATA_VISION_ENCODE_S override them (0 = wait for ever, as before). 346 347 348def _timeout_env (name :str ,default :float )-> float | None : 349try : 350v = float (os .environ .get (name ,default )) 351except ValueError : 352v = default 353return None if v <= 0 else v 354 355 356# #1317 part 2: the quick watchdog for a FROZEN engine. engine_silence_s (above) is generous on purpose: a slow PC reads a 357# prompt chunk for minutes without a line. But an engine that prints nothing for ENGINE_STALL_S and also uses no CPU time and 358# moves no bytes of I/O in that time is not slow, it is idle or frozen (a deadlock in a CUDA call, a driver stall, a lost 359# step), and waiting longer cannot help: it is ended, and the next request starts it again. An engine that is silent but 360# still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable). 361# STRATA_ENGINE_STALL_S overrides it (0 = off). Needs psutil (setup installs it); without it nothing is ended. 362ENGINE_STALL_S = _timeout_env ("STRATA_ENGINE_STALL_S" ,90.0 ) 363PAR_COUNTERS = os .environ .get ("STRATA_PAR_COUNTERS" )== "1" # research counters (queue wait for a slot), shown in /v1/status 364# --batch: new requests take the control lines (one prompt read at a time) short prompts first: a prompt of at most 365# STRATA_ADMIT_SHORT_FIRST tokens goes before longer ones (opt-in; unset or 0: whoever gets the lock first), and a 366# longer one that waited STRATA_ADMIT_MAX_WAIT_S (default 30) counts as short. A chat question then waits for the one 367# read in progress, not for every agent read that came before it. 368try : 369ADMIT_SHORT_FIRST = max (0 ,int (os .environ .get ("STRATA_ADMIT_SHORT_FIRST" )or 0 )) 370except ValueError : 371ADMIT_SHORT_FIRST = 0 372ADMIT_MAX_WAIT_S = _timeout_env ("STRATA_ADMIT_MAX_WAIT_S" ,30.0 )or 0.0 373# STRATA_COALESCE_PREFILL=N (research, PAR-H; needs the engine's BCO / BCOK lines): a request that takes the control lines 374# for its admission also sends the prompts of up to N-1 requests still waiting for them (BCO <slot> <ids>, into free slots 375# it reserves for them); the engine reads all the prompts in ONE layer-major pass, so the experts a layer streams are 376# read once for all of them, and each waiting request then finds its prompt in its slot. 0 / unset: off. 377COALESCE_PREFILL = max (0 ,int (os .environ .get ("STRATA_COALESCE_PREFILL" )or 0 )) 378COALESCE_TOKENS = max (256 ,int (os .environ .get ("STRATA_COALESCE_TOKENS" )or 16384 ))# prompt tokens read together at most 379COALESCE_WAIT_MS = max (0 ,int (os .environ .get ("STRATA_COALESCE_WAIT_MS" )or 0 ))# a burst's later requests register within this long 380# Adaptive: a read is shared (and the leader waits for its followers) only when this engine has seen at least 381# COALESCE_MIN_REQS requests arrive within COALESCE_BURST_MS (the leader's own included). Fewer than that - one or two 382# requests per engine, as 8 requests on 4 replicas - read plainly, with no wait: nothing to share, and the wait and the 383# longer pass only cost (measured 4 x 1 replicas at 8 requests: 168 against 196 tok/s with an unconditional wait). 384COALESCE_MIN_REQS = max (2 ,int (os .environ .get ("STRATA_COALESCE_MIN_REQS" )or 3 )) 385COALESCE_BURST_MS = max (10 ,int (os .environ .get ("STRATA_COALESCE_BURST_MS" )or 250 )) 386STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen 387STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window 388 389 390def engine_frozen (base :tuple [float ,int ],now :tuple [float ,int ])-> bool : 391"""#1317: True when two (cpu seconds, io bytes) samples of the engine show no work between them.""" 392return (now [0 ]- base [0 ])<= STALL_CPU_EPS_S and (now [1 ]- base [1 ])<= STALL_IO_EPS_B 393 394 395VISION_READY_S = _timeout_env ("STRATA_VISION_READY_S" ,300.0 ) 396VISION_ENCODE_S = _timeout_env ("STRATA_VISION_ENCODE_S" ,300.0 ) 397ENGINE_READY_S = _timeout_env ("STRATA_ENGINE_READY_S" ,900.0 ) 398 399 400# ------------------------------------------------------------------------------------------------ engines 401class Engine (Protocol ): 402max_context :int 403def generate (self ,ids :list [int ],max_new :int ,sampling :dict ,cancel :threading .Event )-> Iterator [int ]: ... 404 405 406class MockEngine : 407"""Replays a scripted completion (text) as token ids, one per step, then the end-of-turn token. Given a list of 408scripts, each request gets the next one and the last one repeats (a tool call, then the answer after it).""" 409 410def __init__ (self ,tokenizer ,script :str | list [str ],max_context :int = 32768 ,delay_s :float = 0.0 , 411cycle :bool = False ): 412self .tok ,self .max_context ,self .delay = tokenizer ,max_context ,delay_s 413end = tokenizer .encode (IM_END ,parse_special = True ) 414self .scripts = [tokenizer .encode (x ,parse_special = True )+ end for x in ([script ]if isinstance (script ,str ) 415else script )] 416self .script ,self .turns = self .scripts [0 ],0 417# `cycle` picks the script by request position instead of advancing to the last one and staying 418# there. A harness adds requests the script author did not plan for -- a session title, a re-ask 419# after a tool result -- and with the default behaviour one extra request shifts every later 420# reply, so a run looks like a model that simply chose differently. 421self .cycle = bool (cycle ) 422self .last_prompt :list [int ]= [] 423 424def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 425self .last_prompt = list (ids ) 426self .last_embeddings = embeddings 427if len (self .scripts )> 1 : 428if self .cycle : 429self .script = self .scripts [self .turns % len (self .scripts )] 430else : 431self .script = self .scripts [min (self .turns ,len (self .scripts )- 1 )] 432self .turns += 1 433for t in self .script [:max_new ]: 434if cancel .is_set (): 435return 436if self .delay : 437time .sleep (self .delay ) 438yield t 439 440 441class EngineDied (RuntimeError ): 442"""The engine process ended in the middle of a request (issue #27: on Linux, the out-of-memory killer).""" 443restarts = True # the engine is gone, so the next request starts it again; False for an error raised while the engine is left running (#3961) 444 445 446def died_note (e :Exception )-> str : 447"""What an API error says about an EngineDied: the cause, and that the next request restarts the engine - only where it really is ended.""" 448return f" { e } ; the next request restarts it" if getattr (e ,"restarts" ,True )else str (e ) 449 450 451class EngineStarting (RuntimeError ): 452"""The engine is (re)starting and has not said READY yet (#344): no context size to plan a request with - a 503, 453not a 400 about the prompt.""" 454 455 456class ClientGone (Exception ): 457"""#1999: the client hung up while its request was being prepared (an image URL downloading, a picture encoding or 458waiting for its turn): nothing is left to answer.""" 459 460 461class ModelBusy (RuntimeError ): 462"""Explicit model controls must not interrupt active or queued requests.""" 463 464 465class QueueWaitExpired (RuntimeError ): 466"""An inference call waited too long for its first engine turn.""" 467 468 469class QueueCancelled (RuntimeError ): 470"""The client left before its first serial engine turn.""" 471 472 473class EngineSilent (EngineDied ): 474"""#481: the engine said nothing for too long during a request (or never acknowledged a STOP): the two sides lost 475step - the engine waiting for its next command, the server for this request's end - and the server ended it. An 476EngineDied, so the request ends with an error and the next one starts the engine again.""" 477 478 479class EngineNonFinite (ValueError ): 480"""#879: the engine's DONE (or a slot's BDONE) said `nonfinite`: a window's logits held a NaN or an infinity. The 481engine wrote none of that window's tokens and drops every cached state that may carry the poison, so its next 482request reads the prompt from token 0. Service.run sends a request that had produced nothing yet once more, and 483ends one that had started (as "length"). A ValueError, so a stream that has started reports it as an error event.""" 484 485 486class SessionRefused (ValueError ): 487"""Disk sessions: the engine refused or failed a SAVE / RESTORE and is still in step (`SERR <kind> <published> 488<reason>`). `kind` is the engine's category - invalid (400), storage (507), memory (503), io (500); `published`: 489a save whose new file already replaced the old one before a later step (the folder flush) failed.""" 490 491STATUS = {"invalid" :400 ,"storage" :507 ,"memory" :503 ,"io" :500 } 492 493def __init__ (self ,kind :str ,message :str ,published :bool = False ): 494super ().__init__ (message ) 495self .kind = kind if kind in self .STATUS else "io" 496self .published = published 497 498@property 499def status (self )-> int : 500return self .STATUS [self .kind ] 501 502 503class EngineStuck (RuntimeError ): 504"""The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than 505reporting its GPU and RAM as given back.""" 506 507 508class GpuBusy (RuntimeError ): 509"""The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another 510model server) is using it, so the engine is not started into the little that is left. `retry_after`: seconds 511for the Retry-After header of the 503.""" 512 513def __init__ (self ,message = "" ,retry_after = None ): 514super ().__init__ (message ) 515self .retry_after = retry_after 516 517 518# The page's only CSP directive: its preview frames (srcdoc) may not load any address. Other directives are left out 519# on purpose: a frame made from srcdoc inherits the page's policy, and the opt-in "run scripts" preview needs its own inline script. 520PAGE_CSP = "frame-src 'none'" 521 522 523def unload_wait (value ,default :float )-> float : 524"""#1997: the `wait` of POST /unload?wait=...: absent / 0 / false: 0 (answer "busy" at once, as before); 1 / true / 525yes: `default` seconds; a number of seconds above 1: that long (at most an hour).""" 526if value is None : 527return 0.0 528v = str (value ).strip ().lower () 529if v in ("" ,"0" ,"false" ,"no" ,"off" ): 530return 0.0 531if v in ("1" ,"true" ,"yes" ,"on" ): 532return default 533try : 534return min (3600.0 ,max (0.0 ,float (v ))) 535except ValueError : 536return default 537 538 539ENGINE_REQUEST = re .compile ( 540# "+ 12288 of 98179 read": a request cancelled while its prompt was read (#471) 541r"prompt (?P<prompt>\d+) tokens = (?P<reused>\d+) reused \+ \d+(?: of \d+)? read in (?P<read>[\d.]+) ms " 542r"\((?P<pp>[\d.]+) tok/s\), " 543r"(?P<gen>\d+) generated in (?P<gen_ms>[\d.]+) ms \((?P<tg>[\d.]+) tok/s\)" ) 544 545 546ENGINE_SCR = re .compile (r"SCR cached (?P<cached>\d+) scr (?P<scr>\d+) prefilled (?P<prefilled>\d+) of (?P<prompt>\d+)" ) 547 548 549_echoing :set [str ]= set ()# the logs echo_requests already follows (restart() runs StrataEngine.__init__ again) 550 551DRAFT_HEAD_FAIL = "the draft head does not fit" 552DRAFT_HEAD_HINT = ("a smaller draft vocabulary needs less VRAM: --draft-vocab cyrillic (English, code and the Cyrillic " 553"script) or --draft-vocab en (English and code, ~215 MiB less than the default). Start once with " 554"it - START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model " 555"keeps it; or a smaller --context in setup." ) 556 557 558def start_failure_hint (log :str | None ,offset :int )-> str : 559"""#474: what to change when the engine stopped at the start because the MTP draft head did not fit the VRAM 560left: the engine's own `strata mtp:` lines after that failure (0.1.36+: what it needs, what is free, the smaller 561subsets), else the same advice in words for an older engine. "" for any other failure: the log says why.""" 562if not log : 563return "" 564try : 565with open (log ,"rb" )as f : 566f .seek (offset ) 567text = f .read ().decode ("utf-8" ,"replace" ) 568except (OSError ,ValueError ): 569return "" 570if DRAFT_HEAD_FAIL not in text : 571return "" 572said = [x .strip ()[len ("strata mtp: " ):]for x in text .splitlines () 573if x .strip ().startswith ("strata mtp: " )and ("draft head over" in x or "hint:" in x )] 574return ". mtp: " + DRAFT_HEAD_FAIL + ". " + (" " .join (said )if said else "Hint: " + DRAFT_HEAD_HINT ) 575 576 577def start_log_text (log :str | None ,offset :int ,limit :int = 1 << 20 )-> str : 578"""Everything this engine start has written to the log so far (at most `limit` bytes), "" when there is no log.""" 579if not log : 580return "" 581try : 582with open (log ,"rb" )as f : 583f .seek (max (0 ,offset )) 584return f .read (limit ).decode ("utf-8" ,"replace" ) 585except (OSError ,ValueError ): 586return "" 587 588 589def start_log_tail (log :str | None ,offset :int ,n :int = 20 )-> str : 590"""#496: the last n lines this start wrote to the engine log, for the error when the engine ended before READY - 591whatever the failure, the engine's own reason is in them (people posted the traceback without the log). "" when 592there is no log or nothing in it from this start.""" 593if not log : 594return "" 595try : 596with open (log ,"rb" )as f : 597f .seek (0 ,2 ) 598start = max (offset ,f .tell ()- 64 * 1024 )# enough for 20 lines, never an earlier start's 599f .seek (start ) 600text = f .read ().decode ("utf-8" ,"replace" ) 601except (OSError ,ValueError ): 602return "" 603lines = text .splitlines ()[1 if start > offset else 0 :]# not a line cut in half 604lines = [x .rstrip ()for x in lines if x .strip ()][- n :] 605if not lines : 606return "" 607return "\nthe engine log's last lines:\n" + "\n" .join (" " + x for x in lines ) 608 609 610# Windows NTSTATUS exit codes of a process the system ended (a crash, not an error the engine reported) 611_WIN_CRASH = {0xC000001D :"illegal instruction (the CPU lacks an instruction the program uses)" , 6120xC0000005 :"access violation" ,0xC0000409 :"stack buffer overrun / fast-fail" , 6130xC0000135 :"a DLL the program needs was not found" ,0xC0000139 :"entry point not found in a DLL" , 6140xC0000142 :"a DLL failed to initialize" ,0xC000007B :"bad image (32-bit / 64-bit mix-up)" , 6150xC00000FD :"stack overflow" ,0xC0000094 :"integer division by zero" ,0xC0000096 :"privileged instruction" } 616 617 618def engine_exit_words (rc :int | None )-> str : 619"""What a process's exit status says, in words: "killed by signal 4 (SIGILL, Illegal instruction)" (a negative status 620on Linux / macOS), a Windows NTSTATUS crash code, or "exit code N". "" when there is no status.""" 621if rc is None : 622return "" 623if rc < 0 and os .name != "nt" : 624try : 625sig = signal .Signals (- rc ) 626return f"killed by signal { - rc } ( { sig . name } , { signal . strsignal ( sig ) or sig . name } )" 627except (ValueError ,AttributeError ): 628return f"killed by signal { - rc } " 629code = rc & 0xFFFFFFFF 630if code in _WIN_CRASH : 631return f"exit code 0x { code :08X } : { _WIN_CRASH [ code ] } " 632if 0xC0000000 <= code < 0xD0000000 : 633return f"exit code 0x { code :08X } (a system error status)" 634return f"exit code { rc } " 635 636 637def engine_crashed (rc :int | None )-> bool : 638"""True when the engine process was ended by the system (an illegal instruction, a bad memory access, the 639out-of-memory killer, a missing DLL ...) rather than leaving by itself: nothing a second try fixes.""" 640if rc is None : 641return False 642if rc < 0 and os .name != "nt" : 643return - rc in {int (getattr (signal ,n ))for n in ("SIGILL" ,"SIGSEGV" ,"SIGBUS" ,"SIGFPE" ,"SIGKILL" ) 644if hasattr (signal ,n )} 645return 0xC0000000 <= (rc & 0xFFFFFFFF )< 0xD0000000 # an NTSTATUS error code 646 647 648def cpu_isa_words ()-> tuple : 649"""(text, missing): the CPU's model and which of AVX / AVX2 / FMA / F16C it reports (Linux: /proc/cpuinfo), and the 650ones of those it lacks. ("", []) where it cannot be read.""" 651try : 652text = Path ("/proc/cpuinfo" ).read_text (errors = "replace" ) 653except OSError : 654return "" , [] 655model = next ((x .split (":" ,1 )[1 ].strip ()for x in text .splitlines ()if x .lower ().startswith ("model name" )),"" ) 656flags = next ((x .split (":" ,1 )[1 ].split ()for x in text .splitlines ()if x .lower ().startswith ("flags" )), []) 657have = ", " .join (f" { f } { 'yes' if f in flags else 'NO' } " for f in ("avx" ,"avx2" ,"fma" ,"f16c" ,"avx512f" )) 658missing = [f for f in ("avx" ,"avx2" ,"fma" ,"f16c" )if f not in flags ] 659return f" { model or 'this CPU' } ( { have } )" ,missing 660 661 662def start_exit_note (rc :int | None ,exe = None )-> str : 663"""The sentence the start error carries about how the engine process ended (the engine log is silent when the 664system ends it): "" without a status, else a line, with the CPU's AVX flags after an illegal instruction.""" 665words = engine_exit_words (rc ) 666if not words : 667return "" 668note = f"\nthe engine process ended: { words } " 669try :# 0xC0000135: say which DLL (the loader prints nothing) 670from serve .loader_diag import missing_note 671note += missing_note (rc ,exe ) 672except Exception : 673pass 674if rc is not None and ((rc < 0 and os .name != "nt" and - rc == int (getattr (signal ,"SIGILL" ,4 )))or 675 (rc & 0xFFFFFFFF )== 0xC000001D ): 676isa ,missing = cpu_isa_words () 677note += "\n An illegal instruction: the engine ran an instruction this CPU cannot execute" 678if isa and missing : 679note += f" ( { ', ' . join ( m . upper () for m in missing ) } missing; { isa } )" 680elif isa : 681note += f"; the CPU reports AVX, AVX2, FMA and F16C ( { isa } ), so this is a bug in the engine" 682note += ". Please report it with the CPU model (github.com/Niko1221/Strata/issues)." 683return note 684 685 686def start_log_marks (log :str | None ,offset :int )-> list : 687"""The GPU runtime failure texts (TRANSIENT_START_MARKS) this start wrote to the log: what lets a retry notice say the 688GPU runtime failed. [] when none, or no log.""" 689if not log : 690return [] 691try : 692with open (log ,"rb" )as f : 693f .seek (offset ) 694text = f .read (64 * 1024 ).decode ("utf-8" ,"replace" ) 695except (OSError ,ValueError ): 696return [] 697return [m for m in TRANSIENT_START_MARKS if m in text ] 698 699 700# A start that ends at once with the GPU runtime's own failure and none of the engine's lines: on ROCm, a start right 701# after the previous engine exited can fail inside the runtime's device/queue set-up while the old process's queues are 702# still being torn down ("terminate called after throwing an instance of 'rocr::AMD::hsa_exception'", or an exit with 703# nothing in the log). Such a start is tried again after a short wait (STRATA_START_RETRIES, default 3; 0: never). 704TRANSIENT_START_MARKS = ("hsa_exception" ,"HSA_STATUS_ERROR" ,"hsaKmt" ) 705START_RETRIES = max (0 ,int (os .environ .get ("STRATA_START_RETRIES" ,"3" )or 0 )) 706 707 708def transient_start_failure (log :str | None ,offset :int ,elapsed_s :float ,rc :int | None = None )-> bool : 709"""True when the start that wrote the log from `offset` failed the transient way above: within 30 s, and its lines 710are only the launcher's own "engine started" line plus (optionally) a GPU runtime failure. An exit with no line 711at all counts only when it was not the engine's own error exit (1: it said why on stdout).""" 712if not log or elapsed_s > 30.0 : 713return False 714try : 715with open (log ,"rb" )as f : 716f .seek (offset ) 717text = f .read (64 * 1024 ).decode ("utf-8" ,"replace" ) 718except (OSError ,ValueError ): 719return False 720lines = [x .strip ()for x in text .splitlines ()if x .strip ()] 721engine_lines = [x for x in lines if not x .startswith ("[strata]" )] 722if any (m in text for m in TRANSIENT_START_MARKS ): 723return all (x .startswith ("terminate called" )or x .startswith ("what()" )or 724any (m in x for m in TRANSIENT_START_MARKS )for x in engine_lines ) 725# it exited without writing a single line of its own - but not when the system ended it (an illegal instruction, a 726# bad memory access, the OOM killer, a missing DLL): that is a crash a second try repeats, and the retry notice 727# must not call it a GPU runtime start (#2324: an old CPU's illegal instruction was retried 3 times as "GPU 728# runtime" and the real reason never shown) 729return not engine_lines and rc != 1 and not engine_crashed (rc ) 730 731 732def echo_requests (log_path :str ,offset :int )-> None : 733"""STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log. 734 735The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this 736process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the 737total the two times make: `request prompt P cached C output O prompt_read R ms total S ms prefill X tok/s decode Y 738tok/s` (prompt_read: the time the engine spent reading the prompt's new tokens, not a time to first token). 739""" 740with open (log_path ,"r" ,encoding = "utf-8" ,errors = "replace" )as f : 741f .seek (offset ) 742while True : 743line = f .readline () 744if not line : 745time .sleep (0.2 ) 746continue 747s = ENGINE_SCR .search (line ) 748if s : 749"[strata] request scr cached %s scr %s prefilled %s of %s" % (s ["cached" ],s ["scr" ],s ["prefilled" ],s ["prompt" ]), 750flush = True ) 751m = ENGINE_REQUEST .search (line ) 752if m : 753read_ms ,gen_ms = float (m ["read" ]),float (m ["gen_ms" ]) 754"[strata] request prompt %s cached %s output %s prompt_read %.0f ms total %.0f ms prefill %s " 755"tok/s decode %s tok/s" % (m ["prompt" ],m ["reused" ],m ["gen" ],read_ms ,read_ms + gen_ms ,m ["pp" ], 756m ["tg" ]),flush = True ) 757 758 759def experts_loading_words (args :list ,size :str )-> str : 760"""#505: what the start does with the experts, by the engine's flags (generate.cpp's option parsing): a RAM budget 761copies the hottest N GiB into RAM (--resident-budget-gib), the resident low-RAM mode the ones the GPU does not hold 762(--resident-experts), plain --mmap-experts reads them from the model files through the OS file cache (nothing is 763loaded into RAM up front); otherwise all of them go into RAM.""" 764if "--resident-budget-gib" in args : 765try : 766n = f"up to { float ( args [ args . index ( '--resident-budget-gib' ) + 1 ]):g } GiB" 767except (IndexError ,ValueError ): 768n = "a RAM budget" 769return (f"loading the most-used experts into RAM ( { n } ; the rest are read from the model files as needed) " 770"and locking part of them for the GPU." ) 771if "--resident-experts" in args : 772return (f"loading the experts the GPU does not hold into RAM (of { size } ) and locking part of them for the " 773"GPU." ) 774if "--mmap-experts" in args : 775return (f"mapping the experts from the model files ( { size } , --mmap-experts): they are not loaded into RAM - " 776"the OS file cache reads them as the GPU's expert cache fills and as requests need them." ) 777return f"loading the experts into RAM ( { size } ) and locking part of them for the GPU." 778 779 780OPENS_BROWSER = False # set in main() when the server was started with --open: only then may a message say a browser opens 781 782 783# STRATA_DS4_RESTORE_POINTS (4): the DeepSeek engine keeps restore points where a later prompt is likely to leave this 784# one - its GEN line carries marks=<pos>,..., tail=<pos> and shared=<pos> - besides the end of the last prompt, the 785# position before it and the anchor it keeps anyway. N (1-16) turns them on, and is also the engine's cap a 786# conversation (it reads the same setting); 0: no keys, every GEN line as before. STRATA_DS4_RESTORE_TAIL (512): how 787# far before the prompt's end the tail point sits (0: none). (Project Maya #639, restore points.) 788RESTORE_LEAST = 1024 # no point before this many tokens: such a start is read again in about the time a point costs 789 790 791def restore_point_settings (env = None )-> tuple [bool ,int ]: 792"""(on, tail) from STRATA_DS4_RESTORE_POINTS and STRATA_DS4_RESTORE_TAIL.""" 793env = os .environ if env is None else env 794 795def whole (name ,default ): 796try : 797return max (0 ,int (str (env .get (name ,default )).strip ())) 798except ValueError : 799return default 800return whole ("STRATA_DS4_RESTORE_POINTS" ,4 )> 0 ,whole ("STRATA_DS4_RESTORE_TAIL" ,512 ) 801 802 803def deepseek_restore_points (ids ,user_id ,system_id = None ,tail = 512 ,least = RESTORE_LEAST )-> dict : 804"""Where the DeepSeek engine keeps restore points for this prompt -> {"marks": [pos, ...], "tail": pos, "shared": 805pos} (any may be missing; {}: none). From the prompt's ids as the template wrote them: a turn opens with its role's 806special token (<|User|>, a tool result's turn too; <|System|> for a system message after the first user turn), and 807text inside a message never encodes to one, so the positions are the template's own. 808 809- the start of the last user turn: its last message edited, or sent again after another answer, goes back there; 810- "tail": `tail` tokens before the end, when the last turn is longer than that: a new question after the same long 811document in the same message; 812- "shared": the end of the system prompt and its tools (the first user turn): another conversation behind the same 813start goes back there, and the engine gives that point up last. 814Positions under `least` are left out: a start that short is read again in about the time a point costs.""" 815if user_id is None or len (ids )< 2 : 816return {} 817first = last = None 818for i ,t in enumerate (ids ): 819if t == user_id : 820first = i if first is None else first 821last = i 822elif t == system_id and first is not None : 823last = i 824marks ,out = [], {} 825if first is not None and first >= least : 826out ["shared" ]= first 827if last is not None and last >= least and last != first : 828marks .append (last ) 829t = len (ids )- tail 830if tail > 0 and t >= least and (last is None or t > last ): 831out ["tail" ]= t 832if marks : 833out ["marks" ]= sorted (marks ) 834return out 835 836 837def narrate_start (log_path :str ,offset :int ,args :list ,done :threading .Event ,heartbeat = 20.0 )-> None : 838"""While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GB 839into RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more - 840people closed the window thinking it had hung. The warning comes at that step, not after it.""" 841gb = 0.0 842if "--native" in args :# about the size of the experts it will read 843try : 844gb = os .path .getsize (args [args .index ("--native" )+ 1 ])/ 1e9 845except (OSError ,IndexError ): 846pass 847size = f"about { gb :.0f } GB" if gb >= 1 else "tens of GB" 848loading = experts_loading_words (args ,size ) 849t0 = last = time .time () 850said = set () 851 852def say (key ,text ): 853nonlocal last 854if key not in said : 855said .add (key ) 856last = time .time () 857text ,flush = True ) 858 859say ("weights" ,"[strata] starting the engine: reading the model's weights ..." ) 860pos = offset 861while not done .wait (0.5 ): 862try : 863with open (log_path ,"rb" )as f : 864f .seek (pos ) 865chunk = f .read () 866except OSError : 867chunk = b"" 868if chunk .count (b"\n" ): 869cut = chunk .rfind (b"\n" )+ 1 870pos += cut 871for line in chunk [:cut ].decode ("utf-8" ,"replace" ).splitlines (): 872if "PLE on" in line or "expert arena:" in line or "experts via mmap" in line :# #505: mapped 873say ("arena" ,f"[strata] { loading } \n" 874" YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES NOW - this is normal.\n" 875" Please wait and don't close this window" 876+ ("; the browser opens when it is ready." if OPENS_BROWSER else "; the server says when it is ready." )) 877elif " loaded " in line and "GiB at" in line : 878say ("loaded" ,"[strata] experts loaded: " + line .split (" loaded " ,1 )[1 ].strip ()+ 879f" ( { time . time () - t0 :.0f } s so far)" ) 880elif "expert cache " in line and " slots, " in line and "auto" not in line : 881n = line .split ("expert cache " ,1 )[1 ].split (";" )[0 ].replace (" slots," ," experts," ).strip () 882say ("cache" ,f"[strata] filling the GPU's expert cache ( { n } ) ..." ) 883elif "session is up" in line : 884say ("up" ,"[strata] almost ready ..." ) 885if time .time ()- last > heartbeat : 886last = time .time () 887f"[strata] still starting ( { time . time () - t0 :.0f } s) - please wait ..." ,flush = True ) 888 889 890class ConvCacheLog : 891"""#596: the engine's conversation cache as its log tells it (the engine writes "strata serve: conversation 892cache: parked N tokens ...; parked=P bytes=B evictions=E" and "restored N tokens ...; parked=P bytes=B" to stderr, 893which is the log): read on from where it was last read, from the start of the engine's current run.""" 894EVENT = re .compile (r"conversation cache: (parked|skipped|restored) (\d+) tokens.*?parked=(\d+) bytes=(\d+)" 895r"(?: evictions=(\d+))?" ) 896DROPPED = re .compile (r"conversation cache: dropped \d+ superseded .*?parked=(\d+)" ) 897READ_MAX = 1 << 20 # at most the last MiB of new lines per read 898 899def __init__ (self ): 900self .key ,self .pos = None ,0 901self .lock = threading .Lock ()# polls come from several request / monitor threads at once 902self .reset () 903 904def reset (self ): 905self .state = {"parked" :0 ,"bytes" :0 ,"evictions" :0 ,"parks" :0 ,"restores" :0 ,"last_event" :None , 906"last_tokens" :None ,"last_at" :None } 907 908def poll (self ,path ,start )-> dict : 909"""The state after the log's new lines; `start` is where the engine's current run began in it. One poll at a 910time: a second one moved `pos` between the size check and the seek and raised ValueError (negative seek).""" 911with self .lock : 912return self ._poll (path ,start ) 913 914def _poll (self ,path ,start )-> dict : 915if not path or start is None : 916return dict (self .state ) 917if self .key != (path ,start ):# another start of the engine: its cache starts empty 918self .key ,self .pos = (path ,start ),start 919self .reset () 920try : 921size = os .path .getsize (path ) 922if size < self .pos :# the log was emptied or replaced 923self .pos = 0 924if size - self .pos > self .READ_MAX : 925self .pos = size - self .READ_MAX 926with open (path ,"rb" )as f : 927f .seek (self .pos ) 928data = f .read (size - self .pos ) 929except OSError : 930return dict (self .state ) 931end = data .rfind (b"\n" )+ 1 # whole lines only: the rest is read next time 932self .pos += end 933now = time .time () 934for line in data [:end ].decode ("utf-8" ,"replace" ).splitlines (): 935if "conversation cache:" not in line : 936continue 937m = self .EVENT .search (line ) 938if m : 939st = self .state 940st ["parked" ],st ["bytes" ]= int (m .group (3 )),int (m .group (4 )) 941if m .group (5 )is not None : 942st ["evictions" ]= int (m .group (5 )) 943if m .group (1 )!= "skipped" : 944st ["parks" if m .group (1 )== "parked" else "restores" ]+= 1 945st ["last_event" ],st ["last_tokens" ],st ["last_at" ]= m .group (1 ),int (m .group (2 )),now 946continue 947m = self .DROPPED .search (line ) 948if m : 949self .state ["parked" ]= int (m .group (1 )) 950return dict (self .state ) 951 952 953def conversation_slots (engine )-> int | None : 954"""How many conversations the engine's cache holds: its --conversation-cache-slots argument, which is known 955before the engine has started (a lazy start has reported no INFO line yet), else the INFO line it reported.""" 956args = engine .spawn [1 ]if hasattr (engine ,"spawn" )else [] 957if "--conversation-cache-slots" in args [:- 1 ]: 958try : 959return int (args [args .index ("--conversation-cache-slots" )+ 1 ]) 960except ValueError : 961pass 962slots = (getattr (engine ,"info" ,None )or {}).get ("conversation_cache_slots" ) 963return slots if isinstance (slots ,int )else None 964 965 966def conversation_cache_view (info :dict ,hist :list ,totals :dict ,parked :dict )-> dict : 967"""#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in 968--conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back.""" 969mib = info .get ("conversation_cache_mib" ) 970last = hist [- 1 ]if hist else None 971return {"enabled" :isinstance (mib ,int )and mib > 0 ,"budget_mib" :mib if isinstance (mib ,int )else None , 972"slots" :info .get ("conversation_cache_slots" ),** parked , 973"requests" :len (hist ),"requests_reused" :sum (1 for r in hist if (r .get ("reused" )or 0 )> 0 ), 974"reused_tokens" :totals .get ("reused" ,0 ),"prompt_tokens" :totals .get ("prompt_tokens" ,0 ), 975"last_reused" :last .get ("reused" )if last else None , 976"last_prompt" :last .get ("prompt_tokens" )if last else None } 977 978 979_BTRACE = bool (os .environ .get ("STRATA_BATCH_TRACE" )) 980 981 982def btrace (* a ): 983if _BTRACE : 984"[batch-trace]" ,threading .get_ident ()% 10000 ,* a ,file = sys .stderr ,flush = True ) 985 986 987EOS_IDS = {248044 ,248046 }# <|endoftext|>, <|im_end|>: the engine's default --eos-ids 988 989 990# The engine's own words for a verifier that cannot go on (its GPU waits were released, or an earlier window never 991# finished, #267): the process may stay alive and even print DONE, but it must not take another request. 992FATAL_PREFIXES = ("ERR verify: timed out at layer " ,"ERR verify batch: timed out at layer " , 993"ERR verify: an earlier window never finished" ,"ERR verify batch: an earlier window never finished" ) 994 995 996def parse_engine_stage_line (line :str )-> list [dict ]| None : 997"""Accept only the engine's final, contiguous stage plan (inclusive layer ends).""" 998prefix = "strata serve: layer split: layers " 999suffix = ", one hand-off per window" 1000if not line .startswith (prefix )or not line .rstrip ("\r\n" ).endswith (suffix ): 1001return None 1002body = line .rstrip ("\r\n" )[len (prefix ):- len (suffix )] 1003parts = body .split (", " ) 1004if not 2 <= len (parts )<= 16 : 1005return None 1006stages ,next_layer = [],0 1007for i ,part in enumerate (parts ): 1008match = re .fullmatch (r"([0-9]{1,5})-([0-9]{1,5}) \(CUDA([0-9]{1,2})\)" ,part ) 1009if match is None : 1010return None 1011first ,last ,ordinal = map (int ,match .groups ()) 1012if first != next_layer or last < first or last > 65535 or ordinal > 15 : 1013return None 1014stages .append ({"stage" :i ,"layer_start" :first ,"layer_end" :last , 1015"engine_ordinal" :ordinal }) 1016next_layer = last + 1 1017return stages 1018 1019 1020def read_engine_stage_log (path :str | None ,start :int ,limit :int = 2 << 20 )-> list [dict ]: 1021"""Read this engine start only; oversized/unavailable logs leave placement unknown.""" 1022if not path or start < 0 : 1023return [] 1024try : 1025with open (path ,"rb" )as source : 1026source .seek (start ) 1027data = source .read (limit + 1 ) 1028except OSError : 1029return [] 1030if len (data )> limit : 1031return [] 1032for line in reversed (data .decode ("utf-8" ,errors = "replace" ).splitlines ()): 1033stages = parse_engine_stage_line (line ) 1034if stages is not None : 1035return stages 1036return [] 1037 1038 1039def visible_device_order (env :dict | None ,backend :str | None )-> list [int ]: 1040"""Map engine ordinals to OS GPU indices only when the visibility list is unambiguous.""" 1041if backend not in (None ,"cuda" ,"hip" ): 1042return [] 1043if backend != "hip" and (env or {}).get ("CUDA_DEVICE_ORDER" )!= "PCI_BUS_ID" : 1044return [] 1045name = "HIP_VISIBLE_DEVICES" if backend == "hip" else "CUDA_VISIBLE_DEVICES" 1046value = (env or {}).get (name ) 1047if not isinstance (value ,str )or not re .fullmatch (r"[0-9]{1,5}(?:,[0-9]{1,5}){0,15}" ,value ): 1048return [] 1049devices = [int (part )for part in value .split ("," )] 1050return devices if all (0 <= device <= 65535 for device in devices )and len (set (devices ))== len (devices )else [] 1051 1052 1053def configure_batch_telemetry_env (env :dict ,cfg :dict ,override :bool | None )-> None : 1054"""Only an explicit setting changes the inherited opt-in engine environment.""" 1055choice = override if override is not None else cfg .get ("batch_telemetry" ) 1056if choice is True : 1057env ["STRATA_BATCH_TELEMETRY" ]= "1" 1058elif choice is False : 1059env .pop ("STRATA_BATCH_TELEMETRY" ,None ) 1060 1061 1062def parse_batch_window_sample (line :str )-> dict | None : 1063"""Read an opt-in engine BSTAT sample; rows are verifier work, not emitted tokens.""" 1064if len (line )> 80 : 1065return None 1066match = re .fullmatch (r"BSTAT ([1-9][0-9]{0,8}) ([1-9][0-9]{0,9}) " 1067r"([1-9][0-9]{0,9}) ([1-9][0-9]{0,9})\r?\n?" ,line ) 1068if match is None : 1069return None 1070windows ,rows ,active ,elapsed_ms = map (int ,match .groups ()) 1071if rows > windows * 8 or active > rows or elapsed_ms > 86_400_000 : 1072return None 1073return {"windows" :windows ,"processed_rows" :rows ,"active_rows" :active , 1074"elapsed_ms" :elapsed_ms } 1075 1076 1077def parse_stage_in_flight_sample (line :str )-> dict | None : 1078"""Read bounded PSTAT host scheduling spans; these are not GPU utilization.""" 1079if len (line )> 256 or re .fullmatch ( 1080r"PSTAT (?:[2-9]|1[0-6]) [1-9][0-9]{0,10}(?: (?:0|[1-9][0-9]{0,10})){2,16}\r?\n?" ,line )is None : 1081return None 1082parts = line .strip ().split (" " ) 1083stages ,elapsed_us = int (parts [1 ]),int (parts [2 ]) 1084in_flight_us = [int (value )for value in parts [3 :]] 1085if len (in_flight_us )!= stages or elapsed_us > 86_400_000_000 or \ 1086any (value > elapsed_us for value in in_flight_us ): 1087return None 1088return {"elapsed_us" :elapsed_us ,"in_flight_us" :in_flight_us } 1089 1090 1091class _RequestOwned : 1092"""#4451: a per-request control field of a --batch engine. With batch slots several requests run on their own 1093threads, and the control lines serve one at a time; a field every request writes (`_ctl_mode`, `_ctl_result`, 1094`_yielded`, `_last_done`, `_ctl_erred`) must not be seen by another request that gets the lines next. So each 1095thread has its own copy; one request at a time, it is the one attribute as before.""" 1096 1097def __init__ (self ,default = None ): 1098self .default = default 1099 1100def __set_name__ (self ,owner ,name ): 1101self .name = name 1102 1103def _store (self ,obj ): 1104d = obj .__dict__ 1105if d .get ("batch" ): 1106return d .setdefault ("_own_tl" ,threading .local ()).__dict__ 1107return d .setdefault ("_own_plain" , {}) 1108 1109def __get__ (self ,obj ,owner = None ): 1110if obj is None : 1111return self 1112return self ._store (obj ).get (self .name ,self .default ) 1113 1114def __set__ (self ,obj ,value ): 1115self ._store (obj )[self .name ]= value 1116 1117 1118class StrataEngine : 1119"""The resident engine: `strata --serve` reads `GEN <max_new> <ids>` lines and streams `T <id>` lines, then 1120`DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough. 1121 1122Per-request sampling rides the same line as engine-side keys between max_new and the ids 1123(`temperature=F top_p=F top_k=N seed=N`, the engine's own spelling). An absent temperature keeps the 1124engine's default, which is greedy; `temperature=0` means the same thing, so it is not forwarded. 1125""" 1126silence_s = ENGINE_SILENCE_S # #481: main() sets the config's engine_silence_s (survives restart()) 1127silent_note = None # #481: why the server ended a silent engine (death_note says it) 1128gpu_busy = None # #1317: () -> bool, "the GPU is working" (the telemetry's reading); a GPU at work is not frozen 1129last_err = None # #997: an ERR that was its last stdout line (death_note says it) 1130batch = 0 # --batch: the engine's batch slots (0: one request at a time) 1131_ctl_mode = _RequestOwned ()# the request that has the control lines: solo / batch (see _RequestOwned) 1132_ctl_result = _RequestOwned () 1133_yielded = _RequestOwned () 1134_last_done = _RequestOwned () 1135_ctl_erred = _RequestOwned (False ) 1136_ctl_held = _RequestOwned (False )# this thread already holds the control lines (Service.vram takes them itself) 1137CONTROL_WAIT_S = 300.0 # how long vram() / session_file() wait for the control lines of a batch engine 1138DRAIN_TIMEOUT_S = 300.0 # how long an interrupted request waits, with no line from its engine, for DONE / BADM 1139QUARANTINE_S = 600.0 # ... and how long a slot or the control lines stay held after that with no line 1140multi = 0 # DeepSeek --parallel (READY ... multi=N): conversations the engine holds at once (batch = N too) 1141 1142# `last`: the figures of the engine's last DONE line. With batch slots several requests run at once, each on its 1143# own thread, so each one reads its own request's figures (Service.run records them); one at a time, the one dict. 1144@property 1145def last (self ): 1146if self .batch : 1147tl = self .__dict__ .setdefault ("_tl" ,threading .local ()) 1148if not hasattr (tl ,"last" ): 1149tl .last = {} 1150return tl .last 1151return self .__dict__ .get ("_last" , {}) 1152 1153@ last . setter 1154def last (self ,value ): 1155self .__dict__ ["_last" ]= value 1156if self .batch : 1157tl = self .__dict__ .setdefault ("_tl" ,threading .local ()) 1158tl .last = value 1159 1160def __init__ (self ,exe :str ,args :list [str ],cwd :str | None = None ,log :str | None = None , 1161env :dict | None = None ,lazy :bool = False ,cpus :list [int ]| None = None ,_attempt :int = 0 , 1162retry_args :list [str ]| None = None ,retry_vram_args :list [str ]| None = None ): 1163# retry_args: the arguments to start again with, once, when this start ends before the engine is ready (an Auto start that picked DFlash2: mtp_retry_args) 1164# retry_vram_args: the same start with no drafter (nodraft_retry_args), used instead when the engine ended because a card ran out of memory: swapping DFlash2 for 1165# the MTP takes MORE memory from a card that is already short, so that direction is never taken then 1166self .spawn = (exe ,list (args ),cwd ,log ,env ,False ,cpus )# to start it again after it died (issue #27) 1167# the all-cards split engine (sFNX, strata-split-N[-arch]): its GEN parser accepts fewer keys than Strata's engine (tests/split/test_split_gen_keys.py pins them) 1168self .split_engine = os .path .basename (str (exe )).startswith ("strata-split" ) 1169self .session_save_reclaim = '--session-save-reclaim' in args 1170paths = {k :v for k ,v in zip (args ,args [1 :])if k in ("--native" ,"--pack" )} 1171self .model_path = paths .get ("--native" )or paths .get ("--pack" ,"pack/full" ) 1172self .log_path = log 1173self .proc ,self .pump ,self .log = None ,None ,None 1174self .ended ,self .unloaded = True ,True 1175self .max_context = int (args [args .index ("--max-context" )+ 1 ])if "--max-context" in args else 4096 1176self .can_stop = False # the engine honours a STOP line mid-request (READY <ctx> stop) 1177self .can_hold = False # the engine takes GEN hold=N:ID (READY <ctx> ... hold) 1178self .can_hold_batch = False # ... and its --batch slots end at the hold too, BDONE hold (READY ... holdb) 1179self .last = {} 1180self .info = {}# INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) 1181self .terminal_stages :list [dict ]= []# final layer ranges from this engine start's bounded stderr log 1182self .terminal_batch_sample :dict | None = None 1183self .terminal_stage_sample :dict | None = None 1184self .prefill_tok_s_mean = None 1185self .progress = None # (read, total) prompt tokens while a prompt is read, from PP lines 1186self .progress_ms = 0 # PP's own milliseconds since the prompt started (its third field) 1187self .reused = 0 # RESUME: prompt tokens not read again (a client takes them out of the work) 1188self .silent_note = None 1189self .last_err = None 1190try :# a ready-made engine's BUILD.json says its version 1191self .info ["version" ]= json .loads ((Path (exe ).parent / "BUILD.json" ).read_text ()).get ("version" ) 1192except (OSError ,ValueError ): 1193self .info ["version" ]= None 1194if lazy : 1195return 1196self .unloaded = False # `ended` stays True until READY (below): not alive while starting (#344) 1197self .log = open (log ,"a" ,encoding = "utf-8" )if log else subprocess .DEVNULL 1198loading = threading .Event ()# set once READY: the narrator below stops 1199log_start = os .path .getsize (log )if log else 0 # where this start's lines begin (start_failure_hint) 1200self .log_start = log_start # #596: the Monitor's conversation cache reads from here 1201if log : 1202threading .Thread (target = narrate_start ,args = (log ,os .path .getsize (log ),args ,loading ), 1203daemon = True ).start () 1204# once per log: the follower keeps reading the same (appended) log across restarts and reloads 1205if os .environ .get ("STRATA_REQUEST_LINES" )and os .path .abspath (log )not in _echoing : 1206_echoing .add (os .path .abspath (log )) 1207threading .Thread (target = echo_requests ,args = (log ,os .path .getsize (log )),daemon = True ).start () 1208if log :# #779: when an engine started (a crash report has the time) 1209try : 1210self .log .write (f"[strata] { time . strftime ( '%Y-%m-%d %H:%M:%S' ) } engine started: { exe } --serve " 1211f" { ' ' . join ( args ) } \n" ) 1212self .log .flush () 1213except OSError : 1214pass 1215self .max_context = 0 # before the new process is visible: never its predecessor's 1216pin = {} 1217if cpus and hasattr (os ,"sched_setaffinity" ):# replicas: this engine's own physical cores (serve/replicas.py) 1218pin ["preexec_fn" ]= lambda :os .sched_setaffinity (0 ,cpus ) 1219nice = engine_nice (env )# Linux with built-in Radeon graphics: the desktop keeps its share of the CPU 1220if nice : 1221say_nice = pin .get ("preexec_fn" ) 1222pin ["preexec_fn" ]= lambda : (say_nice ()if say_nice else None ,os .nice (nice ))[0 ] 1223f"[strata] engine priority: nice + { nice } (this PC has built-in Radeon graphics that usually draw the desktop; " 1224"STRATA_ENGINE_NICE=0 turns it off)" ,flush = True ) 1225end_leftover_engines (exe )# one an earlier run lost still holds the GPU and the memory 1226spawned_at = time .monotonic () 1227try : 1228self .proc = popen ("the Strata engine" , [exe ,"--serve" ,* args ],cwd = cwd ,stdin = subprocess .PIPE , 1229stdout = subprocess .PIPE ,stderr = self .log ,text = True ,encoding = "utf-8" ,errors = "replace" , 1230bufsize = 1 ,env = env ,** pin )# (#5044: a byte that is not UTF-8 killed the reader thread) 1231except OSError :# nothing started: the narrator stops, the log handle goes back 1232loading .set () 1233if log : 1234self .log .close () 1235raise 1236proc = self .proc # THIS start's process: a close() from another thread may set self.proc to None meanwhile (#4792) 1237# the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream 1238# stays for _pump (one reader at a time) 1239ready_q :queue .Queue = queue .Queue () 1240threading .Thread (target = self ._ready_pump ,args = (self .proc ,ready_q ),daemon = True ).start () 1241ready_deadline = None if ENGINE_READY_S is None else time .monotonic ()+ ENGINE_READY_S 1242timed_out = False 1243while True : 1244left = None if ready_deadline is None else ready_deadline - time .monotonic () 1245if left is not None and left <= 0 : 1246timed_out = True 1247break 1248try : 1249line = ready_q .get (timeout = left ) 1250except queue .Empty : 1251continue 1252if line is None : 1253break 1254if line .startswith ("INFO " ): 1255for kv in line .split ()[1 :]: 1256k ,_ ,v = kv .partition ("=" ) 1257self .info [k ]= int (v )if v .lstrip ("-" ).isdigit ()else v 1258if line .startswith ("READY" ): 1259f = line .split () 1260self .max_context = int (f [1 ]) 1261self .can_stop = "stop" in f [2 :] 1262self .can_hold = "hold" in f [2 :] 1263self .can_hold_batch = "holdb" in f [2 :] 1264self .multi = next ((int (x [6 :])for x in f [2 :]if x .startswith ("multi=" )and x [6 :].isdigit ()),0 ) 1265break 1266loading .set () 1267if self .max_context <= 0 : 1268if timed_out :# still loading, or hung: end it, so the turn is not held for good 1269try : 1270proc .kill () 1271except OSError : 1272pass 1273try :# its pipes and our handle on its log (the log stays) 1274proc .wait (timeout = 5 ) 1275proc .stdin .close () 1276proc .stdout .close () 1277if log : 1278self .log .close () 1279except (OSError ,subprocess .TimeoutExpired ): 1280pass 1281if not timed_out and _attempt < START_RETRIES and \ 1282transient_start_failure (log ,log_start ,time .monotonic ()- spawned_at ,proc .returncode ): 1283wait_s = 2.0 * (2 ** _attempt )# 2, 4, 8 s: the previous process's GPU queues go away 1284exit_words = engine_exit_words (proc .returncode ) 1285if start_log_marks (log ,log_start ):# the runtime said so itself (hsa_exception ...) 1286f"[strata] the engine stopped while the GPU runtime was starting (most often right after " 1287f"another engine exited, whose GPU queues were still being released" 1288f" { '; ' + exit_words if exit_words else '' } ): starting it again in { wait_s :.0f } s " 1289f"(try { _attempt + 2 } of { START_RETRIES + 1 } )" ,flush = True ) 1290else :# an exit with nothing in the log: say only what is known 1291f"[strata] the engine exited before it wrote anything to its log" 1292f" { ' (' + exit_words + ')' if exit_words else '' } ; it may be a GPU runtime that was not " 1293f"ready yet: starting it again in { wait_s :.0f } s (try { _attempt + 2 } of { START_RETRIES + 1 } )" , 1294flush = True ) 1295time .sleep (wait_s ) 1296StrataEngine .__init__ (self ,exe ,args ,cwd ,log ,env ,lazy ,cpus ,_attempt + 1 ,retry_args ,retry_vram_args ) 1297return 1298short_reason = None if timed_out else vram_fit .engine_stop_reason (start_log_text (log ,log_start ).splitlines ()) 1299if short_reason and retry_vram_args and retry_vram_args != list (args ): 1300# a card ran out of memory (the engine's own reason is in its log): one more start with no drafter, in one quiet line 1301f"[strata] { drafting . line ( 'off' , drafting . SHORT_OF_VRAM ) } : starting again without a drafter ( { short_reason } )" ,flush = True ) 1302try : 1303with open (log ,"a" ,encoding = "utf-8" )as handle : 1304handle .write (f"[strata] { time . strftime ( '%Y-%m-%d %H:%M:%S' ) } the engine ended before it was ready because a card was short of memory " 1305f"(exit code { proc . returncode } ); starting it again without a drafter\n" ) 1306except (OSError ,TypeError ): 1307pass 1308drafting .remember_note (drafting .SHORT_OF_VRAM ) 1309StrataEngine .__init__ (self ,exe ,retry_vram_args ,cwd ,log ,env ,lazy ,cpus ,0 ,None ,None ) 1310return 1311if not timed_out and not short_reason and retry_args and retry_args != list (args ): 1312# Auto picked DFlash2 and the engine ended before it was ready (an engine that does not take one of its flags, a drafter file it cannot read...): 1313# one more start with the MTP, said in one quiet line. The person named DFlash2 themselves: no retry, the start fails with its reason below. 1314f"[strata] { drafting . line ( 'mtp' , drafting . DIDNT_START ) } : starting again with the MTP" ,flush = True ) 1315try : 1316with open (log ,"a" ,encoding = "utf-8" )as handle : 1317handle .write (f"[strata] { time . strftime ( '%Y-%m-%d %H:%M:%S' ) } the engine ended before it was ready with the DFlash2 drafter " 1318f"(exit code { proc . returncode } ); starting it again with the MTP\n" ) 1319except (OSError ,TypeError ): 1320pass 1321drafting .remember_note (drafting .DIDNT_START ) 1322StrataEngine .__init__ (self ,exe ,retry_args ,cwd ,log ,env ,lazy ,cpus ,0 ,None ,None ) 1323return 1324why = (f"the engine did not report READY within { ENGINE_READY_S :.0f } s" if timed_out else 1325"the engine exited before it was ready" ) 1326# EngineDied, not bare RuntimeError: a request waiting on this load must end with a 503 1327# through the request path's handler - a RuntimeError there left the turn with no answer (#1527) 1328note = "" if timed_out else start_exit_note (proc .returncode ,exe ) 1329tail = start_log_tail (log ,log_start ) 1330lines = [x for x in tail .split ("\n" )[2 :]if x .strip ()] 1331if tail and lines and all (x .strip ().startswith ("[strata]" )for x in lines ): 1332tail += "\n (those are the launcher's own lines: the engine itself wrote nothing)" 1333raise EngineDied (why + (f" (see { log } )" if log else "" )+ note + 1334start_failure_hint (log ,log_start )+ tail ) 1335self .known_ctx = self .max_context # survives a failed restart: requests keep their limit and restart it 1336# (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that 1337# report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones 1338if self .info .get ("engine" ): 1339self .info ["version" ]= str (self .info ["engine" ]) 1340self .terminal_stages = read_engine_stage_log (log ,log_start )if log else [] 1341try :# which drafter runs, and in plain words why not the one that was asked for 1342self .info .update (drafting .engine_info (args ,start_log_text (log ,log_start ),drafting .take_note ())) 1343except Exception :# noqa: BLE001 - a note must never stop a start 1344pass 1345self .ended = False # READY: alive from here (restart() set it True, #344) 1346# the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks) 1347self .gen = self .__dict__ .get ("gen" ,0 )+ 1 # which engine process this is (a request notes its own); first, so 1348# a request that sees the new number sees the new queues (#4451) 1349self .lines :queue .Queue = queue .Queue () 1350# --batch: concurrent requests in the engine's batch slots (see generate_batched). The engine says how many 1351# it runs (INFO batch_slots=N: it may have fewer than asked, or none, when they do not fit) 1352asked = next ((int (args [args .index (k )+ 1 ])for k in ("--batch" ,"--slots" ,"--parallel" )if k in args ),0 ) 1353self .batch = int (self .info .get ("batch_slots" )or 0 ) 1354if self .multi :# DeepSeek --parallel: several requests at once, in its own protocol 1355self .batch = self .multi # (the server's parallel paths key on it: no FIFO, a request's own figures) 1356if asked and self .batch != asked : 1357f"[strata] parallel requests: { asked } asked, the engine runs { self . batch or 'one at a time' } " 1358"(its log says why)" ,flush = True ) 1359_bg = args [args .index ("--batch-groups" )+ 1 ]if "--batch-groups" in args else "default" 1360# no `--batch-groups` (the default on a layer split) or `auto`: the engine picks the groups and says so 1361# (INFO batch_groups=G); a number is the group count asked for (1 = off) 1362groups = int (self .info .get ("batch_groups" )or 1 )if _bg in ("auto" ,"default" )else int (_bg ) 1363groups = groups if self .batch and groups > 0 and self .batch % groups == 0 else 1 1364gs = self .batch // groups if self .batch else 0 1365# slots in the order that spreads requests over the pipeline's groups first: 0, gs, 2gs, .., 1, gs+1, .. 1366self .slot_order = [g * gs + t for t in range (gs )for g in range (groups )] 1367self .slot_group = [b // gs if gs else 0 for b in range (self .batch )]# each slot's pipeline group 1368self .slot_groups = groups 1369# pipelined groups (the engine says how many it runs: INFO batch_groups; older engines: the args). A pipelined 1370# group's window spans its slots up to its last busy one, and the engine keeps no pipelined slot as a 1371# conversation cache - see pick_slot 1372groups_run = int (self .info .get ("batch_groups" )or groups ) 1373self .slot_gs = gs if groups > 1 and groups_run > 1 else 0 1374self .slot_q = [queue .Queue ()for _ in range (self .batch )] 1375self .slot_busy = [False ]* self .batch 1376# #1603: who owns a busy flag. slot_claims: slots a request of this server picked or reserved and has not 1377# given back; slot_releasing: slots handed to the background BDONE wait. A busy slot in neither has no owner 1378# (its flag leaked) and would keep every later request waiting for a slot that nothing will free. 1379self .slot_claims :set [int ]= set () 1380self .slot_releasing :set [int ]= set () 1381self ._orphan_seen :dict [int ,float ]= {} 1382# what each slot's sessions hold (prompt + every token a window fed), so a conversation's next turn goes to 1383# the slot that has its start (the engine checks it again); when the slot was last used 1384self .slot_held :list [list [int ]]= [[]for _ in range (self .batch )] 1385self .slot_used = [0.0 ]* self .batch 1386self .slot_live :list [dict | None ]= [None ]* self .batch # /metrics: the request in each slot 1387# #1012: the admission state belongs to the server, not to one engine process. restart() runs this again 1388# while requests still wait on it (they hold these very objects), so it is made once and kept: new ones 1389# would leave the waiters on a lock and a condition nobody notifies, with their counts missing from the 1390# new lists. 1391if "slot_cv" not in self .__dict__ : 1392self .slot_cv = threading .Condition () 1393self .waiting = 0 # requests waiting for the control lines (ctl) 1394self .admitting = 0 # #1603: ... and those that gave the lines back to wait for a slot 1395self .par_counters = {"queued" :0 ,"queue_wait_s" :0.0 } 1396self .wait_lens :list [list [int ]]= []# ... their prompt lengths (a long read gives way to short ones) 1397self .arrivals = collections .deque (maxlen = 64 )# monotonic times of the last requests that came for the control lines (STRATA_COALESCE_*) 1398self .ctl_epoch = 0 # how often the control lines were taken 1399self .ctl = threading .Lock ()# one admission or solo request on the control lines at a time 1400if "rid_lock" not in self .__dict__ : 1401self .rid_lock = threading .Lock () 1402self .rid_n = 0 # --parallel requests' ids (rid=): never reused, a restart goes on from here 1403self .rid_q :dict [int ,queue .Queue ]= {}# this process's: rid -> that request's lines (T / PP / DONE / ERR, rid taken out) 1404self .multi_stat = "" # the engine's last STAT line over everything it wrote 1405self ._ctl_erred = False # #1059: the control lines ended on an ERR 1406self ._yielded = None # (slot, tokens read): the last request on them gave way 1407self .wlock = threading .Lock ()# stdin writes from several request threads 1408self .pump = threading .Thread (target = self ._pump ,daemon = True ) 1409self .pump .start () 1410 1411def _pump (self ): 1412proc ,lines = self .proc ,self .lines # this process's: a restart replaces both (#344) 1413slot_q = self .slot_q 1414slot_busy = self .slot_busy # this process's (a restart makes new ones) 1415rid_q = self .rid_q 1416multi = self .multi 1417line = None 1418for line in proc .stdout : 1419# checked before batch routing: a fatal line is never a slot's own 1420if line .startswith (FATAL_PREFIXES ): 1421# release_gpu_waits invalidates the verifier, even if the native 1422# process stays alive and prints DONE afterwards. 1423if self .proc is proc : 1424self .silent_note = "Unrecoverable native verification failure: " + line [4 :].strip () 1425self .ended = True 1426try : 1427proc .terminate () 1428except OSError : 1429pass 1430break # publish EOF, never the trailing DONE 1431if line .startswith ("BSTAT" ): 1432sample = parse_batch_window_sample (line ) 1433if sample is not None and self .proc is proc : 1434self .terminal_batch_sample = {** sample ,"observed_monotonic" :time .monotonic ()} 1435continue # control telemetry never enters a request's token stream 1436if line .startswith ("PSTAT" ): 1437sample = parse_stage_in_flight_sample (line ) 1438if sample is not None and self .proc is proc : 1439self .terminal_stage_sample = {** sample ,"observed_monotonic" :time .monotonic ()} 1440continue 1441if multi :# DeepSeek --parallel: `T <rid> <id>`, `PP <rid> ...`, `DONE <rid> ...`, `ERR <rid> ...` 1442head ,_ ,rest = line .partition (" " ) 1443if head in ("T" ,"PP" ,"DONE" ,"ERR" )and rest [:1 ].isdigit (): 1444rid_s ,_ ,tail = rest .partition (" " ) 1445rq = rid_q .get (int (rid_s )) 1446if rq is not None :# (a request that has ended: its late lines go nowhere) 1447rq .put (head + (" " + tail if tail else "\n" )) 1448continue 1449if head == "STAT" :# over everything the engine wrote, not one request's 1450self .multi_stat = line 1451continue 1452if line .startswith (("BT " ,"BDONE " ))and slot_q :# --batch: a batch slot's own lines 1453try : 1454b = int (line .split ()[1 ]) 1455if 0 <= b < len (slot_q )and not slot_busy [b ]: 1456# #4451: a frame for a slot that no request has claimed belongs to a request that is over (its 1457# slot was given back too early, or never claimed): the next request on the slot must not read it 1458self .stale_frames = getattr (self ,"stale_frames" ,0 )+ 1 1459btrace ("stale frame dropped" ,line .strip ()[:60 ]) 1460continue 1461slot_q [b ].put (line ) 1462continue 1463except (IndexError ,ValueError ): 1464pass 1465lines .put (line ) 1466if self .proc is proc :# a killed engine's pump must not mark its successor dead 1467self .ended = True # its output closed: it is gone, even before the OS says so 1468if line and line .startswith ("ERR" ):# #997 #890: why it exited, though no request may read it 1469self .last_err = line [4 :].strip ()# (a failed batch window: every request reads its slot) 1470lines .put (None ) 1471for q in slot_q : 1472q .put (None ) 1473for q in list (rid_q .values ()): 1474q .put (None ) 1475 1476def death_note (self )-> str : 1477"""Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM.""" 1478if getattr (self ,"silent_note" ,None ):# #481: the server ended it, not the OS or the engine itself 1479return self .silent_note 1480tail = wide = "" 1481try : 1482with open (self .log_path ,"rb" )as f : 1483f .seek (0 ,2 ) 1484f .seek (max (0 ,f .tell ()- 262144 )) 1485wide = f .read ().decode ("utf-8" ,"replace" ) 1486tail = wide [- 4096 :] 1487except (OSError ,TypeError ): 1488pass 1489# #1705: STRATA_VERIFY_TRACE dumps are ~30 KB and push the watchdog's line out of a 4 KB tail 1490for line in reversed (wide .splitlines ()): 1491if "issue #29" in line : 1492return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log " 1493"line: " + line .strip ()+ " - please report it at github.com/Niko1221/Strata/issues." ) 1494if (self .last_err or "" ).startswith ("fatal GPU error" ):# #4350: the engine ended itself; the next request starts it again 1495return ("The graphics card reported a fatal error (" + self .last_err [len ("fatal GPU error:" ):].strip ()[:160 ]+ "), so the engine " 1496"ended. The next request starts it again. If this repeats, please report it at github.com/Niko1221/Strata/issues " 1497"with the log." ) 1498proc = self .proc # None while a restart has not started the next one yet 1499rc = proc .poll ()if proc is not None else None 1500if rc is not None and rc >= 0 and self .last_err :# its own last words on stdout: they say why 1501return (f"The engine exited (code { rc } ) after it reported: { self . last_err } - please report it at " 1502"github.com/Niko1221/Strata/issues with the log." ) 1503last = next ((x .strip ()for x in reversed (tail .splitlines ())if x .strip ().startswith (("strata" ,"ERR" ))),"" ) 1504if rc is not None and rc >= 0 and last :# it ended by itself: its own last words say why (#215) 1505return (f"The engine exited (code { rc } ). Its last log line: { last } - if that does not explain it, please " 1506"report it at github.com/Niko1221/Strata/issues with the log." ) 1507rt_note = rttime_limit_note ()if rc == - 9 else "" 1508if rt_note :# #3238: the kernel killed it, but not for RAM 1509return ("The engine was ended by signal 9. " + rt_note + " If dmesg (sudo dmesg | grep -i -E 'killed " 1510"process|out of memory') shows an out-of-memory kill instead, close other programs or use a smaller " 1511"model (Q2_0 / IQ2_XS)." ) 1512return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | " 1513"grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a " 1514"smaller model (Q2_0 / IQ2_XS)." ) 1515 1516def alive (self )-> bool : 1517proc = self .proc # read once: restart() / close() may set it to None meanwhile 1518return proc is not None and not getattr (self ,"ended" ,False )and proc .poll ()is None 1519 1520def exit_code (self ): 1521if self .proc is None : 1522return None 1523try : 1524return self .proc .wait (timeout = 5 ) 1525except subprocess .TimeoutExpired : 1526return None 1527 1528def unload (self ): 1529"""Release GPU/RAM between requests, retaining the spawn config for automatic reloading.""" 1530self .close () 1531self .unloaded = True 1532 1533RESTART_RETRY_S = 15.0 # between the tries of restart(): a dying engine's VRAM may take a while to come back 1534 1535@staticmethod 1536def _ready_pump (proc ,out :queue .Queue )-> None : 1537"""The engine's first lines up to READY, for a read that can time out; None when its output closed first.""" 1538done = False 1539try : 1540for line in proc .stdout : 1541out .put (line ) 1542if line .startswith ("READY" ): 1543done = True 1544return 1545except (OSError ,ValueError ):# the pipe closed under us (the engine was killed) 1546pass 1547finally : 1548if not done : 1549out .put (None ) 1550 1551def restart (self ,tries :int = 3 ): 1552"""Start the engine again (the same command) after it died; the new process has its own line queue. 1553close() ends and waits for the old process first (EngineStuck when it cannot be ended). A start that still 1554exits before READY - a dead engine's VRAM can take a while to come back, notably on ROCm - is retried 1555(PR #637).""" 1556info = dict (self .info ) 1557self .starting = True # prepare() answers 503 "starting" meanwhile (#344) 1558try : 1559self .close () 1560for i in range (tries ): 1561# #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says 1562# READY, and a request that saw alive() in that window skipped load() and failed with "context 1563# (0)". __init__ clears `ended` itself once READY (before its pump thread can set it again). 1564self .ended = True 1565try : 1566self .__init__ (* self .spawn ) 1567break 1568except RuntimeError : 1569try : 1570self .proc .wait (timeout = 60 ) 1571except (subprocess .TimeoutExpired ,OSError ): 1572pass 1573if i == tries - 1 : 1574raise 1575f"[strata] the engine did not start (try { i + 1 } of { tries } ); again in " 1576f" { self . RESTART_RETRY_S :g } s" ,flush = True ) 1577time .sleep (self .RESTART_RETRY_S ) 1578finally : 1579self .starting = False 1580# a lazy first start never reached the post-READY __init__ where slot_cv is made (#1527) 1581if "slot_cv" in self .__dict__ : 1582with self .slot_cv :# #1012: wake the requests that waited through it: they go on with the 1583self .slot_cv .notify_all ()# new engine, or (it did not start) end with a clean EngineDied 1584self .info = {** info ,** self .info } 1585 1586def _parse_done (self ,line ): 1587f = line .split () 1588self .last = {"generated" :int (f [1 ]),"prompt_tokens" :int (f [2 ]),"prompt_ms" :float (f [3 ]), 1589"decode_ms" :float (f [4 ]),"finish" :f [5 ]} 1590if len (f )>= 9 :# the conversation cache's fields (engine 0.1.3+) 1591self .last .update (drafts_accepted = int (f [6 ]),drafts_offered = int (f [7 ]),reused = int (f [8 ])) 1592if len (f )>= 11 :# decode hit rate fields 1593self .last .update (hits = int (f [9 ]),lookups = int (f [10 ])) 1594if len (f )>= 14 :# the expert tiers (engine 0.1.31+): RAM / file blobs, file MB 1595self .last .update (ram_blobs = int (f [11 ]),file_blobs = int (f [12 ]),file_mb = float (f [13 ])) 1596if len (f )>= 15 :# #471 (engine 0.1.36+): the prompt tokens actually read 1597self .last .update (prompt_read = int (f [14 ])) 1598if len (f )>= 16 :# #588 (engine 0.1.39+): routed experts read over PCIe 1599self .last .update (offloaded = int (f [15 ])) 1600for tok in f [16 :]:# key=value fields after the positional ones (the prompt's 1601key ,eq ,value = tok .partition ("=" )# first chunk and its streamed expert blobs) 1602if eq and key in ("chunk" ,"experts_streamed" ,"cached" ,"scr" ,"prefilled" ):# (SCR: cached/scr/prefilled) 1603try : 1604self .last [key ]= int (value ) 1605except ValueError : 1606pass 1607 1608@ contextlib . contextmanager 1609def _exclusive_control (self ): 1610"""#4451 (same class): on a batch engine the control lines carry one exchange at a time, and every request takes 1611them (`ctl`) before it sends or reads anything there. VRAM and SAVE / RESTORE read the same lines for their 1612answer; run beside an admission they took its PP / T / BADM lines, and the admission its answer. They take the 1613lines like a request does. One request at a time: nothing to take.""" 1614ctl = self .__dict__ .get ("ctl" ) 1615if not self .batch or ctl is None or self ._ctl_held : 1616yield 1617return 1618if not ctl .acquire (timeout = self .CONTROL_WAIT_S ): 1619raise ValueError ("a request is still running; try again when it has finished" ) 1620try : 1621yield 1622finally : 1623ctl .release () 1624 1625def vram (self ,reserve_mib :int | None ,timeout :float = 120.0 )-> dict : 1626with self ._exclusive_control (): 1627return self ._vram (reserve_mib ,timeout ) 1628 1629def _vram (self ,reserve_mib :int | None ,timeout :float = 120.0 )-> dict : 1630"""#533: `VRAM <reserve_mib>` between requests (the caller holds the service's FIFO): the engine shrinks its 1631expert cache until that much VRAM is free, or grows it back when more is free; None: back to the reserve it 1632started with. -> the engine's figures (expert_slots, expert_cache_mib, vram_free_mib, ...); raises ValueError 1633with the engine's reason (e.g. it was not started with --vram-elastic), EngineDied when it ended.""" 1634if not self .alive (): 1635raise EngineDied ("the engine is not running" ) 1636self .proc .stdin .write ("VRAM" + ("" if reserve_mib is None else f" { int ( reserve_mib ) } " )+ "\n" ) 1637self .proc .stdin .flush () 1638deadline = time .time ()+ timeout 1639while True : 1640try : 1641line = self .lines .get (timeout = max (0.1 ,deadline - time .time ())) 1642except queue .Empty : 1643raise EngineDied ("the engine did not answer the VRAM command" )from None 1644if line is None : 1645raise EngineDied ("the engine ended" ) 1646line = line .strip () 1647if line .startswith ("ERR" ): 1648raise ValueError (line [4 :].strip ()or "the engine refused the VRAM command" ) 1649if line .startswith ("VRAM " ): 1650out = {} 1651for kv in line .split ()[1 :]: 1652k ,_ ,v = kv .partition ("=" ) 1653out [k ]= int (v )if v .lstrip ("-" ).isdigit ()else v 1654self .info .update ({k :out [k ]for k in ("expert_slots" ,"vram_free_mib" )if k in out }) 1655self .info ["vram" ]= out 1656return out 1657if time .time ()> deadline : 1658raise EngineDied ("the engine did not answer the VRAM command" ) 1659 1660def pen_from_key (self ,orig_len :int ,prompt_len :int )-> str : 1661"""` pen_from=N` for a leg that continues a request (prompt + what it generated): where the reply began, Strata's penalty window start. The all-cards split engine 1662(sFNX) counts its penalty window over the last penalty_last_n tokens of the whole context, so the continued prompt gives it the same window and the engine refuses the 1663key (GEN: unknown key pen_from): it is not sent.""" 1664if self .split_engine or prompt_len <= orig_len : 1665return "" 1666return f" pen_from= { orig_len - 1 } " 1667 1668@staticmethod 1669def sampling_keys (sampling :dict )-> str : 1670keys = "" 1671t = sampling .get ("temperature" ) 1672if isinstance (t , (int ,float ))and float (t )> 0.0 : 1673keys += f" temperature= { float ( t )!r } " 1674tp = sampling .get ("top_p" ) 1675if isinstance (tp , (int ,float ))and float (tp )< 1.0 : 1676keys += f" top_p= { float ( tp )!r } " 1677tk = sampling .get ("top_k" ) 1678if isinstance (tk ,int )and not isinstance (tk ,bool )and tk >= 0 : 1679# the engine's sampled path keeps at most 64 candidates: 0 ("off") and wider lists get all 64 1680keys += f" top_k= { tk if 1 <= tk <= 64 else 64 } " 1681mp = sampling .get ("min_p" ) 1682if isinstance (mp , (int ,float ))and 0.0 < float (mp )<= 1.0 : 1683keys += f" min_p= { float ( mp )!r } " 1684rp = sampling .get ("repetition_penalty" ) 1685rp_on = isinstance (rp , (int ,float ))and float (rp )!= 1.0 1686pf = sampling .get ("frequency_penalty" ) 1687pf_on = isinstance (pf , (int ,float ))and float (pf )!= 0.0 1688pp = sampling .get ("presence_penalty" ) 1689pp_on = isinstance (pp , (int ,float ))and float (pp )!= 0.0 1690if rp_on : 1691keys += f" penalty_repeat= { float ( rp )!r } " 1692if pf_on : 1693keys += f" penalty_freq= { float ( pf )!r } " 1694if pp_on : 1695keys += f" penalty_present= { float ( pp )!r } " 1696if rp_on or pf_on or pp_on : 1697# a penalty without a window counts over nothing: the engine's default is the last 64 tokens 1698pln = sampling .get ("penalty_last_n" ) 1699if isinstance (pln ,int )and not isinstance (pln ,bool )and pln > 0 : 1700keys += f" penalty_last_n= { pln } " 1701else : 1702keys += " penalty_last_n=64" 1703seed = sampling .get ("seed" ) 1704if isinstance (seed ,int )and seed > 0 : 1705keys += f" seed= { seed } " 1706# setup's calibration (tools/calibrate.py): engine settings for this request only, measured without a restart 1707tune = sampling .get ("strata_tune" ) 1708if isinstance (tune ,dict ): 1709for k in ("pcie_frac" ,"spec_min_p" ): 1710v = tune .get (k ) 1711if isinstance (v , (int ,float ))and not isinstance (v ,bool )and 0.0 <= float (v )<= 1.0 : 1712keys += f" { k } = { float ( v )!r } " 1713# a layer split's prompt chunks (--prefill-pipe): 0 off, 1 evened out, > 1 the rig's b/a in tokens 1714v = tune .get ("prefill_pipe" ) 1715if isinstance (v , (int ,float ))and not isinstance (v ,bool )and 0.0 <= float (v )<= 262144.0 : 1716keys += f" pipe= { float ( v )!r } " 1717# --aux-cpus for this request: 1 puts the engine's threads that are neither pool workers nor the host on the 1718# spare CPUs, 0 leaves them where they were created (true/false or 1/0; the engine started without a spare CPU 1719# ignores a 1). Anything else is not sent. 1720ac = tune .get ("aux_cpus" ) 1721if isinstance (ac ,bool )or (isinstance (ac , (int ,float ))and ac in (0 ,1 )): 1722keys += f" aux_cpus= { int ( ac ) } " 1723# the thinking budget's hold (HOLD_KEY): set by the server for an engine that says "hold", never by a client 1724hold = sampling .get (HOLD_KEY ) 1725if (isinstance (hold ,tuple )and len (hold )== 2 and all (isinstance (x ,int )and not isinstance (x ,bool )for x in hold ) 1726and hold [0 ]> 0 and hold [1 ]>= 0 ): 1727keys += f" hold= { hold [ 0 ] } : { hold [ 1 ] } " 1728# "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request 1729# extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before. 1730if sampling .get ("strata_checkpoint" )is False : 1731keys += " ckpt=0" 1732# #2228: the pictures' keys (hex, in prompt order): the engine matches a picture by them, not by its embeddings 1733ik = sampling .get ("strata_img_keys" ) 1734if isinstance (ik ,list )and ik and all (isinstance (k ,str )and k and all (c in "0123456789abcdef" for c in k ) 1735for k in ik ): 1736keys += " img_keys=" + "," .join (ik ) 1737# "strata_prefix" (resolved by Service.resolve_prefix to {"tokens": N}): the first N prompt tokens are a shared 1738# prefix - the engine pins the checkpoint there. Absent or unresolved = as before. 1739prefix = sampling .get ("strata_prefix" ) 1740if isinstance (prefix ,dict ): 1741pn = prefix .get ("tokens" ) 1742if isinstance (pn ,int )and not isinstance (pn ,bool )and pn > 0 : 1743keys += f" pin= { pn } " 1744# restore points (Service.prepare puts them in `_restore`; only the DeepSeek engine gets them) 1745keys += StrataEngine .restore_keys (sampling ) 1746# logprobs: the engine writes an `LP` line after each `T` line (an engine without them ignores 1747# the key, so an older engine answers exactly as it did). Absent = no LP lines at all. 1748k = top_logprobs (sampling ) 1749if k is not None : 1750keys += f" logprobs= { k } " 1751ids = allowed_ids (sampling ) 1752if ids : 1753# only these ids are printed; the engine's comma-separated list, renormalised below 1754keys += " allowed=" + "," .join (str (i )for i in ids ) 1755return keys + StrataEngine .projection_key (sampling )+ bias_api .engine_key (sampling .get ("logit_bias" )) 1756 1757@staticmethod 1758def restore_keys (sampling :dict )-> str : 1759"""`marks=<pos>,...`, `tail=<pos>` and `shared=<pos>`: the DeepSeek engine's restore points for this prompt 1760(Service.prepare puts them in `_restore` with STRATA_DS4_RESTORE_POINTS; no other engine gets them). "" without: 1761the line as before.""" 1762pts = sampling .get ("_restore" ) 1763if not isinstance (pts ,dict ): 1764return "" 1765 1766def pos (v ): 1767return isinstance (v ,int )and not isinstance (v ,bool )and v > 0 1768marks = [p for p in pts .get ("marks" )or ()if pos (p )] 1769tail ,shared = pts .get ("tail" ),pts .get ("shared" ) 1770return ((" marks=" + "," .join (str (p )for p in marks )if marks else "" )+ 1771 (f" tail= { tail } " if pos (tail )else "" )+ (f" shared= { shared } " if pos (shared )else "" )) 1772 1773@staticmethod 1774def projection_key (sampling :dict )-> str : 1775"""`cvec=0|1`: the experimental-speed-projection control vector for this request, when the engine was 1776started with one (--control-vector-scaled; an engine without one ignores the key). Absent = on.""" 1777on = sampling .get ("experimental_speed_projection" ) 1778return f" cvec= { int ( on ) } " if isinstance (on ,bool )else "" 1779 1780def _send (self ,text :str ): 1781btrace ("send>" ,text [:60 ]) 1782try : 1783with self .wlock : 1784self .proc .stdin .write (text + "\n" ) 1785self .proc .stdin .flush () 1786except (OSError ,AttributeError ):# the pipe is gone (or a restart's close() took the process): 1787raise EngineDied (f"the engine stopped unexpectedly (exit code { self . exit_code () } )" )from None 1788 1789def _send_for (self ,born :int ,text :str ): 1790"""#4451: a line meant for the engine process `born`. After a restart the same slot number belongs to another 1791request of the new process: a BSTOP or BYIELD that followed the old request would end that one.""" 1792if self .gen != born : 1793raise EngineDied ("the engine restarted while this request was running; it was not completed" ) 1794self ._send (text ) 1795 1796def _quarantine_control (self ,until :str ,born :int ,lines_q ,slot ,holding :bool )-> None : 1797"""#4451: a request left (cancel, disconnect, error) and the engine has not yet given the line that ends its 1798exchange (`until`: DONE of a solo read, BADM of an admission) while it said nothing for DRAIN_TIMEOUT_S. The control lines (and the 1799admission's slot) stay with this exchange - nobody else is given them - until the engine confirms, so what it 1800still prints can not reach a later request. The engine silent for QUARANTINE_S more: it is ended. (Only after a STOP or 1801BSTOP, and only for silence: a generation that is still producing lines is never cut off.)""" 1802if slot is not None : 1803with self .slot_cv : 1804self .slot_releasing .add (slot )# busy stays: no request may take the slot 1805self .slot_claims .discard (slot ) 1806 1807def run (): 1808try : 1809line = self ._drain_control (until ,timeout = self .QUARANTINE_S ,born = born ,lines_q = lines_q ) 1810if line is None : 1811self ._end_out_of_step (born ,"the engine did not end an interrupted request (STOP) in time" ) 1812cont = bool (until == "BADM" and line and line .startswith ("BADM " )and line .split ()[2 :3 ]== ["1" ]) 1813if slot is not None and self .gen == born : 1814if cont and self .alive (): 1815self ._release_slot_when_done (slot ,None ,born )# it went on in the slot: BSTOP, free at BDONE 1816else : 1817with self .slot_cv : 1818self .slot_busy [slot ]= False 1819self .slot_releasing .discard (slot ) 1820self .slot_cv .notify_all () 1821finally : 1822if holding : 1823self .ctl .release () 1824with self .slot_cv : 1825self .slot_cv .notify_all () 1826threading .Thread (target = run ,daemon = True ).start () 1827 1828def _control (self ,cancel ,on_token ,stop_when = None ,on_quiet = None ,want_lp = False ,lines_q = None ): 1829"""Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats. Calls on_token(id) 1830for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE). `stop_when()` 1831true sends STOP once (the request is then read to its DONE). `on_quiet()` runs whenever the engine has been 1832quiet for half a second: between two PP lines of a read whose chunks take longer than that. 1833 1834`want_lp`: a batch admission's token is the only one this reader ever sees with an `LP` line after it (a 1835slot's `BT` lines carry none), so a request asking for logprobs there is a `max_tokens` 1 one: read the 1836line here, for the request itself (its own lines: the engine's is shared by the slots' readers).""" 1837stopped = False 1838beat = time .monotonic () 1839held = NO_LINE # a line read while looking for a token's LP line 1840lines_q = self .lines if lines_q is None else lines_q # #4451: the request's own engine's lines (a restart makes new ones) 1841 1842def send_stop (): 1843if lines_q is self .lines :# (a STOP to the engine that replaced this one would stop another request) 1844self ._send ("STOP" ) 1845while True : 1846if held is not NO_LINE : 1847line ,held = held ,NO_LINE 1848else : 1849try : 1850# A client can leave before the first PP/token. Poll its Event as often as _take_control does; 1851# the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine. 1852line = lines_q .get (timeout = 0.5 ) 1853except queue .Empty : 1854if cancel .is_set ()and not stopped : 1855send_stop () 1856stopped = True 1857if on_quiet is not None : 1858on_quiet () 1859if time .monotonic ()- beat >= 10.0 : 1860beat = time .monotonic () 1861yield None 1862continue 1863beat = time .monotonic () 1864if line is None : 1865raise EngineDied (f"the engine stopped unexpectedly (exit code { self . exit_code () } )" ) 1866if not line .startswith (("PP " ,"INFO" )): 1867btrace ("ctl<" ,self ._ctl_mode ,line .strip ()[:60 ]) 1868if line .startswith ("T " ): 1869t = int (line [2 :]) 1870if want_lp : 1871# the engine writes the token and its LP line in one flush: the next line is that one, or a 1872# line this reader must still see (held for the next turn, as generate() does) 1873try : 1874held = lines_q .get (timeout = 0.5 ) 1875except queue .Empty : 1876held = NO_LINE 1877if isinstance (held ,str )and held .startswith ("LP " ): 1878own = getattr (cancel ,"_strata_lp_lines" ,None ) 1879if own is not None : 1880own .append ((t ,held )) 1881held = NO_LINE 1882on_token (t ) 1883if not stopped and (cancel .is_set ()or (stop_when is not None and stop_when ())): 1884send_stop () 1885stopped = True 1886yield False # a token is pending (not a heartbeat) 1887elif line .startswith ("PP " ): 1888f = line .split () 1889if len (f )>= 3 and f [1 ].isdigit ()and f [2 ].isdigit (): 1890self .progress = (int (f [1 ]),int (f [2 ])) 1891self .progress_ms = float (f [3 ])if len (f )>= 4 else 0.0 1892self .prefill_tok_s_mean = float (f [4 ])if len (f )>= 5 else None 1893if not stopped and cancel .is_set (): 1894# #879: a Stop during the prompt read went out only after the first token (or after 10 s of 1895# silence, which a stream of PP lines never allows): the engine read the whole prompt first 1896send_stop () 1897stopped = True 1898yield None 1899elif line .startswith ("DONE" ): 1900self ._parse_done (line ) 1901self ._last_done = line 1902elif line .startswith ("BADM " ): 1903f = line .split () 1904self ._ctl_result = ("badm" ,len (f )>= 3 and f [2 ]== "1" ) 1905return 1906elif line .startswith ("BCOK " ):# STRATA_COALESCE_PREFILL: <slot> <tokens>: the slot holds a waiting prompt 1907pass 1908elif line .startswith ("YIELDED " ):# the read gave way (BYIELD): <slot> <tokens read> 1909f = line .split () 1910if len (f )>= 3 and f [1 ].lstrip ("-" ).isdigit ()and f [2 ].isdigit (): 1911self ._yielded = (int (f [1 ]),int (f [2 ])) 1912elif line .startswith ("ERR" ): 1913self ._ctl_erred = True # #1059: the engine refused it and is idle: no DONE follows 1914self ._raise_if_fatal_gpu (line ) 1915raise ValueError (line [4 :].strip ()) 1916if line .startswith ("DONE" )and self ._ctl_mode == "solo" : 1917self ._ctl_result = ("done" ,None ) 1918return 1919 1920def _done_finish (self )-> str | None : 1921"""The finish field of the DONE line the control lines read last (None: none since it was cleared).""" 1922f = (getattr (self ,"_last_done" ,None )or "" ).split () 1923return f [5 ]if len (f )> 5 else None 1924 1925def _drain_control (self ,until :str ,timeout :float | None = None ,born :int | None = None ,lines_q = None ): 1926"""After a consumer left early: read the control lines up to the next `until` line (DONE or BADM) so the next 1927request does not read this one's leftovers. Returns that line (None: the engine ended or never answered). 1928`born`: the engine process (self.gen) the request started on; once that one is gone there is nothing to 1929drain - its end line was read already (by the request's own EngineDied), and waiting for another one held 1930a request that had failed for the whole 300 s (#1012), or read the lines of the engine that replaced it. 1931`timeout` (DRAIN_TIMEOUT_S) is a NO-PROGRESS limit: it counts from the last line the engine wrote, so an engine that 1932is still talking (PP / T lines of a read or a decode it was told to stop but has not yet) is never given up on; 1933only one that says nothing for that long is.""" 1934wait_s = self .DRAIN_TIMEOUT_S if timeout is None else timeout 1935end = time .monotonic ()+ wait_s 1936lines_q = self .lines if lines_q is None else lines_q 1937while time .monotonic ()< end : 1938if born is not None and (self .gen != born or not self .alive ()): 1939return None 1940try : 1941line = lines_q .get (timeout = max (0.1 ,min (1.0 ,end - time .monotonic ()))) 1942except queue .Empty : 1943continue 1944if line is None : 1945return None 1946end = time .monotonic ()+ wait_s # any line is progress 1947if line .startswith ("DONE" ): 1948self ._parse_done (line ) 1949if line .startswith (until )or line .startswith ("ERR" ): 1950return line 1951return None 1952 1953def _apply_bdone (self ,f :list [str ])-> None : 1954"""BDONE counts the admission token too, but its clock starts after the admission's DONE.""" 1955if len (f )>= 5 and isinstance (self .last ,dict ): 1956admission_ms = self .last .get ("decode_ms" ) 1957self .last = {** self .last ,"finish" :f [3 ], 1958"decode_ms" :admission_ms + float (f [4 ])if admission_ms is not None else None , 1959"generated" :int (f [2 ])if f [2 ].isdigit ()else None } 1960 1961def _raise_if_fatal_gpu (self ,line :str )-> None : 1962"""#4350: the engine's ERR line "fatal GPU error: ..." means it is ending (its GPU context is gone). The request in flight fails 1963as an engine death (a 503 the client can send again), not as a bad request (400), and the engine counts as ended, so the next 1964request starts it again at once instead of finding a closed pipe.""" 1965text = line [4 :].strip () 1966if not text .startswith ("fatal GPU error" ): 1967return 1968self .last_err = text 1969self .ended = True 1970raise EngineDied ("the GPU reported a fatal error and the engine ended: " + text [len ("fatal GPU error:" ):].strip ()[:200 ]) 1971 1972def _bdone_after_eos (self ,slot :int ,wait_s :float = 2.0 ,q = None ): 1973"""#1869: a request in a slot whose consumer left at the stop token has its BDONE right behind it (the engine prints it 1974in the same window). Read it here, so the request's figures are the slot leg's (the background wait would eat it, 1975and the request kept the admission's single token). None when it does not come in `wait_s`: then the background 1976wait takes over.""" 1977if q is None and slot >= len (self .slot_q ): 1978return None 1979q = self .slot_q [slot ]if q is None else q 1980end = time .monotonic ()+ wait_s 1981while time .monotonic ()< end : 1982try : 1983line = q .get (timeout = max (0.05 ,end - time .monotonic ())) 1984except queue .Empty : 1985return None 1986if line is None : 1987return None 1988if line .startswith ("BDONE " ): 1989return line 1990return None 1991 1992def _end_out_of_step (self ,born :int ,what :str )-> None : 1993"""#4451: the engine did not give a line it owes (a BDONE after BSTOP, a DONE / BADM after STOP) within the 1994quarantine: what it may still print can not be told from a later request's lines, so the engine is ended (the 1995same end as a silent one, #481) and the next request starts it again. Only the engine process it concerns.""" 1996if self .gen == born and self .alive (): 1997self ._silent (what ) 1998 1999def _release_slot_when_done (self ,slot :int ,stream :list [int ]| None = None ,born :int | None = None ): 2000"""A slot whose consumer left (a stop token, a stop string, a disconnect): BSTOP it and free it once the engine 2001says BDONE (in the background). `stream`: the prompt and every token of it so far - with the tokens still to 2002come before BDONE, all but the last are what the slot holds then (the next turn of its conversation).""" 2003if slot >= len (self .slot_q ):# the engine restarted with fewer slots: this one is gone 2004return 2005if born is not None and self .gen != born :# #4451: the engine this slot belonged to is gone; BSTOP now would stop 2006return # (and the wait below would read) a request of the NEW engine 2007born = self .gen if born is None else born 2008try : 2009self ._send (f"BSTOP { slot } " ) 2010except EngineDied : 2011pass 2012q ,busy ,held = self .slot_q [slot ],self .slot_busy ,self .slot_held # this process's: restart() replaces them 2013releasing = self .slot_releasing 2014releasing .add (slot ) 2015 2016def wait (): 2017end = time .monotonic ()+ self .QUARANTINE_S # no-progress limit: every line of the slot starts it again 2018tail = list (stream or []) 2019confirmed = False 2020while time .monotonic ()< end : 2021try : 2022line = q .get (timeout = 5.0 ) 2023except queue .Empty : 2024if self .gen != born or not self .alive (): 2025break 2026continue 2027if line is None : 2028tail = [] 2029break 2030end = time .monotonic ()+ self .QUARANTINE_S 2031if line .startswith ("BT " ): 2032try : 2033tail .append (int (line .split ()[2 ])) 2034except (IndexError ,ValueError ): 2035tail = [] 2036if line .startswith ("BDONE " ): 2037confirmed = True 2038if line .split ()[3 :4 ]== ["nonfinite" ]:# #879: the engine dropped the slot's state 2039tail = [] 2040break 2041if not confirmed : 2042tail = [] 2043# #4451: no BDONE in the quarantine from an engine that still runs: the slot is NOT handed on with its 2044# lines still to come - the engine is ended instead (a dead engine's slots are free by being gone) 2045self ._end_out_of_step (born ,"the engine did not end a stopped batch slot (BSTOP) in time" ) 2046held [slot ]= tail [:- 1 ]if stream and tail else [] 2047with self .slot_cv : 2048busy [slot ]= False 2049releasing .discard (slot ) 2050self .slot_cv .notify_all () 2051threading .Thread (target = wait ,daemon = True ).start () 2052 2053BGEN_REFUSALS_MAX = 6 # #1994: how often one request tries another slot after the engine refused a BGEN 2054SLOT_PARK_S = 2.0 # ... and how long a refused slot stays out of the picks 2055 2056def _park_slot (self ,slot :int )-> None : 2057"""#1994: the engine refused a BGEN for `slot`. Keep it busy here for SLOT_PARK_S (no request owns it), then 2058give it back: the engine's view has caught up, or the next refusal parks it again.""" 2059with self .slot_cv : 2060self .slot_claims .discard (slot ) 2061self .slot_busy [slot ]= True 2062busy = self .slot_busy 2063 2064def free (): 2065with self .slot_cv : 2066if slot not in self .slot_claims and slot not in self .slot_releasing : 2067busy [slot ]= False 2068self .slot_cv .notify_all () 2069t = threading .Timer (self .SLOT_PARK_S ,free ) 2070t .daemon = True 2071t .start () 2072 2073ORPHAN_SLOT_S = 3.0 # #1603: a busy flag nobody owns this long is a leak and is given back 2074 2075def _reap_orphan_slots (self )-> list [int ]: 2076"""#1603: free the slots whose busy flag has no owner (no request holds or reserves them and no BDONE wait is 2077running for them). The caller holds slot_cv. A flag that leaked kept every later request waiting for a slot 2078that nothing would free - with nothing running, nothing queued and nothing for the frozen-engine check to see. 2079A slot is only given back after it has looked ownerless for ORPHAN_SLOT_S, so a flag set a moment before its 2080owner registers is never taken.""" 2081now = time .monotonic () 2082freed = [] 2083for b ,busy in enumerate (self .slot_busy ): 2084if busy and b not in self .slot_claims and b not in self .slot_releasing : 2085first = self ._orphan_seen .setdefault (b ,now ) 2086if now - first >= self .ORPHAN_SLOT_S : 2087self .slot_busy [b ]= False 2088self ._orphan_seen .pop (b ,None ) 2089freed .append (b ) 2090else : 2091self ._orphan_seen .pop (b ,None ) 2092if freed : 2093f"[strata] parallel: slot(s) { ', ' . join ( map ( str , freed )) } were marked busy with no request using them " 2094"(issue #1603); freed, the waiting request goes on" ,flush = True ) 2095self .slot_cv .notify_all () 2096return freed 2097 2098YIELDS_MAX = 2 # #656: how often one request's prompt read gives way to a shorter waiting one 2099 2100def _take_control (self ,cancel ,plen :int ,after_epoch :int | None = None ,new :bool = False ,prompt = None ): 2101"""Waits for the control lines (one prompt read at a time), yielding None heartbeats; False when cancelled. 2102`after_epoch`: a request whose read gave way lets the requests waiting then go first. 2103`new`: the request's first admission (STRATA_ADMIT_SHORT_FIRST orders only these).""" 2104entry = [plen ,time .monotonic (),new ,prompt ,cancel ]# (length, arrival, ordered: STRATA_ADMIT_SHORT_FIRST; the prompt and request, for STRATA_COALESCE_PREFILL) 2105with self .slot_cv : 2106self .waiting += 1 2107self .wait_lens .append (entry ) 2108self .arrivals .append (entry [1 ]) 2109beat = time .monotonic () 2110try : 2111while True : 2112deadline = getattr (cancel ,"_strata_queue_deadline" ,None ) 2113if deadline is not None and time .monotonic ()>= deadline : 2114raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 2115if not self .alive ()and not getattr (self ,"starting" ,False ): 2116# #1012: the engine is gone and nobody is starting it again: this request was not sent, so it 2117# ends now (a clean 503) instead of waiting for control lines nothing will answer on. While a 2118# restart is under way it keeps waiting and goes on with the new engine. 2119raise EngineDied ("the engine stopped while this request waited; it was not sent" ) 2120with self .slot_cv : 2121turn = after_epoch is None or self .ctl_epoch > after_epoch or self .waiting <= 1 2122if turn and new and ADMIT_SHORT_FIRST > 0 : 2123turn = self ._admit_next ()is entry 2124left = deadline - time .monotonic ()if deadline is not None else 0.5 2125if turn and left > 0 and self .ctl .acquire (timeout = min (0.5 ,left )): 2126if new and ADMIT_SHORT_FIRST > 0 : 2127with self .slot_cv :# a shorter one came while this one waited in acquire() 2128first = self ._admit_next ()is entry 2129if not first : 2130self .ctl .release () 2131with self .slot_cv : 2132self .slot_cv .notify_all () 2133continue 2134if self .alive (): 2135if deadline is not None and time .monotonic ()>= deadline : 2136self .ctl .release () 2137raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 2138break 2139self .ctl .release ()# it died (or is being restarted) while this one was getting 2140turn = False # the lines: not the engine this request was meant for 2141if not turn : 2142with self .slot_cv : 2143# #4738 (PR #4738's approach): the turn was read, and the lock given up, before this wait: a 2144# notification sent in between is gone. Read it again under the lock and only wait when this 2145# request still has to. 2146eligible = after_epoch is None or self .ctl_epoch > after_epoch or self .waiting <= 1 2147if eligible and new and ADMIT_SHORT_FIRST > 0 : 2148eligible = self ._admit_next ()is entry 2149if not eligible or not self .alive (): 2150self .slot_cv .wait (timeout = min (0.5 ,max (0 ,left ))) 2151if cancel .is_set (): 2152return False 2153if time .monotonic ()- beat >= 10.0 :# a heartbeat every 10 s, as the engine's own wait 2154beat = time .monotonic () 2155yield None 2156finally : 2157with self .slot_cv : 2158previous_waiting = self .waiting 2159self .waiting = max (0 ,self .waiting - 1 ) 2160if entry in self .wait_lens : 2161self .wait_lens .remove (entry ) 2162if (previous_waiting > 1 and self .waiting <= 1 )or (new and ADMIT_SHORT_FIRST > 0 ): 2163# a waiter that leaves (cancelled, closed) can make another one the next in turn: tell it 2164self .slot_cv .notify_all () 2165with self .slot_cv : 2166self .ctl_epoch += 1 2167self .slot_cv .notify_all () 2168return True 2169 2170def _release_preslot (self ,cancel ): 2171"""STRATA_COALESCE_PREFILL: the request that was given a slot ahead of its turn left before using it.""" 2172slot = getattr (cancel ,"_strata_preslot" ,None ) 2173if slot is None : 2174return 2175cancel ._strata_preslot = None 2176with self .slot_cv : 2177self .slot_busy [slot ]= False 2178self .slot_claims .discard (slot ) 2179self .slot_cv .notify_all () 2180 2181def _coalesce (self ,cancel ,lead_prompt ): 2182"""STRATA_COALESCE_PREFILL (the caller holds the control lines and sends its BGEN right after): reserve free slots 2183for requests still waiting for the control lines and send their prompts as BCO lines; the engine reads them in the 2184same layer-major pass as the BGEN's prompt. Each follower finds its slot in cancel._strata_preslot.""" 2185picked = [] 2186total = len (lead_prompt ) 2187def seen ()-> int : 2188now = time .monotonic () 2189with self .slot_cv : 2190return max (sum (1 for t in self .arrivals if now - t <= COALESCE_BURST_MS / 1000.0 ),1 + len (self .wait_lens )) 2191recent = seen () 2192if recent < COALESCE_MIN_REQS and COALESCE_WAIT_MS > 0 : 2193time .sleep (0.010 )# (the first request of a burst holds the lines before its neighbours have arrived) 2194recent = seen () 2195if recent < COALESCE_MIN_REQS : 2196return # one or two requests on this engine: a plain read, at most 10 ms lost 2197if COALESCE_WAIT_MS > 0 : 2198time .sleep (COALESCE_WAIT_MS / 1000.0 )# the requests of a burst reach the server a few ms apart 2199with self .slot_cv : 2200for e in list (self .wait_lens ): 2201if len (picked )>= COALESCE_PREFILL - 1 : 2202break 2203prompt = e [3 ]if len (e )> 4 else None 2204rq = e [4 ]if len (e )> 4 else None 2205if prompt is None or rq is None or rq is cancel or getattr (rq ,"_strata_preslot" ,None )is not None : 2206continue 2207if getattr (rq ,"_strata_co" ,False )or len (prompt )< 32 or total + len (prompt )> COALESCE_TOKENS : 2208continue 2209slot = self .pick_slot (prompt ) 2210if slot is None : 2211break 2212self .slot_busy [slot ]= True 2213self .slot_claims .add (slot ) 2214self .slot_held [slot ]= [] 2215rq ._strata_preslot = slot 2216rq ._strata_co = True 2217total += len (prompt ) 2218picked .append ((slot ,prompt )) 2219for slot ,prompt in picked : 2220self ._send (f"BCO { slot } { ',' . join ( str ( int ( t )) for t in prompt ) } " ) 2221if picked : 2222f"[strata] coalesce: { len ( picked ) } waiting prompt(s) ( { total - len ( lead_prompt ) } tokens) read with this " 2223f"request's { len ( lead_prompt ) } " ,flush = True ) 2224 2225def _admit_next (self ): 2226"""STRATA_ADMIT_SHORT_FIRST=<tokens> (the caller holds slot_cv): the new request that takes the control lines 2227next - one whose prompt is at most that long (it reads little) before a longer one, in arrival order within 2228each; a longer one that has waited STRATA_ADMIT_MAX_WAIT_S counts as short (it is never held back for good). 2229Off (unset or 0): whoever gets the lock first, as before. Only the order changes, never what is read.""" 2230now = time .monotonic () 2231ordered = [e for e in self .wait_lens if len (e )> 2 and e [2 ]] 2232if not ordered : 2233return None 2234return min (ordered ,key = lambda e : (0 if e [0 ]<= ADMIT_SHORT_FIRST or now - e [1 ]>= ADMIT_MAX_WAIT_S else 1 , 2235e [1 ])) 2236 2237SOLO_AGAIN_MAX = 2 # how often a request left alone in a slot goes back to the solo path 2238SOLO_AGAIN_MIN_LEFT = 32 # ... only with at least this many tokens still allowed (max_tokens) 2239 2240def _may_go_solo (self ,left :int ,times :int ,embeddings )-> bool : 2241"""A request decoding in a slot that is alone now (no other slot busy, nobody waiting) goes back to the solo 2242path with its MTP drafts: the engine continues it from the slot's sessions (its slot cache; INFO 2243slot_cache=1). STRATA_PARALLEL_SOLO=0 keeps it in the slot.""" 2244if (embeddings or times >= self .SOLO_AGAIN_MAX or left < self .SOLO_AGAIN_MIN_LEFT or 2245not (self .info or {}).get ("slot_cache" )or os .environ .get ("STRATA_PARALLEL_SOLO" )== "0" ): 2246return False 2247with self .slot_cv : 2248return sum (1 for b in self .slot_busy if b )== 1 and self .waiting == 0 2249 2250def _shorter_waiting (self ,plen :int )-> bool : 2251"""#656: someone waits for the control lines with a prompt under half this one's: worth giving way to.""" 2252with self .slot_cv : 2253return any (e [0 ]* 2 <= plen for e in self .wait_lens ) 2254 2255def generate_batched (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 2256"""--batch. Alone (no slot busy, nobody waiting): the solo path (GEN, with drafts: the fastest stream) 2257- and when another request arrives meanwhile, this one is STOPped and continues in a batch slot (BGEN with 2258its prompt + what it generated: the engine reuses that prefix). Otherwise: BGEN into a free slot, then the 2259slot's own BT lines until BDONE. Several requests run at once; the control lines (prompt reading, admission) 2260are taken one request at a time - and a long prompt read gives way at a chunk boundary to a waiting request 2261with a much shorter prompt (#656: `BYIELD <slot>`; the part read waits in a slot and the read goes on after). 2262A consumer that stops early leaves the engine in step: the solo request is STOPped and read to its DONE, an 2263admission to its BADM, a slot is BSTOPped and freed at its BDONE.""" 2264if not self .alive (): 2265raise EngineDied ("the engine is unavailable; this request was not sent" ) 2266self .progress ,self .progress_ms ,self .reused = None ,0 ,0 2267born = self .gen # the engine process this request is sent to 2268hold = (sampling or {}).get (HOLD_KEY )# the thinking budget's hold (P2b): the reasoning tokens left when this pass starts, and </think>'s id 2269keys0 = self .sampling_keys ({k :v for k ,v in (sampling or {}).items ()if k != HOLD_KEY })# (the hold's key goes on per leg: leg_keys below) 2270# logprobs: only an admission's token can have an LP line here (the slot's "BT" lines carry none), so the 2271# server refuses these requests unless max_tokens is 1. The lines go to the request itself, through its 2272# cancel Event: several requests read control lines at once, and the engine's lp_lines is one attribute. 2273want_lp = top_logprobs (sampling or {})is not None 2274if want_lp : 2275cancel ._strata_lp_lines = LPLines (cancel ) 2276out :list [int ]= [] 2277pending :list [int ]= [] 2278prompt ,left = list (ids ),int (max_new ) 2279 2280def leg_keys ()-> str : 2281"""The budget's hold counts what this pass still has: a leg that starts after `out` tokens of it holds the rest (at least one); 2282once </think> is in `out` the hold is over and no key goes.""" 2283if isinstance (hold ,tuple )and len (hold )== 2 and hold [0 ]> 0 and hold [1 ]>= 0 and hold [1 ]not in out : 2284return keys0 + f" hold= { max ( 1 , hold [ 0 ] - len ( out )) } : { hold [ 1 ] } " 2285return keys0 2286orig_len = len (prompt )# a leg that continues (prompt + what it generated) names where the reply began: pen_from, the penalty window's start 2287reused0 = None # the first read's reused tokens: a continued leg's count includes this request's own output 2288carry = {}# #1869: the figures of the legs that ended in a hand-back to the solo path (the final DONE adds to them) 2289yielded_legs = []# prompt reads that gave way before producing output 2290ok = yield from self ._take_control (cancel ,len (prompt ),new = True , 2291prompt = prompt if (COALESCE_PREFILL > 1 and not embeddings )else None ) 2292if not ok : 2293self ._release_preslot (cancel ) 2294return 2295holding ,born = True ,self .gen # (the engine it now has the control lines of) 2296lines_q ,sq = self .lines ,self .slot_q # #4451: ... and its queues; a restart makes new ones, and a request 2297# of the old process must never read (or answer on) the new ones 2298btrace ("ctl acquired" ) 2299slot ,gen0 ,reserved = None ,None ,None 2300pre = getattr (cancel ,"_strata_preslot" ,None ) 2301if pre is not None :# STRATA_COALESCE_PREFILL: a request before this one read the prompt into this slot 2302slot ,cancel ._strata_preslot = pre ,None 2303phase = "none" # solo -> (admit -> slot) ; "done" once the engine has finished with this request 2304stop_sent = False 2305admission_pending ,admission_before = False ,None # the admission's DONE is partial until BADM 0 or BDONE 2306yields ,solo_again ,refused = 0 ,0 ,0 2307admit_wait ,admit_since ,admit_said = False ,0.0 ,False # #1603: waiting for a slot, since when, said 2308try : 2309while True :# a request in a slot that is left alone goes back to the solo path 2310if not holding : 2311ok = yield from self ._take_control (cancel ,len (prompt )) 2312if not ok : 2313return 2314holding ,born = True ,self .gen # (the engine it now has the control lines of) 2315lines_q ,sq = self .lines ,self .slot_q # (it holds no slot of the engine before: nothing to lose) 2316with self .slot_cv : 2317alone = not any (self .slot_busy )and self .waiting == 0 2318if alone and left > 1 : 2319pf = self .pen_from_key (orig_len ,len (prompt )) 2320head = f"GENI { left } { leg_keys () } { pf } { embeddings } " if embeddings else f"GEN { left } { leg_keys () } { pf } " 2321self ._last_done = None # (#879: this request's DONE decides below) 2322deadline = getattr (cancel ,"_strata_queue_deadline" ,None ) 2323if deadline is not None and time .monotonic ()>= deadline : 2324raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 2325self ._send (f" { head } { ',' . join ( str ( int ( t )) for t in prompt ) } " ) 2326if deadline is not None : 2327cancel ._strata_queue_deadline = None 2328started = getattr (cancel ,"_strata_queue_started" ,None ) 2329if started is not None : 2330started () 2331phase = "solo" 2332self ._ctl_mode ,self ._ctl_result ,self ._yielded = "solo" ,None ,None 2333self ._ctl_erred = False 2334def others (): 2335with self .slot_cv : 2336return self .waiting > 0 2337 2338def give_way ():# at a PP line, and between two far apart (the engine takes it at its next boundary) 2339nonlocal reserved 2340if (reserved is None and not out and not embeddings and yields < self .YIELDS_MAX and 2341self ._shorter_waiting (len (prompt ))): 2342with self .slot_cv :# the slot the part read will wait in 2343reserved = self .pick_slot (prompt ) 2344if reserved is not None : 2345self .slot_busy [reserved ]= True 2346self .slot_claims .add (reserved ) 2347if reserved is not None : 2348self ._send_for (born ,f"BYIELD { reserved } " ) 2349for x in self ._control (cancel ,pending .append ,stop_when = others ,on_quiet = give_way , 2350want_lp = want_lp ,lines_q = lines_q ): 2351while pending : 2352t = pending .pop (0 ) 2353out .append (t ) 2354yield t 2355if x is None :# a heartbeat (False: a token, flushed above) 2356give_way () 2357yield None 2358phase = "none" # its DONE is read 2359while pending : 2360t = pending .pop (0 ) 2361out .append (t ) 2362yield t 2363if self ._done_finish ()== "nonfinite" :# #879 (never promoted to a slot) 2364raise EngineNonFinite ("the engine's logits became non-finite (#879)" ) 2365if self ._yielded is not None and reserved is not None and self ._yielded [0 ]== reserved : 2366yielded_legs .append (self .last ) 2367slot ,reserved = reserved ,None # gave way: the read goes on in that slot (below) 2368elif reserved is not None :# it did not give way: the slot is free again 2369with self .slot_cv : 2370self .slot_busy [reserved ]= False 2371self .slot_claims .discard (reserved ) 2372self .slot_cv .notify_all () 2373reserved = None 2374if slot is None : 2375finish = (self .last or {}).get ("finish" )if isinstance (self .last ,dict )else None 2376left = int (max_new )- len (out ) 2377if cancel .is_set ()or left <= 0 or finish in ("stop" ,"length" ,"hold" )or (out and out [- 1 ]in EOS_IDS ): 2378return # ("hold": the budget's cut: the caller wraps up or asks for more) 2379if reused0 is None : 2380reused0 = (self .last or {}).get ("reused" ) 2381carry_leg (carry ,self .last )# #1869: the solo leg's figures; the slot's admission (a copy of 2382# the held prefix: prompt_read 1) and BDONE replace them 2383prompt = list (ids )+ out # promoted: it continues in a batch slot from here 2384while True : 2385if slot is None : 2386# a free slot (they free themselves at BDONE, which needs no control lines): the one that holds 2387# the start of this prompt (its conversation's last turn), else the one used longest ago. 2388# With none free the control lines are given back while waiting: a slot can be held by a read 2389# that gave way (BYIELD) and needs them to go on, so waiting with them is a deadlock - long, 2390# long, short at 0.25 s steps under parallel: 2 (ENGINE_REVIEW finding 1, reproduced in 0.1.41). 2391while True : 2392deadline = getattr (cancel ,"_strata_queue_deadline" ,None ) 2393if deadline is not None and time .monotonic ()>= deadline : 2394raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 2395with self .slot_cv : 2396slot = self .pick_slot (prompt ) 2397if slot is not None : 2398self .slot_busy [slot ]= True 2399self .slot_claims .add (slot ) 2400if admit_wait : 2401admit_wait = False 2402self .admitting = max (0 ,self .admitting - 1 ) 2403if PAR_COUNTERS :# STRATA_PAR_COUNTERS=1: time spent waiting for a free slot 2404self .par_counters ["queued" ]+= 1 2405self .par_counters ["queue_wait_s" ]+= time .monotonic ()- admit_since 2406break 2407if not admit_wait :# #1603: counted while it waits for a slot (it holds no 2408admit_wait ,admit_since = True ,time .monotonic ()# control lines then) 2409self .admitting += 1 2410if holding : 2411self .ctl .release () 2412holding = False 2413with self .slot_cv : 2414if self .pick_slot (prompt )is None : 2415if (ENGINE_STALL_S or 0 )> 0 and time .monotonic ()- admit_since >= ENGINE_STALL_S : 2416# the stall check of #1317 only watches a request on the control lines; one 2417# waiting here is covered by looking for a slot nobody owns, and by saying so 2418if not admit_said : 2419admit_said = True 2420busy = [b for b ,v in enumerate (self .slot_busy )if v ] 2421f"[strata] parallel: a request has waited { time . monotonic () - admit_since :.0f } s " 2422f"for a free slot (busy: { busy } , in use: { sorted ( self . slot_claims ) } , " 2423f"ending: { sorted ( self . slot_releasing ) } ) (issue #1603)" ,flush = True ) 2424self ._reap_orphan_slots () 2425if self .pick_slot (prompt )is None : 2426wait_remaining = deadline - time .monotonic ()if deadline is not None else 1.0 2427self .slot_cv .wait (timeout = min (1.0 ,max (0 ,wait_remaining ))) 2428if cancel .is_set (): 2429return 2430if not holding : 2431ok = yield from self ._take_control (cancel ,len (prompt )) 2432if not ok : 2433return 2434holding ,born = True ,self .gen 2435lines_q ,sq = self .lines ,self .slot_q # (a slot is claimed below, on this engine) 2436if self ._yielded is not None :# it gave way: the others waiting then go first 2437self .slot_held [slot ]= list (prompt [:self ._yielded [1 ]]) 2438self ._yielded = None 2439yields += 1 2440self .ctl .release () 2441holding = False 2442with self .slot_cv : 2443epoch = self .ctl_epoch 2444ok = yield from self ._take_control (cancel ,len (prompt ),after_epoch = epoch ) 2445if not ok : 2446return 2447if self .gen != born :# #4451: the slot it holds was the old engine's 2448holding = True 2449raise EngineDied ("the engine restarted while this request waited for it; it was not completed" ) 2450holding ,born = True ,self .gen # (the engine it now has the control lines of) 2451while not sq [slot ].empty (): 2452sq [slot ].get_nowait () 2453pf = self .pen_from_key (orig_len ,len (prompt )) 2454head = f"BGENI { slot } { left } { leg_keys () } { pf } { embeddings } " if embeddings else f"BGEN { slot } { left } { leg_keys () } { pf } " 2455live = {"slot" :slot ,"request_id" :getattr (cancel ,"_strata_request_id" ,None ), 2456"state" :"reading" ,"prompt_tokens" :len (prompt ),"prompt_read" :0 ,"generated" :0 , 2457"started" :time .time (),"first_token" :None } 2458deadline = getattr (cancel ,"_strata_queue_deadline" ,None ) 2459if deadline is not None and time .monotonic ()>= deadline : 2460raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 2461self .slot_live [slot ]= live 2462self ._last_done = None # (#879: this admission's DONE decides below) 2463if COALESCE_PREFILL > 1 and not embeddings : 2464self ._coalesce (cancel ,prompt ) 2465self ._send (f" { head } { ',' . join ( str ( int ( t )) for t in prompt ) } " ) 2466if deadline is not None : 2467cancel ._strata_queue_deadline = None 2468started = getattr (cancel ,"_strata_queue_started" ,None ) 2469if started is not None : 2470started () 2471self .slot_held [slot ]= []# the admission overwrites what the slot held 2472admission_pending ,admission_before = True ,self .last 2473phase = "admit" 2474self ._ctl_mode ,self ._ctl_result ,self ._yielded = "batch" ,None ,None 2475self ._ctl_erred = False 2476asked = False 2477 2478def ask ():# as give_way above, for the slot this admission reads into 2479nonlocal asked 2480if (not asked and not embeddings and yields < self .YIELDS_MAX and 2481self ._shorter_waiting (len (prompt ))): 2482self ._send_for (born ,f"BYIELD { slot } " ) 2483asked = True 2484 2485def note_progress (): 2486# the terminal layer's live prompt counter (the batch admission path) 2487if self .progress and live ["state" ]== "reading" : 2488live ["prompt_read" ]= self .progress [0 ] 2489try : 2490for x in self ._control (cancel ,pending .append ,on_quiet = lambda : (ask (),note_progress ()), 2491want_lp = want_lp ,lines_q = lines_q ): 2492while pending : 2493t = pending .pop (0 ) 2494out .append (t ) 2495yield t 2496if x is None : 2497ask () 2498note_progress () 2499yield None 2500except ValueError as e : 2501# #1994: the engine says this slot is not free (its view and ours differ for a moment, or a 2502# slot it still holds). That is not the request's fault and nothing was read: park the slot 2503# for a moment (busy here too), and wait for another one - never a 400 for the conversation. 2504if not (self ._ctl_erred and str (e ).startswith ("BGEN:" )and left >= 1 and not cancel .is_set ()): 2505raise 2506refused += 1 2507f"[strata] parallel: the engine refused slot { slot } ( { e } ); trying another slot " 2508f"( { refused } / { self . BGEN_REFUSALS_MAX } ) (issue #1994)" ,flush = True ) 2509if refused > self .BGEN_REFUSALS_MAX : 2510raise GpuBusy ("the engine's batch slots are not free right now; try again in a moment" , 2511retry_after = 5 )from e 2512self .slot_live [slot ]= None 2513self .slot_held [slot ]= [] 2514phase = "none" 2515self ._ctl_erred = False 2516self ._park_slot (slot ) 2517slot = None 2518continue 2519cont = bool (self ._ctl_result and self ._ctl_result [1 ]) 2520admission_pending = cont 2521phase = "slot" if cont else "none" 2522while pending : 2523t = pending .pop (0 ) 2524out .append (t ) 2525yield t 2526if not cont and self ._done_finish ()== "nonfinite" :# #879 2527raise EngineNonFinite ("the engine's logits became non-finite (#879)" ) 2528if not cont and self ._yielded is not None and self ._yielded [0 ]== slot and not cancel .is_set (): 2529yielded_legs .append (self .last ) 2530continue # gave way: again once the shorter request is in 2531break 2532self .ctl .release () 2533holding = False 2534if not cont : 2535return 2536live .update (state = "decoding" ,first_token = time .time (),generated = len (out )) 2537gen0 = len (out )- 1 # the admission's own token: the slot feeds it first 2538going_solo = False 2539while True : 2540try : 2541line = sq [slot ].get (timeout = 10.0 ) 2542except queue .Empty : 2543if self .gen != born :# #4451: the engine it was admitted on is gone (and so is its slot) 2544phase = "none" 2545raise EngineDied ("the engine restarted while this request was running; it was not completed" ) 2546if cancel .is_set ()and not stop_sent : 2547self ._send_for (born ,f"BSTOP { slot } " ) 2548stop_sent = True 2549yield None 2550continue 2551if line is None : 2552phase = "none" 2553raise EngineDied (f"the engine stopped unexpectedly (exit code { self . exit_code () } )" ) 2554if line .startswith ("BT " ): 2555t = int (line .split ()[2 ]) 2556out .append (t ) 2557live ["generated" ]= len (out ) 2558if cancel .is_set (): 2559if not stop_sent : 2560self ._send_for (born ,f"BSTOP { slot } " ) 2561stop_sent = True 2562continue 2563yield t 2564if not going_solo and not stop_sent and self ._may_go_solo (int (max_new )- len (out ),solo_again , 2565embeddings ): 2566self ._send_for (born ,f"BSTOP { slot } " )# alone now: on with the drafts (below) 2567going_solo = True 2568elif line .startswith ("BDONE " ): 2569phase = "none" 2570f = line .split () 2571self ._apply_bdone (f ) 2572admission_pending = False 2573# what the slot's sessions hold now: the prompt and every token fed (all but the last one) 2574self .slot_held [slot ]= list (prompt )+ out [gen0 :- 1 ]if len (out )> gen0 else [] 2575if f [3 :4 ]== ["nonfinite" ]:# #879: the engine dropped the slot's state 2576self .slot_held [slot ]= [] 2577raise EngineNonFinite ("the engine's logits became non-finite (#879)" ) 2578if (going_solo and f [3 :4 ]== ["cancel" ]and not cancel .is_set ()and len (out )< int (max_new ) 2579and not (out and out [- 1 ]in EOS_IDS )): 2580# the solo path continues it: the engine copies the slot's sessions back (all but the 2581# last token are in them) and decodes with MTP drafts again 2582carry_leg (carry ,self .last )# #1869: the solo path's DONE replaces these figures 2583self .slot_live [slot ]= None 2584self .slot_used [slot ]= time .time () 2585with self .slot_cv : 2586self .slot_busy [slot ]= False 2587self .slot_claims .discard (slot ) 2588self .slot_cv .notify_all () 2589slot ,gen0 = None ,None 2590if reused0 is None : 2591reused0 = (self .last or {}).get ("reused" ) 2592prompt ,left = list (ids )+ out ,int (max_new )- len (out ) 2593solo_again += 1 2594btrace ("back to the solo path" ) 2595break 2596return 2597finally : 2598# a consumer that left early (or an error): keep the engine and this server in step 2599btrace ("finally phase" ,phase ,"slot" ,slot ,"holding" ,holding ) 2600same = self .gen == born # #4451: the slot state below is this engine's; after a restart it is the NEW 2601# engine's lists and flags, which belong to other requests 2602undrained = None # the line this request's exchange still owes, from an engine that runs 2603try : 2604if phase in ("solo" ,"admit" )and (self .gen != born or not self .alive ()): 2605phase = "none" # #1012: its engine is gone: nothing to stop or drain 2606if phase in ("solo" ,"admit" )and self ._ctl_erred : 2607phase = "none" # #1059: it ended on the engine's ERR: no DONE to wait 300 s for 2608if phase == "solo" : 2609self ._send ("STOP" ) 2610if self ._drain_control ("DONE" ,born = born ,lines_q = lines_q )is None and self .gen == born and self .alive (): 2611undrained = "DONE" 2612elif phase == "admit" : 2613line = self ._drain_control ("BADM" ,born = born ,lines_q = lines_q ) 2614if line and line .startswith ("BADM " ): 2615admission_pending = line .split ()[2 :3 ]== ["1" ] 2616if line and line .startswith ("BADM " )and line .split ()[2 :3 ]== ["1" ]: 2617phase = "slot" 2618elif line is None and self .gen == born and self .alive (): 2619undrained = "BADM" 2620except EngineDied : 2621pass 2622handed = False 2623if undrained is not None : 2624# #4451: the engine has not said it is done with this request; whatever it prints later must not be read 2625# by the next one. The control lines (and the admission's slot) stay quarantined until it does. 2626self ._quarantine_control (undrained ,born ,lines_q ,slot if undrained == "BADM" else None ,holding ) 2627holding ,handed = False ,True 2628bdone_in = False 2629if phase == "slot" and slot is not None and out and out [- 1 ]in EOS_IDS and same : 2630bd = self ._bdone_after_eos (slot ,q = sq [slot ])# (#1869) the slot's figures, not the admission's 2631if bd is not None : 2632self ._apply_bdone (bd .split ()) 2633admission_pending = False 2634bdone_in = True 2635ended_on_yield = bool (yielded_legs and self .last is yielded_legs [- 1 ]) 2636if admission_pending and isinstance (self .last ,dict )and (self .last is not admission_before or carry ): 2637# A background drain owns the rest. The admission's one token and time are not this request's totals. 2638self .last = {** self .last ,"generated" :None ,"decode_ms" :None } 2639if reused0 is not None and isinstance (self .last ,dict ): 2640self .last = {** self .last ,"reused" :reused0 } 2641if carry and isinstance (self .last ,dict ): 2642self .last = add_carry (carry ,self .last ) 2643earlier_reads = yielded_legs [:- 1 ]if ended_on_yield else yielded_legs 2644if earlier_reads and isinstance (self .last ,dict ): 2645self .last = prefill_leg_stats (earlier_reads ,self .last ,len (ids )) 2646if holding : 2647self .ctl .release () 2648if admit_wait : 2649with self .slot_cv : 2650self .admitting = max (0 ,self .admitting - 1 ) 2651if reserved is not None and same : 2652with self .slot_cv : 2653self .slot_busy [reserved ]= False 2654self .slot_claims .discard (reserved ) 2655self .slot_cv .notify_all () 2656if slot is not None and same and not handed : 2657self .slot_live [slot ]= None 2658self .slot_used [slot ]= time .time () 2659if phase == "slot" and bdone_in : 2660stream = list (prompt )+ out [gen0 :]if gen0 is not None and len (out )> gen0 else None 2661self .slot_held [slot ]= stream [:- 1 ]if stream else []# as the BDONE wait leaves it 2662with self .slot_cv : 2663self .slot_busy [slot ]= False 2664self .slot_claims .discard (slot ) 2665self .slot_cv .notify_all () 2666elif phase == "slot" : 2667self .slot_held [slot ]= [] 2668stream = list (prompt )+ out [gen0 :]if gen0 is not None and len (out )> gen0 else None 2669self ._release_slot_when_done (slot ,stream ,born )# freed at its BDONE 2670self .slot_claims .discard (slot )# (the BDONE wait owns it now) 2671else : 2672with self .slot_cv : 2673self .slot_busy [slot ]= False 2674self .slot_claims .discard (slot ) 2675self .slot_cv .notify_all () 2676 2677slot_groups = 1 # --batch-groups (set when the engine starts) 2678SLOT_PREFIX_MIN = 512 # a held prefix shorter than this is not worth unbalancing the pipeline's groups 2679BRANCH_BOUNDARY_MIN = 8192 # the engine's message-boundary checkpoint (STRATA_CACHE_MESSAGE_BOUNDARY) starts at this many tokens 2680TURN_ID = 248045 # <|im_start|>: the engine's default --turn-token (its turn checkpoint sits at the last one) 2681 2682def pick_slot (self ,prompt :list [int ])-> int | None : 2683"""A free slot for `prompt` (the caller holds slot_cv): the one whose held tokens are the longest start of the 2684prompt (the engine then reads only the rest), else an empty one, else the one used longest ago - so the 2685conversations other slots hold stay for their next turns. None: every slot is busy.""" 2686free = [b for b in self .slot_order if not self .slot_busy [b ]] 2687if not free : 2688return None 2689gs = getattr (self ,"slot_gs" ,0 ) 2690if gs > 1 : 2691# pipelined groups of several slots: the engine keeps no idle slot below a busy one as a conversation cache 2692# (its pad row writes the slot), so nothing is worth keeping free for a next turn. A group's window spans 2693# its slots up to its last busy one, so first fill a hole below a busy slot of the same group (it costs no 2694# extra row), then follow the spreading order 2695# (reported on #793: least-recently-used picks left leading holes, [_ B], that cost a whole row each) 2696def fills_hole (b ): 2697g0 = b - b % gs 2698return any (self .slot_busy [x ]for x in range (b + 1 ,g0 + gs )) 2699return min (free ,key = lambda b : (not fills_hole (b ),self .slot_order .index (b ))) 2700agreed = {} 2701def agree (b ): 2702# how many leading tokens slot b's held stream and the prompt share (slice compares: streams reach 100k tokens) 2703if b not in agreed : 2704h = self .slot_held [b ] 2705lo ,hi = 0 ,min (len (h ),len (prompt )) 2706while lo < hi : 2707mid = (lo + hi + 1 )// 2 2708if h [:mid ]== prompt [:mid ]: 2709lo = mid 2710else : 2711hi = mid - 1 2712agreed [b ]= lo 2713return agreed [b ] 2714def held_prefix (b ): 2715# what of `prompt` the slot's cache serves: the slot's whole held stream (the prompt and what it decoded) 2716# when this prompt continues it, else its turn checkpoint - the engine takes one at the last <|im_start|> of 2717# a prompt (the next request of the chat renders the history again, but not the reply it decoded or the 2718# assistant header), so a prompt that agrees with the held tokens up to there is that chat's next turn 2719# too (#2518: it was only found by the engine's own source search, after pick_slot had sent it to another 2720# slot and the request in that slot had overwritten the chat whose cache the next one needed) 2721h = self .slot_held [b ] 2722if not h : 2723return 0 2724if len (h )< len (prompt )and prompt [:len (h )]== h : 2725return len (h ) 2726if self .TURN_ID not in h : 2727return 0 2728lo = agree (b ) 2729last = len (h )- 1 - h [::- 1 ].index (self .TURN_ID ) 2730if 0 < last < len (prompt )and last <= lo : 2731return last 2732# a branch: the same history with the last question replaced agrees with the held stream only up to an 2733# EARLIER message boundary, where the engine may hold a checkpoint of this chat 2734# (STRATA_CACHE_MESSAGE_BOUNDARY, prefixes of at least BRANCH_BOUNDARY_MIN tokens). The engine finds that 2735# source itself but copies it into the slot chosen here, so another chat's slot would be overwritten (#2518). 2736i = min (lo ,len (prompt )- 1 ,last - 1 ) 2737if i < self .BRANCH_BOUNDARY_MIN : 2738return 0 2739window = h [self .BRANCH_BOUNDARY_MIN :i + 1 ] 2740if self .TURN_ID not in window : 2741return 0 2742i -= window [::- 1 ].index (self .TURN_ID ) 2743# a boundary every other held conversation shares as well (the system prompt and tools of one client) says 2744# nothing about whose it is: the old order (an empty slot, then the least recent one) keeps all chats 2745if not any (agree (c )< i for c in range (self .batch )if c != b and self .slot_held [c ]): 2746return 0 2747return i 2748best = max (free ,key = held_prefix ) 2749# without --batch-groups a held prefix of any length is taken, as before 2750if held_prefix (best )>= (self .SLOT_PREFIX_MIN if self .slot_groups > 1 else 1 ): 2751return best 2752# with --batch-groups: the group with the fewest busy slots first, so the requests spread over the 2753# pipeline's stages (two requests in one group leave the other stage idle); then empty, then least recent 2754busy_in = {} 2755for b in range (self .batch ): 2756if self .slot_busy [b ]: 2757busy_in [self .slot_group [b ]]= busy_in .get (self .slot_group [b ],0 )+ 1 2758return min (free ,key = lambda b : (busy_in .get (self .slot_group [b ],0 )if self .slot_groups > 1 else 0 , 2759bool (self .slot_held [b ]),self .slot_used [b ])) 2760 2761def slots_view (self )-> list [dict ]: 2762"""/metrics: each batch slot - idle (with the tokens it holds for a next turn), reading or decoding.""" 2763now ,view = time .time (), [] 2764for b in range (self .batch ): 2765r = self .slot_live [b ] 2766if r is None : 2767view .append ({"slot" :b ,"state" :"idle" ,"held_tokens" :len (self .slot_held [b ])}) 2768continue 2769ft = r .get ("first_token" ) 2770view .append ({"slot" :b ,"state" :r ["state" ],"prompt_tokens" :r ["prompt_tokens" ], 2771"prompt_read" :r .get ("prompt_read" )if r ["state" ]== "reading" else None , 2772"generated" :r ["generated" ],"elapsed_s" :round (now - r ["started" ],1 ), 2773"tok_s" :round (r ["generated" ]/ max (1e-6 ,now - ft ),1 )if ft else None }) 2774return view 2775 2776def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ,prefill_only = False ): 2777"""Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): 2778the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that 2779has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" 2780if not self .alive (): 2781raise EngineDied ("the engine is unavailable; this request was not sent" ) 2782bias_api .validate_request (sampling or {},self ,None ) 2783refuse_for_split (self ,sampling or {}) 2784if getattr (self ,"batch" ,0 )and not self .multi : 2785yield from self .generate_batched (ids ,max_new ,sampling ,cancel ,embeddings ) 2786return 2787self .progress ,self .progress_ms ,self .reused = None ,0 ,0 2788self .prefill_tok_s_mean = None 2789# DeepSeek --parallel: the engine holds several conversations; this request is one of them (GEN ... rid=<id>), its 2790# lines come on a queue of their own and its STOP names it. One at a time (self.multi 0): the one queue, as before. 2791rid ,lines_q ,stop_line = None ,self .lines ,"STOP\n" 2792if self .multi : 2793with self .rid_lock : 2794self .rid_n += 1 2795rid = self .rid_n 2796lines_q = queue .Queue () 2797self .rid_q [rid ]= lines_q 2798stop_line = f"STOP { rid } \n" 2799# logprobs: the engine writes "LP <logprob> [id:logprob ...]" right after each "T <id>" (the same 2800# flush), read here before the token is yielded, so whoever takes the token finds its line in 2801# lp_lines. Not asked for = the deque stays empty and nothing on this path changes. 2802want_lp = top_logprobs (sampling or {})is not None 2803self .lp_lines = LPLines (cancel ) 2804carry = NO_LINE # a line read for a token's LP line, held until it is used 2805# an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) 2806rid_key = f" rid= { rid } " if rid is not None else "" 2807head = f"GENI { int ( max_new ) } { self . sampling_keys ( sampling or {}) } { rid_key } { embeddings } " if embeddings else \ 2808f"GEN { int ( max_new ) } { self . sampling_keys ( sampling or {}) } { rid_key } " 2809if prefill_only :# split serving (serve/split.py): read the prompt, make no token 2810if embeddings or int (max_new )!= 0 : 2811raise ValueError ("prefill_only is a text prompt and max_new 0" ) 2812head = f"GEN 0 prefill=1 { rid_key } " 2813try : 2814if rid is not None :# several requests write to the engine at once 2815self ._send (f" { head } { ',' . join ( str ( int ( t )) for t in ids ) } " ) 2816else : 2817self .proc .stdin .write (f" { head } { ',' . join ( str ( int ( t )) for t in ids ) } \n" ) 2818self .proc .stdin .flush () 2819except (OSError ,EngineDied ):# the pipe is gone: the engine died (not the client) 2820if rid is not None : 2821self .rid_q .pop (rid ,None ) 2822raise EngineDied (f"the engine stopped unexpectedly (exit code { self . exit_code () } )" )from None 2823done = False 2824# #481: how long the engine may stay silent from here. Until the first line: the request's first prompt 2825# chunk at the slowest prompt reading on top of silence_s; a PP line resets it to its own chunk's time. 2826silence = float (self .silence_s or 0 ) 2827allow = silence + min (len (ids ),PP_CHUNK_MAX )/ PP_FLOOR_TOK_S if silence > 0 else 0.0 2828heard ,read_to = time .monotonic (),0 2829beat = heard 2830stall_s = ENGINE_STALL_S or 0.0 2831stall_state :dict = {} 2832try : 2833while True : 2834wait = 10.0 2835if allow > 0 : 2836wait = min (wait ,allow - (time .monotonic ()- heard )) 2837if wait <= 0 : 2838done = True # no STOP and no drain: nothing is listening 2839raise self ._silent (f"the engine said nothing for { time . monotonic () - heard :.0f } s during " 2840"the request" ) 2841try : 2842if carry is not NO_LINE :# the line read after a token for its LP line 2843line ,carry = carry ,NO_LINE 2844else : 2845line = lines_q .get (timeout = min (wait ,0.5 )) 2846except queue .Empty : 2847if cancel .is_set (): 2848return 2849if stall_s > 0 : 2850try : 2851self ._stall_check (heard ,stall_state ,stall_s ) 2852except EngineSilent : 2853done = True # as above: nothing is listening 2854raise 2855if allow > 0 and time .monotonic ()- heard >= allow : 2856continue # enforce the expired deadline before another heartbeat 2857if time .monotonic ()- beat >= 10.0 : 2858beat = time .monotonic () 2859yield None # polling cancellation does not add HTTP heartbeats 2860continue 2861if line is None : 2862done = True 2863raise EngineDied (f"the engine stopped unexpectedly (exit code { self . exit_code () } )" ) 2864heard = time .monotonic ()# any line is output: T, PP, RESUME, INFO ... 2865beat = heard 2866if stall_state : 2867stall_state .clear () 2868if line .startswith ("T " ): 2869allow = silence 2870if cancel .is_set (): 2871return 2872t = int (line [2 :]) 2873if want_lp : 2874# the engine writes the token and its `LP` line in one flush, so the line is 2875# here now; an engine without logprobs leaves the next line a normal one 2876try : 2877carry = lines_q .get (timeout = 0.5 ) 2878except queue .Empty : 2879carry = NO_LINE 2880if isinstance (carry ,str )and carry .startswith ("LP " ): 2881self .lp_lines .append ((t ,carry )) 2882carry = NO_LINE 2883yield t 2884elif line .startswith ("PP " ): 2885f = line .split () 2886if len (f )>= 3 and f [1 ].isdigit ()and f [2 ].isdigit (): 2887self .progress = (int (f [1 ]),int (f [2 ]))# prompt progress, one per chunk: also a heartbeat (the 2888self .progress_ms = float (f [3 ])if len (f )>= 4 else 0.0 2889self .prefill_tok_s_mean = float (f [4 ])if len (f )>= 5 else None 2890rate ,chunk = self .prefill_tok_s_mean or 0.0 ,int (f [1 ])- read_to 2891read_to = int (f [1 ]) 2892if silence > 0 and rate > 0 and chunk > 0 :# #481: the next chunk, as long as this one 2893allow = max (silence ,PP_SLACK * chunk / rate ) 2894if cancel .is_set ():# lines reset the 10 s wait, so without this a long prompt 2895return # would send no keep-alives at all) 2896yield None 2897elif line .startswith ("RESUME " ):# the reused tokens: the first chunk starts after them 2898try : 2899read_to = self .reused = int (line .split ()[1 ]) 2900except (IndexError ,ValueError ): 2901pass 2902elif line .startswith ("DONE" ): 2903self ._parse_done (line ) 2904done = True 2905if self .last .get ("finish" )== "nonfinite" :# #879 2906raise EngineNonFinite ("the engine's logits became non-finite (#879)" ) 2907return 2908elif line .startswith ("ERR" ): 2909done = True 2910self ._raise_if_fatal_gpu (line ) 2911self ._swallow_trailing_done (lines_q )# an engine that ended the request on ERR may still print its DONE 2912raise ValueError (line [4 :].strip ()) 2913finally : 2914if not done :# the consumer stopped early: stop the engine, drain to DONE 2915# the engine can be ended or restarted on another thread meanwhile: Engine.close() closes stdin (a 2916# write then raises ValueError) before it clears `proc` (None then) - the STOP has nobody to reach, and 2917# the request's own outcome must not be replaced by that error 2918proc = self .proc 2919if self .can_stop and proc is not None : 2920try : 2921proc .stdin .write (stop_line ) 2922proc .stdin .flush () 2923except (OSError ,ValueError ): 2924pass 2925# #481: never an untimed wait here - it holds the request FIFO, and an engine that lost step never 2926# answers. An engine that honours STOP gets the current allowance in all (a STOP during a prompt 2927# chunk is seen after it); an older one runs on to max_new, so each line only has to come in time. 2928heard = time .monotonic () 2929while True : 2930left = allow - (time .monotonic ()- heard )if allow > 0 else None 2931try : 2932if carry is not NO_LINE :# read already, after the last token 2933line ,carry = carry ,NO_LINE 2934elif left is not None and left <= 0 : 2935raise queue .Empty 2936else : 2937line = lines_q .get (timeout = left ) 2938except queue .Empty : 2939raise self ._silent ("the engine did not finish the request after it was stopped (STOP) " 2940f"within { allow :.0f } s" )from None 2941if line is None or line .startswith ("ERR" ): 2942break 2943if line .startswith ("DONE" ): 2944self ._parse_done (line ) 2945break 2946if not self .can_stop : 2947heard = time .monotonic () 2948if rid is not None :# this request's lines are over (a late one goes nowhere) 2949self .rid_q .pop (rid ,None ) 2950 2951@staticmethod 2952def _swallow_trailing_done (lines_q ,wait :float = 0.3 )-> None : 2953"""A request that ends on `ERR ...` is over, but an engine that also prints the request's `DONE` after it (the DeepSeek 2954engine did, after its NaN stop) would hand that DONE to the NEXT request as its own: 0 tokens at once, and every answer 2955after it one request late. So a short wait for a trailing DONE (or ERR) of the same request, taken off the queue and 2956dropped, before the request is reported failed and the FIFO released. An engine that prints only the ERR costs the wait.""" 2957end = time .monotonic ()+ wait 2958while True : 2959left = end - time .monotonic () 2960if left <= 0 : 2961return 2962try : 2963late = lines_q .get (timeout = left ) 2964except queue .Empty : 2965return 2966if late is None or late .startswith (("DONE" ,"ERR" )): 2967return 2968 2969def _activity (self )-> tuple [float ,int ]| None : 2970"""#1317: (CPU seconds, I/O bytes) the engine process has used so far, or None when they cannot be read.""" 2971try : 2972import psutil 2973pr = psutil .Process (self .proc .pid ) 2974t = pr .cpu_times () 2975io = pr .io_counters () 2976return (t .user + t .system ,io .read_bytes + io .write_bytes ) 2977except Exception :# noqa: BLE001 - psutil missing, the process gone, no permission: no reading 2978return None 2979 2980def _stall_check (self ,heard :float ,state :dict ,stall_s :float )-> None : 2981"""#1317: called while the engine is silent. Takes a baseline soon after the last line, and at stall_s of silence 2982compares: no CPU and no I/O in all that time -> the engine is ended (EngineSilent); work going on -> one warning.""" 2983age = time .monotonic ()- heard 2984if state .get ("base" )is None : 2985state ["base" ]= self ._activity () 2986return 2987if age < state .get ("next" ,stall_s )or state ["base" ]is None : 2988return 2989now = self ._activity () 2990try : 2991gpu_working = bool (self .gpu_busy ())if self .gpu_busy is not None else False 2992except Exception :# noqa: BLE001 - a telemetry hiccup must not decide anything 2993gpu_working = False 2994if now is not None and not gpu_working and engine_frozen (state ["base" ],now ): 2995raise self ._silent (f"the engine said nothing for { age :.0f } s and used no CPU or disk in that time (frozen; " 2996"STRATA_ENGINE_STALL_S sets this, 0 = off)" ) 2997if now is not None :# working: look again after another window from here, and say so once 2998state ["base" ],state ["next" ]= now ,age + stall_s 2999if not state .get ("warned" ): 3000state ["warned" ]= True 3001f"[strata] the engine has said nothing for { age :.0f } s but is still working; it is not ended (the " 3002"limit is engine_silence_s). If it is stuck, \"engine_silence_s\" can be set lower." ,flush = True ) 3003else : 3004state ["next" ]= float ("inf" )# no reading (psutil missing): nothing to decide on 3005 3006def _silent (self ,what :str )-> EngineSilent : 3007"""#481: end an engine that lost step with the server (its main thread waits for a command the server never 3008sends), so the next request starts it again: killed now, its GPU and RAM go back with the process.""" 3009self .silent_note = ("The engine and the server lost step (issue #481; a very slow PC can raise " 3010"\"engine_silence_s\" in the config, 0 = wait forever). If it happens again, please add " 3011"the end of the engine log to github.com/Niko1221/Strata/issues/481." ) 3012self .ended = True # not alive from now: the next request restarts it 3013proc = self .proc 3014try : 3015proc .kill () 3016proc .wait (timeout = 20 )# restart() -> close() handles one that is still exiting 3017except (OSError ,AttributeError ,subprocess .TimeoutExpired ): 3018pass 3019return EngineSilent (f" { what } ; the server ended the engine" ) 3020 3021def end_for_restart (self )-> None : 3022"""End the engine now and mark it ended, so the next request starts it again (#3961: a run that stopped without its end event left the two sides 3023out of step; the restart is what puts them back).""" 3024self .ended = True 3025try : 3026self .proc .kill () 3027self .proc .wait (timeout = 20 ) 3028except (OSError ,AttributeError ,subprocess .TimeoutExpired ): 3029pass 3030 3031def session_file (self ,action :str ,path :str )-> dict : 3032with self ._exclusive_control (): 3033return self ._session_file (action ,path ) 3034 3035def _session_file (self ,action :str ,path :str )-> dict : 3036"""Disk sessions: `SAVE <path>` / `RESTORE <path>` between requests (the caller holds the service FIFO). 3037-> {"tokens", "bytes", "ms"}. SessionRefused (kind, published) when the engine refused or failed the file and 3038is still in step (`SERR <kind> <0|1> <reason>`). Any line this exchange does not allow - an unknown or 3039malformed one, a bare ERR, an answer with negative counts or a non-finite time - means the two sides lost 3040step: the engine is ended (EngineDied) and the next request starts it again. EngineDied also when it ended 3041by itself (a restore transfer that failed after the device state changed ends it on purpose: FATAL), and 3042EngineSilent (#481) when it printed nothing valid for engine_silence_s - a SESSION progress line (one per 3043block of the file moved, at most 16 MiB) counts only when its numbers are. `SWAIT <phase> <seconds>` announces 3044a step that blocks in one call (a flush, the device transfer): until the next line the wait is that step's 3045explicit allowance (at most SESSION_WAIT_MAX_S) when it is longer than engine_silence_s - no more, so a step 3046that never ends is still ended.""" 3047if action not in ("save" ,"restore" )or any (c in path for c in "\r\n\0" ): 3048raise ValueError ("invalid session command" ) 3049try : 3050self .proc .stdin .write (f" { 'SAVE' if action == 'save' else 'RESTORE' } { path } \n" ) 3051self .proc .stdin .flush () 3052except OSError : 3053raise EngineDied (f"the engine stopped unexpectedly (exit code { self . exit_code () } )" )from None 3054silence = float (self .silence_s or 0 ) 3055heard = time .monotonic () 3056want = "SAVED" if action == "save" else "RESTORED" 3057 3058def out_of_step (line :str )-> EngineDied : 3059self .ended = True # not alive from now: the next request restarts it 3060try : 3061self .proc .kill () 3062self .proc .wait (timeout = 20 ) 3063except (OSError ,AttributeError ,subprocess .TimeoutExpired ): 3064pass 3065return EngineDied (f"the engine answered a session { action } with { line . strip ()[: 200 ]!r } ; " 3066"the server ended the engine" ) 3067 3068def count (s :str )-> int : 3069if not s .isdigit ():# no sign, no blank, no fraction 3070raise ValueError 3071return int (s ) 3072 3073last_done = - 1 3074allow = 0.0 # the announced blocking step's allowance, seconds 3075while True : 3076limit = max (silence ,allow ) 3077left = limit - (time .monotonic ()- heard )if silence > 0 else None 3078try : 3079if left is not None and left <= 0 : 3080raise queue .Empty 3081line = self .lines .get (timeout = left ) 3082except queue .Empty : 3083raise self ._silent (f"the engine said nothing for { limit :.0f } s during a session { action } " 3084+ (f" (in a blocking step allowed { allow :.0f } s)" if allow > silence else "" ))from None 3085if line is None : 3086raise EngineDied (f"the engine stopped unexpectedly (exit code { self . exit_code () } )" ) 3087f = line .split () 3088head = f [0 ]if f else "" 3089if head == "SESSION" :# a large file moving: progress, and a heartbeat 3090try : 3091if len (f )!= 3 : 3092raise ValueError 3093done ,total = count (f [1 ]),count (f [2 ]) 3094if done > total or done < last_done : 3095raise ValueError 3096except ValueError : 3097raise out_of_step (line )from None 3098last_done = done 3099heard ,allow = time .monotonic (),0.0 3100continue 3101if head == "SWAIT" :# a blocking step starts: its bounded allowance 3102try : 3103if len (f )!= 3 or not f [1 ].isalpha ()or not f [1 ].isascii (): 3104raise ValueError 3105seconds = count (f [2 ]) 3106if not 0 < seconds <= SESSION_WAIT_MAX_S : 3107raise ValueError 3108except ValueError : 3109raise out_of_step (line )from None 3110heard ,allow = time .monotonic (),float (seconds ) 3111continue 3112if head == "FATAL" : 3113raise EngineDied (line [6 :].strip ()or "the engine ended during a session restore" ) 3114if head == "SERR" : 3115parts = line .rstrip ("\r\n" ).split (" " ,3 ) 3116if len (parts )!= 4 or parts [1 ]not in SessionRefused .STATUS or parts [2 ]not in ("0" ,"1" ): 3117raise out_of_step (line ) 3118raise SessionRefused (parts [1 ],parts [3 ].strip (),parts [2 ]== "1" ) 3119if head == want : 3120try : 3121if len (f )!= 4 : 3122raise ValueError 3123tokens ,size ,ms = count (f [1 ]),count (f [2 ]),float (f [3 ]) 3124if not math .isfinite (ms )or ms < 0 : 3125raise ValueError 3126except ValueError : 3127raise out_of_step (line )from None 3128return {"tokens" :tokens ,"bytes" :size ,"ms" :ms } 3129if head == "INFO" or head == "WARN" :# engine log lines may interleave; they are not answers 3130heard = time .monotonic () 3131continue 3132raise out_of_step (line ) 3133 3134def close (self ): 3135"""End the engine process: STOP + QUIT first (the engine frees its memory itself - unpinning tens of GB can take 3136a while; ENGINE_QUIT_WAIT_S), then terminate (ENGINE_TERM_WAIT_S), then kill (ENGINE_KILL_WAIT_S). Raises 3137EngineStuck when it still runs after all three.""" 3138if self .proc is None : 3139return 3140try : 3141if self .proc .poll ()is None : 3142try : 3143# STOP first: a request still running ends at its next step instead of being waited for (the 3144# engine reads stdin on its own thread; QUIT behind a long answer would sit in its queue) 3145self .proc .stdin .write ("STOP\nQUIT\n" ) 3146self .proc .stdin .flush () 3147self .proc .stdin .close ()# Windows' detached stdin reader must see EOF before shutdown 3148self .proc .wait (timeout = ENGINE_QUIT_WAIT_S ) 3149except (OSError ,ValueError ,subprocess .TimeoutExpired ): 3150self .proc .terminate () 3151self .proc .wait (timeout = ENGINE_TERM_WAIT_S ) 3152except subprocess .TimeoutExpired : 3153self .proc .kill () 3154try : 3155self .proc .wait (timeout = ENGINE_KILL_WAIT_S ) 3156except subprocess .TimeoutExpired : 3157raise EngineStuck ("Strata is still releasing GPU/RAM; retry unloading after it exits" )from None 3158except OSError : 3159pass 3160finally : 3161if self .proc .poll ()is not None : 3162if self .pump is not None and self .pump .ident is not None :# a restart can stop before starting it 3163self .pump .join (timeout = 2 ) 3164try : 3165self .proc .stdin .close ()# buffered data may flush again after the engine has exited 3166except OSError : 3167pass 3168self .proc .stdout .close () 3169if self .log not in (None ,subprocess .DEVNULL ): 3170self .log .close () 3171self .proc = None 3172self .ended = True 3173self .progress ,self .last = None , {} 3174self .progress_ms ,self .reused = 0 ,0 3175 3176 3177IMAGE_URL_MAX = 32 << 20 # an image URL is read up to this (the web app attaches pictures of up to 20 MB) 3178 3179 3180def network_path (path :str )-> bool : 3181r"""A path to another computer: \\host\share or //host/share (either slash), \\?\UNC\host\..., \\.\UNC\host\... 3182or the NT form \??\UNC\host\... Windows connects to that host at the first look at the path (os.path.isfile is 3183enough) and signs in with the user's NTLM credentials. \\?\ and \??\ name local files too; no client needs them.""" 3184p = path .replace ("/" ,"\\" ) 3185return p .startswith ("\\\\" )or p .startswith ("\\??\\" ) 3186 3187 3188def vision_log_size (log = None )-> int : 3189"""How long the encoder's stderr file is now (0 when there is none): a start reads only what it wrote after this.""" 3190try : 3191name = getattr (log ,"name" ,None ) 3192return os .path .getsize (name )if name else 0 3193except (OSError ,TypeError ): 3194return 0 3195 3196 3197def vision_log_tail (log = None ,limit :int = 16384 ,since :int = 0 )-> str : 3198"""The last `limit` bytes of the encoder's stderr file (`log` is the file object it was started with; "" when there 3199is none or it cannot be read), but nothing from before `since` (the file's size when this start began: a log that several starts share).""" 3200try : 3201name = getattr (log ,"name" ,None ) 3202if name : 3203with open (name ,"rb" )as f : 3204f .seek (0 ,2 ) 3205f .seek (max (since ,f .tell ()- limit )) 3206return f .read ().decode ("utf-8" ,"replace" ) 3207except (OSError ,ValueError ): 3208pass 3209return "" 3210 3211 3212# What the CUDA / HIP runtimes print when the reader has no code for the card it runs on (a binary built without that 3213# architecture: #3669, the Windows cuda12 package's reader on a Pascal card). 3214_VISION_ARCH_SIGNS = ("device kernel image is invalid" ,"no kernel image is available" ,"im2col failed" , 3215"unsupported gpu architecture" ,"invalid device function" ,"unknown gpu architecture" ) 3216 3217 3218def vision_start_error (line :str ,log = None ,code :int | None = None ,waited :float | None = None ,strays = (),since :int = 0 )-> str : 3219"""The message when the image encoder answered something other than READY. #1445: a card in the Exclusive_Process 3220compute mode (or one another process holds) refuses the encoder's CUDA context with "busy or unavailable"; that 3221cause is named instead of leaving the user the first line of a traceback. `log` is the encoder's stderr file, whose 3222tail is searched too (the CUDA error is printed there). An encoder that dies before it prints anything (#3645, #3444, 3223#3669, #3697) used to give a blank sentence: now the last lines of its stderr, its exit status (`code`) and, for a 3224kernel-image error, the card/architecture hint come with it. `waited`: it said nothing for that many seconds. `strays`: lines it printed on 3225its output before it ended that were not an answer (a debugger's, a library's); they are searched for the causes below and named in the message.""" 3226text = line .strip () 3227tail = vision_log_tail (log ,since = since ) 3228both = (text + chr (10 )+ chr (10 ).join (strays )+ chr (10 )+ tail ).lower () 3229if "busy or unavailable" in both : 3230return ("the vision encoder did not start: the GPU refused a second CUDA context (\"CUDA-capable device(s) " 3231"is/are busy or unavailable\"). This is usually the compute mode Exclusive_Process: only one process " 3232"may use the card, and the engine already holds it. Check with: nvidia-smi --query-gpu=compute_mode " 3233"--format=csv; set it back with: sudo nvidia-smi -c DEFAULT (or run the encoder on another card). " 3234"First line from the encoder: " + (text or "(none)" )) 3235lines = [x .strip ()for x in tail .splitlines ()if x .strip ()] 3236room = reader_room .find ((text + chr (10 )+ chr (10 ).join (strays )+ chr (10 )+ tail ).splitlines ()) 3237if room :# a card another program filled: ggml's cudaMalloc line, then an abort the reader cannot answer for 3238asked = (f" (it asked for { room . need_mib :.0f } MiB" + (f" on its card { room . device } " if room .device is not None else "" )+ ")" )if room .need_mib else "" 3239said = [text ,* strays ,* lines ] 3240evidence = (next ((x for x in reversed (said )if "malloc failed" in x .lower ()),None ) 3241or next ((x for x in reversed (said )if "failed to allocate" in x .lower ()),text )) 3242return "the vision encoder did not start: the graphics card has no room for it" + asked + ". From the encoder: " + evidence .strip ()[:300 ] 3243if any (sign in both for sign in _VISION_ARCH_SIGNS ): 3244evidence = next ((x for x in reversed (lines )if any (sign in x .lower ()for sign in _VISION_ARCH_SIGNS )),text ) 3245return ("the vision encoder did not start: it has no code for this graphics card (a kernel-image error: the " 3246"picture reader in this engine package was built for other card generations than yours). Update the " 3247"engine, or read pictures on the CPU (Models, Read pictures, Image encoder device: CPU; or run setup " 3248"again with --vision cpu). From the encoder: " + evidence [:300 ]) 3249if text : 3250msg = "the vision encoder did not start: " + text 3251elif waited is not None : 3252msg = f"the vision encoder did not start: it said nothing for { waited :g } s (it never reported READY)" 3253else : 3254msg = "the vision encoder did not start: it ended without saying anything" 3255extra = [] 3256if code is not None : 3257words = engine_exit_words (code ) 3258if words : 3259extra .append (words ) 3260if strays : 3261extra .append ("it also printed on its output: " + " | " .join (x [:120 ]for x in list (strays )[- 3 :])) 3262shown = [x for x in lines [- 3 :]if x != text ] 3263if shown : 3264extra .append ("last lines of its log: " + " | " .join (x [:200 ]for x in shown )) 3265if extra : 3266msg += " (" + "; " .join (extra )+ ")" 3267return msg 3268 3269 3270def card_free_mib (index :int | None ,amd :bool = False )-> int | None : 3271"""Free memory of one card in MiB, from the backend's reader (NVML, the amdgpu files); None when it cannot be read (nothing is refused for that).""" 3272try : 3273from serve .telemetry import gpu_reader 3274g = gpu_reader (int (index or 0 ),amd = amd ) 3275if not g .ok (): 3276return None 3277r = g .read () 3278if r .get ("mem_total" )is None or r .get ("mem_used" )is None : 3279return None 3280return int ((r ["mem_total" ]- r ["mem_used" ])>> 20 ) 3281except Exception :# noqa: BLE001 3282return None 3283 3284 3285class VisionNoRoom (RuntimeError ): 3286"""The picture reader could not start because its card has no room for it (`room`: strata_control.reader_room.NoRoom).""" 3287 3288def __init__ (self ,message :str ,room ): 3289super ().__init__ (message ) 3290self .room = room 3291 3292 3293class Vision : 3294"""The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC <image> <out>` 3295lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that 3296sends the same picture again (every turn, with most clients) encodes it once.""" 3297 3298@staticmethod 3299def work_dir ()-> Path : 3300"""#480: the directory for the encoder's files. The engine reads the embeddings file named in a `GENI` line 3301and the encoder the output named in an `ENC <image> <out>` line, both split at spaces, so a space in the path 3302(a %TEMP% under a user name with a space) broke every image. The system temp directory is used while its path 3303has no space, then the working directory, then the system drive's root; the plain temp directory is the last 3304resort (the encoder's own files are then named relative to it, see `_start`).""" 3305for parent in (None ,Path .cwd (),Path (os .environ .get ("SystemDrive" ,"C:" )+ os .sep )): 3306try : 3307d = Path (tempfile .mkdtemp (prefix = "strata-vision-" ,dir = parent )) 3308except OSError : 3309continue # not writable, or no such drive 3310if " " not in str (d ): 3311return d 3312try : 3313d .rmdir ()# just created, so still empty 3314except OSError : 3315pass 3316return Path (tempfile .mkdtemp (prefix = "strata-vision-" )) 3317 3318def __init__ (self ,cfg :dict ,log = None ,env :dict | None = None ,lazy :bool = False ): 3319args = self .reader_args (cfg ) 3320self .dir = self .work_dir () 3321self .spawn = (args ,log ,env )# to start it again after an unload 3322# AMD: the GPU reader (strata-vision-hip) has the CPU reader (strata-vision, same program, no GPU runtime) to 3323# fall back on when it does not start; _start switches to it by itself 3324# the NVIDIA reader (strata-vision) is the CPU reader too, without --gpu: a GPU reader that does not start, resident or on demand, reads on the 3325# processor instead of ending the launch (owner, 2026-11-10); the person's image limit stays 3326cpu = vision_reader .cpu_fallback (cfg ,same_program = True ) 3327self .fallback = (self .reader_args (cpu ),log ,env )if cpu else None 3328self .gpu_spawn ,self .cpu_spawn = self .spawn ,self .fallback # an on-demand reader tries the GPU one again at every start 3329self .on_cpu = False # the CPU reader is what runs (the GPU one did not start, or there was no room) 3330self .cpu_note = None # why, in words for the person (strata_control/reader_room.py), when the card had no room 3331self .reader = None # "own" (Strata's) or "mtmd" (llama.cpp's) from the READY line; None for an older reader 3332self .proc = None 3333self .stopped = True 3334self .lock = threading .Lock () 3335self .cache :dict [str ,tuple [Path ,int ]]= {} 3336# opt-in (the vision section's "elastic": true, with the config's "vram_elastic"): the encoder starts with the 3337# first picture and stops after elastic_idle_s without one; while it runs, the engine's expert cache keeps 3338# elastic_mib of VRAM free for it (Service._vision_up / _vision_idle_down) 3339self .max_tokens = self .token_limit (cfg ) 3340self .elastic = cfg .get ("elastic" )is True 3341self .elastic_mib = self .elastic_ask_mib (cfg ,self .max_tokens ) 3342self .elastic_idle_s = float (cfg .get ("elastic_idle_s" )or 120 ) 3343if not lazy and not self .elastic : 3344self ._start () 3345 3346# What a picture may become when the config does not say (setup writes the same numbers, setup.VISION): an old, hand-edited or migrated 3347# config without vision.max_tokens left the reader unclamped, and #3690 saw one picture become 93,700 image tokens (I7). A key that is 3348# there is the person's: 0 means no limit, as before. 3349DEFAULT_MAX_TOKENS = {"gpu" :1024 ,"cpu" :300 } 3350 3351@staticmethod 3352def elastic_ask_mib (cfg :dict ,max_tokens :int )-> int : 3353"""The VRAM the expert cache keeps free for an elastic reader: the config's elastic_mib when the person set one, else the reader's 3354need at its image limit (strata_control/reader_room.py; 0 = no limit counts as 16,384), never below 2,048. At the default limit of 33551,024 tokens that is 2,048; at 16,384 it is 3,674 (a 2,048 ask left the encoder out of memory for one large picture on an RTX A6000).""" 3356if cfg .get ("elastic_mib" ): 3357return int (cfg ["elastic_mib" ]) 3358return max (2048 ,math .ceil (reader_room .reader_needs_mib (max_tokens ))) 3359 3360@staticmethod 3361def token_limit (cfg :dict )-> int : 3362"""The --max-tokens of a reader config: its max_tokens, else the default of its kind (GPU 1024, CPU 300).""" 3363if cfg .get ("max_tokens" )is not None : 3364try : 3365return max (0 ,int (cfg ["max_tokens" ])) 3366except (TypeError ,ValueError ): 3367pass 3368return Vision .DEFAULT_MAX_TOKENS ["gpu" if cfg .get ("gpu" )else "cpu" ] 3369 3370@staticmethod 3371def reader_args (cfg :dict )-> list : 3372absolute = lambda p :os .path .abspath (p )if os .path .dirname (str (p ))else p # the encoder runs in its own dir (#480) # noqa: E731 3373args = [absolute (cfg ["exe" ]),"--mmproj" ,absolute (cfg ["mmproj" ]),"--model" ,absolute (cfg ["model" ])] 3374if cfg .get ("gpu" ): 3375args .append ("--gpu" ) 3376if cfg .get ("threads" ): 3377args += ["--threads" ,str (cfg ["threads" ])] 3378limit = Vision .token_limit (cfg ) 3379if limit : 3380args += ["--max-tokens" ,str (limit )] 3381if cfg .get ("min_tokens" ):# #767: mtmd's image_min_tokens (a hand-edited key) 3382args += ["--min-tokens" ,str (cfg ["min_tokens" ])] 3383return args 3384 3385def _ensure_dir (self ): 3386"""#3370: a temp cleaner (Windows Storage Sense) removes the empty work folder while the encoder is unloaded; the next 3387start then failed with WinError 267 for as long as the server lived. Make it again; pictures cached in it are gone.""" 3388if not self .dir .is_dir (): 3389self .dir .mkdir (parents = True ,exist_ok = True ) 3390self .cache .clear () 3391 3392def _start (self ): 3393"""Start the reader. When a GPU reader that has a CPU reader to fall back on does not start (the GPU runtime does not 3394load, the card is not in its build, the card is busy), the CPU reader is started instead, for good, with one log line 3395and no question.""" 3396try : 3397self ._start_gpu_reader () 3398except (RuntimeError ,OSError )as e : 3399fallback = getattr (self ,"fallback" ,None ) 3400if fallback is None : 3401raise 3402why = " " .join (str (e ).split ())[:240 ] 3403again = " until it is idle" if getattr (self ,"elastic" ,False )else "" 3404self .cpu_note = self .no_room_note (e .room )if isinstance (e ,VisionNoRoom )else self .not_started_note () 3405f"[strata] the GPU picture reader did not start ( { why } ); pictures are read on the CPU { again } " ,flush = True ) 3406self .spawn ,self .fallback ,self .on_cpu = fallback ,None ,True 3407self ._start_reader () 3408 3409def _start_gpu_reader (self ): 3410"""`_start_reader`, tried again when the start failed in the GPU context itself on a Linux Arm machine with shared memory (DGX Spark; see 3411vision_reader.retry_gpu_start): a new spawn may start while less than CONTEXT_RETRY_BUDGET_S have passed since the first one started, at most CONTEXT_RETRIES 3412times, CONTEXT_RETRY_WAIT_S apart. Every other start, and the last failure, are `_start_reader`'s as before (the CPU reader follows in `_start`). 3413STRATA_VIT_PROF=1 (the reader's diagnostic switch) prints the retry count and the time of a start that needed one.""" 3414args ,log ,_env = self .spawn 3415retries = 0 3416first = time .monotonic ()# the first spawn's start: a new spawn may start only within vision_reader.CONTEXT_RETRY_BUDGET_S of it 3417prof = bool (os .environ .get ("STRATA_VIT_PROF" )) 3418while True : 3419since = vision_log_size (log ) 3420try : 3421res = self ._start_reader () 3422if prof and retries : 3423f"vit-prof: GPU reader started after { retries } retries, { time . monotonic () - first :.2f } s" ,flush = True ) 3424return res 3425except (RuntimeError ,OSError )as e : 3426text = str (e )+ chr (10 )+ vision_log_tail (log ,since = since ) 3427if not vision_reader .retry_gpu_start (linux = sys .platform .startswith ("linux" ),arm = platform .machine ().lower ()in ("aarch64" ,"arm64" ), 3428hip = "hip" in Path (str (args [0 ])).name .lower (),text = text ,retries_done = retries , 3429next_start_s = time .monotonic ()- first + vision_reader .CONTEXT_RETRY_WAIT_S ): 3430if prof and retries : 3431f"vit-prof: GPU reader did not start after { retries } retries, { time . monotonic () - first :.2f } s" ,flush = True ) 3432raise 3433retries += 1 3434time .sleep (vision_reader .CONTEXT_RETRY_WAIT_S ) 3435 3436def no_room_note (self ,room )-> str : 3437"""The sentence for the person when the card had no room for the reader and the processor reads instead: which card (as nvidia-smi numbers it), what 3438the reader needed, what is free now that it is gone.""" 3439amd ,visible = self .visible_cards () 3440card = reader_room .physical_card (room .device ,visible ) 3441need = reader_room .whole_need_mib (room .need_mib ,getattr (self ,"max_tokens" ,None ))# the reader's whole need at its limit, not the one allocation that failed 3442return reader_room .on_processor (card ,need ,card_free_mib (card ,amd )if card is not None else None ) 3443 3444def not_started_note (self )-> str : 3445"""The sentence for the person when the GPU reader did not start for any other reason and the processor reads instead: the card it would have used 3446(the first one it is shown), and where the reason is (the engine log, which is the reader's stderr).""" 3447_amd ,visible = self .visible_cards () 3448card = None if sys .platform == "darwin" else reader_room .physical_card (0 ,visible )# a Mac has no numbered cards 3449return reader_room .not_started_on_processor (card ,getattr (self .spawn [1 ],"name" ,None )) 3450 3451def visible_cards (self ): 3452"""(is it the AMD reader, the cards its environment shows it: CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES or None).""" 3453args ,_log ,env = self .spawn 3454amd = "hip" in Path (str (args [0 ])).name .lower () 3455return amd , (env if env is not None else os .environ ).get ("HIP_VISIBLE_DEVICES" if amd else "CUDA_VISIBLE_DEVICES" ) 3456 3457def use_cpu (self )-> bool : 3458"""The next start is the CPU reader's (the card has no room for the GPU one): False when there is no CPU reader to use.""" 3459if self .fallback is None : 3460return False 3461self .spawn ,self .fallback ,self .on_cpu = self .fallback ,None ,True 3462return True 3463 3464def _start_reader (self ): 3465args ,log ,env = self .spawn 3466self ._ensure_dir () 3467# cwd is the encoder's directory: the ENC lines name the files relative to it (#480: no space in the line) 3468since = vision_log_size (log )# this start's own lines of a log that earlier starts wrote to as well 3469self .proc = popen ("the image encoder" ,args ,role = "vision" ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE , 3470stderr = log or subprocess .DEVNULL ,text = True ,encoding = "utf-8" ,errors = "replace" ,bufsize = 1 , 3471env = env ,cwd = self .dir ) 3472strays :list [str ]= [] 3473try : 3474line = self ._await_ready (VISION_READY_S ,strays ) 3475except RuntimeError as e :# silent for VISION_READY_S: it was ended, and it is not left half-started 3476self .proc ,self .stopped = None ,True 3477if VISION_READY_S : 3478raise RuntimeError (vision_start_error ("" ,log ,waited = VISION_READY_S ,strays = strays ,since = since ))from None 3479raise RuntimeError (str (e ))from None 3480if not line .startswith ("READY" ): 3481proc ,self .proc = self .proc ,None 3482self .stopped = True 3483code = proc .poll ()if hasattr (proc ,"poll" )else None # an encoder that died by itself has its status already 3484try : 3485proc .kill () 3486proc .wait (timeout = 5 ) 3487except (OSError ,subprocess .TimeoutExpired ): 3488pass 3489if code is None : 3490code = getattr (proc ,"returncode" ,None ) 3491message = vision_start_error (line ,log ,code ,strays = strays ,since = since ) 3492room = reader_room .find ((line + chr (10 )+ chr (10 ).join (strays )+ chr (10 )+ vision_log_tail (log ,since = since )).splitlines ()) 3493raise (VisionNoRoom (message ,room )if room else RuntimeError (message )) 3494self .stopped = False 3495# "READY <n_embd> <reader> [fallback]": the reader that runs (own: Strata's, mtmd: llama.cpp's; an older strata-vision says only "READY <n_embd>"), 3496# and "fallback" when Strata's reader did not start and llama.cpp's took its place (strata-vision wrote the reason to the log) 3497words = line .split () 3498self .reader = words [2 ]if len (words )> 2 else None 3499if "fallback" in words [3 :]: 3500"[strata] Strata's picture reader did not start; pictures are read with llama.cpp's reader. Details are in the log." ,flush = True ) 3501 3502#: how long a reader that has already ended may still hold its output pipe open (a debugger attached to it, a child it started) before the start is 3503#: judged: the pipe's end does not come, the process's end is what counts. 3504READY_GRACE_S = 2.0 3505#: lines kept from a reader's output before its answer (and written to the log): enough to see what it said, not a flood 3506STRAY_KEEP = 20 3507 3508def _await_ready (self ,timeout :float | None ,strays :list )-> str : 3509"""The reader's answer to its start: "READY ..." or "ERR ..." (what strata-vision prints on stdout; everything else it says goes to stderr), 3510or "" when it has ended. Any other line on stdout is a stray line - a debugger a crashing reader started, a library's banner - and is not an 3511answer: it is kept in `strays` (the last STRAY_KEEP), written to the log, and the wait goes on. A reader that is only printing is never killed. 3512The wait has ONE deadline of `timeout` s (None: for ever); on it the reader is killed and the read raises RuntimeError, as `_readline` does. A 3513reader whose process has ended while a debugger or a child still holds its pipe open counts as ended after READY_GRACE_S. The thread that 3514reads stops at the answer, so the encode answers that follow are never taken by it.""" 3515proc = self .proc 3516got :queue .Queue = queue .Queue () 3517 3518def read (): 3519while True : 3520try : 3521line = proc .stdout .readline () 3522except (OSError ,ValueError ):# killed under the read 3523line = "" 3524got .put (line ) 3525if not line or line .startswith (("READY" ,"ERR" )): 3526return 3527 3528threading .Thread (target = read ,daemon = True ).start () 3529deadline = None if timeout is None else time .monotonic ()+ timeout 3530ended_at = None 3531said = 0 3532while True : 3533now = time .monotonic () 3534if deadline is not None and now >= deadline : 3535try : 3536proc .kill () 3537except OSError : 3538pass 3539raise RuntimeError (f"the vision encoder did not start: it said nothing for { timeout :.0f } s" ) 3540try : 3541line = got .get (timeout = 0.25 if deadline is None else max (0.01 ,min (0.25 ,deadline - now ))) 3542except queue .Empty : 3543code = proc .poll ()if hasattr (proc ,"poll" )else None 3544if code is not None : 3545ended_at = now if ended_at is None else ended_at 3546if now - ended_at >= self .READY_GRACE_S : 3547return "" 3548continue 3549if not line or line .startswith (("READY" ,"ERR" )): 3550return line 3551stray = line .strip () 3552if stray : 3553strays .append (stray [:300 ]) 3554del strays [:- self .STRAY_KEEP ] 3555said += 1 3556if said <= self .STRAY_KEEP : 3557f"[strata] the image encoder printed on its output, not an answer: { stray [: 200 ] } " ,flush = True ) 3558 3559def _readline (self ,timeout :float ,what :str )-> str : 3560"""One line from the encoder, waiting at most `timeout` s (#1317). On a timeout the encoder is killed, so the 3561next request starts a fresh one, and the read raises RuntimeError instead of holding the request turn.""" 3562proc = self .proc 3563got :queue .Queue = queue .Queue () 3564 3565def read (): 3566try : 3567got .put (proc .stdout .readline ()) 3568except (OSError ,ValueError ):# killed under the read 3569got .put ("" ) 3570 3571threading .Thread (target = read ,daemon = True ).start () 3572try : 3573return got .get (timeout = timeout ) 3574except queue .Empty : 3575try : 3576proc .kill () 3577except OSError : 3578pass 3579raise RuntimeError (f" { what } : it said nothing for { timeout :.0f } s" )from None 3580 3581def alive (self )-> bool : 3582return self .proc is not None and not self .stopped and self .proc .poll ()is None 3583 3584def unload (self ): 3585"""Stop the encoder process (its VRAM or RAM goes back); the encoded images stay cached on disk.""" 3586self .close () 3587self .stopped = True 3588if self .elastic and self .on_cpu :# the next start tries the card again 3589self .spawn ,self .fallback ,self .on_cpu = self .gpu_spawn ,self .cpu_spawn ,False 3590self .cpu_note = None 3591 3592def all_cached (self ,sources :list )-> bool : 3593"""Every picture of `sources` was encoded already (a conversation sends its pictures with each turn): no reader has to run.""" 3594try : 3595with self .lock : 3596self ._ensure_dir () 3597return all (hashlib .sha256 (self .normalize (src if isinstance (src ,bytes )else self .load (src ))).hexdigest ()[:32 ]in self .cache 3598for src in sources ) 3599except (ValueError ,OSError ): 3600return False # encode() says what is wrong with it 3601 3602def restart (self ): 3603"""Start the encoder again after an unload (or if it died); the cache of encoded images is kept.""" 3604if self .proc is not None : 3605try : 3606self .proc .kill () 3607except OSError : 3608pass 3609self .proc = None 3610self .stopped = True 3611self ._start () 3612 3613@staticmethod 3614def load (source :str )-> bytes : 3615if source .startswith ("data:" ): 3616try : 3617return base64 .b64decode (source .split ("," ,1 )[1 ]) 3618except (IndexError ,ValueError )as e :# no comma, or not base64 3619raise ValueError (f"the image's data: URL could not be read ( { e } )" )from None 3620if source .startswith (("http://" ,"https://" )): 3621return Vision .download (source ) 3622path = source [7 :]if source .startswith ("file://" )else source 3623# refused before anything looks at the path: file://host/share/x.png is \\host\share\x.png ("file://C:/x.png", 3624# a drive, is a client's spelling of file:///C:/x.png) 3625host = re .split (r"[/\\]" ,path ,maxsplit = 1 )[0 ]if source .startswith ("file://" )else "" 3626if network_path (path )or host and not re .fullmatch (r"[A-Za-z]:|localhost" ,host ,re .IGNORECASE ): 3627raise ValueError ("an image file must be on this computer: network paths (\\\\host\\share, //host/share, " 3628"file://host/...) are not read" ) 3629if path and os .path .isfile (path ): 3630try : 3631return Path (path ).read_bytes () 3632except OSError as e : 3633raise ValueError (f"the image could not be read from { path } ( { e } )" )from None 3634raise ValueError ("an image must be a data: URL, an http(s) URL or a local file path" ) 3635 3636@staticmethod 3637def download (url :str )-> bytes : 3638"""An image URL's bytes, at most IMAGE_URL_MAX of them: the whole response was read, so a huge or endless one 3639filled the memory. One that cannot be read is a ValueError (a 400 that says so), not a dropped connection.""" 3640too_big = f"the image URL's file is over { IMAGE_URL_MAX >> 20 } MiB" 3641try : 3642with urllib .request .urlopen (urllib .request .Request (url ,headers = {"User-Agent" :"strata" }),timeout = 60 )as r : 3643size = r .headers .get ("Content-Length" )or "" 3644if size .isdigit ()and int (size )> IMAGE_URL_MAX : 3645raise ValueError (too_big ) 3646data = r .read (IMAGE_URL_MAX + 1 ) 3647except (OSError ,HTTPException )as e : 3648raise ValueError (f"the image URL could not be read: { e } " )from None 3649if len (data )> IMAGE_URL_MAX : 3650raise ValueError (too_big ) 3651return data 3652 3653@staticmethod 3654def _exif_rotated (data :bytes )-> bool : 3655"""A JPEG whose EXIF Orientation says it is stored turned (phones do this for portrait photos): the decoder 3656(stb_image) ignores the tag. False without Pillow, or when the tag is missing, 1 or unreadable (#1229).""" 3657try : 3658import io 3659from PIL import Image 3660with Image .open (io .BytesIO (data ),formats = PICTURE_FORMATS )as im : 3661return im .getexif ().get (0x0112 ,1 )not in (None ,0 ,1 ) 3662except Exception :# noqa: BLE001 - any failure leaves the image as it was sent 3663return False 3664 3665@staticmethod 3666def normalize (data :bytes )-> bytes : 3667"""The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG. 3668A JPEG with an EXIF Orientation other than 1 is turned upright first (needs Pillow).""" 3669jpeg = data [:3 ]== b"\xff\xd8\xff" 3670if (jpeg and not Vision ._exif_rotated (data ))or data [:8 ]== b"\x89PNG\r\n\x1a\n" or data [:2 ]== b"BM" or \ 3671data [:6 ]in (b"GIF87a" ,b"GIF89a" ): 3672return data 3673try : 3674import io 3675from PIL import Image 3676except ImportError : 3677raise ValueError ("this image format needs Pillow (python -m pip install pillow); JPEG, PNG, BMP and " 3678"GIF work without it" )from None 3679try : 3680im = Image .open (io .BytesIO (data ),formats = PICTURE_FORMATS ) 3681im .load () 3682from PIL import ImageOps 3683im = ImageOps .exif_transpose (im )# the camera's orientation tag, applied (#1229) 3684except Exception as e : 3685raise ValueError (f"the image could not be read ( { e } )" )from None 3686if im .mode in ("RGBA" ,"LA" ,"P" )and "transparency" in im .info or im .mode in ("RGBA" ,"LA" ): 3687im = im .convert ("RGBA" ) 3688bg = Image .new ("RGB" ,im .size , (255 ,255 ,255 ))# transparent areas become white, not black 3689bg .paste (im ,mask = im .split ()[- 1 ]) 3690im = bg 3691elif im .mode != "RGB" : 3692im = im .convert ("RGB" ) 3693out = io .BytesIO () 3694im .save (out ,format = "PNG" ) 3695return out .getvalue () 3696 3697def encode_all (self ,sources :list ,cancel = None )-> list [tuple [Path ,int ]]: 3698"""encode() for every image of one request: the files of this request's earlier images are never evicted to 3699make room for a later one (#1072: with more than 64 unique images the first was deleted before the request 3700had read it). `cancel` (#1999): a request whose client left does not encode its next pictures.""" 3701out :list [tuple [Path ,int ]]= [] 3702for src in sources : 3703if cancel is not None and cancel .is_set (): 3704raise ClientGone () 3705out .append (self .encode (src ,keep = [p for p ,_ in out ])) 3706return out 3707 3708def encode (self ,source :str | bytes ,keep = ())-> tuple [Path ,int ]: 3709"""-> (embeddings file, number of image tokens). `source`: what load() reads, or the image's bytes. 3710`keep`: files the caller still needs (never evicted by this call).""" 3711data = self .normalize (source if isinstance (source ,bytes )else self .load (source )) 3712key = hashlib .sha256 (data ).hexdigest ()[:32 ] 3713with self .lock : 3714self ._ensure_dir () 3715if key in self .cache : 3716self .cache [key ]= self .cache .pop (key )# most recently used last 3717return self .cache [key ] 3718if self .proc is None or self .proc .stdin is None :# an elastic encoder not started yet, or one that was unloaded 3719raise ValueError ("the picture reader is not running" ) 3720img ,out = self .dir / f" { key } .img" ,self .dir / f" { key } .sve" 3721img .write_bytes (data ) 3722try : 3723self .proc .stdin .write (f"ENC { img . name } { out . name } \n" )# relative to the encoder's cwd (#480) 3724self .proc .stdin .flush () 3725try : 3726line = self ._readline (VISION_ENCODE_S ,"the image could not be read" ).strip () 3727except RuntimeError as e :# silent for VISION_ENCODE_S: the encoder was ended (#1317) 3728self .stopped = True # alive() is False, so the next request starts it again 3729raise ValueError (str (e ))from None 3730finally :# #352: also when the encoder's pipe is gone 3731img .unlink (missing_ok = True ) 3732if not line .startswith ("OK" ): 3733raise ValueError ("the image could not be read: " + (line [4 :]if line .startswith ("ERR" )else 3734"the vision encoder stopped" )) 3735self .cache [key ]= (out ,int (line .split ()[1 ])) 3736self .warn_if_over_limit (self .cache [key ][1 ]) 3737held = {str (p )for p in keep }| {str (out )} 3738for old in list (self .cache ):# oldest first, but never one still in use 3739if len (self .cache )<= 64 : 3740break 3741if str (self .cache [old ][0 ])not in held : 3742self .cache .pop (old )[0 ].unlink (missing_ok = True ) 3743return self .cache [key ] 3744 3745def warn_if_over_limit (self ,tokens :int )-> None : 3746"""I7: one picture that became more than 4 times the limit is logged with the numbers, so the next report has them (the reader's own 3747stderr has the warm-up line). A reader built before the limit was enforced inside it (strata-vision refuses these now) still lets them by.""" 3748limit = getattr (self ,"max_tokens" ,0 ) 3749if limit and tokens > 4 * limit : 3750f"[strata] images: one picture became { tokens } image tokens, more than 4 times the limit of { limit } (vision.max_tokens); " 3751"the picture reader is not applying its limit. Update the engine, and send the line 'strata-vision: warmed up at N image " 3752"tokens' from the reader's log with the report" ,flush = True ) 3753 3754def close (self ): 3755proc ,self .proc = self .proc ,None 3756if proc is None : 3757self .stopped = True 3758return 3759try : 3760proc .stdin .write ("QUIT\n" ) 3761proc .stdin .flush () 3762proc .wait (timeout = 10 ) 3763except Exception : 3764try : 3765proc .kill () 3766except OSError : 3767pass 3768try : 3769proc .wait (timeout = 10 ) 3770except (OSError ,subprocess .TimeoutExpired ): 3771pass 3772self .stopped = True 3773 3774def shutdown (self ): 3775"""#914: close() for good: the server ends, so the encoder's directory (one ~10 MB .sve per image, on a tmpfs 3776/tmp that is RAM) goes with it instead of piling up with every start. unload() keeps it for the restart.""" 3777self .close () 3778shutil .rmtree (self .dir ,ignore_errors = True ) 3779 3780 3781def gpu_list (cfg :dict )-> list [int ]: 3782"""The config's "gpu": one card (2), or several for a layer split ([0, 2] or "0,2"), numbered as nvidia-smi 3783numbers them; [] when it names none.""" 3784roles ,_ = gpu_roles .saved_roles (cfg )# "gpu_roles" (Main / Helper / Off per card) wins unless "gpu" was edited by hand 3785if roles is not None : 3786legacy = _gpu_numbers (cfg .get ("gpu" )) 3787return legacy if legacy else gpu_roles .engine_order (roles )# Main LAST; Off cards left out; [] when every card is Off 3788return _gpu_numbers (cfg .get ("gpu" )) 3789 3790 3791def _gpu_numbers (g )-> list [int ]: 3792if g is None or g == "" : 3793return [] 3794items = g if isinstance (g , (list ,tuple ))else str (g ).split ("," ) 3795return [int (str (x ).strip ())for x in items if str (x ).strip ()!= "" ] 3796 3797 3798def gpu_roles_active (cfg :dict )-> bool : 3799"""True when the run settings carry usable "gpu_roles": the card order is the person's (Main last), never re-sorted by speed.""" 3800return gpu_roles .saved_roles (cfg )[0 ]is not None 3801 3802 3803def gpu_all_off (cfg :dict )-> bool : 3804"""Every card is set to Off ("gpu_roles" with no card on, or "gpu_none": true).""" 3805roles ,_ = gpu_roles .saved_roles (cfg ) 3806return roles is not None and not any (r != "off" for r in roles .values ()) 3807 3808 3809def card_roles_lines (cfg :dict )-> list [str ]: 3810"""The plain lines printed at start: the roles (cards numbered as nvidia-smi numbers them), a hand-edited "gpu" that beat them, and the 3811all-Off case. SystemExit when every card is Off and the engine cannot start without one (the CUDA, HIP and SYCL engines).""" 3812roles ,problem = gpu_roles .saved_roles (cfg ) 3813out = [f"[strata] { problem } " ]if problem else [] 3814if roles is None : 3815return out 3816if gpu_all_off (cfg ): 3817if cfg .get ("backend" )in ("cpu" ,"metal" )or sys .platform == "darwin" : 3818out .append ("[strata] every graphics card is Off: " + gpu_roles .CPU_ONLY_LINE ) 3819return out 3820raise SystemExit ("[strata] every graphics card is set to Off, and this engine cannot start without one. Turn a card on " 3821"(Main or Helper) in the app or with strata launch --gpu-roles." ) 3822word = {"main" :"Main" ,"helper" :"Helper" ,"off" :"Off" } 3823out .append ("[strata] card roles: " + ", " .join (f" { word [ r ] } GPU { i } " for r in ("main" ,"helper" ,"off" ) 3824for i in sorted (roles )if roles [i ]== r )+ " (numbers as nvidia-smi gives them)" ) 3825return out 3826 3827 3828def engine_binary (exe :str ,cfg :dict | None = None )-> str : 3829"""The file that holds the engine's own option strings, for a feature check that reads it. The Intel launcher 3830(sycl/serve/strata-sycl.sh) is a shell script that runs its repo's STRATA_SYCL_BIN (default build-sycl-aot/strata) 3831in a container, so the check reads that binary, not the script. Any other `exe` is the engine itself.""" 3832p = Path (exe ) 3833if p .name == "strata-sycl.sh" : 3834rel = ((cfg or {}).get ("env" )or {}).get ("STRATA_SYCL_BIN" )or os .environ .get ("STRATA_SYCL_BIN" ) \ 3835or "build-sycl-aot/strata" 3836b = p .resolve ().parents [2 ]/ rel 3837if b .is_file (): 3838return str (b ) 3839return exe 3840 3841 3842def effort_end_args (cfg :dict ,exe :str ,tok )-> list [str ]| None : 3843"""#458 (opt-in): the engine arguments for "effort_position": "end" - the id of "system" as --tail-role-token, so 3844the engine checkpoints in front of the trailing effort turn - or None when the config leaves it at the top (the 3845default) or the engine is too old for it (said once; the prompt stays the default one). ValueError for a value 3846other than "start" / "end".""" 3847pos = cfg .get ("effort_position" ,"start" ) 3848if pos not in ("start" ,"end" ): 3849raise ValueError (f'"effort_position" must be "start" (the default) or "end", not { pos !r } ' ) 3850if pos == "start" : 3851return None 3852try : 3853with open (engine_binary (exe ,cfg ),"rb" )as f : 3854known = b"--tail-role-token" in f .read () 3855except OSError : 3856known = False 3857role = tok .encode ("system" ,parse_special = True ) 3858if not known or len (role )!= 1 : 3859"[strata] effort_position \"end\" needs engine 0.1.39 or newer (--tail-role-token): the reasoning " 3860"effort stays at the top of the prompt" ,flush = True ) 3861return None 3862"[strata] effort_position end: a request's non-default reasoning effort goes right before the answer, so " 3863"changing it keeps the cached conversation" ,flush = True ) 3864return ["--tail-role-token" ,str (role [0 ])] 3865 3866 3867def engine_silence_s (cfg :dict )-> float : 3868"""#481: the config's "engine_silence_s" - seconds an engine may print nothing during a request before the server 3869ends it (default ENGINE_SILENCE_S; 0 = wait forever). ValueError for anything but a number >= 0.""" 3870v = cfg .get ("engine_silence_s" ) 3871if v is None : 3872return ENGINE_SILENCE_S 3873if isinstance (v ,bool )or not isinstance (v , (int ,float ))or v < 0 : 3874raise ValueError (f'"engine_silence_s" must be a number of seconds >= 0 (0 = no limit), not { v !r } ' ) 3875return float (v ) 3876 3877 3878def layer_split_value (cfg :dict )-> str : 3879"""#644: the config's "layer_split" as the engine's --layer-split value: "auto" (the default), or the FIRST LAYER of 3880each later GPU's share - one rising number per GPU after the first, e.g. "24,36,42" for 4 GPUs (layers 0-23 on the 3881first card, 24-35, 36-41, 42 to the end) - as a string or a JSON list ([24, 36, 42]). ValueError with the format 3882and an example for anything else, such as per-card layer counts ("24,16,12,12").""" 3883v = cfg .get ("layer_split" ) 3884if v is None or (isinstance (v ,str )and v .strip ().lower ()in ("" ,"auto" )): 3885return "auto" 3886n = len (gpu_list (cfg )) 3887items = v if isinstance (v , (list ,tuple ))else str (v ).split ("," )if isinstance (v , (str ,int ))else None 3888vals = [] 3889for x in items or []: 3890try : 3891if isinstance (x ,bool )or isinstance (x ,float ): 3892raise ValueError 3893vals .append (int (str (x ).strip ())) 3894except ValueError : 3895vals = None 3896break 3897want = max (n - 1 ,1 ) 3898example = "," .join (str (round (48 * (i + 1 )/ (want + 1 )))for i in range (want )) 3899hint = (f'"layer_split" is the first layer of each later GPU, one rising number per GPU after the first ' 3900f'( { want } for { n } GPUs), not a count of layers per card - e.g. " { example } " (or [ { example . replace ( "," , ", " ) } ])' 3901f' for an even share of 48 layers, or "auto" (the default) to place them by each card\'s free VRAM' ) 3902if not vals : 3903raise ValueError (f" { hint } ; got { v !r } " ) 3904if n > 1 and len (vals )!= n - 1 : 3905raise ValueError (f" { hint } ; got { len ( vals ) } number(s) ( { v !r } ) for { n } GPUs" ) 3906if vals [0 ]< 2 or any (b <= a for a ,b in zip (vals ,vals [1 :])): 3907raise ValueError (f" { hint } ; got { v !r } , which does not rise from 2 or more" ) 3908return "," .join (str (x )for x in vals ) 3909 3910 3911def apply_ready_timeout (cfg :dict )-> None : 3912"""The config's "engine_ready_s": how long a start may take before READY (default ENGINE_READY_S, 900). A model of 300+ GB read 3913from a slow disk (DeepSeek-V4.1-Flash: setup writes 3600) needs more. ValueError for anything but a number > 0.""" 3914global ENGINE_READY_S 3915v = cfg .get ("engine_ready_s" ) 3916if v is None : 3917return 3918if isinstance (v ,bool )or not isinstance (v , (int ,float ))or not v > 0 : 3919raise ValueError (f'"engine_ready_s" must be a number of seconds above 0, not { v !r } ' ) 3920ENGINE_READY_S = float (v ) 3921 3922 3923def layer_split_of (cfg :dict )-> bool : 3924"""Several GPUs in the config are a layer split, unless the args put the later card(s) to another use: with 3925--peer-device the second card is an expert-cache tier, and the engine refuses that beside --layer-split (#665).""" 3926return len (gpu_list (cfg ))> 1 and "--peer-device" not in cfg ["args" ] 3927 3928 3929_CARD_CLASS :list = [] 3930 3931 3932def drafting_card_class ()-> str : 3933"""The class of this computer's graphics card for the drafter table (strata_control/drafting.py), looked up once.""" 3934if not _CARD_CLASS : 3935archs :list [str ]= [] 3936try : 3937from strata_control import engine_component 3938archs = list (engine_component .cuda_archs_present ())+ list (engine_component .hip_archs_present ()) 3939except Exception :# noqa: BLE001 - an unknown card is the "other" class, never an error 3940pass 3941_CARD_CLASS .append (drafting .card_class (archs )) 3942return _CARD_CLASS [0 ] 3943 3944 3945def ds4_engine_vision (cfg :dict ,engine )-> "ds4_vision.Ds4Vision | None" : 3946"""DeepSeek-V4.1's own vision tower, in the engine: on when the pack has one (pack_gguf.py --mmproj) and the 3947args do not say --vision off. None when the engine reported that its tower did not load (INFO vision=off).""" 3948args = list (cfg .get ("args" )or []) 3949opts = dict (zip (args ,args [1 :])) 3950if opts .get ("--vision" )== "off" or "--pack" not in opts : 3951return None 3952pack = opts ["--pack" ]if os .path .isabs (opts ["--pack" ])else os .path .join (cfg .get ("cwd" )or "." ,opts ["--pack" ]) 3953geo = ds4_vision .pack_geometry (pack ) 3954if geo is None : 3955return None 3956if (getattr (engine ,"info" ,None )or {}).get ("vision" )== "off" : 3957"[strata] images: OFF - the engine's vision tower did not load (see its log)" ,flush = True ) 3958return None 3959f"[strata] images: DeepSeek's vision tower in the engine (up to { geo . get ( 'vision.max_image_tokens' ) } " 3960"tokens a picture)" ,flush = True ) 3961return ds4_vision .Ds4Vision (geo ,Vision .work_dir (),Vision .load ) 3962 3963 3964def drafting_vram_mib (cfg :dict ,backend :str | None ,archs )-> float | None : 3965"""MiB of graphics memory of the ONE card DFlash2 would run on, for the drafter's confidence (drafting.expected_slots); None for several cards, a 3966chip that shares the computer's memory (Strix Halo, the Spark: their experts are all "resident") or a card the driver does not answer for.""" 3967try : 3968gl = gpu_list (cfg ) 3969arch = str ((list (archs or ["" ])or ["" ])[0 ]).lower () 3970if len (gl )> 1 or arch in HIP_IGPU_ARCHS or arch == "sm_121" : 3971return None 3972got = gpu_vram_mib (gl or [0 ],hip = (backend == "hip" )) 3973return float (next (iter (got .values ())))if got else None 3974except Exception :# noqa: BLE001 - an unreadable card keeps the plain 0.35, never stops a start 3975return None 3976 3977 3978def own_path_context_warning (cfg :dict ,args :list ,vram_mib :float | None )-> str | None : 3979"""The sentence for a Qwen3.6 start whose --max-context does not fit its one card (strata_control/own_path_fit.py, the rule setup's menu 3980uses); None for any other model, a context that fits, or a card that is not known. Nothing about the start changes.""" 3981try : 3982from strata_control import own_path_fit 3983fit = own_path_fit .from_model_name (cfg .get ("model_name" )) 3984if not fit or not vram_mib or "--max-context" not in args : 3985return None 3986ctx = int (args [args .index ("--max-context" )+ 1 ]) 3987return own_path_fit .warning (fit ,float (vram_mib )/ 1024 ,ctx ,own_path_fit .MENU ) 3988except Exception :# noqa: BLE001 - an estimate that fails says nothing; the engine still says what does not fit 3989return None 3990 3991 3992def mtp_retry_args (cfg :dict ,exe :str | None ,extra :list [str ]| None = None )-> list [str ]| None : 3993"""The arguments to start again with when an Auto start that picked DFlash2 ends before the engine is ready: the same start with the MTP (or no drafter, when 3994the MTP layer is not on this computer). None when there is nothing to retry: the person named DFlash2 themselves (that start fails with its reason, as it 3995should), the choice was not DFlash2, or the MTP arguments are the same. Builds the arguments without any line or note (engine_args announce=False).""" 3996if drafting .normalize (cfg .get ("drafting" ))!= "auto" or "args" not in cfg : 3997return None 3998try : 3999first = engine_args (cfg ,exe ,announce = False ) 4000if "--draft" not in first or first [first .index ("--draft" )+ 1 :first .index ("--draft" )+ 2 ]!= ["dflash2" ]: 4001return None 4002alt = engine_args ({** cfg ,"drafting" :"mtp" },exe ,announce = False )+ list (extra or []) 4003except Exception :# noqa: BLE001 - a retry that cannot be worked out is no retry 4004return None 4005return alt if alt != first + list (extra or [])else None 4006 4007 4008def nodraft_retry_args (cfg :dict ,exe :str | None ,extra :list [str ]| None = None )-> list [str ]| None : 4009"""The arguments to start again with when an Auto start ends before the engine is ready because a card ran out of memory: the same start with no drafter 4010(the draft layer and DFlash2's buffers are the biggest optional part on a card that is short), never the MTP in place of DFlash2. None when the drafting 4011was not Auto (the person named a drafter: that start fails with the engine's reason), when the first start has no drafter anyway, or when nothing differs.""" 4012if drafting .normalize (cfg .get ("drafting" ))!= "auto" or "args" not in cfg : 4013return None 4014try : 4015first = engine_args (cfg ,exe ,announce = False ) 4016if "--draft" not in first and "--mtp" not in first : 4017return None 4018alt = engine_args ({** cfg ,"drafting" :"off" },exe ,announce = False )+ list (extra or []) 4019except Exception :# noqa: BLE001 - a retry that cannot be worked out is no retry 4020return None 4021return alt if alt != first + list (extra or [])else None 4022 4023 4024def engine_args (cfg :dict ,exe :str | None = None ,* ,announce :bool = True )-> list [str ]: 4025"""The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in the 4026config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32"; see 4027layer_split_value). `exe` is the engine program that will start: the drafter's flags follow what that program takes 4028(strata_control/drafting.py engine_form). `announce=False` builds the arguments without the "[strata] drafting" lines 4029and without leaving a note for the next engine start (the retry arguments of mtp_retry_args).""" 4030args = list (cfg ["args" ]) 4031# "user_args" (strata_control/user_args.py): the options the person set by hand, over the generated ones at every start, 4032# so a setup run or the app rewriting "args" cannot undo them (#3216 #3215 #3270) 4033if cfg .get ("user_args" ): 4034args = user_args .merge (args ,cfg ["user_args" ]) 4035# "drafting": auto | mtp | dflash2 | off (strata_control/drafting.py; the Models screen and `strata launch --drafting` write it): which drafter 4036# guesses ahead. ONE drafter per run: DFlash2 alone (no --mtp, --draft-fallback none) or the MTP alone (no DFlash2 option). Auto is DFlash2 where the engine 4037# has it, on one card and on a layer split over several cards. A choice that cannot be applied (no drafter file yet, several requests at once) starts the other one if it is on this computer, 4038# else none, and says why in the engine's /metrics ("drafting_note"). The start never downloads. 4039shaped = {** cfg ,"args" :args } 4040backend ,archs = drafting .detect_hardware () 4041parallel_n = cfg .get ("parallel" ) 4042decision = drafting .apply (shaped ,klass = drafting_card_class (),data_dir = drafting .data_dir_of (args ),backend = backend ,archs = archs , 4043vram_mib = drafting_vram_mib (cfg ,backend ,archs ), 4044slots = parallel_n if isinstance (parallel_n ,int )and not isinstance (parallel_n ,bool )else 0 ,engine = exe ) 4045args = shaped ["args" ] 4046if announce : 4047drafting .remember_note (decision .note ) 4048if decision .note : 4049f"[strata] { drafting . line ( decision . drafter , decision . note ) } " ,flush = True ) 4050hint = drafting .fetch_hint (decision ,model_name = cfg .get ("model_name" ),backend = backend ,archs = archs ,data_dir = drafting .data_dir_of (args ),args = args , 4051vram_mib = drafting_vram_mib (cfg ,backend ,archs )) 4052if hint : 4053f"[strata] { hint } " ,flush = True ) 4054elif decision .flags and drafting .slot_drafts_run (args ,parallel_n ,layer_split_of (cfg )): 4055f"[strata] { drafting . SLOT_DRAFTS_LINE } " ,flush = True ) 4056elif decision .flags : 4057f"[strata] drafting: DFlash2 alone ( { ' ' . join ( decision . flags [: 2 ]) } , --draft-conf { args [ args . index ( '--draft-conf' ) + 1 ] if '--draft-conf' in args else '-' } )" ,flush = True ) 4058if decision .vocab :# log only (a support log shows which draft vocabulary was used and why) 4059f"[strata] drafting: { decision . vocab } " ,flush = True ) 4060# A card that is short of VRAM for this start (a single request on a small card, or "parallel" 2 or more, every request slot a session of its own) gets work moved off 4061# the GPU, never a smaller context and never fewer requests (owner, 2026-11-02): a smaller KV window on CUDA, a smaller prompt chunk and reserve on Arc, and the 4062# engine sizes the rest; one plain note says it is slower (strata_control/vram_fit.py fit_start). The person's own values are kept. Nothing changes without one 4063# card's memory, on a layer split, or for DeepSeek. 4064try : 4065args ,fit_parallel ,fit_note = vram_fit .fit_start (cfg ,args ,drafting_vram_mib (cfg ,backend ,archs ),backend ) 4066except Exception :# noqa: BLE001 - an estimate that fails decides nothing; the engine still refuses what does not fit 4067fit_parallel ,fit_note = None ,"" 4068if fit_note and announce :# (announce=False builds the arguments without any line) 4069f"[strata] { fit_note } " ,flush = True ) 4070if announce :# #5715: Qwen3.6 with a context its card cannot hold: said before the start, nothing changed 4071too_big = own_path_context_warning (cfg ,args ,drafting_vram_mib (cfg ,backend ,archs )) 4072if too_big : 4073f"[strata] { too_big } " ,flush = True ) 4074if fit_parallel is not None : 4075cfg = {** cfg ,"parallel" :fit_parallel } 4076# "mtp": false (the Models settings, `strata launch --mtp off`, or by hand): no draft layer, whatever the args say. A setup run 4077# that writes --mtp back into the args cannot undo it, because this is applied at every start. (A DFlash2 start keeps its own --mtp DIR, which only names 4078# the vocabulary for an engine that takes it that way.) 4079if draft_layer .is_off (cfg )and not decision .flags : 4080args ,removed = draft_layer .strip (args ) 4081if removed : 4082f'[strata] "mtp": false - starting without the draft layer ( { " " . join ( removed ) } left out)' ,flush = True ) 4083# #1322: a config with a "vision" section but without --vision in its args (written by an older setup run, or edited by 4084# hand) advertised images and then refused every picture ("this engine was started without --vision"). The section 4085# says images are wanted: start the engine with them, and keep the encoder's VRAM free as setup does for a GPU encoder 4086# (only when the config has no reserve of its own). 4087if isinstance (cfg .get ("vision" ),dict )and "--vision" not in args : 4088args .append ("--vision" ) 4089note = "added --vision" 4090if cfg ["vision" ].get ("gpu" )and "--vram-reserve-mib" not in args : 4091args += ["--vram-reserve-mib" ,"700" ] 4092note += " and --vram-reserve-mib 700" 4093f'[strata] the config has a "vision" section but no --vision in its args: { note } (run setup again with ' 4094"--vision to write them)" ,flush = True ) 4095if layer_split_of (cfg )and "--layer-split" not in args : 4096args += ["--layer-split" ,layer_split_value (cfg )] 4097# opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV 4098if layer_split_of (cfg )and cfg .get ("split_skip_if_fits" )and "--split-skip-if-fits" not in args : 4099args .append ("--split-skip-if-fits" ) 4100# #533 (opt-in): "vram_elastic": true - the expert cache in segments, so POST /v1/vram can give VRAM back to other 4101# programs and take it back; "vram_segment_mib" sets the segment size (the engine's default: 512) 4102if cfg .get ("vram_elastic" )is True and "--vram-elastic" not in args : 4103args .append ("--vram-elastic" ) 4104seg = cfg .get ("vram_segment_mib" ) 4105if isinstance (seg ,int )and not isinstance (seg ,bool )and seg > 0 and "--vram-segment-mib" not in args : 4106args += ["--vram-segment-mib" ,str (seg )] 4107args += parallel_args (cfg ,args ) 4108args += pool_cores_args (cfg ,args ) 4109return draft_costs_args (cfg ,learned_profile_args (cfg ,args ),exe or cfg .get ("exe" )) 4110 4111 4112PARALLEL_MAX = 8 # without a layer split the engine's batch window holds at most 8 rows (kVerifyNarrowT); --batch-mtp waves more through it 4113 4114 4115SPLIT_MAX_LANES = 8 # the all-cards split engine runs 1..8 lanes (strata_control/split_engine.py MAX_LANES) 4116 4117 4118def parallel_flag_conflicts (cfg :dict )-> bool : 4119"""`--parallel N` next to the saved engine args' own --batch/--slots is refused, except for the all-cards split engine's run config (split_config's 4120"split_engine_note"): its --batch is its lane count, and "parallel" sets it (parallel_args). The app's Concurrent requests reaches the server this way.""" 4121args = cfg .get ("args" , []) 4122return ("--batch" in args or "--slots" in args )and not cfg .get ("split_engine_note" ) 4123 4124 4125def parallel_args (cfg :dict ,args :list [str ])-> list [str ]: 4126"""#465 (opt-in): "parallel": N in the config - up to N requests decode together in the engine's batch slots 4127(--batch N); more wait their turn. 1 or absent: one request at a time, as before. A value the engine cannot use 4128is said and passed on: the engine warns and adjusts (recommend, never force).""" 4129ds = (cfg .get ("arch" )or "" )== "deepseek41" 4130if cfg .get ("split_engine_note" )and "--batch" in args : 4131# the all-cards split engine: its run config carries --batch N (its lanes); "parallel" (the Terminal's --parallel, the app's Concurrent requests) sets N 4132n = cfg .get ("parallel" ) 4133if isinstance (n ,int )and not isinstance (n ,bool )and n >= 1 : 4134args [args .index ("--batch" )+ 1 ]= str (min (n ,SPLIT_MAX_LANES )) 4135return [] 4136if "--batch" in args or "--slots" in args or (ds and "--parallel" in args ): 4137return [] 4138n = cfg .get ("parallel" ) 4139if n is None or n is False : 4140return [] 4141if isinstance (n ,bool )or not isinstance (n ,int ): 4142f'[strata] "parallel" must be a whole number of requests (2.. { PARALLEL_MAX } ), not { n !r } : ignored' , 4143flush = True ) 4144return [] 4145if n <= 1 : 4146return [] 4147if ds : 4148# DeepSeek: --parallel N (the engine holds N conversations at once, each its own rings and KV in VRAM, taken out of the 4149# experts' room; their tokens are decoded together). Not --batch: that is the Qwen engine's slots. 4150# An engine package from before this flag would stop at the start on it ("unknown option"): asked of the engine itself, and said. 4151try : 4152from strata_control import dsv41_flags 4153old_engine = dsv41_flags .takes_parallel (cfg .get ("exe" ))is False 4154except Exception :# noqa: BLE001 - a probe that fails decides nothing 4155old_engine = False 4156if old_engine : 4157f'[strata] "parallel": { n } - this DeepSeek engine ( { cfg . get ( "exe" ) } ) is from before --parallel, so it answers one request at a ' 4158"time. Update the engine (strata update) to answer several at once." ,flush = True ) 4159return [] 4160if n > PARALLEL_MAX : 4161f'[strata] "parallel": { n } - the DeepSeek engine runs at most { PARALLEL_MAX } conversations at once; it will use ' 4162f" { PARALLEL_MAX } " ,flush = True ) 4163return ["--parallel" ,str (min (n ,PARALLEL_MAX ))] 4164# (on a layer split the pipelined groups each hold up to 8 slots - 16 in a HIP engine with wide windows - so more than 8 is 4165# not a limit there: the engine says how many slots it runs, INFO batch_slots) 4166if (n > PARALLEL_MAX and "--batch-mtp" not in args and os .environ .get ("STRATA_BATCH_MTP" ,"0" )in ("" ,"0" ) 4167and not layer_split_of (cfg )): 4168f'[strata] "parallel": { n } - the engine runs at most { PARALLEL_MAX } requests together; it will use ' 4169f" { PARALLEL_MAX } " ,flush = True ) 4170return ["--batch" ,str (n )] 4171 4172 4173_POOL_CORES_OK = re .compile (r"^[0-9]+(-[0-9]+(:[0-9]+)?)?(,[0-9]+(-[0-9]+(:[0-9]+)?)?)*$" ) 4174 4175 4176def pool_cores_args (cfg :dict ,args :list [str ])-> list [str ]: 4177"""Experimental, off by default: "pool_cores": "0,2,4,6" (or "2-14:2", or a list of numbers) in the config pins the CPU 4178expert workers to exactly those logical processors (--pool-cores; docs/DETAILS.md, "Which logical processors the CPU 4179workers use"). The engine warns about two entries on one core or the host's own and leaves out processors the process may 4180not use; a text this cannot read is said here and ignored (recommend, never force). An engine option already in the args wins.""" 4181value = cfg .get ("pool_cores" ) 4182if value is None or value is False or value == "" or value == []: 4183return [] 4184if "--pool-cores" in args : 4185return [] 4186if isinstance (value ,list )and value and all (isinstance (v ,int )and not isinstance (v ,bool )and v >= 0 for v in value ): 4187text = "," .join (str (v )for v in value ) 4188elif isinstance (value ,str ): 4189text = value .replace (" " ,"" ) 4190else : 4191text = "" 4192if not _POOL_CORES_OK .match (text ): 4193f'[strata] "pool_cores" must be logical processor numbers like "0,2,4,6" or "2-14:2", not { value !r } : ignored ' 4194"(the CPU workers keep their default placement)" ,flush = True ) 4195return [] 4196return ["--pool-cores" ,text ] 4197 4198 4199def profile_shape (path :str )-> tuple [int ,int ]| None : 4200"""An expert profile's (layers, experts per layer), from its header (tools/make_profile.py's format), or None 4201when the file is missing, is not one or is shorter than the pairs its header promises.""" 4202try : 4203with open (path ,"rb" )as f : 4204head = f .read (24 ) 4205size = os .fstat (f .fileno ()).st_size 4206except OSError : 4207return None 4208if len (head )< 24 or head [:4 ]!= b"STRP" : 4209return None 4210_ ,nl ,ne ,_ ,n = struct .unpack ("<5I" ,head [4 :]) 4211return (nl ,ne )if size >= 24 + 4 * n else None 4212 4213 4214def learned_profile_args (cfg :dict ,args :list [str ])-> list [str ]: 4215"""#477 (opt-in): "expert_profile_save": "<path>" in the config has the engine (0.1.36+) save what its adaptive 4216tier learned there - on QUIT and every "expert_profile_save_every" minutes (10 by default, 0 = at QUIT only) - 4217and the next start begins from it instead of the config's --expert-profile, when it is a profile of the same 4218model (its header's layers and experts match); otherwise from the config's own, as before. A relative path is 4219the engine's (the config's "cwd"). Without the key, the arguments are the config's, unchanged.""" 4220save = cfg .get ("expert_profile_save" ) 4221if not isinstance (save ,str )or not save .strip ()or "--expert-profile-save" in args : 4222return args 4223args = args + ["--expert-profile-save" ,save ] 4224every = cfg .get ("expert_profile_save_every" ) 4225if isinstance (every , (int ,float ))and not isinstance (every ,bool )and every >= 0 : 4226args += ["--expert-profile-save-every" ,str (every )] 4227if "--expert-profile" in args [:- 1 ]: 4228i = args .index ("--expert-profile" )+ 1 4229here = cfg .get ("cwd" )or "." 4230learned = profile_shape (save if os .path .isabs (save )else os .path .join (here ,save )) 4231base = profile_shape (args [i ]if os .path .isabs (args [i ])else os .path .join (here ,args [i ])) 4232if learned is not None and learned == base : 4233args [i ]= save 4234return args 4235 4236 4237DRAFT_COSTS_DEFAULT_PLATFORMS = ("darwin" ,)# Metal: the taken-over table measured above live costs there (M5 Max: Q2_0 code +2.6 %, chat +2.4 %, JSON +0.2 %; IQ3_S +0.2 / +0.6 / +0.7 %) 4238 4239 4240def draft_costs_default (platform :str | None = None )-> bool : 4241"""Repeatable output (owner decision) is the default only where the table was measured at or above live costs: Metal. On CUDA (RTX PRO 5000, IQ3_S: code 4242-1.5 %, chat -1.5 %, JSON +1.9 % against live costs) and HIP the engine keeps live costs, as an engine started without --draft-costs does. `"draft_costs": true` 4243in a config turns the table on anywhere (tests and A/Bs), `"draft_costs": false` turns it off.""" 4244return (platform or sys .platform )in DRAFT_COSTS_DEFAULT_PLATFORMS 4245 4246 4247DRAFT_COSTS_DEFAULT = draft_costs_default ()# "draft_costs": true / false in a config overrides it 4248_engine_texts :dict = {} 4249 4250 4251def engine_has_text (exe :str ,needle :bytes )-> bool | None : 4252"""Does the engine program contain `needle` (an option it knows)? None when it cannot be read. Read once per path, size and time.""" 4253import mmap 4254try : 4255st = os .stat (exe ) 4256except (OSError ,ValueError ): 4257return None 4258key = (str (exe ),st .st_size ,st .st_mtime_ns ,needle ) 4259if key not in _engine_texts : 4260try : 4261with open (exe ,"rb" )as handle ,mmap .mmap (handle .fileno (),0 ,access = mmap .ACCESS_READ )as data : 4262_engine_texts [key ]= data .find (needle )>= 0 4263except (OSError ,ValueError ): 4264_engine_texts [key ]= None 4265return _engine_texts [key ] 4266 4267 4268def draft_costs_dir ()-> Path : 4269"""Where the learned draft cost tables live: beside the saved tunings (strata_control/presets.py), in the user's Strata settings folder 4270(%APPDATA%\\Strata\\draft-costs, ~/.config/strata/draft-costs), which the Windows uninstaller's "remove my data" deletes with them. 4271STRATA_DRAFT_COSTS_DIR: another folder (tests and test jobs, which never write into a real settings folder).""" 4272explicit = os .environ .get ("STRATA_DRAFT_COSTS_DIR" ) 4273if explicit : 4274return Path (explicit ).expanduser () 4275from strata_control import profiles 4276return profiles .profile_dir ().parent / "draft-costs" 4277 4278 4279def draft_costs_args (cfg :dict ,args :list [str ],exe :str | None = None )-> list [str ]: 4280"""Repeatable output: the engine (0.1.60+ with --draft-costs) fixes its draft window costs to a table it learned once on this computer, so 4281the same request gives the same answer on every start; until the table exists it learns it in the background with today's policy. 4282"draft_costs": true / false in the config overrides DRAFT_COSTS_DEFAULT. The file name follows the model and every engine argument, so 4283another model or setting gets its own table; the engine itself checks the card, the driver and its own version inside the file and 4284learns again when they changed. An engine that does not know the flag is not given it.""" 4285explicit = "draft_costs" in cfg 4286want = cfg .get ("draft_costs" ,DRAFT_COSTS_DEFAULT ) 4287if want is not True or "--draft-costs" in args : 4288return args 4289knows = engine_has_text (exe ,b"--draft-costs" )if exe else None 4290# by default only an engine that is seen to have the option gets it; a config that asks for it by name gets it unless the engine is seen without it 4291if knows is False or (not explicit and knows is not True ): 4292return args 4293name = re .sub (r"[^A-Za-z0-9._-]+" ,"-" ,str (cfg .get ("model_name" )or "model" ))[:64 ] 4294digest = hashlib .sha256 ("\0" .join (map (str ,args )).encode ("utf-8" ,"replace" )).hexdigest ()[:12 ] 4295out = args + ["--draft-costs" ,str (draft_costs_dir ()/ f" { name } - { digest } .costs" )] 4296try : 4297size = os .path .getsize (exe )if exe else None 4298except OSError : 4299size = None 4300if size : 4301out += ["--draft-costs-key" ,f"engine file { size } bytes" ] 4302return out 4303 4304 4305def hip_visible (cfg :dict )-> list [int ]: 4306"""AMD: the devices the engine should see, as the HIP runtime numbers them (HIP_VISIBLE_DEVICES). 4307 4308On Linux setup's KFD order is HIP's order, so the config's "gpu" is it. On Windows setup finds the cards in the 4309display-adapter order, and an integrated Radeon that HIP also enumerates takes ordinal 0 and pushes the discrete 4310card to 1 (#325): setup records the ordinal `strata-device --list-devices` gave the card as "hip_ordinal", which 4311wins for a one-card config. Without it (a config from before), the config's "gpu".""" 4312ordinal = cfg .get ("hip_ordinal" ) 4313if ordinal is not None and str (ordinal ).strip ()!= "" and len (gpu_list (cfg ))<= 1 : 4314try : 4315return [int (str (ordinal ).strip ())] 4316except ValueError : 4317pass 4318return ordered_gpus (cfg ) 4319 4320 4321def gpu_speed_scores (indices :list [int ])-> dict [int ,float ]| None : 4322"""Multiprocessors x max clock for each NVIDIA card, numbered as nvidia-smi numbers them (the CUDA driver API, 4323which every driver ships: no toolkit needed); None when it cannot say for every one of them.""" 4324code = ( 4325"import ctypes,sys,os\n" 4326"os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'\n" 4327"lib=ctypes.CDLL('nvcuda.dll' if os.name=='nt' else 'libcuda.so.1')\n" 4328"assert lib.cuInit(0)==0\n" 4329"n=ctypes.c_int()\n" 4330"assert lib.cuDeviceGetCount(ctypes.byref(n))==0\n" 4331"for i in range(n.value):\n" 4332" d=ctypes.c_int()\n" 4333" assert lib.cuDeviceGet(ctypes.byref(d),i)==0\n" 4334" sm=ctypes.c_int(); mhz=ctypes.c_int()\n" 4335" lib.cuDeviceGetAttribute(ctypes.byref(sm),16,d)\n" 4336" lib.cuDeviceGetAttribute(ctypes.byref(mhz),13,d)\n" 4337" print(i,sm.value,mhz.value)\n" ) 4338try : 4339env = dict (os .environ ) 4340env ["CUDA_DEVICE_ORDER" ]= "PCI_BUS_ID" 4341env .pop ("CUDA_VISIBLE_DEVICES" ,None ) 4342r = subprocess .run ([sys .executable ,"-c" ,code ],capture_output = True ,text = True ,timeout = 30 ,env = env ) 4343got = {} 4344for line in r .stdout .splitlines (): 4345i ,sm ,khz = (int (x )for x in line .split ()) 4346got [i ]= float (sm )* float (khz ) 4347except (OSError ,ValueError ,subprocess .SubprocessError ): 4348return None 4349return got if all (i in got and got [i ]> 0 for i in indices )else None 4350 4351 4352def hip_speed_scores (indices :list [int ],root :str = "/sys/class/kfd/kfd/topology/nodes" )-> dict [int ,float ]| None : 4353"""AMD on Linux: SIMDs x max engine clock of each card, from the KFD topology (the order setup and the engine use 4354for "gpu" there: the GPU nodes in node order). None when the files are not there (Windows, no ROCm driver).""" 4355try : 4356nodes = sorted ((int (n )for n in os .listdir (root )if n .isdigit ())) 4357except OSError : 4358return None 4359cards = [] 4360for n in nodes : 4361try : 4362with open (os .path .join (root ,str (n ),"properties" ))as fh : 4363props = dict (line .split ()for line in fh if len (line .split ())== 2 ) 4364simd ,clk = int (props .get ("simd_count" ,0 )),int (props .get ("max_engine_clk_fcompute" ,0 )) 4365except (OSError ,ValueError ): 4366continue 4367if simd > 0 : 4368cards .append (float (simd )* float (clk or 1 )) 4369got = dict (enumerate (cards )) 4370return got if all (i in got for i in indices )else None 4371 4372 4373def engine_nice (env :dict | None = None ,archs :dict [int ,str ]| None = None ,platform :str | None = None )-> int : 4374"""Linux only: the nice value the engine starts with. The engine's CPU pool spins at 100% on every physical core but one and its host 4375thread on another; with the desktop drawn by a built-in Radeon (HIP_IGPU_ARCHS: Strix Halo and the other APUs) the compositor then 4376competes with them for the CPU, which reads as a frozen screen. +5 gives the desktop its share and costs nothing when nothing else 4377runs. STRATA_ENGINE_NICE=N sets it (0 = off, also for any PC without such a chip). Not on Windows / macOS.""" 4378if not (platform or sys .platform ).startswith ("linux" ): 4379return 0 4380asked = (env or os .environ ).get ("STRATA_ENGINE_NICE" ) 4381if asked is not None and str (asked ).strip ()!= "" : 4382try : 4383return max (0 ,min (19 ,int (str (asked ).strip ()))) 4384except ValueError : 4385return 0 4386ar = archs if archs is not None else hip_gpu_archs () 4387return 5 if ar and any (a in HIP_IGPU_ARCHS for a in ar .values ())else 0 4388 4389 4390def hip_gpu_archs (root :str = "/sys/class/kfd/kfd/topology/nodes" )-> dict [int ,str ]| None : 4391"""AMD on Linux: {HIP ordinal: "gfx1151"} from the KFD topology (GPU nodes in node order, as hip_speed_scores and setup number them). 4392None when the files are not there (Windows, no ROCm driver).""" 4393try : 4394nodes = sorted (int (n )for n in os .listdir (root )if n .isdigit ()) 4395except OSError : 4396return None 4397out :dict [int ,str ]= {} 4398for n in nodes : 4399try : 4400with open (os .path .join (root ,str (n ),"properties" ))as fh : 4401props = dict (line .split ()for line in fh if len (line .split ())== 2 ) 4402ver ,simd = int (props .get ("gfx_target_version" ,0 )),int (props .get ("simd_count" ,0 )) 4403except (OSError ,ValueError ): 4404continue 4405if simd > 0 and ver > 0 : 4406out [len (out )]= f"gfx { ver // 10000 } {( ver // 100 ) % 100 :x } { ver % 100 :x } " 4407return out or None 4408 4409 4410def igpu_cards (indices :list [int ],archs :dict [int ,str ]| None )-> set [int ]: 4411"""The cards of `indices` that are integrated (their memory is the system RAM, and they usually draw the desktop).""" 4412return {i for i in indices if archs and archs .get (i )in HIP_IGPU_ARCHS } 4413 4414 4415def gpu_vram_mib (indices :list [int ],hip :bool = False )-> dict [int ,int ]| None : 4416"""Total VRAM of each card in MiB (NVML / amdgpu sysfs); None when any of them cannot be read.""" 4417try : 4418from serve .telemetry import gpu_reader 4419except ImportError : 4420return None 4421out = {} 4422for i in indices : 4423g = gpu_reader (i ,amd = hip ) 4424if not g .ok (): 4425return None 4426total = g .read ().get ("mem_total" ) 4427if total is None : 4428return None 4429out [i ]= int (total )>> 20 4430return out 4431 4432 4433def ordered_gpus (cfg :dict ,scores = None ,vrams = None ,archs = None )-> list [int ]: 4434"""#1352: the cards of a layer split in the order the engine stages them. With "layer_split": "auto" (the 4435default) the faster card goes LAST - the last stage runs the head, the draft layer and the verify, and a prompt 4436chunk waits on it (the reporter's 4070 Ti SUPER + 5060 Ti: a 6K prompt took 50 s one way round and 15 s the 4437other); "faster" is multiprocessors x max clock. Equal cards - scores within 5% - keep the config's order, and 4438so does anything we cannot measure. "gpu_order": "as_given" keeps the config's order whatever the cards. A 4439manual "layer_split" ("24") also keeps it: the user placed the layers. #1576: the reorder is skipped when it 4440would land the last stage on a card with less total VRAM than the one the config put there - that stage's head, 4441draft and verify have a floor the smaller card cannot afford. scores/vrams: {index: value} (tests); None asks 4442the driver - injected scores without injected vrams means no VRAM check (a test seam is a test seam).""" 4443gl = gpu_list (cfg ) 4444if len (gl )< 2 or cfg .get ("gpu_order" )== "as_given" or gpu_roles_active (cfg ): 4445return gl 4446args = cfg .get ("args" )or [] 4447if "--peer-device" in args or "--layer-split" in args or layer_split_value (cfg )!= "auto" : 4448return gl 4449hip = cfg .get ("backend" )== "hip" 4450if hip : 4451# An integrated Radeon (Strix Halo beside an R9700) is never the LAST stage: that stage runs the head, the draft layer and the 4452# check of the guesses, and the iGPU usually draws the desktop. Its "VRAM" is the BIOS carve-out (up to 96 GB), which made the 4453# #1576 memory guard below keep it last. It goes first, the cards with memory of their own follow in speed order. 4454# archs: {index: "gfx1151"} (tests); None asks the KFD topology, unless scores were injected (a test seam). 4455ar = archs if archs is not None else (hip_gpu_archs ()if scores is None else None ) 4456ig = igpu_cards (gl ,ar ) 4457if ig and len (ig )< len (gl ): 4458sc0 = scores if scores is not None else hip_speed_scores (gl ) 4459rest = [i for i in gl if i not in ig ] 4460if sc0 and all (i in sc0 for i in rest ): 4461rest = sorted (rest ,key = lambda i :sc0 [i ])if max (sc0 [i ]for i in rest )>= 1.05 * min (sc0 [i ]for i in rest )else rest 4462out = [i for i in gl if i in ig ]+ rest 4463if out != gl : 4464f"[strata] layer split: card order { ',' . join ( map ( str , out )) } (GPU { ',' . join ( str ( i ) for i in sorted ( ig )) } is built-in " 4465f"graphics: it takes the first layers, never the last stage; \"gpu_order\": \"as_given\" keeps { ',' . join ( map ( str , gl )) } )" , 4466flush = True ) 4467return out 4468sc = scores if scores is not None else (hip_speed_scores (gl )if hip else gpu_speed_scores (gl )) 4469if not sc or any (i not in sc for i in gl ): 4470return gl 4471# the decision itself (5% rule #1760, faster card last #1352, VRAM guard #1576) is strata_control/gpu_roles.speed_stage_order, which `strata launch --plan` 4472# calls too (gpu_roles.from_legacy), so the plan names the same Main card as this start 4473out ,why ,seen = gpu_roles .speed_stage_order ( 4474gl ,sc ,vrams if vrams is not None else (None if scores is not None else (lambda :gpu_vram_mib (gl ,hip )))) 4475if why == "kept-vram" : 4476f"[strata] layer split: keeping card order { ',' . join ( map ( str , gl )) } - the faster card has " 4477f"less VRAM than the one the split ends on ( { seen [ 0 ] } vs { seen [ 1 ] } MiB, #1576)" , 4478flush = True ) 4479elif why == "faster-last" : 4480f"[strata] layer split: card order { ',' . join ( map ( str , out )) } (the faster card last; " 4481f'"gpu_order": "as_given" keeps { "," . join ( map ( str , gl )) } , #1352)' ,flush = True ) 4482return out 4483 4484 4485#: AMD chips that share the system memory (an iGPU): never preferred over a card that has memory of its own. 4486HIP_IGPU_ARCHS = ("gfx1035" ,"gfx1036" ,"gfx1037" ,"gfx1103" ,"gfx1150" ,"gfx1151" ,"gfx1152" ,"gfx90c" ) 4487 4488 4489def parse_hip_devices (text :str )-> list [dict ]: 4490"""`strata-device --list-devices`: [{"index", "name", "arch", "vram_gb", "integrated", "cannot_run"}], numbered as the HIP runtime numbers them.""" 4491found :list [dict ]= [] 4492for line in text .splitlines (): 4493s = line .strip () 4494m = re .match (r"device\s+(\d+):\s*(.*)$" ,s ) 4495if m : 4496found .append ({"index" :int (m .group (1 )),"name" :m .group (2 ).strip (),"arch" :"" ,"vram_gb" :0.0 ,"integrated" :False ,"cannot_run" :None }) 4497continue 4498if not found : 4499continue 4500a = re .match (r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB(.*)$" ,s ) 4501if a and not found [- 1 ]["arch" ]: 4502found [- 1 ]["arch" ],found [- 1 ]["vram_gb" ]= a .group (1 ),float (a .group (2 )) 4503found [- 1 ]["integrated" ]= "integrated" in a .group (3 )# a newer engine says so itself 4504elif s .startswith ("cannot run:" ): 4505found [- 1 ]["cannot_run" ]= s [len ("cannot run:" ):].strip () 4506for d in found : 4507d ["integrated" ]= d ["integrated" ]or d ["arch" ]in HIP_IGPU_ARCHS 4508return found 4509 4510 4511def hip_no_card_message (devices :list [dict ])-> str : 4512"""The plain line when the engine has code for none of the computer's cards.""" 4513cards = ", " .join (f" { d [ 'name' ] or 'graphics card' } ( { d [ 'arch' ] or 'unknown' } { ', integrated' if d [ 'integrated' ] else '' } )" for d in devices ) 4514built = next ((m .group (1 )for d in devices for m in [re .search (r"compiled for \(([^)]*)\)" ,d ["cannot_run" ]or "" )]if m ),"" ) 4515text = f"[strata] none of this computer's graphics cards has code in this Strata engine { f' (it is built for { built } )' if built else '' } . Cards found: { cards } ." 4516note = engine_component .no_package_note ([d ["arch" ]for d in devices ]) 4517return text + (f" { note } " if note else "" ) 4518 4519 4520def pick_hip_devices (devices :list [dict ])-> tuple [list [int ]| None ,str | None ]: 4521"""Which card an "Automatic" start runs on: (HIP_VISIBLE_DEVICES to set, or None to leave the runtime's own order; a plain problem or 4522None). Cards this engine has no code for are skipped, and so are integrated chips while a card of its own can run (#3203: a mini PC's 4523Radeon 760M is HIP's device 0 and the engine died on it; the RX 6800 XT behind it was never tried). When device 0 is already the right 4524kind nothing changes.""" 4525if not devices : 4526return None ,None 4527runnable = [d for d in devices if not d ["cannot_run" ]] 4528if not runnable : 4529return None ,hip_no_card_message (devices ) 4530pool = [d for d in runnable if not d ["integrated" ]]or runnable 4531if devices [0 ]in pool : 4532return None ,None 4533best = max (pool ,key = lambda d : (round (d ["vram_gb" ]),- d ["index" ])) 4534return [best ["index" ]],None 4535 4536 4537def hip_auto_devices (cfg :dict ,env :dict )-> list [int ]| None : 4538"""HIP_VISIBLE_DEVICES for a start that names no card (see pick_hip_devices), asked of the engine package's own `strata-device`. 4539None leaves everything as it was: a card the config or the environment names, no probe next to the engine, or a probe that fails. 4540SystemExit with the plain line when no card of this computer can run.""" 4541if cfg .get ("backend" )!= "hip" or gpu_list (cfg )or gpu_all_off (cfg )or str (cfg .get ("hip_ordinal" )if cfg .get ("hip_ordinal" )is not None else "" ).strip () \ 4542or env .get ("HIP_VISIBLE_DEVICES" )or env .get ("ROCR_VISIBLE_DEVICES" ): 4543return None 4544exe = cfg .get ("exe" ) 4545if not isinstance (exe ,str )or not exe or engine_component .is_reference (exe ): 4546return None 4547probe = Path (exe ).with_name ("strata-device.exe" if os .name == "nt" else "strata-device" ) 4548if not probe .is_file (): 4549return None 4550try : 4551done = subprocess .run ([str (probe ),"--list-devices" ],capture_output = True ,text = True ,timeout = 60 ,cwd = str (probe .parent ),env = env , 4552creationflags = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 )) 4553except (OSError ,subprocess .SubprocessError ): 4554return None 4555if done .returncode != 0 : 4556return None 4557devices = parse_hip_devices (done .stdout ) 4558visible ,problem = pick_hip_devices (devices ) 4559if problem : 4560raise SystemExit (problem ) 4561if visible : 4562d = next (x for x in devices if x ["index" ]== visible [0 ]) 4563f"[strata] automatic GPU choice: GPU { d [ 'index' ] } ( { d [ 'name' ] } , { d [ 'arch' ] } ); the engine skips cards it has no code for and " 4564f"integrated chips while a card of its own can run" ,flush = True ) 4565return visible 4566 4567 4568DS41_SLOT_KEEP_DEFAULT = "1" # the engine keeps a displaced conversation in RAM and in the slot folder (see below) 4569DS41_SLOT_GB_DEFAULT = "2" # the folder's cap in GB (a 6.5K-token conversation is about 17 MB) 4570 4571 4572def deepseek_slot_env (env :dict ,cfg :dict )-> None : 4573"""DeepSeek-V4.1 only. The engine sets a conversation aside when another request takes the model and takes it back 4574at its checkpoints (agents and sub-agents that take turns do not read their prompts again). STRATA_DS4_SLOT_KEEP 4575switches it (the default above; a config's env or the shell wins); the folder is `ds4-slots` next to the run log, in 4576Strata's data folder (STRATA_DS4_SLOT_DIR names another), and the engine caps it (STRATA_DS4_SLOT_GB, 2 here, 16 in the engine) and 4577removes what is older than a week or not this model's. On by default; STRATA_DS4_SLOT_KEEP=0 turns it off.""" 4578env .setdefault ("STRATA_DS4_SLOT_KEEP" ,DS41_SLOT_KEEP_DEFAULT ) 4579env .setdefault ("STRATA_DS4_SLOT_GB" ,DS41_SLOT_GB_DEFAULT ) 4580log = cfg .get ("log" ) 4581if "STRATA_DS4_SLOT_DIR" not in env and log : 4582env ["STRATA_DS4_SLOT_DIR" ]= str (Path (log ).parent / "ds4-slots" ) 4583 4584 4585# 0.2.10: the two parts that need the card's free VRAM are the ENGINE's own, never an environment variable of ours: the FP16 weight 4586# cache (bit-exact; takes only VRAM beyond 3 GiB kept free) and no loan of cache slots (only when every expert is resident and the 4587# prompt path's own buffers fit beside 3 GiB; KL 0.006, QUAL-PAR2). STRATA_PF_W16_CACHE_MIB=0 and STRATA_AUTO_NOBORROW=0 turn them off. 4588# (The parallel-request stack, the GDN prompt speedups, the Q8_0 hyper-connection read and the fp16 decode windows are the engine's own defaults now: 4589# src/core/arch_defaults.cpp, generate.cpp, metal window.cpp. Nothing here sets them.) 4590 4591 4592def parallel_slots (cfg :dict )-> int : 4593"""How many batch slots the config asks for (0 = none): the args' own --batch/--slots, else "parallel".""" 4594args = list (cfg .get ("args" )or []) 4595for k in ("--batch" ,"--slots" ): 4596if k in args : 4597try : 4598return int (args [args .index (k )+ 1 ]) 4599except (IndexError ,ValueError ): 4600return 0 4601n = cfg .get ("parallel" ) 4602return n if isinstance (n ,int )and not isinstance (n ,bool )and n > 1 else 0 4603 4604 4605def child_env (cfg :dict ,* ,offline :bool = False )-> dict : 4606"""The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that 4607compiled it) first on the library search path.""" 4608env = quiet_crash_env (dict (os .environ ))# no debugger on a user's machine: ggml's abort path forks gdb (strata_control/childenv.py) 4609if gpu_all_off (cfg ):# every card Off: the engine sees none (a CPU engine runs; the others say so at start) 4610env ["CUDA_VISIBLE_DEVICES" ]= "" 4611env ["HIP_VISIBLE_DEVICES" ]= "" 4612elif hip_visible (cfg )and cfg .get ("backend" )== "hip" :# AMD: numbered as HIP numbers them (hip_visible) 4613env ["HIP_VISIBLE_DEVICES" ]= "," .join (str (i )for i in hip_visible (cfg )) 4614elif gpu_list (cfg ):# issue #51: the GPU(s) to run on, numbered as nvidia-smi does; CUDA's 4615env ["CUDA_DEVICE_ORDER" ]= "PCI_BUS_ID" # own default order (fastest first) can number the cards otherwise 4616env ["CUDA_VISIBLE_DEVICES" ]= "," .join (str (i )for i in ordered_gpus (cfg )) 4617for k ,v in (cfg .get ("env" )or {}).items ():# engine settings the config carries (AMD: the GEMM tuning table) 4618env [str (k )]= str (v ) 4619if (cfg .get ("arch" )or "" )== "deepseek41" :# (only this engine reads these; Qwen's environment is untouched) 4620deepseek_slot_env (env ,cfg ) 4621# Strict offline reaches children through the environment, because a tool subprocess or a model 4622# loader is code this server does not own. Applied last so a profile's own `env` cannot remove 4623# the policy by naming the same variable. 4624if offline : 4625try : 4626from strata_control import offline as offline_policy 4627env .update (offline_policy .OFFLINE_ENV ) 4628except ImportError : 4629# The policy module is part of the application; without it, refuse rather than silently 4630# running a child with network access under a flag that promised otherwise. 4631env ["STRATA_OFFLINE" ]= "1" 4632env ["HF_HUB_OFFLINE" ]= "1" 4633env ["TRANSFORMERS_OFFLINE" ]= "1" 4634dirs = [d for d in cfg .get ("lib_dirs" )or []if Path (d ).is_dir ()] 4635if dirs : 4636var = "PATH" if os .name == "nt" else "LD_LIBRARY_PATH" 4637env [var ]= os .pathsep .join (dirs + ([env [var ]]if env .get (var )else [])) 4638if cfg .get ("backend" )== "hip" : 4639hip_env_guard (env ,cfg ) 4640note = sh_stream_warning (env ,cfg ) 4641if note : 4642note ,flush = True ) 4643auto = hip_auto_devices (cfg ,env ) 4644if auto : 4645env ["HIP_VISIBLE_DEVICES" ]= "," .join (str (i )for i in auto ) 4646return env 4647 4648 4649def _dir_writable (p :str )-> bool : 4650try : 4651with tempfile .TemporaryFile (dir = p ): 4652return True 4653except OSError : 4654return False 4655 4656 4657def sh_stream_warning (env :dict ,cfg :dict )-> str | None : 4658"""#3895: the shared-expert fork (STRATA_SH_STREAM=1) together with KV streaming (--kv-resident) made one Windows RX 6900 XT fail on the first 4659request ("verify: unspecified launch failure"); each alone, or Linux, did not. A warning, not a refusal: the person set the variable, the 4660engine runs as asked, and the line says what to take out.""" 4661if os .name != "nt" or str (env .get ("STRATA_SH_STREAM" ,"" )).strip ()in ("" ,"0" ): 4662return None 4663args = [str (a )for a in cfg .get ("args" )or []] 4664if "--kv-resident" not in args : 4665return None 4666return ("[strata] WARNING: STRATA_SH_STREAM=1 with --kv-resident (KV streaming) failed on the first request on one Windows RX 6000 PC " 4667"(\"verify: unspecified launch failure\", #3895). If the engine stops that way, take STRATA_SH_STREAM out of the config's env " 4668"(AMD runs without it by default) or run without --kv-resident, and tell us the card and the driver." ) 4669 4670 4671def hip_env_guard (env :dict ,cfg :dict )-> list [str ]: 4672"""#654: two things in an AMD user's environment that crash the HIP runtime before it prints a line. (1) HIP_PATH, 4673HIP_DEVICE_LIB_PATH or LLVM_PATH naming a folder that is gone (a ROCm build that was deleted): the bundled runtime 4674follows them. They are dropped, and only when the folder does not exist. (2) A TEMP / TMP / TMPDIR the engine cannot 4675create a file in: the runtime's comgr JIT builds its blit kernels through temporary files and the first call 4676crashes in amdhip64 (0xC0000005). A writable folder next to the engine's log takes its place. Returns what it 4677changed (said once, on stderr); a healthy environment is left exactly as it was.""" 4678said :list [str ]= [] 4679for k in ("HIP_PATH" ,"HIP_DEVICE_LIB_PATH" ,"LLVM_PATH" ): 4680v = env .get (k ) 4681if v and not Path (v ).exists (): 4682del env [k ] 4683said .append (f" { k } = { v } does not exist: not passed to the engine" ) 4684bad = [k for k in ("TEMP" ,"TMP" ,"TMPDIR" )if env .get (k )and not _dir_writable (env [k ])] 4685if bad : 4686base = Path (cfg .get ("log" )or cfg .get ("cwd" )or ROOT ).resolve () 4687for d in (base .parent / "tmp" ,ROOT / "tmp" ): 4688try : 4689d .mkdir (parents = True ,exist_ok = True ) 4690except OSError : 4691continue 4692if _dir_writable (str (d )): 4693for k in bad : 4694said .append (f" { k } = { env [ k ] } is not writable: using { d } " ) 4695env [k ]= str (d ) 4696break 4697else : 4698said .append (f" { ', ' . join ( bad ) } not writable (AMD's runtime needs a writable temporary folder)" ) 4699for line in said : 4700f"strata serve: AMD: { line } " ,file = sys .stderr ,flush = True ) 4701return said 4702 4703 4704def igpu_split_warning (cfg :dict ,archs :dict [int ,str ]| None = None )-> str | None : 4705"""A plain line when the layers are split over built-in Radeon graphics AND a card with memory of its own. A recommendation, not a 4706refusal: the split runs as asked. The iGPU's memory is the RAM, it usually draws the desktop, and compute on it can freeze the screen.""" 4707if cfg .get ("backend" )!= "hip" : 4708return None 4709gl = gpu_list (cfg ) 4710if len (gl )< 2 : 4711return None 4712ar = archs if archs is not None else hip_gpu_archs () 4713ig = igpu_cards (gl ,ar ) 4714if not ig or len (ig )== len (gl ): 4715return None 4716return ("[strata] note: GPU " + ", " .join (str (i )for i in sorted (ig ))+ " is built-in graphics (its memory is the system RAM, and it " 4717"usually draws the desktop). Running part of the model on it can freeze the screen and uses RAM twice; the cards with memory of " 4718"their own are faster alone (docs/STRIX_HALO.md). Turn it Off in the card roles, or name only the other card, to leave it out" ) 4719 4720 4721def card_note (cfg :dict ,env :dict )-> str | None : 4722"""One plain line that ties the engine's own numbering to the person's: the engine counts the cards it is given from 0 ("GPU 0", 4723"CUDA0" in its log), so a person who chose GPU 1 would read "GPU 0" and think the choice was lost. Said only when the two differ 4724(NVIDIA, numbered as nvidia-smi numbers them); None otherwise.""" 4725if cfg .get ("backend" )== "hip" or not gpu_list (cfg ): 4726return None 4727mine = [x .strip ()for x in str ((env or {}).get ("CUDA_VISIBLE_DEVICES" ,"" )).split ("," )if x .strip ()!= "" ] 4728if not mine or mine == [str (i )for i in range (len (mine ))]: 4729return None 4730names = [f"CUDA { i } " for i in range (len (mine ))] 4731if len (mine )== 1 : 4732return f"[strata] running on GPU { mine [ 0 ] } (as nvidia-smi numbers it); the engine's log calls it GPU 0 / CUDA0" 4733return (f"[strata] cards in stage order: GPU { ', then GPU ' . join ( mine ) } (as nvidia-smi numbers them); the engine's log calls them " 4734f" { ', ' . join ( names ) } - the first runs the first layers and the picture reader, the last runs the head and the draft layer" ) 4735 4736 4737def engine_arch_note (cfg :dict ,cards :dict [int ,int ]| None = None ,built :dict | None = None )-> str | None : 4738"""#4662: a compiled engine holds code for the architectures it was built for (BUILD.json "archs"); on a card of another one a long prompt 4739ends in "unspecified launch failure" (the kernels it needs are a trap there). One plain line when a card this run uses is not covered 4740(NVIDIA; a build with PTX also covers newer cards). Said, never refused: the engine is started as asked. `cards`: {nvidia-smi number: 4741compute capability x 10}; `built`: the BUILD.json dict - both read here when not given. None when everything is covered or unknown.""" 4742try : 4743if cfg .get ("backend" )== "hip" : 4744return None 4745if built is None : 4746exe = cfg .get ("exe" ) 4747if not isinstance (exe ,str )or engine_component .is_reference (exe ): 4748return None 4749built = json .loads ((Path (exe ).parent / "BUILD.json" ).read_text (encoding = "utf-8-sig" )) 4750archs = sorted ({int (re .sub (r"\D" ,"" ,str (a )))for a in built .get ("archs" )or []if re .sub (r"\D" ,"" ,str (a ))}) 4751if not archs : 4752return None 4753if cards is None : 4754r = subprocess .run (["nvidia-smi" ,"--query-gpu=index,compute_cap" ,"--format=csv,noheader" ],capture_output = True ,text = True , 4755errors = "replace" ,timeout = 10 ) 4756cards = {int (i ):int (round (float (c )* 10 ))for i ,c in (ln .split ("," )for ln in (r .stdout or "" ).strip ().splitlines ())} 4757used = gpu_list (cfg )or sorted (cards ) 4758miss = sorted ({cards [i ]for i in used if i in cards and cards [i ]not in archs and not (built .get ("ptx" )and cards [i ]> max (archs ))}) 4759if not miss : 4760return None 4761names = ", " .join (f"sm_ { m } " for m in miss ) 4762return (f"[strata] this engine was built for { ', ' . join ( f'sm_ { a } ' for a in archs ) } , but a graphics card in use is { names } : long prompts " 4763"can stop with \"unspecified launch failure\". Update the engine (./update.sh, or `strata update`) so it is built for every card in this PC." ) 4764except Exception : 4765return None 4766 4767 4768def vision_card_off_igpu (env :dict ,archs :dict [int ,str ]| None = None )-> int | None : 4769"""AMD: the picture reader is a separate program that sees the engine's HIP_VISIBLE_DEVICES and runs on the FIRST visible card. With a 4770layer split that starts on a built-in Radeon (Strix Halo beside an R9700) that is the iGPU: the card that draws the desktop and whose 4771memory is the RAM the experts live in. Returns the HIP ordinal of the last visible card with memory of its own (the Main stage), or 4772None when nothing needs changing (one card, no integrated chip among them, or the topology is unknown).""" 4773vis = [x .strip ()for x in str (env .get ("HIP_VISIBLE_DEVICES" )or "" ).split ("," )if x .strip ().isdigit ()] 4774if len (vis )< 2 : 4775return None 4776idx = [int (x )for x in vis ] 4777ar = archs if archs is not None else hip_gpu_archs () 4778ig = igpu_cards (idx ,ar ) 4779own = [i for i in idx if i not in ig and ar and i in ar ] 4780if not ig or not own : 4781return None 4782f"[strata] the picture reader runs on GPU { own [ - 1 ] } , not on the built-in graphics (GPU { ',' . join ( str ( i ) for i in sorted ( ig )) } ) " 4783"that draws the desktop; \"vision\": {\"cuda_device\": N} chooses another card" ,flush = True ) 4784return own [- 1 ] 4785 4786 4787def vision_env (cfg :dict ,env :dict ,archs :dict [int ,str ]| None = None )-> dict : 4788"""The image encoder's environment: the engine's, unless the config's vision section names its own "cuda_device" 4789(numbered like nvidia-smi) - then the encoder runs on that card alone, so a spare GPU can hold it while the engine 4790keeps all of its own cards' VRAM (#408, Efs-O). Without it, nothing changes.""" 4791dev = (cfg .get ("vision" )or {}).get ("cuda_device" ) 4792if dev is None and cfg .get ("backend" )== "hip" : 4793dev = vision_card_off_igpu (env ,archs ) 4794if dev is None : 4795return env 4796env = dict (env ) 4797if cfg .get ("backend" )== "hip" : 4798env ["HIP_VISIBLE_DEVICES" ]= str (dev ) 4799else : 4800env ["CUDA_DEVICE_ORDER" ]= "PCI_BUS_ID" 4801env ["CUDA_VISIBLE_DEVICES" ]= str (dev ) 4802return env 4803 4804 4805class ByteTokenizer : 4806"""Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256.""" 4807SPECIALS = ["<|im_start|>" ,"<|im_end|>" ,"<|endoftext|>" ,"<|vision_start|>" ,"<|image_pad|>" ,"<|vision_end|>" ] 4808 4809ALWAYS = ()# specials matched without parse_special (type 4, as <think>) 4810 4811@property 4812def max_special_len (self ): 4813return max (len (s )for s in self .SPECIALS ) 4814 4815@property 4816def control_tokens (self ): 4817return [s for s in self .SPECIALS if s not in self .ALWAYS ] 4818 4819def encode (self ,text ,parse_special = False ,plain = ()): 4820return self .encode_marked (text ,parse_special ,plain )[0 ] 4821 4822def encode_marked (self ,text ,parse_special = False ,plain = ()): 4823"""encode() and its resume points (after each special), as strata_tokenizer's for PromptEncoder.""" 4824out ,marks ,i = [], [],0 4825while i < len (text ): 4826for k ,s in enumerate (self .SPECIALS ): 4827if (parse_special or s in self .ALWAYS )and text .startswith (s ,i )and not any ( 4828a <= i < b for a ,b in plain ): 4829out .append (256 + k ) 4830i += len (s ) 4831marks .append ((i ,len (out ))) 4832break 4833else : 4834out .extend (text [i ].encode ("utf-8" )) 4835i += 1 4836return out ,marks 4837 4838def decode (self ,ids ,errors = "replace" ): 4839raw = bytearray () 4840for t in ids : 4841raw += self .SPECIALS [t - 256 ].encode ()if t >= 256 else bytes ([t ]) 4842return raw .decode ("utf-8" ,errors = errors ) 4843 4844 4845# ------------------------------------------------------------------------------------------------ end tokens 4846def end_token_ids (tokenizer )-> set [int ]: 4847"""The ids that end a reply for a tokenizer whose family was not named (Service.set_family sets them for DeepSeek). 4848 4849Qwen's <|im_end|> and <|endoftext|> end a reply only where each is ONE token. A tokenizer without them (DeepSeek-V4.1's 4850splits "<|im_end|>" into '<', '|', 'im', '_end', '|', '>') would make every piece of them a stop id: the reply ended in front 4851of the first "|", ">", "end", "of", "text" or "im" it wrote, so "Nerazim" came out as "Neraz" (#4576, and a table's first 4852"|" in #4137). Those ids are left out, and the end token the tokenizer names (special_ids "eos") ends the reply instead.""" 4853ids :set [int ]= set () 4854for marker in (IM_END ,"<|endoftext|>" ): 4855got = tokenizer .encode (marker ,parse_special = True ) 4856if len (got )== 1 : 4857ids .add (int (got [0 ])) 4858if not ids : 4859eos = (getattr (tokenizer ,"special_ids" ,None )or {}).get ("eos" ) 4860if eos is not None : 4861ids .add (int (eos )) 4862return ids 4863 4864 4865# ------------------------------------------------------------------------------------------------ core 4866class Detokenizer : 4867"""Incremental decode: each token's bytes go through an incremental UTF-8 decoder, which emits the complete 4868characters and holds a multi-byte character split across tokens until it is complete (invalid bytes become 4869U+FFFD, as a whole decode with errors="replace" makes them). Constant time per token - the old re-decode of 4870every generated id cost 2 ms per token after 8K tokens and 4 ms after 16K (perf-review F-1). A tokenizer 4871without `token_bytes` (the tests' byte tokenizer) keeps the re-decode.""" 4872 4873def __init__ (self ,tok ): 4874self .tok ,self .ids ,self .sent = tok , [],0 4875self .inc = codecs .getincrementaldecoder ("utf-8" )(errors = "replace" )if hasattr (tok ,"token_bytes" )else None 4876 4877def pending (self )-> bool : 4878"""A character is split across the tokens so far: its first bytes are held.""" 4879if self .inc is not None : 4880return bool (self .inc .getstate ()[0 ]) 4881return self .tok .decode (self .ids ).endswith ("\ufffd" ) 4882 4883def push (self ,t :int )-> str : 4884if self .inc is not None : 4885return self .inc .decode (self .tok .token_bytes (t )) 4886self .ids .append (t ) 4887text = self .tok .decode (self .ids ) 4888if text .endswith ("�" ): 4889return "" 4890delta ,self .sent = text [self .sent :],len (text ) 4891return delta 4892 4893 4894OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop` 4895 4896 4897#: What a request may ask for that the all-cards split engine cannot do (its GEN parser has no such keys): answered with a 400 before anything is sent, not with an error in 4898#: the middle of a reply. logit_bias is refused the same way by logit_bias.validate_request (the split engine does not report logit_bias=1). 4899SPLIT_REFUSED_FEATURES = ("logprobs" ,"logit_bias" ) 4900 4901 4902def refuse_for_split (engine ,req :dict )-> None : 4903if not getattr (engine ,"split_engine" ,False ): 4904return 4905if top_logprobs (req )is not None : 4906raise ValueError ("logprobs: not supported by the all-cards split engine; start with --split-engine off" ) 4907 4908 4909def top_logprobs (req :dict ): 4910"""The K for the engine's logprobs=K, or None when the request did not ask. 4911 4912OpenAI: "logprobs": true with "top_logprobs" 0..20; the legacy completions form, 4913"logprobs": N, is taken as N.""" 4914lp = req .get ("logprobs" ) 4915if lp is True : 4916k = req .get ("top_logprobs" ) 4917return max (0 ,min (20 ,k ))if isinstance (k ,int )and not isinstance (k ,bool )else 0 4918if isinstance (lp ,int )and not isinstance (lp ,bool )and lp >= 0 : 4919return min (20 ,lp ) 4920return None 4921 4922 4923def allowed_ids (req :dict )-> list : 4924"""`allowed_token_ids`: the ids a caller named, or [] (vLLM's semantics, see LogprobEntries).""" 4925ids = req .get ("allowed_token_ids" ) 4926if not isinstance (ids , (list ,tuple )): 4927return [] 4928return [x for x in ids if isinstance (x ,int )and not isinstance (x ,bool )and x >= 0 ] 4929 4930 4931def batch_slots_on (engine )-> bool : 4932"""Does this engine run requests in batch slots ("parallel", whose `BT` lines carry no LP lines)? 4933 4934Asked of each engine behind a ReplicaEngine: its own `batch` is how many requests it can run at once, so it 4935counts a replica without slots as one (serve/replicas.py) -- a server with `--replicas 2` and no `--parallel` 4936has none, and reads every reply by the GEN path, which does write them.""" 4937return any (int (getattr (e ,"batch" ,0 )or 0 )for e in (getattr (engine ,"engines" ,None )or [engine ])) 4938 4939 4940NO_LINE = object ()# StrataEngine.generate: no line held after a token 4941 4942 4943def stop_strings (req :dict )-> list [str ]: 4944"""The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences` 4945(a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated.""" 4946req = req or {} 4947if req .get ("stop" )is not None : 4948stop = req ["stop" ] 4949stop = [stop ]if isinstance (stop ,str )else stop 4950if not isinstance (stop ,list )or not all (isinstance (x ,str )for x in stop ): 4951raise ValueError ("stop must be a string or a list of strings" ) 4952if len (stop )> OPENAI_MAX_STOP : 4953raise ValueError (f"stop takes at most { OPENAI_MAX_STOP } strings" ) 4954elif req .get ("stop_sequences" )is not None : 4955stop = req ["stop_sequences" ] 4956if not isinstance (stop ,list )or not all (isinstance (x ,str )for x in stop ): 4957raise ValueError ("stop_sequences must be a list of strings" ) 4958else : 4959return [] 4960return [x for x in stop if x ] 4961 4962 4963class StopMatcher : 4964"""Cuts the answer's text at the first stop string. Text that could still be the start of a stop string is held 4965back (only that tail, never more), so a stop string split across tokens or chunks is still found and never sent.""" 4966 4967def __init__ (self ,stops :list [str ]): 4968self .stops ,self .held ,self .hit = stops ,"" ,None 4969 4970def push (self ,text :str )-> str : 4971"""-> the text that is safe to send now; after a match, self.hit is the stop string and nothing more comes.""" 4972if self .hit is not None : 4973return "" 4974buf = self .held + text 4975first = None 4976for s in self .stops : 4977i = buf .find (s ) 4978if i >= 0 and (first is None or i < first [0 ]): 4979first = (i ,s ) 4980if first is not None : 4981self .held ,self .hit = "" ,first [1 ] 4982return buf [:first [0 ]] 4983keep = 0 # the longest end of buf that a stop string starts with 4984for s in self .stops : 4985for k in range (min (len (s )- 1 ,len (buf )),keep ,- 1 ): 4986if buf .endswith (s [:k ]): 4987keep = k 4988break 4989self .held = buf [len (buf )- keep :]if keep else "" 4990return buf [:len (buf )- keep ] 4991 4992def flush (self )-> str : 4993held ,self .held = self .held ,"" 4994return held 4995 4996 4997 4998# Windows names that open a device whatever their extension or folder (Microsoft, "Naming Files, Paths, and Namespaces") 4999_WIN_DEVICES = {"con" ,"prn" ,"aux" ,"nul" ,"conin$" ,"conout$" ,* (f"com { i } " for i in "123456789\u00b9\u00b2\u00b3" ), 5000* (f"lpt { i } " for i in "123456789\u00b9\u00b2\u00b3" )} 5001 5002 5003def slot_filename_problem (name )-> str | None : 5004"""/slots/0 {"filename": NAME}: why NAME is not one plain file name inside the slot save path, on Linux and on 5005Windows alike (None when it is). No separator or drive (`D:x`), no stream (`a:b`), no device (`NUL.txt`), no 5006trailing dot or space (Windows drops them), no control character, no leading dot (temporary files use it).""" 5007if not isinstance (name ,str )or not name : 5008return "must be a non-empty string" 5009if len (name .encode ("utf-8" ,"surrogatepass" ))> 200 : 5010return "is too long (at most 200 bytes)" 5011if any (ord (c )< 32 or ord (c )== 127 for c in name ): 5012return "must not contain control characters" 5013if any (c in name for c in '/\\:*?"<>|' ): 5014return "must be a plain file name (no / \\ : * ? \" < > |)" 5015if name .startswith ("." ): 5016return "must not start with a dot" 5017if name .endswith (("." ," " )): 5018return "must not end with a dot or a space" 5019if name .split ("." )[0 ].rstrip (" " ).lower ()in _WIN_DEVICES : 5020return "names a Windows device" 5021try : 5022name .encode ("utf-8" ) 5023except UnicodeEncodeError : 5024return "is not valid Unicode" 5025return None 5026 5027 5028def slot_save_dir (value ,base :str | None = None )-> str : 5029"""The slot save path as one absolute, normalized directory (relative to `base`, else the server's working 5030directory), created private to this user when missing. ValueError for anything else.""" 5031if not isinstance (value ,str )or not value .strip (): 5032raise ValueError ("slot_save_path must be a directory path (a string)" ) 5033if any (ord (c )< 32 for c in value ): 5034raise ValueError ("slot_save_path must not contain control characters" ) 5035path = os .path .abspath (os .path .join (base ,value )if base and not os .path .isabs (value )else value ) 5036os .makedirs (path ,mode = 0o700 ,exist_ok = True ) 5037if not os .path .isdir (path ): 5038raise ValueError (f"slot_save_path { path } is not a directory" ) 5039return path 5040 5041class Service : 5042def __init__ (self ,engine :Engine ,tokenizer ,template :ChatTemplate ,model_name :str = "qwen3.8-flash-next" , 5043vision :Vision | None = None ,sampling_defaults :dict | None = None , 5044fit_max_tokens :bool = True ): 5045self .engine ,self .tok ,self .template ,self .model ,self .vision = engine ,tokenizer ,template ,model_name ,vision 5046self .literals = literal_tags (getattr (tokenizer ,"control_tokens" , ()))# texts that stay text inside a message 5047self .fit_max_tokens = fit_max_tokens # default: clamp the output cap to the room left; False (--no-fit-max-tokens) = 400 5048self .aliases :list [str ]= []# #297: other names of the model (the config's `aliases`) 5049self .answer_room = True # 0.1.45: see ANSWER_ROOM_MIN_CAP (the config's "answer_room": false turns it off) 5050self .reasoning_close_retry = False # #1053 (opt-in): close the thinking once when a reply ends inside it 5051self .codex_compaction_cache = False # #924 (opt-in): a Codex compaction is rendered with its conversation's tools 5052self .codex_thread_titles = False # #923 (opt-in): answer Codex's thread-title turns without the engine 5053self .sampling_defaults = dict (sampling_defaults or {})# the run config's `sampling` block 5054self .model_arch = None # the config's family ("qwen4exp", "qwen35moe"): None = no model-card defaults 5055self .shared = {}# the web app's Chat settings for every client (POST /settings) 5056self .shared_path = None # where they are kept between starts (next to the config) 5057self .config_effort = None # #1641: the config's "reasoning_effort": the level for requests with none 5058self .keep_awake = None # #1727 (opt-in): serve.keepawake.KeepAwake, the config's "prevent_sleep" 5059self .fifo = threading .Lock () 5060self .slot_save_path = None # --slot-save-path: /slots/0?action=save|restore (off when None) 5061self .embeddings = threading .local ()# the current request's image embeddings file (GENI) 5062self .api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) 5063# #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system 5064# turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation 5065self .effort_end = False 5066self .conv_log = ConvCacheLog ()# #596: the parked conversations, from the engine's log 5067self .config_path = None # #564: the run config the web page's Settings view edits 5068self .config_lock = threading .Lock () 5069# #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that 5070# matters); empty = no CORS headers at all, as before 5071self .cors_origins :list [str ]= [] 5072# #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a 5073# reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard 5074self .trusted_origins :list [str ]= [] 5075# DNS rebinding: extra Host names this server answers to (the config's allowed_hosts, $STRATA_ALLOWED_HOSTS; 5076# "*" = any), and every name it answers to, which serve() works out from the address it listens on 5077self .allowed_hosts :list [str ]= [] 5078self .host_names :set [str ]= set (LOOPBACK_NAMES ) 5079self .status = {"busy" :False ,"queued" :0 }# GET /status: what the model is doing right now 5080self .rate = collections .deque (maxlen = 32 )# (time, generated) samples for the live tok/s window 5081# "parallel" (the engine's batch slots): every running request's own status and rate window; self.status 5082# then says busy while any runs and shows the newest one 5083self .live_reqs :dict [int ,tuple [dict ,collections .deque ]]= {} 5084# Privacy-safe correlation for terminal telemetry. No prompts, client identity or tool text is stored. 5085self .terminal_requests :dict [str ,dict ]= {} 5086self .terminal_events = collections .deque (maxlen = 128 )# fixed-shape request transitions only 5087self .terminal_event_seq = 0 5088# HTTP admission is reserved before generation or SSE headers. This bounds pending inference calls even 5089# while a model is loading or a request is between MCP rounds; the engine's own slots remain unchanged. 5090self .max_queue :int | None = None 5091self .queue_timeout_s :float | None = None 5092self .admission_reserved = 0 5093self .admission_rejected = 0 5094self .queue_timeouts = 0 5095self .client_disconnect_cancels = 0 5096self .draining = False 5097self .active_cancels :set [threading .Event ]= set () 5098# #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory, 5099# so it is off unless the config's "api_monitor" (or --api-monitor) turns it on 5100self .api_monitor = False 5101self .api_requests = collections .deque (maxlen = 100 )# bounded I/O in memory; no headers or API keys 5102self .request_trace = threading .local () 5103self .history = collections .deque (maxlen = 500 )# the last finished requests, newest last (GET /metrics) 5104# since the server started (the Monitor's totals, issue #35) 5105self .totals = {"since" :time .time (),"requests" :0 ,"prompt_tokens" :0 ,"reused" :0 ,"output_tokens" :0 , 5106"prompt_ms" :0.0 ,"decode_ms" :0.0 , 5107"drafts_offered" :0 ,"drafts_accepted" :0 ,# #457: the MTP drafts, summed where reported 5108"scr_cached" :0 ,"scr" :0 ,"scr_prefilled" :0 }# SCR's split of the prompts (engine with SCR on) 5109self .last_timings = None # the last finished request's, llama.cpp's names (/v1/status) 5110# /metrics/prometheus' two throughput gauges need the totals as they stood at the last scrape, because 5111# llama.cpp averages them over the window between two scrapes (#2341). 5112self .scrape_bucket = (0 ,0.0 ,0 ,0.0 ) 5113from serve .prometheus import Latencies 5114self .latencies = Latencies ()# GET /metrics in Prometheus text: the latency histograms 5115self .last_request_at = None # when a request last started or finished 5116self .started_at = time .time () 5117self .instance_id = uuid .uuid4 ().hex 5118self .status_lock = threading .Lock () 5119self .admission_changed = threading .Condition (self .status_lock ) 5120self .mcp = None # serve/mcp.py's McpHub when MCP servers are configured 5121self .offline = False # no image URL fetch or MCP subprocess in strict local mode 5122self .telemetry_key = "" # optional read-only key, valid only on /v1/telemetry 5123# sharing the GPU with other programs (all off by default): unload the engine after this many idle seconds, 5124# only start it again when this much VRAM is free, and run this command first (e.g. to unload another 5125# server's model); the next request after an unload starts the engine again 5126self .idle_unload_s = 0 5127self .min_free_vram_mib = 0 5128self .before_load = None 5129self .before_load_timeout_s = 120.0 # #1997: how long the before_load command may run 5130self .before_load_ignore_failure = False # #1997: load even when it fails, without a VRAM check 5131self .vram_free_wait_s = 15.0 # how long a full card is waited on (memory given back) 5132self .before_load_strict = False # #1997: refuse (503) whenever it fails 5133self .vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's) 5134self .vram_reserve_asked = False # a POST /v1/vram was made (vram_reserve None is then asked) 5135self .vision_held = False # an elastic encoder holds VRAM the expert cache gave it 5136self .vision_no_shrink = False # the engine said its cache never shrinks (no --vram-elastic) 5137self .vision_no_shrink_said = False 5138self .last_image_at = 0.0 # when an image turn last ended (the elastic encoder's idle) 5139self .reasoning_loop_recovery = False 5140self .reasoning_budget_configured = False # the config named reasoning_budget_tokens (0 included): no family default 5141self .reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) 5142self .repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) 5143self .thinking_loop_tokens = 0 # one token this many times in a row in the thinking closes it (0: off) 5144self .anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False 5145self .undeclared_tool_calls = "text" # #4622: config "undeclared_tool_calls": "call" hands a call of an undeclared name to the client 5146self .tool_call_recovery = True # default on (0.2.8): tool calls in forms next to the template's; config "tool_call_recovery": false turns it off 5147self .images = None # serve/images.py's ImageGen when the config has "images" 5148self .restore_after_load = None # a session file an image job saved before it unloaded 5149self .stop_ids = end_token_ids (tokenizer ) 5150self .family = None # the model family ("deepseek41"): set_family() below 5151self .parser_cls = parser_for_template (getattr (template ,"source" ,None ))# reads the model's output (reasoning, content, tool calls): by the template's tool-call form 5152# #567: a prompt re-encodes only what follows the last special token it shares with a recent prompt (the 5153# same ids as a full encode: tools/strata_tokenizer.py PromptEncoder). Tokenizers without resume points 5154# encode in full. 5155self .prompts = None 5156if hasattr (tokenizer ,"encode_marked" )and hasattr (tokenizer ,"max_special_len" ): 5157from strata_tokenizer import PromptEncoder 5158# one kept prompt per conversation the engine's cache can hold (--conversation-cache-slots); the 5159# encoder's own default without that setting 5160slots = conversation_slots (engine ) 5161self .prompts = PromptEncoder (tokenizer ,keep = slots )if slots is not None and slots > 0 \ 5162else PromptEncoder (tokenizer ) 5163 5164def set_family (self ,family :str | None )-> None : 5165"""A family whose text differs from the Qwen form this server was written for (DeepSeek-V4.1: its own end 5166token, DSML tool calls, reasoning-effort words). The others keep the defaults.""" 5167self .family = family 5168if family == "deepseek41" : 5169from serve import dsml 5170eos = (getattr (self .tok ,"special_ids" ,None )or {}).get ("eos" ,1 ) 5171self .stop_ids = {int (eos )} 5172self .parser_cls = dsml .DsmlOutputParser 5173self ._force_text = dsml .to_dsml_force 5174import serve .frontend as _frontend 5175_frontend .use_family (family ) 5176 5177_force_text = None 5178 5179def force_text (self ,force ): 5180"""forced_call's opening of the call the reply must make, in this model's spelling.""" 5181return self ._force_text (force )if self ._force_text is not None else force 5182 5183def loaded (self )-> bool : 5184return not hasattr (self .engine ,"alive" )or self .engine .alive () 5185 5186def admission_limit (self )-> int | None : 5187if self .max_queue is None : 5188return None 5189return max (1 ,int (getattr (self .engine ,"batch" ,0 )or 0 ))+ self .max_queue 5190 5191def _terminal_event_locked (self ,request_id :str ,event :str ,outcome :str | None = None )-> None : 5192"""Append one redacted transition while holding status_lock; never include request content.""" 5193if event not in ("queued" ,"admitted" ,"reading" ,"first_token" ,"finished" ,"cancelled" , 5194"disconnected" ,"timeout" ,"error" ): 5195return 5196if outcome is not None and outcome not in ("stop" ,"length" ,"cancel" ,"disconnect" ,"timeout" ,"error" ): 5197outcome = "error" 5198self .terminal_event_seq += 1 5199row = {"seq" :self .terminal_event_seq ,"at" :time .time (), 5200"request_id" :request_id ,"event" :event } 5201if outcome is not None : 5202row ["outcome" ]= outcome 5203self .terminal_events .append (row ) 5204 5205def reserve_inference (self )-> bool | None : 5206"""Reserve one bounded HTTP inference call before response headers are written.""" 5207with self .status_lock : 5208if self .draining : 5209return None 5210limit = self .admission_limit () 5211if limit is not None and self .admission_reserved >= limit : 5212self .admission_rejected += 1 5213return False 5214self .admission_reserved += 1 5215return True 5216 5217def release_inference (self )-> None : 5218with self .admission_changed : 5219self .admission_reserved -= 1 5220self .admission_changed .notify_all () 5221 5222def note_client_disconnect (self ,cancel :threading .Event )-> None : 5223"""Cancel once; count only work that was still queued or active when the client left.""" 5224with self .status_lock : 5225if not cancel .is_set (): 5226request_id = getattr (cancel ,"_strata_request_id" ,None ) 5227active = request_id in self .terminal_requests 5228cancel .set () 5229if active : 5230self .client_disconnect_cancels += 1 5231 5232@ contextlib . contextmanager 5233def _inference_fifo (self ,deadline :float | None ,cancel :threading .Event | None = None ): 5234if deadline is None : 5235with self .fifo : 5236yield 5237return 5238while True : 5239if cancel is not None and cancel .is_set (): 5240raise QueueCancelled ("the client disconnected while waiting for the engine" ) 5241left = deadline - time .monotonic () 5242if left <= 0 : 5243raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 5244if self .fifo .acquire (timeout = min (0.1 ,left )): 5245break 5246try : 5247if cancel is not None and cancel .is_set (): 5248raise QueueCancelled ("the client disconnected while waiting for the engine" ) 5249if time .monotonic ()>= deadline : 5250raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 5251yield 5252finally : 5253self .fifo .release () 5254 5255def begin_drain (self )-> int : 5256"""Stop new inference admission and return the number of owned calls to drain.""" 5257with self .admission_changed : 5258self .draining = True 5259self .admission_changed .notify_all () 5260return self .admission_reserved 5261 5262def wait_for_drain (self ,timeout :float )-> int : 5263"""Wait for reserved inference calls; return the number still in flight.""" 5264deadline = time .monotonic ()+ max (0.0 ,timeout ) 5265with self .admission_changed : 5266while self .admission_reserved : 5267left = deadline - time .monotonic () 5268if left <= 0 : 5269break 5270self .admission_changed .wait (left ) 5271return self .admission_reserved 5272 5273def cancel_owned_requests (self )-> int : 5274"""Cancel only requests admitted by this Service, never unrelated GPU work.""" 5275with self .status_lock : 5276active = list (self .active_cancels ) 5277for cancel in active : 5278cancel .set () 5279return len (active ) 5280 5281def slot_action (self ,slot :str ,action :str ,filename )-> tuple [int ,dict ]: 5282"""llama-server's POST /slots/{id}?action=save|restore {"filename": ...}: the conversation the engine holds, 5283to or from a file in slot_save_path. -> (HTTP status, body).""" 5284def error (code ,message ): 5285return code , {"error" : {"code" :code ,"message" :message , 5286"type" :"invalid_request_error" if code < 500 else "server_error" }} 5287if not self .slot_save_path or not hasattr (self .engine ,"session_file" ): 5288return error (501 ,"slot save/restore is disabled (start the server with --slot-save-path DIR)" ) 5289if getattr (self .engine ,"batch" ,0 ): 5290# #465 parallel requests do not hold the FIFO and share the engine's control lines: a session file 5291# could interleave with a request being admitted, so the two are not combined (the engine refuses too) 5292return error (501 ,"slot save/restore is not available with parallel requests (\"parallel\" / --batch)" ) 5293if slot != "0" : 5294return error (400 ,"this server has one slot: 0" ) 5295if action not in ("save" ,"restore" ): 5296return error (400 ,"action must be save or restore" ) 5297why = slot_filename_problem (filename ) 5298if why : 5299return error (400 ,f"filename { why } " ) 5300path = os .path .join (self .slot_save_path ,filename ) 5301if action == "restore" : 5302try : 5303os .lstat (path )# the engine opens it without following a link 5304except OSError : 5305return error (404 ,f"no saved session named { filename } " ) 5306self .last_request_at = time .time ()# the idle unload counts this as activity 5307with self .status_lock : 5308self .status ["queued" ]+= 1 5309waiting = True 5310try : 5311with self .fifo : 5312with self .status_lock : 5313self .status ["queued" ]-= 1 5314waiting = False 5315if not self .loaded (): 5316return error (503 ,"the model is not loaded" ) 5317with self .status_lock : 5318self .status .update (busy = True ,phase = "saving the session" if action == "save" 5319else "restoring a session" ,started = time .time (),first_token = None , 5320prompt_tokens = None ,generated = None ,max_tokens = None ) 5321try : 5322if action == 'save' and getattr (self .engine ,'session_save_reclaim' ,False ): 5323from serve .session_save_retry import session_file 5324r = session_file (self ,action ,path ,SessionRefused ) 5325else : 5326r = self .engine .session_file (action ,path ) 5327except SessionRefused as e : 5328body = error (e .status ,str (e )) 5329body [1 ]["error" ]["kind" ]= e .kind 5330if e .published : 5331body [1 ]["error" ]["published" ]= True 5332return body 5333except ValueError as e :# the request itself (an invalid command) 5334return error (400 ,str (e )) 5335finally : 5336with self .status_lock : 5337self .status ["busy" ]= False 5338self .last_request_at = time .time () 5339finally : 5340if waiting :# never reached the FIFO (an exception while waiting) 5341with self .status_lock : 5342self .status ["queued" ]-= 1 5343if action == "save" : 5344return 200 , {"id_slot" :0 ,"filename" :filename ,"n_saved" :r ["tokens" ],"n_written" :r ["bytes" ], 5345"timings" : {"save_ms" :r ["ms" ]}} 5346return 200 , {"id_slot" :0 ,"filename" :filename ,"n_restored" :r ["tokens" ],"n_read" :r ["bytes" ], 5347"timings" : {"restore_ms" :r ["ms" ]}} 5348 5349def set_aliases (self ,aliases )-> None : 5350"""#297: the config's `aliases` - a list of names (or one comma-separated string), like llama-server's --alias. 5351ValueError for anything else.""" 5352if aliases is None : 5353aliases = [] 5354if isinstance (aliases ,str ): 5355aliases = aliases .split ("," ) 5356if not isinstance (aliases ,list )or not all (isinstance (x ,str )for x in aliases ): 5357raise ValueError (f"aliases= { aliases !r } : expected a list of model names" ) 5358names = [] 5359for x in (x .strip ()for x in aliases ): 5360if x and x != self .model and x not in names : 5361names .append (x ) 5362self .aliases = names 5363 5364def model_names (self )-> list [str ]: 5365return [self .model ,* self .aliases ] 5366 5367def model_for (self ,req )-> str : 5368"""The name to answer with: the request's own when it is the model's name or an alias (#297), else the model's. 5369Other names are still served, as before.""" 5370asked = req .get ("model" )if isinstance (req ,dict )else None 5371return asked if isinstance (asked ,str )and asked in self .aliases else self .model 5372 5373def reported_ctx (self )-> int : 5374"""The context the endpoints report (/v1/status, /v1/models, /props, /health, /slots, /metrics): the engine's, 5375or the last one it reported while it restarts (max_context is 0 until READY, and a client that sizes its 5376prompt from it would send nothing, #351). Reporting only: requests are checked in prepare().""" 5377return int (getattr (self .engine ,"max_context" ,0 )or getattr (self .engine ,"known_ctx" ,0 )or 0 ) 5378 5379def reasoning_budget (self ,req )-> int | None : 5380"""#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens` (or, as 5381llama.cpp reads it, `thinking_budget_tokens`), else the config's. 0 (or less) means no budget, so a request can 5382turn a configured one off. ValueError (a 400) for anything that is not a whole number.""" 5383req = req if isinstance (req ,dict )else {} 5384value = req .get ("reasoning_budget_tokens" ) 5385if value is None :# a null does not hide the other name 5386value = req .get ("thinking_budget_tokens" ) 5387if value is None : 5388value = self .reasoning_budget_tokens 5389if not value and self .family == "deepseek41" and not self .reasoning_budget_configured : 5390value = DS41_DEFAULT_BUDGET # DeepSeek-V4.1 only, as Maya ships it: no budget anywhere = this one 5391if isinstance (value ,float )and value .is_integer (): 5392value = int (value ) 5393if isinstance (value ,bool )or not isinstance (value ,int ): 5394raise ValueError (f"reasoning_budget_tokens= { value !r } : expected a whole number of tokens (0: no budget)" ) 5395return value if value > 0 else None 5396 5397def _release_orphan_encoder (self )-> bool : 5398"""The engine is not running but its picture encoder still is (the engine died under a request; the encoder is a process of its own): stop it, 5399and its VRAM goes back, so the free-VRAM check does not count this server's own encoder as "another program" and refuse every load after 5400it, and the load that follows starts it again together with the engine (#4352). True when an encoder was stopped.""" 5401vision = self .vision 5402if vision is None or not hasattr (vision ,"alive" )or not hasattr (vision ,"unload" )or self .loaded (): 5403return False 5404try : 5405if not vision .alive (): 5406return False 5407"[strata] the engine is not running but its picture encoder is: stopping the encoder to give its memory back" ,flush = True ) 5408vision .unload () 5409self .vision_held = False 5410return True 5411except Exception as e :# noqa: BLE001 - freeing memory never turns a request into a crash 5412f"[strata] the picture encoder could not be stopped: { e } " ,flush = True ) 5413return False 5414 5415def _vision_down (self )-> bool : 5416"""The encoder should run and does not (the engine's load starts it again). An elastic encoder is down 5417between pictures by design: it starts in the image turn (_vision_up), not with the engine.""" 5418return (self .vision is not None and hasattr (self .vision ,"alive" )and not self .vision .alive () 5419and not getattr (self .vision ,"elastic" ,False )) 5420 5421def _engine_reserve (self )-> int | None : 5422"""The VRAM the engine keeps free for other programs outside an elastic encoder's turn: the last POST /v1/vram 5423reserve, or 0 when none was asked (the cache grows back to its full size; None would leave the reserve the engine 5424started with, a segment or more below the size it had).""" 5425return self .vram_reserve if self .vram_reserve_asked else 0 5426 5427def _vision_up (self ): 5428"""The image turn's start for an elastic encoder that is not running (the caller holds self.fifo): the expert 5429cache first keeps the encoder's elastic_mib of VRAM free on top of the reserve, then the encoder starts (load and 5430warm-up, a few seconds). If the cache cannot shrink (an engine without --vram-elastic, the resident low-RAM mode) 5431the encoder starts anyway, as a non-elastic one would.""" 5432v = self .vision 5433if not getattr (v ,"elastic" ,False )or v .alive (): 5434return 5435if hasattr (self .engine ,"vram" )and self .loaded ()and not self .vision_no_shrink : 5436try : 5437out = self .engine .vram ((self ._engine_reserve ()or 0 )+ v .elastic_mib ) 5438self .vision_held = True 5439f"[strata] images: the expert cache keeps { v . elastic_mib } MiB free for the image encoder " 5440f"( { out . get ( 'expert_cache_mib' ) } of { out . get ( 'expert_cache_full_mib' ) } MiB left)" ,flush = True ) 5441except ValueError as e : 5442self .vision_no_shrink = "--vram-elastic" in str (e )# an engine that never shrinks: not asked again 5443note = "" if self .vision_no_shrink and self .vision_no_shrink_said else f" ( { e } )" 5444self .vision_no_shrink_said = True 5445self ._vision_room_check (v ,note ) 5446elif self .vision_no_shrink : 5447self ._vision_room_check (v ,"" ) 5448if self .vision_held : 5449time .sleep (0.2 )# the driver's free-VRAM counter shows the cache's release a moment later 5450free0 ,t0 = self .free_vram_mib (),time .time () 5451try : 5452v .restart () 5453except Exception as e :# a 503 as for a non-elastic encoder at a load, not a dropped connection 5454raise EngineDied (f"the image encoder failed to start: { e } " )from e 5455free1 = self .free_vram_mib () 5456took = f", { free0 - free1 } MiB of VRAM" if free0 is not None and free1 is not None else "" 5457on_cpu = getattr (v ,"on_cpu" ,False ) 5458f"[strata] images: the image encoder started in { time . time () - t0 :.1f } s { ', on the CPU' if on_cpu else took } " ,flush = True ) 5459if on_cpu and self .vision_held and hasattr (self .engine ,"vram" )and self .loaded (): 5460# the CPU reader needs no VRAM: the cache takes back what it made room for 5461try : 5462self .engine .vram (self ._engine_reserve ()) 5463except ValueError as e : 5464f"[strata] images: the expert cache did not grow back ( { e } )" ,flush = True ) 5465self .vision_held = False 5466 5467def _vision_room_check (self ,v ,note :str ): 5468"""The expert cache cannot make room: the GPU reader goes into the VRAM that is free, if that is READER_NEEDS_MIB, else the 5469CPU reader reads (a picture is read right either way).""" 5470free = self .free_vram_mib () 5471need = min (v .elastic_mib ,READER_NEEDS_MIB ) 5472if free is not None and free < need and getattr (v ,"use_cpu" ,lambda :False )(): 5473f"[strata] images: only { free } MiB of VRAM is free and the GPU reader needs about { need } { note } : this picture is " 5474"read on the CPU" ,flush = True ) 5475elif note : 5476f"[strata] images: the expert cache did not make room for the image encoder { note } ; starting it anyway" ,flush = True ) 5477 5478def _vision_idle_down (self ,force :bool = False )-> str : 5479"""An elastic encoder idle for elastic_idle_s (or force) stops, and the expert cache takes its VRAM back: 5480"down", "busy" (a request holds the turn, or a picture came more recently) or "nothing" (not elastic or not 5481holding anything).""" 5482v = self .vision 5483if not getattr (v ,"elastic" ,False )or not (self .vision_held or v .alive ()): 5484return "nothing" 5485if not force and time .time ()- self .last_image_at < v .elastic_idle_s : 5486return "busy" 5487if not self .fifo .acquire (blocking = False ): 5488return "busy" 5489try : 5490v .unload () 5491back = "" 5492if self .vision_held and hasattr (self .engine ,"vram" )and self .loaded (): 5493out = self .engine .vram (self ._engine_reserve ()) 5494back = (f"; the expert cache took its VRAM back ( { out . get ( 'expert_cache_mib' ) } of " 5495f" { out . get ( 'expert_cache_full_mib' ) } MiB)" ) 5496# also when the cache never made room (a layer split, an engine without --vram-elastic): the stop happened 5497f"[strata] images: the image encoder stopped after { v . elastic_idle_s :g } s without a picture { back } " , 5498flush = True ) 5499self .vision_held = False 5500return "down" 5501finally : 5502self .fifo .release () 5503 5504def start_vision_idle (self ): 5505v = self .vision 5506if not getattr (v ,"elastic" ,False ): 5507return 5508f"[strata] images: the image encoder starts with the first picture and stops after { v . elastic_idle_s :g } s " 5509f"without one" ,flush = True ) 5510 5511def loop (): 5512while True : 5513time .sleep (max (1.0 ,min (30.0 ,v .elastic_idle_s / 4 ))) 5514try : 5515self ._vision_idle_down () 5516except Exception as e :# tried again at the next turn; the thread keeps running 5517f"[strata] images: stopping the idle image encoder: { e } " ,flush = True ) 5518threading .Thread (target = loop ,daemon = True ).start () 5519 5520def free_vram_mib (self )-> int | None : 5521"""Free VRAM on the engine's (first) GPU, from the backend's reader - NVML, the amdgpu sysfs files (#301) or 5522IOKit on macOS (Metal backend); None when it can't be read (then nothing is refused).""" 5523try : 5524from serve .telemetry import gpu_reader 5525g = gpu_reader (int (getattr (self ,"gpu_index" ,0 )or 0 ),amd = getattr (self ,"backend" ,None )== "hip" ) 5526if not g .ok (): 5527return None 5528r = g .read () 5529if r .get ("mem_total" )is None or r .get ("mem_used" )is None : 5530return None 5531return int ((r ["mem_total" ]- r ["mem_used" ])>> 20 ) 5532except Exception : 5533return None 5534 5535FATAL_GPU_MAX = 3 # fatal GPU errors of one engine within FATAL_GPU_WINDOW_S: after that it is not started again 5536FATAL_GPU_WINDOW_S = 600.0 5537 5538def _note_fatal_gpu_exit (self ,code )-> None : 5539"""#4350: the engine ends itself after a fatal GPU error (the device context cannot be used again) and says so in its last 5540ERR line. The next request starts it again, like any engine death, with one plain line here; the request that was in 5541flight already failed with a 503. Three such deaths within ten minutes mean a restart will not help (a bad card, driver or 5542model state): then the server stops starting it and says so (503), until the ten minutes have passed.""" 5543why = getattr (self .engine ,"last_err" ,None )or "" 5544if "fatal GPU error" not in why : 5545return 5546pid = getattr (getattr (self .engine ,"proc" ,None ),"pid" ,None ) 5547seen = self .__dict__ .setdefault ("_fatal_gpu_pids" ,set ()) 5548times = self .__dict__ .setdefault ("_fatal_gpu_times" , []) 5549now = time .time () 5550if pid not in seen :# one death counts once, however many requests find it dead 5551seen .add (pid ) 5552times .append (now ) 5553times [:]= [t for t in times if now - t < self .FATAL_GPU_WINDOW_S ] 5554f"[strata] the GPU reported a fatal error ( { why [ len ( 'fatal GPU error:' ):]. strip ()[: 160 ] } ); the engine ended " 5555f"(exit code { code } ) and is started again; the request that was running failed and can be sent again " 5556f"( { len ( times ) } of { self . FATAL_GPU_MAX } allowed in { self . FATAL_GPU_WINDOW_S / 60 :g } minutes)" ,flush = True ) 5557if len (times )>= self .FATAL_GPU_MAX : 5558raise EngineDied (f"the GPU reported a fatal error { len ( times ) } times in { self . FATAL_GPU_WINDOW_S / 60 :g } minutes, so " 5559"the engine is not started again (the last: " + why [:160 ]+ "). Check the graphics driver, the " 5560"card's temperature and power, and the log; a request after " 5561f" { self . FATAL_GPU_WINDOW_S / 60 :g } minutes tries again" ) 5562 5563def ensure_loaded (self ): 5564"""Start the engine if it is not running (unloaded, or it died - issue #27), after the before_load hook and 5565the free-VRAM check. The caller holds self.fifo.""" 5566if self .loaded ()and not self ._vision_down (): 5567return 5568hook_failed = None 5569if self .before_load : 5570cmd = self .before_load 5571f"[strata] before loading: { cmd if isinstance ( cmd , str ) else ' ' . join ( map ( str , cmd )) } " ,flush = True ) 5572why = None 5573try : 5574r = subprocess .run (cmd ,shell = isinstance (cmd ,str ),timeout = self .before_load_timeout_s , 5575stdin = subprocess .DEVNULL ) 5576if r .returncode != 0 : 5577why = f"it exited with code { r . returncode } " 5578except subprocess .TimeoutExpired : 5579why = f"it did not finish in { self . before_load_timeout_s :g } s (before_load_timeout_s)" 5580except (OSError ,subprocess .SubprocessError )as e : 5581why = f"it could not run ( { e } )" 5582if why is not None : 5583# #1997: a failing hook (e.g. the other server's /unload that is still busy) may mean the GPU was not 5584# given back. A peer that is simply not running also makes `curl` fail (exit 7), so the exit code alone 5585# does not refuse: the card's free VRAM decides (min_free_vram_mib, checked just below); "strict" always 5586# refuses, "ignore" always loads. 5587if self .before_load_strict and not self .before_load_ignore_failure : 5588f"[strata] the before_load command failed ( { why } ); the model stays unloaded and this " 5589"request is answered 503 - try again (before_load_strict)" ,flush = True ) 5590raise GpuBusy (f"the before_load command failed ( { why } ): the GPU was not given back, so the " 5591"model was not loaded; try again in a moment" ,retry_after = 15 ) 5592hook_failed = why 5593if self .before_load_ignore_failure or not self .min_free_vram_mib : 5594f"[strata] the before_load command failed ( { why } ); loading anyway" 5595+ ("" if self .before_load_ignore_failure else 5596" (set min_free_vram_mib to have the free VRAM checked, or before_load_strict to refuse)" ), 5597flush = True ) 5598else : 5599f"[strata] the before_load command failed ( { why } ); checking the free VRAM" ,flush = True ) 5600if self .min_free_vram_mib and not (hook_failed and self .before_load_ignore_failure ): 5601free = self .free_vram_mib () 5602if free is not None and free < self .min_free_vram_mib and self ._release_orphan_encoder (): 5603free = self .free_vram_mib ()# the encoder's share is back: the card is judged without our own process (#4352) 5604deadline = time .time ()+ self .vram_free_wait_s # memory another process just gave back can take a moment 5605while free is not None and free < self .min_free_vram_mib and time .time ()< deadline : 5606time .sleep (0.5 ) 5607free = self .free_vram_mib () 5608if free is not None and free < self .min_free_vram_mib : 5609if hook_failed and not self .before_load_ignore_failure : 5610f"[strata] the before_load command failed ( { hook_failed } ) and only { free } MiB of VRAM is " 5611f"free (the model needs { self . min_free_vram_mib } ): not loading; 503" ,flush = True ) 5612raise GpuBusy (f"the GPU is in use by another program: { free } MiB of VRAM free, the model needs " 5613f" { self . min_free_vram_mib } (min_free_vram_mib) - it stays unloaded until that is free" 5614+ (f"; the before_load command failed ( { hook_failed } )" if hook_failed else "" ), 5615retry_after = 15 ) 5616if hook_failed and not self .before_load_ignore_failure : 5617f"[strata] the before_load command failed ( { hook_failed } ), but { free } MiB of VRAM is free: " 5618"loading" ,flush = True ) 5619vision_started = False 5620if self ._vision_down ():# first, as at a start: a GPU encoder takes its VRAM before 5621"[strata] starting the vision encoder ..." ,flush = True )# the engine sizes its cache 5622try : 5623self .vision .restart () 5624except Exception as e : 5625raise EngineDied (f"the vision encoder failed to start: { e } " )from e 5626vision_started = True 5627if self .loaded (): 5628return 5629if getattr (self .engine ,"unloaded" ,False ): 5630"[strata] loading the model again (it was unloaded) ..." ,flush = True ) 5631else : 5632code = self .engine .exit_code ()if hasattr (self .engine ,"exit_code" )else None 5633self ._note_fatal_gpu_exit (code ) 5634f"[strata] the engine had stopped (exit code { code } ); starting it again " 5635"(a minute or two) ..." ,flush = True ) 5636try : 5637self .engine .restart () 5638except Exception as e : 5639if vision_started : 5640self .vision .unload () 5641# the program could not be started at all (missing, not executable, or blocked by Windows - #735): the 5642# request path answers EngineDied with a 503, but takes a bare OSError for a client that went away (#2496) 5643if isinstance (e ,OSError ): 5644raise EngineDied (f"the engine could not be started: { e } " )from e 5645raise 5646"[strata] the engine is running again" ,flush = True ) 5647if self .restore_after_load :# an image job unloaded it: its conversation comes back 5648images_api .restore_session (self ) 5649if self .vram_reserve is not None and hasattr (self .engine ,"vram" ):# #533: the reserve asked for last 5650try : 5651self .engine .vram (self .vram_reserve ) 5652except (ValueError ,EngineDied )as e : 5653f"[strata] the VRAM reserve ( { self . vram_reserve } MiB) was not applied: { e } " ,flush = True ) 5654 5655vram_wait_s = 300.0 # #533: how long POST /v1/vram waits for a running request 5656 5657def vram (self ,reserve_mib :int | None )-> dict : 5658"""#533, POST /v1/vram: keep `reserve_mib` of VRAM free for other programs (None: the reserve the engine 5659started with), applied between requests - a request that is running finishes first (up to wait_s). Only an 5660engine started with --vram-elastic (the config's "vram_elastic": true) can do it; it never resizes on its own. 5661An unloaded engine applies it when it loads. -> {"status": ..., and the engine's figures}.""" 5662if not hasattr (self .engine ,"vram" ): 5663raise ValueError ("this engine cannot resize its VRAM use" ) 5664if not self .fifo .acquire (timeout = self .vram_wait_s ): 5665raise ModelBusy ("a request is still running; try again when it has finished" ) 5666# parallel requests do not hold the fifo: the engine's control lines (a prompt being admitted) are taken too, 5667# and the engine refuses a resize while a slot decodes 5668ctl = getattr (self .engine ,"ctl" ,None )if getattr (self .engine ,"batch" ,0 )else None 5669if ctl is not None and not ctl .acquire (timeout = self .vram_wait_s ): 5670self .fifo .release () 5671raise ModelBusy ("a request is still running; try again when it has finished" ) 5672if ctl is not None : 5673self .engine ._ctl_held = True # engine.vram() below must not wait for the lines this call holds 5674try : 5675if not self .loaded (): 5676self .vram_reserve ,self .vram_reserve_asked = reserve_mib ,True 5677return {"status" :"not loaded" ,"reserve_mib" :reserve_mib , 5678"note" :"applied when the model loads" } 5679# an elastic encoder that runs keeps its VRAM on top of the asked reserve 5680out = self .engine .vram ((reserve_mib or 0 )+ self .vision .elastic_mib if self .vision_held else reserve_mib ) 5681self .vram_reserve ,self .vram_reserve_asked = reserve_mib ,True 5682f"[strata] VRAM: { out . get ( 'vram_free_mib' ) } MiB free, expert cache { out . get ( 'expert_cache_mib' ) } of " 5683f" { out . get ( 'expert_cache_full_mib' ) } MiB ( { out . get ( 'expert_slots' ) } experts)" ,flush = True ) 5684return {"status" :"ok" ,** out } 5685finally : 5686if ctl is not None : 5687self .engine ._ctl_held = False 5688ctl .release () 5689self .fifo .release () 5690 5691def _say_died (self ,e :Exception )-> None : 5692"""The server window's line for an engine that died (or was ended, #481) in the middle of a request.""" 5693note = self .engine .death_note ()if hasattr (self .engine ,"death_note" )else "" 5694log = getattr (self .engine ,"log_path" ,None ) 5695f"[strata] { e } . { note } The next request starts the engine again." 5696f" { ' Its log: ' + log if log else '' } " ,flush = True ) 5697 5698def load (self ): 5699"""POST /load and every generation request: start the engine now if it is unloaded (raises GpuBusy).""" 5700# a request is on its way: the idle thread must not unload between this and the request's own start 5701self .last_request_at = time .time () 5702if self .loaded ()and not self ._vision_down (): 5703return 5704trace = getattr (self .request_trace ,"record" ,None ) 5705waiting = time .perf_counter () 5706with self .status_lock :# #1603: waiting for the fifo to start the engine is queued, not nothing 5707self .status ["queued" ]+= 1 5708counted = True 5709try : 5710with self .fifo : 5711with self .status_lock : 5712self .status ["queued" ]-= 1 5713counted = False 5714loading = time .perf_counter () 5715if trace is not None : 5716with self .status_lock : 5717trace ["queue_s" ]+= round (loading - waiting ,3 ) 5718trace ["state" ]= "loading" 5719try : 5720self .ensure_loaded () 5721finally : 5722if trace is not None : 5723with self .status_lock : 5724trace ["load_s" ]+= round (time .perf_counter ()- loading ,3 ) 5725trace ["state" ]= "queued" 5726finally : 5727if counted : 5728with self .status_lock : 5729self .status ["queued" ]-= 1 5730 5731UNLOAD_WAIT_S = 300.0 # #1997: POST /unload?wait=1 waits this long for the running turn (wait=<s> to choose) 5732 5733def end_engine_if_unchanged (self ,born )-> bool : 5734"""End the engine after a request that ended without its end event (#3961), but only if it is still the engine process that request ran on 5735(`born`, the engine's gen) and nobody is on it: the turn is taken without waiting, and held while the engine is ended, so a request admitted 5736right after the lost one is never killed by it. A server with batch slots shares the engine between requests, so it is left alone. True when 5737the engine was ended (the next request then starts it again).""" 5738end = getattr (self .engine ,"end_for_restart" ,None ) 5739if end is None or born is None or batch_slots_on (self .engine ): 5740return False 5741if not self .fifo .acquire (blocking = False ):# the next request is already generating on it 5742return False 5743try : 5744if getattr (self .engine ,"gen" ,None )!= born :# it was ended or restarted since: that is another process 5745return False 5746end () 5747return True 5748finally : 5749self .fifo .release () 5750 5751def unload_waiting (self ,wait_s :float )-> str : 5752"""#1997: unload(), but a running or queued request is waited for (up to wait_s) instead of answering "busy": 5753a peer server that needs this GPU can then free the card on the server's terms. "busy" after wait_s.""" 5754deadline = time .monotonic ()+ max (0.0 ,wait_s ) 5755while True : 5756r = self .unload () 5757if r != "busy" or time .monotonic ()>= deadline : 5758return r 5759time .sleep (0.25 ) 5760 5761def unload (self ,idle_for :float | None = None )-> str : 5762"""Stop the engine between requests: "unloaded", "not loaded", "busy" (a request is running or waiting, or 5763with idle_for: one ran more recently than that) or "unsupported".""" 5764if not hasattr (self .engine ,"unload" ): 5765return "unsupported" 5766if not self .fifo .acquire (blocking = False ): 5767return "busy" 5768try : 5769if not self .engine .alive (): 5770self ._release_orphan_encoder ()# POST /unload gives the card back even when the engine already died (#4352) 5771return "not loaded" 5772with self .status_lock : 5773if self .status .get ("busy" )or self .status .get ("queued" ): 5774return "busy" 5775if idle_for is not None and time .time ()- (self .last_request_at or self .started_at )< idle_for : 5776return "busy" 5777self .engine .unload () 5778if self .vision is not None and hasattr (self .vision ,"unload" ): 5779self .vision .unload () 5780self .vision_held = False 5781f"[strata] model unloaded { f' after { idle_for :.0f } s idle' if idle_for else '' } ; " 5782"the next request loads it again" ,flush = True ) 5783return "unloaded" 5784finally : 5785self .fifo .release () 5786 5787def start_idle_unload (self ): 5788if not self .idle_unload_s or not hasattr (self .engine ,"unload" ): 5789return 5790f"[strata] the model unloads after { self . idle_unload_s } s without requests" ,flush = True ) 5791 5792def loop (): 5793while True : 5794time .sleep (max (1.0 ,min (30.0 ,self .idle_unload_s / 4 ))) 5795try : 5796self .unload (idle_for = self .idle_unload_s ) 5797except EngineStuck as e :# tried again at the next turn; the thread keeps running 5798f"[strata] idle unload: { e } " ,flush = True ) 5799threading .Thread (target = loop ,daemon = True ).start () 5800 5801def set_shared (self ,defaults )-> dict : 5802"""The Chat settings every client gets for what it leaves out; {} / None = clients use their own again.""" 5803self .shared = clean_shared_defaults (defaults ) 5804if self .shared_path : 5805try : 5806if self .shared : 5807Path (self .shared_path ).write_text (json .dumps (self .shared ,indent = 1 ),encoding = "utf-8" ) 5808else : 5809Path (self .shared_path ).unlink (missing_ok = True ) 5810except OSError as e : 5811f"[strata] could not save the shared settings: { e } " ,flush = True ) 5812return self .shared 5813 5814def effort_default (self )-> str | None : 5815"""The thinking level of a request that names none: the Chat settings shared with apps first, then the config's 5816"reasoning_effort" (#1641). Every API reads it here (the Responses API did not: 0.1.44.1).""" 5817return self .shared .get ("reasoning_effort" )or self .config_effort 5818 5819def with_shared (self ,req :dict ,api :str )-> dict : 5820"""The request with the shared thinking level and max tokens filled in where it has none of its own.""" 5821s = self .shared 5822effort = self .effort_default () 5823if not s and not effort : 5824return req 5825req = dict (req ) 5826if "max_tokens" in s and not req .get ("max_tokens" )and not req .get ("max_completion_tokens" ): 5827req ["max_tokens" ]= s ["max_tokens" ] 5828if effort : 5829if api == "openai" : 5830ctk = req .get ("chat_template_kwargs" )if isinstance (req .get ("chat_template_kwargs" ),dict )else {} 5831if req .get ("reasoning_effort" )in (None ,"" )and not req .get ("reasoning" )and \ 5832"enable_thinking" not in ctk and "reasoning_effort" not in ctk : 5833req ["reasoning_effort" ]= effort 5834elif not req .get ("thinking" )and not req .get ("output_config" ): 5835if effort == "none" : 5836req ["thinking" ]= {"type" :"disabled" } 5837else : 5838req ["output_config" ]= {"effort" :effort } 5839return req 5840 5841def start_telemetry (self ): 5842"""The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too.""" 5843if getattr (self ,"telemetry" ,None )is None : 5844from serve .telemetry import Telemetry 5845self .telemetry = Telemetry (extra = lambda : {"tok_s" :self ._tok_s (),"tok_s_mean" :self ._tok_s_mean (), 5846"prefill_tok_s_mean" :self ._prefill_tok_s_mean ()}, 5847gpu_index = int (getattr (self ,"gpu_index" ,0 )or 0 ), 5848gpu_indices = getattr (self ,"gpu_indices" ,None ), 5849amd = getattr (self ,"backend" ,None )== "hip" ) 5850if getattr (self ,"engine" ,None )is not None and hasattr (self .engine ,"gpu_busy" ): 5851# #1317: the quick frozen-engine check does not end an engine whose GPU is busy (a long prompt chunk on a 5852# slow card keeps the GPU at work while the host thread sleeps) 5853self .engine .gpu_busy = lambda : (self .telemetry .snapshot ()["now" ].get ("gpu_util" )or 0 )>= 10 5854 5855def _tok_s (self ): 5856"""tok/s over the last RATE_WINDOW_S seconds. Returns 0.0 while nothing is generating. With parallel requests: 5857the sum of theirs.""" 5858with self .status_lock : 5859many = [(dict (st ),list (rt ))for st ,rt in self .live_reqs .values ()] 5860if many : 5861return sum (self ._rate_of (st ,rt )for st ,rt in many ) 5862with self .status_lock : 5863s = dict (self .status ) 5864rate = list (self .rate ) 5865return self ._rate_of (s ,rate ) 5866 5867@staticmethod 5868def _rate_of (s ,rate ): 5869if not s .get ("busy" )or not s .get ("first_token" ): 5870return 0.0 5871now = time .time () 5872newest = rate [- 1 ]if rate else None 5873oldest = next (((t ,g )for t ,g in rate if now - t <= RATE_WINDOW_S ),None ) 5874if newest and oldest and newest [0 ]- oldest [0 ]>= RATE_MIN_SPAN_S : 5875return max (0.0 , (newest [1 ]- oldest [1 ])/ (newest [0 ]- oldest [0 ])) 5876return s ["generated" ]/ max (RATE_MIN_SPAN_S ,now - s ["first_token" ]) 5877 5878def _tok_s_mean (self ): 5879"""The whole-request mean since the first token (the old formula), kept so the two can be compared.""" 5880with self .status_lock : 5881many = [dict (st )for st ,_ in self .live_reqs .values ()]or [dict (self .status )] 5882return sum (s ["generated" ]/ max (1e-6 ,time .time ()- s ["first_token" ])for s in many 5883if s .get ("busy" )and s .get ("first_token" )) 5884 5885def _prefill_tok_s_mean (self ): 5886"""Engine-reported mean over newly read tokens, excluding the cached prefix.""" 5887with self .status_lock : 5888reading = self .status .get ("busy" )and self .status .get ("first_token" )is None 5889return getattr (self .engine ,"prefill_tok_s_mean" ,None )if reading else 0.0 5890 5891def begin_request (self ,path ,req ): 5892"""#332: a monitor record for this request, or None when the monitor is off (nothing is kept then).""" 5893if not self .api_monitor : 5894return None 5895raw = json .dumps (req ,ensure_ascii = False ,indent = 2 ) 5896record = {"id" :uuid .uuid4 ().hex [:12 ],"path" :path ,"model" :req .get ("model" )or self .model , 5897"started_at" :time .time (),"state" :"queued" ,"stream" :bool (req .get ("stream" )), 5898"response_format" : (req .get ("response_format" )or {}).get ("type" ) 5899if isinstance (req .get ("response_format" ),dict )else None , 5900"input" :raw [:262144 ],"input_truncated" :len (raw )> 262144 , 5901"output" :"" ,"reasoning" :"" ,"output_truncated" :False ,"reasoning_truncated" :False , 5902"queue_s" :0.0 ,"load_s" :0.0 ,"first_token_s" :None , 5903"_clock" :time .perf_counter ()} 5904with self .status_lock : 5905self .api_requests .append (record ) 5906self .request_trace .record = record 5907return record 5908 5909def request_records (self ,request_id = None ): 5910with self .status_lock : 5911records = list (self .api_requests ) 5912if request_id : 5913record = next ((r for r in records if r ["id" ]== request_id ),None ) 5914if record is None : 5915return None 5916return {k :v for k ,v in record .items ()if not k .startswith ("_" )} 5917return [{k :v for k ,v in r .items () 5918if k not in ("input" ,"output" ,"reasoning" ,"response" )and not k .startswith ("_" )} 5919| {"wallclock_s" :r .get ("wallclock_s" ,round (time .perf_counter ()- r ["_clock" ],3 ))} 5920for r in reversed (records )] 5921 5922def metrics (self ,all_requests = False )-> dict : 5923"""GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and 5924the hardware (with a minute of history per series).""" 5925with self .status_lock : 5926s = dict (self .status ) 5927if self .live_reqs :# parallel requests: the newest one's status 5928s = {** s ,** dict (list (self .live_reqs .values ())[- 1 ][0 ]),"queued" :s .get ("queued" ,0 )} 5929hist = list (self .history ) 5930totals = dict (self .totals ) 5931now = time .time () 5932progress = getattr (self .engine ,"progress" ,None ) 5933if s .get ("busy" )and s .get ("first_token" )is None : 5934state = "reading" 5935elif s .get ("busy" ): 5936state = "generating" 5937elif not self .loaded (): 5938state = "unloaded" 5939else : 5940state = "idle" 5941live = {"state" :state ,"queued" :s .get ("queued" ,0 ),"phase" :s .get ("phase" )if s .get ("busy" )else None , 5942"prompt_tokens" :s .get ("prompt_tokens" )if s .get ("busy" )else None , 5943"prompt_read" :None ,"prompt_total" :None ,"generated" :s .get ("generated" )if s .get ("busy" )else None , 5944"max_tokens" :s .get ("max_tokens" )if s .get ("busy" )else None , 5945"elapsed_s" :round (now - s ["started" ],1 )if s .get ("busy" )and s .get ("started" )else None , 5946"tok_s" :round (self ._tok_s (),1 )if state == "generating" else None , 5947"tok_s_mean" :round (self ._tok_s_mean (),1 )if state == "generating" else None , 5948"prefill_tok_s_mean" :getattr (self .engine ,"prefill_tok_s_mean" ,None )if s .get ("busy" )else None , 5949"tok_s_window_s" :RATE_WINDOW_S if state == "generating" else None } 5950if state == "reading" and progress : 5951live ["prompt_read" ],live ["prompt_total" ]= progress 5952par = int (getattr (self .engine ,"batch" ,0 )or 0 ) 5953if par :# #465: the requests running together, slot by slot 5954with self .status_lock : 5955running = len (self .live_reqs ) 5956slots = self .engine .slots_view ()if hasattr (self .engine ,"slots_view" )else [] 5957# the requests in flight that are not in a slot: the one alone on the solo path, or waiting their turn 5958in_slots = sum (1 for x in slots if x ["state" ]!= "idle" ) 5959if PAR_COUNTERS : 5960live ["par_counters" ]= dict (self .par_counters ) 5961live .update (parallel = par ,running = running ,slots = slots ,outside_slots = max (0 ,running - in_slots ), 5962waiting = int (getattr (self .engine ,"waiting" ,0 )or 0 ), 5963admitting = int (getattr (self .engine ,"admitting" ,0 )or 0 )) 5964if running and state == "idle" : 5965live ["state" ]= "generating" 5966if hasattr (self .engine ,"replica_view" ):# opt-in replicas: each one's state and requests routed to it 5967live ["replicas" ]= self .engine .replica_view () 5968if hasattr (self .engine ,"split_view" ):# opt-in split serving: the hand-overs so far (serve/split.py) 5969live ["split_serve" ]= self .engine .split_view () 5970engine = {"model" :self .model ,"max_context" :self .reported_ctx (),"images" :self .vision is not None , 5971** dict (getattr (self .engine ,"info" , {})or {})} 5972if getattr (self .vision ,"cpu_note" ,None ):# the card had no room for the picture reader: the Terminal says so in its summary 5973engine ["vision_note" ]= self .vision .cpu_note 5974tel = self .telemetry .snapshot ()if getattr (self ,"telemetry" ,None )else {"now" : {},"history" : {},"static" : {}} 5975parked = self .conv_log .poll (getattr (self .engine ,"log_path" ,None ),getattr (self .engine ,"log_start" ,None )) 5976return {"engine" :engine ,"live" :live ,"requests" :hist [::- 1 ][:None if all_requests else 12 ], 5977"conversation_cache" :conversation_cache_view (engine ,hist ,totals ,parked ), 5978"requests_kept" :len (hist ),"totals" :totals ,"hardware" :tel ["now" ], 5979"hardware_static" : 5980tel ["static" ],"history" :tel ["history" ],"time" :now } 5981 5982def prometheus (self )-> str : 5983"""GET /metrics/prometheus: the totals and what is running in Prometheus' text format, under llama-server's 5984metric names (llamacpp:*) so its dashboards work unchanged; the drafts and requests as strata:*.""" 5985with self .status_lock : 5986s ,t = dict (self .status ),dict (self .totals ) 5987running = len (self .live_reqs )or int (bool (s .get ("busy" ))) 5988prompt_n = t ["prompt_tokens" ]- t ["reused" ]# what was read, as llama.cpp counts it 5989prompt_s ,decode_s = t ["prompt_ms" ]/ 1000 ,t ["decode_ms" ]/ 1000 5990# llama.cpp reads these two gauges from a bucket it resets on every scrape (server_metrics::bucket, 5991# "the gauges are averaged over the window between two scrapes"), so an idle server reports 0 rather 5992# than its lifetime average. Keep the same window here, or the names lie to llama.cpp dashboards. 5993was_prompt_n ,was_prompt_s ,was_predicted_n ,was_decode_s = self .scrape_bucket 5994self .scrape_bucket = (prompt_n ,prompt_s ,t ["output_tokens" ],decode_s ) 5995d_prompt_n ,d_prompt_s = prompt_n - was_prompt_n ,prompt_s - was_prompt_s 5996d_predicted_n ,d_decode_s = t ["output_tokens" ]- was_predicted_n ,decode_s - was_decode_s 5997rows = [ 5998 ("llamacpp:prompt_tokens_total" ,"counter" ,"Prompt tokens read" ,prompt_n ), 5999 ("llamacpp:prompt_tokens_cached_total" ,"counter" ,"Prompt tokens the conversation cache already held" , 6000t ["reused" ]), 6001 ("llamacpp:prompt_seconds_total" ,"counter" ,"Prompt read time" ,prompt_s ), 6002 ("llamacpp:tokens_predicted_total" ,"counter" ,"Tokens generated" ,t ["output_tokens" ]), 6003 ("llamacpp:tokens_predicted_seconds_total" ,"counter" ,"Generation time" ,decode_s ), 6004 ("llamacpp:prompt_tokens_seconds" ,"gauge" ,"Average prompt read throughput in tokens/s, since the last scrape" , 6005d_prompt_n / d_prompt_s if d_prompt_s > 0 else 0 ), 6006 ("llamacpp:predicted_tokens_seconds" ,"gauge" ,"Average generation throughput in tokens/s, since the last scrape" , 6007d_predicted_n / d_decode_s if d_decode_s > 0 else 0 ), 6008 ("llamacpp:requests_processing" ,"gauge" ,"Requests running" ,running ), 6009 ("llamacpp:requests_deferred" ,"gauge" ,"Requests waiting their turn" ,s .get ("queued" )or 0 ), 6010 ("strata:requests_total" ,"counter" ,"Requests finished" ,t ["requests" ]), 6011 ("strata:drafts_offered_total" ,"counter" ,"Speculative draft tokens offered" ,t ["drafts_offered" ]), 6012 ("strata:drafts_accepted_total" ,"counter" ,"Speculative draft tokens accepted" ,t ["drafts_accepted" ]), 6013 ("strata:tool_calls_unread_total" ,"counter" ,"<tool_call> blocks returned as text (an undeclared name or a form the template does not use)" , 6014t .get ("tool_calls_unread" ,0 )), 6015 ("strata:tool_args_repaired_total" ,"counter" ,"Tool call arguments (a JSON array or object) that were damaged and read as written" , 6016t .get ("tool_args_repaired" ,0 )), 6017 ("strata:scr_cached_tokens_total" ,"counter" ,"SCR: prompt tokens of an exact prefix kept" ,t .get ("scr_cached" ,0 )), 6018 ("strata:scr_tokens_total" ,"counter" ,"SCR: prompt tokens moved from the cached run" ,t .get ("scr" ,0 )), 6019 ("strata:scr_prefilled_tokens_total" ,"counter" ,"SCR: prompt tokens read" ,t .get ("scr_prefilled" ,0 )), 6020 ("strata:model_loaded" ,"gauge" ,"1 while the model is loaded" ,int (self .loaded ())), 6021 ] 6022return "" .join (f"# HELP { name } { help_ } \n# TYPE { name } { kind } \n { name } { value } \n" 6023for name ,kind ,help_ ,value in rows ) 6024 6025def v1_status (self )-> dict : 6026"""GET /v1/status: what this server is and does, for a client that would rather ask than guess (a front-end 6027that polls its OpenAI-compatible server's status, collabosm's for one): the model and its window, images, 6028the APIs, what is running, and the last request's timings in llama.cpp's names. /metrics has the rest.""" 6029with self .status_lock : 6030s ,totals = dict (self .status ),dict (self .totals ) 6031last_t ,last_at = (dict (self .last_timings )if self .last_timings else None ),self .last_request_at 6032running = len (self .live_reqs )if self .live_reqs else int (bool (s .get ("busy" ))) 6033tel = self .telemetry .snapshot ()if getattr (self ,"telemetry" ,None )else {"now" : {},"static" : {}} 6034hw ,static = tel .get ("now" )or {},tel .get ("static" )or {} 6035 6036def scaled (v ,unit ,digits = 0 ): 6037return round (v / unit ,digits )if isinstance (v , (int ,float ))else None 6038 6039busy ,ctx = bool (s .get ("busy" )),self .reported_ctx () 6040images = self .vision is not None 6041return { 6042"service" :"strata" ,"model" :self .model , 6043"loaded" :self .loaded (),"auto_load" :hasattr (self .engine ,"restart" ), 6044"structured_output" : {"formats" : ["json_object" ,"json_schema" ],"method" :"prompt_and_validate" , 6045"constrained_decoding" :False ,"stream_buffered" :True }, 6046"engine" : (getattr (self .engine ,"info" , {})or {}).get ("version" ), 6047"started" :int (self .started_at ),"uptime_s" :int (time .time ()- self .started_at ), 6048"cache_max_tokens" :ctx , 6049"context" : {"native" :ctx ,"max_positions" :ctx }, 6050# one request at a time (more wait their turn), or "parallel": N batch slots (#465) 6051"concurrency" : {"serving" :max (1 ,int (getattr (self .engine ,"batch" ,0 )or 0 )), 6052"requested" :getattr (self ,"requested_slots" ,max (1 ,int (getattr (self .engine ,"batch" ,0 )or 0 )))}, 6053"dialects" : ["/v1/chat/completions" ,"/v1/messages" ,"/v1/responses" ], 6054"vision" : {"enabled" :images ,"available" :images ,"error" :None }, 6055"image_generation" :self .images .status ()if self .images is not None else {"enabled" :False }, 6056"activity" : {"requests" :totals ["requests" ]+ running , 6057"in_flight" :running + int (s .get ("queued" )or 0 ), 6058"last_request_at" :int (last_at )if last_at else None }, 6059"last_timings" :last_t , 6060"vram" :dict ((getattr (self .engine ,"info" , {})or {}).get ("vram" )or {}, 6061elastic = bool ((getattr (self .engine ,"info" , {})or {}).get ("vram_elastic" ))), 6062"machine" : { 6063"at" :int (time .time ()), 6064"gpu" : {"name" :static .get ("gpu_name" ),"used_mib" :scaled (hw .get ("gpu_mem_used" ),2 ** 20 ), 6065"total_mib" :scaled (hw .get ("gpu_mem_total" ),2 ** 20 ),"util_pct" :hw .get ("gpu_util" ), 6066"temp_c" :hw .get ("gpu_temp" ),"power_w" :hw .get ("gpu_power" )}if static .get ("gpu_name" )else None , 6067"ram" : {"used_gib" :scaled (hw .get ("ram_used" ),2 ** 30 ,1 ), 6068"total_gib" :scaled (hw .get ("ram_total" ),2 ** 30 ,1 )}if hw .get ("ram_total" )else None }} 6069 6070def render_prompt (self ,messages ,tools ,kwargs )-> str : 6071"""The template rendered. #458: with `effort_end`, a request with a non-default effort (low, medium or no 6072thinking) is rendered as a default one up to the answer - the same prompt start, so the conversation cache 6073keeps it - and its effort follows in a short system turn right before the answer (thinking off: the template's 6074empty thinking block). The engine (--tail-role-token) checkpoints in front of that turn.""" 6075effort = kwargs .get ("reasoning_effort" ) 6076off = kwargs .get ("enable_thinking" )is False 6077if not self .effort_end or (not off and effort in (None ,"" ,"xhigh" ,"high" )): 6078return self .template .render (messages ,tools = tools ,** kwargs ) 6079base = {k :v for k ,v in kwargs .items ()if k not in ("reasoning_effort" ,"enable_thinking" )} 6080history = self .template .render (messages ,tools = tools ,add_generation_prompt = False ,** base ) 6081full = self .template .render (messages ,tools = tools ,add_generation_prompt = True ,** kwargs ) 6082mine = self .template .render (messages ,tools = tools ,add_generation_prompt = False ,** kwargs ) 6083if not full .startswith (mine ):# a template this cannot take apart: rendered as asked 6084return full 6085tail = "" if off else EFFORT_TURN .format (EFFORT_TEXT .get (effort ,EFFORT_TEXT ["medium" ])) 6086return history + tail + full [len (mine ):] 6087 6088def encode_prompt (self ,messages ,tools ,kwargs ,store :bool = True )-> list [int ]: 6089"""The request's prompt: the template rendered and tokenized. #537: a <think> / </think> written inside a 6090message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are). 6091A control token's text (<|im_start|>, <|im_end|>, <|endoftext|>, ...) inside a message is text as well: only 6092the control tokens the template writes are control tokens. `store=False` (a token count) reuses the kept 6093prompts without adding or replacing one.""" 6094marked ,marked_tools ,changed = mark_think_literals (messages ,tools ,self .literals ) 6095prompt = self .render_prompt (marked ,marked_tools ,kwargs ) 6096plain = () 6097if changed : 6098prompt ,plain = unmark_think_literals (prompt ,self .literals ) 6099if self .prompts is not None :# #567: only what follows the last special shared with a recent prompt 6100return self .prompts .encode (prompt ,plain ,store ) 6101return self .tok .encode (prompt ,parse_special = True ,plain = plain )if plain else \ 6102self .tok .encode (prompt ,parse_special = True ) 6103 6104@ contextlib . contextmanager 6105def _turn (self ,cancel = None ): 6106"""The engine's single turn (self.fifo) for an image encode. #1999: a client that leaves while this request 6107waits for it gives its place up (ClientGone), as a queued generation does (#1619).""" 6108if cancel is None : 6109self .fifo .acquire () 6110else : 6111while not self .fifo .acquire (timeout = 0.25 ): 6112if cancel .is_set (): 6113raise ClientGone () 6114try : 6115yield 6116finally : 6117self .fifo .release () 6118 6119def _note_unreadable_tool_images (self ,messages ,cancel = None ): 6120"""A picture a tool returned (Claude Code's Read of an image file) that this server cannot read - it has no 6121image encoder, or the encoder refuses that picture - becomes a short note in its place instead of a 400. 6122Clients resend the whole history every turn, so one unreadable tool picture would fail every later request of 6123the conversation; a picture the user sends keeps the 400. A picture that encodes stays in the cache, so the 6124prompt's own encode below finds it.""" 6125fetched = {}# a URL's bytes, so prepare() does not download the same picture again 6126for m in messages : 6127content = m .get ("content" ) 6128if m .get ("role" )!= "tool" or not isinstance (content ,list ): 6129continue 6130for n ,item in enumerate (content ): 6131if not isinstance (item ,dict )or item .get ("type" )!= "image" : 6132continue 6133why = "this server has no image encoder" if self .vision is None else None 6134if why is None : 6135src = item ["source" ] 6136try : 6137if cancel is not None and cancel .is_set (): 6138raise ClientGone () 6139if self .offline and src .startswith (("http://" ,"https://" )): 6140raise ValueError ("offline mode cannot download an image URL" ) 6141if src .startswith (("http://" ,"https://" )): 6142src = fetched [item ["source" ]]= Vision .download (src )# outside the FIFO, as in prepare() 6143with self ._turn (cancel ):# the encoder takes its turn with the requests (see below) 6144self ._vision_up ()# an elastic encoder is not running until a picture needs it 6145self .vision .encode (src ) 6146except (ValueError ,OSError ,RuntimeError )as e :# RuntimeError: the encoder did not start 6147why = str (e ) 6148if why is not None : 6149f"[strata] a picture a tool returned was left out of the prompt: { why } " ,flush = True ) 6150content [n ]= {"type" :"text" ,"text" :f"[image omitted: { why } ]" } 6151return fetched 6152 6153def forget_prompt (self ,ids ): 6154if self .prompts is not None : 6155self .prompts .forget (ids ) 6156 6157 6158def prepare (self ,messages ,tools ,kwargs ,max_new = None ,force = None ,req = None ,cancel = None ): 6159"""-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": 6160the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the 6161prompt; with thinking, Service.run writes it once the thinking is over.""" 6162# `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop 6163# between pictures and raise ClientGone 6164# Cached tool images are references in browser history, never arbitrary file paths or huge base64 strings. 6165for message in messages : 6166for part in message .get ("content" , [])if isinstance (message .get ("content" ),list )else []: 6167source = part .get ("source" ,"" )if isinstance (part ,dict )else "" 6168if isinstance (part ,dict )and part .get ("type" )== "image" and isinstance (source ,str )and source .startswith ("strata-tool-media:" ): 6169name = source [len ("strata-tool-media:" ):] 6170if not re .fullmatch (r"[0-9a-f]{64}\.(png|jpg|webp)" ,name ): 6171raise ValueError ("invalid tool image reference" ) 6172# Clients resend old tool results. A removed cache or disabled feature must not poison 6173# every later turn; keep the other text and replace only the unavailable picture. 6174media_dir = self .mcp .media_dir if self .mcp is not None else None 6175image = Path (media_dir )/ name if media_dir is not None else None 6176if image is None or not image .is_file (): 6177why = "tool image cache is disabled" if image is None else "cached tool image is no longer available" 6178part .clear () 6179part .update (type = "text" ,text = f"[image omitted: { why } ]" ) 6180else : 6181part ["source" ]= str (image ) 6182fetched = self ._note_unreadable_tool_images (messages ,cancel ) 6183ids = encoded_ids = self .encode_prompt (messages ,tools ,kwargs ) 6184if force and kwargs .get ("enable_thinking" ,True )is False : 6185ids = ids + self .tok .encode (force ,parse_special = True ) 6186self .embeddings .path = None 6187self .embeddings .keys = None 6188images = images_of (messages ) 6189ds_pics = False # DeepSeek pictures (the engine's own tower): the file is already written 6190if images : 6191if self .offline and any (src .startswith (("http://" ,"https://" ))for src in images ): 6192raise ValueError ("offline mode cannot download an image URL; send a data: image instead" ) 6193if self .vision is None : 6194if self .family == "deepseek41" : 6195raise ValueError ("this server was started without pictures for DeepSeek (--vision off, or a pack made without the " 6196"picture reader): run strata launch again without --vision off to read images" ) 6197raise ValueError ("this server was started without the vision encoder (run setup again and choose " 6198"'vision'), so it cannot read images" ) 6199# An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request 6200# for as long as urlopen waited. 6201def fetch (src ): 6202if cancel is not None and cancel .is_set (): 6203raise ClientGone () 6204return fetched [src ]if src in fetched else Vision .download (src ) \ 6205if src .startswith (("http://" ,"https://" ))else src 6206images = [fetch (src )for src in images ] 6207if isinstance (self .vision ,DsPictures ): 6208ids ,ds_file = self .vision .build (ids , [Vision .load (src )if isinstance (src ,str )else src for src in images ]) 6209self .embeddings .path = ds_file 6210self .embeddings .keys = None 6211images ,ds_pics = [],True 6212if images and isinstance (self .vision ,ds4_vision .Ds4Vision ): 6213# the engine's own tower: only the sizing here (CPU), so no turn is taken; the engine encodes in the GENI 6214encoded = [] 6215for src in images : 6216if cancel is not None and cancel .is_set (): 6217raise ClientGone () 6218encoded .append (self .vision .encode (src ,keep = [p for p ,_ in encoded ])) 6219ids ,ds4_starts = self .vision .expand (ids ,encoded ) 6220elif images : 6221pad = self .tok .encode (IMAGE_PAD ,parse_special = True )[0 ] 6222start = self .tok .encode (VISION_START ,parse_special = True )[0 ] 6223# Encode only while the engine is idle: the engine and the image encoder (a separate process) must not 6224# run on the GPU at the same time - an encode during a running request left that request stuck at 6225# "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the 6226# same FIFO as the requests. 6227with self ._turn (cancel ): 6228if not (hasattr (self .vision ,"all_cached" )and self .vision .all_cached (images )): 6229self ._vision_up () 6230try : 6231encoded = (self .vision .encode_all (images ,cancel )if hasattr (self .vision ,"encode_all" ) 6232else [self .vision .encode (src )for src in images ]) 6233finally : 6234self .last_image_at = time .time () 6235# one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image 6236# (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs, 6237# #150) is kept as plain text, or it took an image's place and the counts no longer matched. 6238literal = self .tok .encode (IMAGE_PAD ,parse_special = False ) 6239out ,k = [],0 6240for j ,t in enumerate (ids ): 6241if t == pad and j > 0 and ids [j - 1 ]== start : 6242# more pairs than images: text parts that cut both markers apart (the literal marks keep whole ones text) 6243if k == len (encoded ): 6244raise ValueError ("the prompt and its images do not match" ) 6245out += [pad ]* encoded [k ][1 ] 6246k += 1 6247elif t == pad : 6248out += literal 6249else : 6250out .append (t ) 6251if k != len (encoded ): 6252raise ValueError ("the prompt and its images do not match" ) 6253ids = out 6254ctx = self .engine .max_context 6255if ctx <= 0 : 6256if getattr (self .engine ,"starting" ,False ):# #344: (re)starting, not a prompt that is too long 6257raise EngineStarting ("the engine is starting (a minute or two); try again shortly" ) 6258# a failed restart leaves max_context 0: check against the last known context, so the request reaches 6259# run() - which starts the engine again - instead of failing with "exceeds the context (0)" forever 6260ctx = getattr (self .engine ,"known_ctx" ,0 ) 6261if ctx <= 0 : 6262raise EngineStarting ("the engine is starting (a minute or two); try again shortly" ) 6263room = ctx - CTX_SLACK - len (ids ) 6264if max_new is None or max_new <= 0 or (self .fit_max_tokens and room < 1 ): 6265if room < 1 : 6266# A prompt refused for the context is not kept (#567): the client cannot resend it unchanged. The 6267# other refusals (engine starting, images) keep it: the same prompt comes back and its encode is reused. 6268self .forget_prompt (encoded_ids ) 6269raise ContextOverflow ("request exceeds the context window: " 6270f"prompt ( { len ( ids ) } tokens) leaves no room to answer in the context " 6271f"( { ctx } ); requests are never truncated" ,prompt = len (ids ),context = ctx ) 6272max_new = room 6273elif max_new > room : 6274if not self .fit_max_tokens : 6275self .forget_prompt (encoded_ids ) 6276raise ContextOverflow ("request exceeds the context window: " 6277f"prompt ( { len ( ids ) } tokens) + max tokens ( { max_new } ) exceeds the context " 6278f"( { ctx } ); requests are never truncated. Send a smaller " 6279f"max_tokens (at most { max ( 0 , room ) } here), or add \"fit_max_tokens\": true to the " 6280"model's strata-<model>.json to shorten it to the room left (#545)" , 6281prompt = len (ids ),context = ctx ,max_new = max_new ) 6282f"[strata] max_tokens { max_new } shortened to { max ( 1 , room ) } : the prompt ( { len ( ids ) } tokens) leaves that much " 6283f"of the context ( { ctx } ); \"fit_max_tokens\": false answers 400 instead" ,flush = True ) 6284max_new = max (1 ,room )# a shorter completion beats a 400 (the default) 6285if images : 6286# The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the 6287# request: one refused after it (the engine starting, no room) left it in the vision directory for good, 6288# one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts. 6289combined = combined_embeddings_path (self .vision .dir ,sum (Path (p ).stat ().st_size for p ,_ in encoded )) 6290self .embeddings .path = combined # first, so a half-written one is found as well 6291if isinstance (self .vision ,ds4_vision .Ds4Vision ):# (pixels: the engine hashes them itself) 6292self .vision .write (combined ,encoded ,ds4_starts ) 6293else : 6294# #2228: each picture's key is its normalized bytes' hash (the encoder's file name), so the engine's 6295# conversation cache matches a picture by what it is, not by its embedding floats: a picture encoded 6296# again (an encoder restart, the cache's eviction) with other bits still matches its checkpoints 6297self .embeddings .keys = [Path (p ).stem [:16 ]for p ,_ in encoded ] 6298write_temporary (combined , [p for p ,_ in encoded ]) 6299if self .family == "deepseek41" and req is not None and req .get ("strata_prefix" )is None and not images and not ds_pics : 6300lead = self .deepseek_shared_start (messages ) 6301if lead : 6302req ["strata_prefix" ]= {"messages" :lead } 6303if req is not None and req .get ("strata_prefix" )is not None : 6304req ["strata_prefix" ]= self .resolve_prefix (req ["strata_prefix" ],messages ,tools ,kwargs ,ids ,bool (images )or ds_pics ) 6305if req is not None : 6306self .set_restore_points (req ,ids ,bool (images )or ds_pics ) 6307return ids ,kwargs .get ("enable_thinking" ,True )is not False ,max_new 6308 6309def deepseek_turn_ids (self ): 6310"""(<|User|>'s id, <|System|>'s id) of the DeepSeek template, each None where the vocabulary has no such single token.""" 6311got = getattr (self ,"_ds_turn_ids" ,None ) 6312if got is None : 6313def one (text ): 6314try : 6315t = self .tok .encode (text ,parse_special = True ) 6316except Exception : 6317return None 6318return int (t [0 ])if len (t )== 1 else None 6319got = self ._ds_turn_ids = (one ("<|User|>" ),one ("<|System|>" )) 6320return got 6321 6322def set_restore_points (self ,req :dict ,ids ,has_images :bool )-> None : 6323"""STRATA_DS4_RESTORE_POINTS: where the DeepSeek engine keeps restore points for this prompt, in req["_restore"] 6324(never a client's own; not with pictures, whose spans the engine reads whole). The shared start is left to 6325strata_prefix (pin=N) where the request has one.""" 6326req .pop ("_restore" ,None ) 6327if self .family != "deepseek41" or has_images : 6328return 6329on ,tail = restore_point_settings () 6330if not on : 6331return 6332user_id ,system_id = self .deepseek_turn_ids () 6333pts = deepseek_restore_points (ids ,user_id ,system_id ,tail ) 6334pref = req .get ("strata_prefix" ) 6335if (isinstance (pref ,dict )and pref .get ("tokens" ))or os .environ .get ("STRATA_DS4_RESTORE_SHARED" )== "0" : 6336pts .pop ("shared" ,None )# (the system prompt is already the pin's, or STRATA_DS4_RESTORE_SHARED=0: no shared mark) 6337if pts : 6338req ["_restore" ]= pts 6339 6340@staticmethod 6341def deepseek_shared_start (messages )-> int : 6342"""DeepSeek-V4.1 only: how many leading messages are the system prompt (its tools are rendered with them). An 6343agent and its sub-agents that work behind the same system prompt and tools share exactly this start, so the 6344engine keeps a checkpoint of its state there (pin=N): the next agent behind the same start goes back to it 6345instead of reading it again. 0: none (STRATA_DS4_AUTO_PIN=0, no system message, or nothing after it).""" 6346if os .environ .get ("STRATA_DS4_AUTO_PIN" ,"1" )== "0" : 6347return 0 6348n = 0 6349for m in messages : 6350if isinstance (m ,dict )and m .get ("role" )in ("system" ,"developer" ): 6351n += 1 6352else : 6353break 6354return n if 0 < n < len (messages )else 0 6355 6356PREFIX_END = "\u0001strata-prefix-end\u0001" # marks where a message's shared part ends in the rendered prompt 6357 6358def resolve_prefix (self ,spec ,messages ,tools ,kwargs ,ids ,has_images = False )-> dict : 6359"""R1: `"strata_prefix"` marks the start of the prompt as a shared read-only prefix: a long document that many 6360short questions follow. Three ways to say where it ends: `{"messages": K}` (the first K messages), `{"message": 6361I, "chars": N}` (the first N characters of message I's text: a document and its question in one message) or 6362`{"tokens": N}`. The engine reads the prompt in two parts there, keeps the checkpoint at the boundary pinned 6363(never evicted) and does not park the branch it leaves, so N questions cost one prefix. Returns 6364{"tokens": N} (what the engine's `pin=N` takes: always a prefix of the prompt's ids, the tokenizer's merge across 6365the boundary included), or {} when the prefix cannot be marked (said in the log: the request is never refused for 6366it). A malformed field is a 400.""" 6367keys = ("messages" ,"message" ,"chars" ,"tokens" ) 6368if (not isinstance (spec ,dict )or not spec or any (k not in keys for k in spec )or 6369set (spec )not in ({"messages" }, {"tokens" }, {"message" ,"chars" })): 6370raise ValueError ('strata_prefix: {"messages": K} (the first K messages), {"message": I, "chars": N} (the first ' 6371'N characters of message I) or {"tokens": N}' ) 6372for k ,v in spec .items (): 6373if not isinstance (v ,int )or isinstance (v ,bool )or v < (0 if k == "message" else 1 ): 6374raise ValueError (f"strata_prefix. { k } : a whole number ( { '0' if k == 'message' else '1' } or more)" ) 6375if has_images : 6376"[strata] strata_prefix ignored: the request has images" ,flush = True ) 6377return {} 6378what = "," .join (f" { k } = { v } " for k ,v in spec .items ()) 6379 6380def lcp (a ,b ): 6381n = 0 6382for x ,y in zip (a ,b ): 6383if x != y : 6384break 6385n += 1 6386return n 6387 6388def head_ids (msgs ): 6389"""The ids the rendered `msgs` start with (a message's trailing marker cut at PREFIX_END when it is there).""" 6390marked ,marked_tools ,changed = mark_think_literals (msgs ,tools ,self .literals ) 6391effort = kwargs .get ("reasoning_effort" ) 6392off = kwargs .get ("enable_thinking" )is False # render_prompt's rule for #458's effort_end 6393kw = ({k :v for k ,v in kwargs .items ()if k not in ("reasoning_effort" ,"enable_thinking" )} 6394if self .effort_end and (off or effort not in (None ,"" ,"xhigh" ,"high" ))else dict (kwargs )) 6395kw ["add_generation_prompt" ]= False 6396text = self .template .render (marked ,tools = marked_tools ,** kw ) 6397cut = text .find (self .PREFIX_END ) 6398if cut >= 0 : 6399text = text [:cut ] 6400if changed : 6401text ,plain = unmark_think_literals (text ,self .literals ) 6402return self .tok .encode (text ,parse_special = True ,plain = plain ) 6403return self .tok .encode (text ,parse_special = True ) 6404 6405if "tokens" in spec : 6406n = spec ["tokens" ] 6407elif "messages" in spec : 6408k = spec ["messages" ] 6409if k >= len (messages ): 6410f"[strata] strata_prefix.messages= { k } ignored: the request has { len ( messages ) } message(s) and the " 6411"prefix must leave at least the last one" ,flush = True ) 6412return {} 6413head = head_ids (messages [:k ]) 6414n = lcp (head ,ids ) 6415else : 6416i ,chars = spec ["message" ],spec ["chars" ] 6417text = messages [i ].get ("content" )if 0 <= i < len (messages )else None 6418if not isinstance (text ,str )or chars > len (text ): 6419f"[strata] strata_prefix ignored: message { i } has no text of { chars } characters" ,flush = True ) 6420return {} 6421cut = messages [:i ]+ [{** messages [i ],"content" :text [:chars ]+ self .PREFIX_END }] 6422head = head_ids (cut ) 6423n = lcp (head ,ids ) 6424if n < 1 or n >= len (ids )- 1 : 6425f"[strata] strata_prefix { what } ignored: it leaves no usable prefix of the { len ( ids ) } -token prompt " 6426f"(common start { n } )" ,flush = True ) 6427return {} 6428return {"tokens" :n } 6429 6430def drop_embeddings (self )-> None : 6431"""Delete the combined image file prepare() wrote when no run() took it over (a run deletes its own as it 6432ends): a request can end before its answer starts - its client gone, anything raised after prepare() - and 6433then nothing else would. The handler calls this when a request is done.""" 6434path ,self .embeddings .path = getattr (self .embeddings ,"path" ,None ),None 6435if path is not None : 6436Path (path ).unlink (missing_ok = True ) 6437 6438def _note (self ,n ,evs ,st = None ,rate = None ): 6439with self .status_lock : 6440s = self .status if st is None else st 6441s ["generated" ]= n 6442if s .get ("first_token" )is None : 6443s ["first_token" ]= time .time () 6444 (self .rate if rate is None else rate ).append ((time .time (),n ))# the live rate's window (RATE_WINDOW_S) 6445for ev in evs : 6446if ev .kind == "reasoning" : 6447s ["phase" ]= "thinking" 6448elif ev .kind == "content" : 6449s ["phase" ]= "answering" 6450elif ev .kind == "tool_start" : 6451s ["phase" ],s ["tool" ]= f"writing a tool call: { ev . call . name } " ,ev .call .name 6452elif ev .kind == "tool_call" : 6453s ["phase" ]= "tool call complete" 6454s ["tail" ]= ((s .get ("tail" )or "" )+ (ev .text or "" ))[- 600 :] 6455 6456def _progress (self ,last_print ,every = 1.0 ,st = None ): 6457"""A progress line in the server window every `every` seconds while a request runs.""" 6458now = time .time () 6459if now - last_print < every : 6460return last_print 6461with self .status_lock : 6462s = dict (self .status if st is None else st ) 6463el = now - s .get ("started" ,now ) 6464if s .get ("first_token" )is None : 6465pr = getattr (self .engine ,"progress" ,None )# (position reached, prompt tokens): a reused prefix counts 6466done = f" { pr [ 0 ]:, } of { pr [ 1 ]:, } " if pr and pr [1 ]else f" { s . get ( 'prompt_tokens' , 0 ):, } " # as read (#29) 6467f"[strata] reading the prompt: { done } tokens, { el :.0f } s so far" ,flush = True ) 6468else : 6469rate = s ["generated" ]/ max (RATE_MIN_SPAN_S ,now - s ["first_token" ]) 6470# #984: while a thinking budget applies, the thinking line shows it, not the request's max_tokens 6471limit = (f"budget { s [ 'thinking_budget' ] } (max { s . get ( 'max_tokens' ) } )" 6472if s ["phase" ]== "thinking" and s .get ("thinking_budget" )else f"max { s . get ( 'max_tokens' ) } " ) 6473f"[strata] { s [ 'phase' ] } : { s [ 'generated' ] } of { limit } tokens, { rate :.1f } tok/s, " 6474f" { el :.0f } s" ,flush = True ) 6475return now 6476 6477def run (self ,ids ,thinking ,tools ,max_new ,sampling ,cancel ,force = None , 6478declared_only = False ,deferred = False )-> Iterator [tuple [str ,object ]]: 6479"""The request's events (see _run); with "prevent_sleep" in the config, the PC stays awake while it runs or waits.""" 6480ka = self .keep_awake 6481if ka is not None : 6482ka .acquire () 6483try : 6484yield from self ._run (ids ,thinking ,tools ,max_new ,sampling ,cancel ,force ,declared_only ,deferred ) 6485finally : 6486if ka is not None : 6487ka .release () 6488 6489def _run (self ,ids ,thinking ,tools ,max_new ,sampling ,cancel ,force = None , 6490declared_only = False ,deferred = False )-> Iterator [tuple [str ,object ]]: 6491"""Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}). 6492`force` (forced_call): the opening of the call the reply must make - see prepare().""" 6493# the model card's sampling for this thinking state, then the config's block, then the Chat settings shared with 6494# apps; the request's own fields win over all of them 6495defaults = {** model_card_sampling (self .model_arch ,thinking ),** self .sampling_defaults ,** self .shared } 6496if defaults :# the request's own fields win (explicit 0 stays greedy) 6497req_values = {k :v for k ,v in (sampling or {}).items ()if v is not None } 6498sampling = {** defaults ,** req_values } 6499# #123: read after the merge, so a budget shared through POST /settings is seen like the other keys 6500budget = self .reasoning_budget (sampling )if thinking else None 6501if thinking and not budget and self .answer_room and max_new and max_new >= ANSWER_ROOM_MIN_CAP : 6502# 0.1.45: max_tokens counts the thinking too. A client that caps the reply at 8192 (the desktop agent's 6503# harness sends max_completion_tokens: 8192 on every request) and a task the model thinks long about got 6504# the cut-off in the middle of the thinking and NO answer. So thinking is closed early enough to leave 6505# the answer its quarter of the cap (the budget's wrap-up: a short closing sentence, </think>, the answer). 6506# A request with a budget of its own, or max_tokens below ANSWER_ROOM_MIN_CAP, is left as it was. 6507budget = max_new - min (max (ANSWER_RESERVE_MIN ,max_new // 4 ),max_new // 2 ) 6508if max_new <= 32768 :f"[strata] thinking limited to { budget } of max_tokens { max_new } so the answer has room " 6509"(\"answer_room\": false in the config turns this off)" ,flush = True ) 6510if (thinking and not budget and self .answer_room and self .family == "deepseek41" 6511and max_new and DS41_SMALL_CAP_MIN <= max_new < ANSWER_ROOM_MIN_CAP ): 6512# DeepSeek-V4.1 only: a short max_tokens (/v1/messages and /v1/chat/completions with 200-600) was spent 6513# entirely on the thinking, so no text block ever arrived. With no budget of the client's own, the thinking 6514# is capped at half of max_tokens; then the wrap-up, </think> and the answer follow in the other half. 6515budget = max_new // 2 6516f"[strata] thinking limited to { budget } of max_tokens { max_new } so the answer has room " 6517"(\"answer_room\": false in the config turns this off)" ,flush = True ) 6518if budget and max_new and max_new > 0 : 6519# #984: a budget at or near max_tokens never fires before the reply is cut off while still thinking, so 6520# it has no answer. Close the thinking early enough to leave room for one. 6521reserve = min (max (ANSWER_RESERVE_MIN ,max_new // 4 ),max_new // 2 ) 6522if budget > max_new - reserve : 6523f"[strata] thinking capped at { max_new - reserve } of max_tokens { max_new } to leave room for " 6524f"the answer (budget { budget } )" ,flush = True ) 6525budget = max (1 ,max_new - reserve ) 6526parser = self .parser_cls (thinking = thinking ,tools = with_history_tools (tools ,sampling ),stream_tools = True , 6527recover = self .tool_call_recovery ,declared_only = declared_only , 6528deferred = deferred or self .undeclared_tool_calls == "call" )# #4622: opt-in, as for a deferred tool 6529detok ,n ,finish = Detokenizer (self .tok ),0 ,"length" 6530run_tok ,run_len ,repeated = None ,0 ,False # #606: the current run of one repeated token 6531thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) 6532stop_list = stop_strings (sampling ) 6533stops = StopMatcher (stop_list )if stop_list else None 6534 6535def cut (evs ): 6536"""The events with the answer's text cut at a stop string (OpenAI stop, Anthropic stop_sequences).""" 6537if stops is None : 6538return evs 6539out = [] 6540for ev in evs : 6541if stops .hit is not None : 6542break # nothing after the stop string is sent 6543if ev .kind == "content" : 6544text = stops .push (ev .text or "" ) 6545if text : 6546out .append (Event ("content" ,text )) 6547continue 6548held = stops .flush ()# a stop string does not run across a tool call or thinking 6549if held : 6550out .append (Event ("content" ,held )) 6551out .append (ev ) 6552return out 6553opening = []# without thinking the prompt ends with the forced opening: 6554if force and not thinking :# the parser reads it as if the model had written it 6555opening ,force = parser .feed (force ),None 6556tail = "" # the last characters written (the newlines before a call) 6557answered ,close_retried = False ,False # #1053: content or a call came out; the thinking was closed 6558nf_retried = False # #879: the request was sent again after non-finite logits 6559timings ,before = None ,None # this request's timings; the engine's `last` before it 6560recovery_count ,reasoning_text ,repeat_coverage = 0 ,"" ,0.0 6561looped ,next_loop_check = False ,LOOP_CHECK_EVERY # #728: reasoning that repeats whole passages 6562raw_ids = []# every generated id (STRATA_DEBUG: dump raw model text) 6563admission_rejected = False # #3040: the engine's batch slots refused it before it read anything 6564emb ,self .embeddings .path = getattr (self .embeddings ,"path" ,None ),None # this run's to delete now 6565img_keys ,self .embeddings .keys = getattr (self .embeddings ,"keys" ,None ),None 6566if emb and img_keys : 6567sampling = {** (sampling or {}),"strata_img_keys" :img_keys }# #2228: sent beside the embeddings file 6568# Only a DONE line replaces engine.last, so a request that died, errored or was disconnected must not have 6569# the PREVIOUS request's decode figures recorded as its own: each pass keeps its own DONE (a segment) if 6570# one arrived. A reasoning-budget continuation is another native generation, not another API request, 6571# so the generated reasoning must not become this request's cached input (#615). 6572segments = [] 6573timed_out = False 6574trace = getattr (self .request_trace ,"record" ,None ) 6575waiting = time .perf_counter () 6576first_engine_token_s = None # this request, from entering the engine queue; includes queue/prefill 6577# #465: with "parallel" (the engine's batch slots) requests run at once: each keeps its own status and rate 6578# window (self.status says busy while any runs); one at a time they are self.status / self.rate, as before 6579par = bool (getattr (self .engine ,"batch" ,0 )) 6580st = {}if par else self .status 6581rate = collections .deque (maxlen = 32 )if par else self .rate 6582request_id = uuid .uuid4 ().hex [:12 ] 6583setattr (cancel ,"_strata_request_id" ,request_id ) 6584deadline = time .monotonic ()+ self .queue_timeout_s if self .queue_timeout_s is not None else None 6585if deadline is not None : 6586setattr (cancel ,"_strata_queue_deadline" ,deadline ) 6587def queue_started (): 6588with self .status_lock : 6589row = self .terminal_requests .get (request_id ) 6590if row is not None and row ["state" ]!= "reading" : 6591row ["state" ]= "reading" 6592self ._terminal_event_locked (request_id ,"reading" ) 6593setattr (cancel ,"_strata_queue_started" ,queue_started ) 6594def replica_selected (index :int )-> None : 6595with self .status_lock : 6596row = self .terminal_requests .get (request_id ) 6597if row is not None : 6598row ["replica" ]= index 6599setattr (cancel ,"_strata_replica_selected" ,replica_selected ) 6600with self .status_lock : 6601self .status ["queued" ]+= 1 6602self .terminal_requests [request_id ]= {"id" :request_id ,"state" :"queued" , 6603"queued_at" :time .time (),"admitted_at" :None , 6604"prompt_tokens" :len (ids )} 6605self ._terminal_event_locked (request_id ,"queued" ) 6606queued_counted = True 6607try : 6608# --batch: the engine runs several requests at once (StrataEngine.generate_batched orders them) 6609turn = contextlib .ExitStack () 6610if not par : 6611# #1619: a request waiting for the single turn sends a keep-alive every QUEUE_BEAT_S, so a client with 6612# a stream idle timeout does not abort a healthy queued request (and its retry read the prompt again); 6613# a client that left while queued gives its place up instead of taking the turn only to cancel there 6614got = False 6615while not got : 6616if cancel .is_set (): 6617raise QueueCancelled ("the client disconnected while waiting for the engine" ) 6618left = deadline - time .monotonic ()if deadline is not None else QUEUE_BEAT_S 6619if left <= 0 : 6620raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 6621got = self .fifo .acquire (timeout = min (QUEUE_BEAT_S ,left )) 6622if got : 6623if cancel .is_set (): 6624self .fifo .release () 6625raise QueueCancelled ("the client disconnected while waiting for the engine" ) 6626if deadline is not None and time .monotonic ()>= deadline : 6627self .fifo .release () 6628raise QueueWaitExpired ("the inference queue wait deadline expired; retry later" ) 6629turn .callback (self .fifo .release ) 6630else : 6631yield "ping" ,None 6632with turn : 6633try : 6634with self .status_lock : 6635if trace is not None : 6636trace ["queue_s" ]+= round (time .perf_counter ()- waiting ,3 ) 6637trace ["state" ]= "generating" 6638if not par : 6639self .status ["queued" ]-= 1 6640queued_counted = False 6641self .terminal_requests [request_id ].update (state = "admitted" ,admitted_at = time .time ()) 6642self ._terminal_event_locked (request_id ,"admitted" ) 6643# issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing 6644# (parallel requests do not hold the fifo: one of them starts it, the others wait for that). 6645# #1603: a parallel request stays counted as queued until it is registered as running below - 6646# waiting here for the fifo (an image encode, a /v1/vram resize) left it neither - and one on a 6647# loaded engine has nothing to start, so it does not wait for the fifo at all 6648if not par : 6649self .ensure_loaded () 6650elif not (self .loaded ()and not self ._vision_down ()): 6651with self ._inference_fifo (deadline ,cancel ): 6652self .ensure_loaded () 6653with self .status_lock : 6654if par : 6655self .status ["queued" ]-= 1 6656queued_counted = False 6657self .terminal_requests [request_id ].update (state = "waiting" ,admitted_at = time .time ()) 6658self ._terminal_event_locked (request_id ,"admitted" ) 6659st .update (busy = True ,phase = "reading the prompt" ,prompt_tokens = len (ids ), 6660generated = 0 ,started = time .time (),first_token = None ,tool = None ,tail = "" , 6661max_tokens = max_new ,reasoning_recoveries = 0 ,thinking_budget = budget ) 6662if par : 6663self .live_reqs [id (st )]= (st ,rate ) 6664self .status .update (st ) 6665self .last_request_at = time .time () 6666rate .clear ()# the previous request's samples must not leak into this one 6667before = getattr (self .engine ,"last" ,None ) 6668last_print = time .time () 6669prompt ,thought = ids ,0 # thought: the reasoning tokens so far (the budget's count) 6670# the engine stops at the budget itself (HOLD_KEY), when it can and </think> is one token: a --batch engine 6671# only when its slots say they hold too (READY holdb) 6672hold_end = None 6673if (budget and getattr (self .engine ,"can_hold" ,False )is True 6674and (not getattr (self .engine ,"batch" ,0 )or getattr (self .engine ,"can_hold_batch" ,False )is True ) 6675and getattr (self .engine ,"split_engine" ,False )is not True ):# (the split engine's parser refuses the key: tests/split/test_split_gen_keys.py) 6676te = self .tok .encode (THINK_END ,parse_special = True ) 6677hold_end = te [0 ]if len (te )== 1 else None 6678for ev in opening : 6679yield "event" ,ev 6680while True : 6681segment_before = getattr (self .engine ,"last" ,None ) 6682segments_before = len (segments )# (#879: a pass sent again leaves no segment) 6683held = hold_end is not None and budget is not None 6684if held :# the reasoning tokens left before the budget (at least one: a cut not yet clean) 6685pass_sampling = {k :v for k ,v in (sampling or {}).items ()if k != HOLD_KEY }# (a copy: the hold is this pass's own) 6686pass_sampling [HOLD_KEY ]= (max (1 ,int (budget )- thought ),int (hold_end )) 6687elif sampling and HOLD_KEY in sampling :# (never a client's: strip it from a copy) 6688pass_sampling = {k :v for k ,v in sampling .items ()if k != HOLD_KEY } 6689else : 6690pass_sampling = sampling # no hold: the engine gets the caller's own sampler object, as before P2 6691gen = self .engine .generate (prompt ,max_new - n ,pass_sampling ,cancel ,embeddings = emb )if emb \ 6692else self .engine .generate (prompt ,max_new - n ,pass_sampling ,cancel ) 6693recover_prompt = None 6694tloop = False # the wrap is for a token repeated in the thinking 6695seg ,wrap ,leaving = [],False ,False # this pass's tokens; the budget is reached; closed 6696nonfinite = False # #879: the engine ended this pass on non-finite logits 6697opens = False # the thinking is over: write the forced call's opening 6698try : 6699# A value the frontend holds back (a tool call's array or object argument is sent 6700# whole, once complete) can keep the stream silent for minutes while tokens are 6701# generated; a client's idle timeout then ends the request. Send the same keep-alive 6702# the engine's heartbeat sends when nothing has gone out for KEEPALIVE_S. 6703last_out = time .perf_counter () 6704for t in gen : 6705if t is None :# heartbeat while the engine is quiet 6706last_print = self ._progress (last_print ,st = st ) 6707last_out = time .perf_counter () 6708yield "ping" ,None 6709continue 6710n += 1 6711if first_engine_token_s is None : 6712first_engine_token_s = round (time .perf_counter ()- waiting ,3 ) 6713with self .status_lock : 6714row = self .terminal_requests .get (request_id ) 6715if row is not None : 6716row ["first_engine_token_s" ]= first_engine_token_s 6717self ._terminal_event_locked (request_id ,"first_token" ) 6718if trace is not None and trace ["first_token_s" ]is None : 6719with self .status_lock : 6720trace ["first_token_s" ]= round (time .perf_counter ()- trace ["_clock" ],3 ) 6721if t in self .stop_ids : 6722if force and parser .state == "reasoning" and parser .buf == THINK_END : 6723opens = True # #537: the held </think> was the end: the call opens there 6724break 6725finish = "stop" 6726raw_ids .append (t ) 6727break 6728raw_ids .append (t ) 6729seg .append (t ) 6730thinking_n += parser .state in ("reasoning" ,"rcall" ) 6731run_len = run_len + 1 if t == run_tok else 1 6732run_tok = t 6733if (self .repeat_stop_tokens and run_len >= self .repeat_stop_tokens 6734and not (self .thinking_loop_tokens and parser .state == "reasoning" )): 6735repeated = True # #606: a degenerate output, not an answer: end it here 6736break 6737piece = detok .push (t ) 6738tail = (tail + piece )[- 2 :] 6739evs = cut (parser .feed (piece )) 6740self ._note (n ,evs ,st ,rate ) 6741last_print = self ._progress (last_print ,st = st ) 6742for ev in evs : 6743if self .reasoning_loop_recovery and ev .kind == "reasoning" : 6744reasoning_text += ev .text or "" 6745if ev .kind in ("content" ,"tool_start" ,"tool_call" ): 6746answered = True 6747yield "event" ,ev 6748if evs : 6749last_out = time .perf_counter () 6750elif time .perf_counter ()- last_out >= KEEPALIVE_S : 6751last_out = time .perf_counter () 6752yield "ping" ,None 6753if stops is not None and stops .hit is not None : 6754finish = "stop" # gen.close() below STOPs the engine, as for a stop token 6755break 6756if (self .reasoning_loop_recovery and not recovery_count and parser .state == "reasoning" 6757and n >= next_loop_check and not parser .buf and not parser .pending 6758and not detok .pending ()): 6759next_loop_check = n + LOOP_CHECK_EVERY 6760repeat_coverage = reasoning_repeat_coverage (reasoning_text ) 6761if repeat_coverage >= LOOP_COVERAGE : 6762if self .reasoning_loop_recovery == "stop" : 6763looped = True # #728: end the reply here, as for a repeated token 6764break 6765if not emb :# "recover": not for a request with pictures 6766recover_prompt = focused_recovery_prompt (self .tok ,ids ,raw_ids ) 6767if recover_prompt is not None : 6768break 6769if (self .thinking_loop_tokens and parser .state == "reasoning" 6770and run_len >= self .thinking_loop_tokens 6771and not parser .buf and not detok .pending ()): 6772wrap = tloop = True # one token repeated in the thinking: close it, answer 6773break 6774if budget and parser .state == "reasoning" : 6775thought += 1 6776# at a clean point: no tag held back, no character split across tokens 6777if thought >= budget and parser .clean and not detok .pending (): 6778wrap = True 6779break 6780if force : 6781if any (ev .kind in ("tool_start" ,"tool_call" )for ev in evs ): 6782force = None # the model is writing a call of its own 6783elif parser .state == "content" and parser .clean and not detok .pending (): 6784opens = True 6785break 6786except EngineNonFinite : 6787nonfinite = True 6788except EngineDied as e : 6789finish = "error" 6790self ._say_died (e ) 6791raise 6792except QueueWaitExpired : 6793finish = "error" 6794timed_out = True 6795raise 6796except ValueError as e :# the engine's ERR line (it may have ended after it) 6797finish = "error" 6798f"[strata] the engine reported an error: { e } " ,flush = True ) 6799raise 6800except GeneratorExit :# the client went away: an engine that never acknowledges 6801leaving = True # the STOP below is ended, but no error replaces this 6802raise 6803finally : 6804try : 6805gen .close ()# STOP+drain to THIS request's DONE while still holding the 6806# fifo, so a stop-token break can't leave the shared engine 6807# queue mid-drain for the next request to read as its own DONE 6808except EngineSilent as e :# #481: the STOP was never acknowledged: the engine is ended 6809finish = "error" 6810self ._say_died (e ) 6811if not leaving and not cancel .is_set (): 6812raise 6813segment_done = getattr (self .engine ,"last" ,None ) 6814if segment_done is not None and segment_done is not segment_before : 6815segments .append (dict (segment_done )) 6816if nonfinite and not cancel .is_set (): 6817# #879: the engine emitted none of the poisoned window's tokens and reads its next prompt 6818# from token 0. Nothing sent yet: the same request once more, unseen by the client 6819if n == 0 and not nf_retried : 6820nf_retried = True 6821# the retry reads from token 0: its DONE, not this one's, says what was reused 6822del segments [segments_before :] 6823"[strata] the engine's logits became non-finite before the first token (#879); it " 6824"dropped its cached state: sending the request again once" ,flush = True ) 6825continue 6826if n == 0 : 6827finish = "error" 6828"[strata] the engine's logits became non-finite again on the retry (#879): the " 6829"request ends with an error" ,flush = True ) 6830raise EngineNonFinite ("the model's output became non-finite (NaN) twice in a row " 6831"(#879); the engine has dropped its cached state - send the " 6832"request again" ) 6833f"[strata] the engine's logits became non-finite after { n } tokens (#879): the reply " 6834"ends here as \"length\"; the engine dropped its cached state, so the next request " 6835"reads its prompt from the start" ,flush = True ) 6836finish = "length" 6837break 6838if recover_prompt is not None and not cancel .is_set ()and n < max_new : 6839recovery_count += 1 6840# Only the two settings that keep the same words coming are raised (temperature to at 6841# least 1.0, presence penalty to at least 1.5): a client's top_p and top_k are never 6842# touched, and its own request dict is copied, not changed. 6843want = (max (1.0 ,float ((sampling or {}).get ("temperature" )or 0 )), 6844max (1.5 ,float ((sampling or {}).get ("presence_penalty" )or 0 ))) 6845if want != tuple (float ((sampling or {}).get (k )or 0 ) 6846for k in ("temperature" ,"presence_penalty" )): 6847sampling = {** (sampling or {}),"temperature" :want [0 ],"presence_penalty" :want [1 ]} 6848prompt = recover_prompt 6849with self .status_lock : 6850st ["reasoning_recoveries" ]= recovery_count 6851if trace is not None : 6852trace ["reasoning_recoveries" ]= recovery_count 6853trace ["reasoning_repeat_coverage" ]= round (repeat_coverage ,3 ) 6854f"[strata] repeated reasoning detected at { n } tokens " 6855f"(coverage= { repeat_coverage :.3f } ); resuming the same output with the low-effort " 6856"instruction (reasoning_loop_recovery)" ,flush = True ) 6857continue 6858if (self .reasoning_close_retry and thinking and finish == "stop" and not close_retried 6859and not answered and not wrap and not opens and parser .state == "reasoning" 6860and parser .buf != THINK_END # #537: not after a held </think>, the end 6861and (stops is None or stops .hit is None )and not cancel .is_set ()): 6862# #1053: the model wrote its reasoning and stopped before </think>: the client would get 6863# an empty answer. Close the thinking once and let it answer. 6864close_retried = True 6865extra = self .tok .encode (REASONING_CLOSE ,parse_special = True ) 6866if max_new - n - len (extra )>= 1 : 6867"[strata] the reply ended inside its thinking with no answer: closing the " 6868"thinking once and continuing (reasoning_close_retry)" ,flush = True ) 6869for t in extra : 6870n += 1 6871raw_ids .append (t ) 6872thinking_n += parser .state in ("reasoning" ,"rcall" ) 6873evs = cut (parser .feed (detok .push (t ))) 6874self ._note (n ,evs ,st ,rate ) 6875for ev in evs : 6876yield "event" ,ev 6877prompt = prompt + seg + extra 6878finish = "length" 6879continue 6880if (held and not (wrap or opens )and not cancel .is_set ()and finish != "stop" and not repeated 6881and not looped and n < max_new and segments and segments [- 1 ].get ("finish" )== "hold" 6882and len (segments )> segments_before ): 6883# the engine stopped at the hold but the cut is not clean yet (a character split across 6884# tokens, a tag held back) or the reasoning count is short: on from the live session 6885prompt = prompt + seg 6886continue 6887if not (wrap or opens )or cancel .is_set (): 6888break 6889# #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a 6890# short wrap-up and </think>) and let it answer: the next pass's prompt is this one plus what 6891# was generated plus the wrap-up, so the engine continues from the prefix it already holds. 6892# A forced call (tool_choice) is opened the same way: after the wrap-up, or where the 6893# thinking ended, after the blank line the template puts before a call. 6894if wrap : 6895budget = st ["thinking_budget" ]= None 6896text = (REASONING_CLOSE if tloop else REASONING_WRAP_UP )+ (force or "" ) 6897else : 6898text = "\n" * (2 - (len (tail )- len (tail .rstrip ("\n" ))))+ force 6899force = None 6900extra = self .tok .encode (text ,parse_special = True ) 6901if max_new - n - len (extra )< 1 : 6902break # no room left to answer: "length", as without a budget 6903if tloop : 6904f"[strata] the thinking repeated one token { run_len } times: closing it " 6905"(thinking_loop_tokens)" ,flush = True ) 6906run_len = 0 6907elif wrap : 6908f"[strata] thinking budget reached ( { thought } tokens): wrapping up the thinking" , 6909flush = True ) 6910for t in extra : 6911n += 1 6912raw_ids .append (t ) 6913thinking_n += parser .state in ("reasoning" ,"rcall" ) 6914evs = cut (parser .feed (detok .push (t ))) 6915self ._note (n ,evs ,st ,rate ) 6916for ev in evs : 6917yield "event" ,ev 6918if stops is not None and stops .hit is not None : 6919finish = "stop" 6920break 6921prompt = prompt + seg + extra 6922if cancel .is_set (): 6923finish = "cancel" 6924elif looped : 6925f"[strata] the thinking repeated the same passages (coverage= { repeat_coverage :.3f } ) at " 6926f" { n } tokens: ended as \"length\" (reasoning_loop_recovery: \"stop\" in " 6927"strata-<model>.json; remove it to turn this off)" ,flush = True ) 6928elif repeated : 6929f"[strata] the reply repeated one token ( { self . tok . decode ([ run_tok ])!r } ) " 6930f" { run_len } times in a row: ended as \"length\" (repeat_stop_tokens in " 6931"strata-<model>.json; 0 turns this off). If a new request with a short prompt does the " 6932"same, restart the server and report it (#606)" ,flush = True ) 6933except GpuBusy : 6934# #3040 (PR #5044's approach): a batch engine can use up its BGEN retries before it has admitted this 6935# request. The monitor keeps an error row, but it is not a completed generation: no prompt tokens 6936# and no part in the totals or latencies. A continuation after native work keeps the old accounting. 6937if not segments and n == 0 : 6938admission_rejected = True 6939finish = "error" 6940raise 6941except GeneratorExit :# the client disconnected mid-stream 6942finish = "disconnect" 6943raise 6944finally : 6945# #266: settle this request's status, history and totals while still holding the fifo: once 6946# it is released the next request sets its own status, which this must not record or clear 6947with self .status_lock : 6948if st .get ("busy" )and not timed_out : 6949last = request_stats (segments )# only this request's own DONEs count 6950started = st .get ("started" ,time .time ()) 6951cvec = (getattr (self .engine ,"info" , {})or {}).get ("cvec" ,0 ) 6952loaded = str (cvec )not in ("0" ,"" ,"None" ) 6953hit_rate = round (last ["hits" ]/ last ["lookups" ],3 )if last .get ("lookups" )else None 6954# #588: the share the GPU read over PCIe (--pcie-frac) or another GPU computed - not in 6955# the hit rate's lookups, which is the VRAM share of the rest (None: an older engine) 6956routed = (last .get ("lookups" )or 0 )+ (last .get ("offloaded" )or 0 ) 6957pcie_share = round (last ["offloaded" ]/ routed ,3 ) \ 6958if last .get ("offloaded" )is not None and routed else None 6959seen = 0 if admission_rejected else prompt_tokens_seen (len (ids ),last )# #471: < len(ids) when cancelled mid-read; #3040 6960self .history .append ({ 6961"id" :request_id , 6962"projection" : (sampling or {}).get ("experimental_speed_projection" )is not False 6963if loaded else None , 6964"time" :started ,"duration_s" :round (time .time ()- started ,1 ),"finish" :finish , 6965"prompt_tokens" :seen ,"reused" :last .get ("reused" ),"output_tokens" :n , 6966"first_engine_token_s" :first_engine_token_s , 6967# the request's whole prompt, and the tokens read of it (None: an older engine) 6968"prompt_total" :len (ids ),"prompt_read" :last .get ("prompt_read" ), 6969"reasoning_recoveries" :recovery_count , 6970"reasoning_repeat_coverage" :round (repeat_coverage ,3 ), 6971"engine_generated" :last .get ("generated" ), 6972"prompt_ms" :last .get ("prompt_ms" ),"decode_ms" :last .get ("decode_ms" ), 6973"decode_tok_s" :round (last ["generated" ]/ (last ["decode_ms" ]/ 1000 ),1 ) 6974if n and (last .get ("generated" )or 0 )>= 2 and last .get ("decode_ms" )else None , 6975"hit_rate" :hit_rate ,"pcie_share" :pcie_share ,"ram_blobs" :last .get ("ram_blobs" ), 6976"file_blobs" :last .get ("file_blobs" ),"file_mb" :last .get ("file_mb" ), 6977# #457: the speculative drafts from the DONE line (None: the engine did not say) 6978"drafts_offered" :last .get ("drafts_offered" ), 6979"drafts_accepted" :last .get ("drafts_accepted" ), 6980# suffix cache reuse (an engine with SCR on): the prompt's exact prefix kept, the tokens 6981# moved from the cached run, and the ones read (None: SCR off) 6982"scr_cached" :last .get ("cached" ),"scr" :last .get ("scr" ), 6983"scr_prefilled" :last .get ("prefilled" )}) 6984if not admission_rejected :# #3040: a refused admission did no work 6985t = self .totals 6986t ["requests" ]+= 1 6987t ["prompt_tokens" ]+= seen 6988t ["reused" ]+= last .get ("reused" )or 0 6989t ["output_tokens" ]+= n 6990t ["prompt_ms" ]+= last .get ("prompt_ms" )or 0.0 6991t ["decode_ms" ]+= last .get ("decode_ms" )or 0.0 6992t ["drafts_offered" ]+= last .get ("drafts_offered" )or 0 6993t ["drafts_accepted" ]+= last .get ("drafts_accepted" )or 0 6994t ["scr_cached" ]+= last .get ("cached" )or 0 6995t ["scr" ]+= last .get ("scr" )or 0 6996t ["scr_prefilled" ]+= last .get ("prefilled" )or 0 6997ft0 = st .get ("first_token" )# this request's own (#465: one per request) 6998self .latencies .observe (ft0 - started if ft0 else None ,n , 6999 (last .get ("decode_ms" )or 0.0 )/ 1000 ,time .time ()- started ) 7000fresh = getattr (self .engine ,"last" ,None ) 7001if fresh is not None and fresh is not before :# the engine's clock for THIS request 7002timings = request_timings (seen ,n ,last ) 7003self .last_timings = dict (timings ,at = int (time .time ()))if timings else None 7004self .last_request_at = time .time () 7005now = time .time () 7006el = now - st .get ("started" ,now ) 7007ft = st .get ("first_token" ) 7008rate = answer_speed (last ,n ,now - ft if ft else None ) 7009hit_msg = f", expert cache { hit_rate * 100 :.1f } % hit" if hit_rate is not None else "" 7010if hit_msg and pcie_share : 7011hit_msg += f" (+ { pcie_share * 100 :.1f } % of the routed experts over PCIe)" 7012rate_txt = f" { rate :.1f } tok/s" if rate is not None else "no speed" 7013f"[strata] done: { n } tokens in { el :.0f } s ( { rate_txt } ) " 7014f"( { finish } , cancel= { cancel . is_set () } ) { hit_msg } " ,flush = True ) 7015if finish == "length" and parser .state in ("reasoning" ,"rcall" ):# #530 7016"[strata] the reply reached max tokens while still thinking, so it has no " 7017"answer: a thinking budget (reasoning_budget_tokens, in the request or in " 7018"strata-<model>.json for every request) leaves room to answer" ,flush = True ) 7019if os .environ .get ("STRATA_DEBUG" )and raw_ids : 7020f"[strata] raw: { self . tok . decode ( raw_ids )!r } " ,flush = True ) 7021f"[strata] raw ids: { list ( raw_ids ) } " ,flush = True ) 7022st ["busy" ]= False 7023st .pop ("tail" ,None )# #212: the answer's end is not kept once it is done 7024st .pop ("tool" ,None ) 7025if par : 7026self .live_reqs .pop (id (st ),None ) 7027if self .live_reqs :# the newest request still running 7028self .status .update (list (self .live_reqs .values ())[- 1 ][0 ]) 7029else : 7030self .status .update (busy = False ) 7031self .status .pop ("tail" ,None ) 7032self .status .pop ("tool" ,None ) 7033except QueueCancelled : 7034finish = "cancel" 7035yield "done" , {"finish" :"cancel" ,"completion_tokens" :0 ,"reused" :0 ,"timings" :None , 7036"reasoning_tokens" :0 ,"reasoning_recoveries" :0 } 7037return 7038except QueueWaitExpired : 7039finish = "timeout" 7040with self .status_lock : 7041self .queue_timeouts += 1 7042raise 7043except Exception : 7044finish = "error" 7045raise 7046finally : 7047with self .status_lock : 7048if queued_counted : 7049self .status ["queued" ]-= 1 7050self .terminal_requests .pop (request_id ,None ) 7051event = {"stop" :"finished" ,"length" :"finished" ,"cancel" :"cancelled" , 7052"disconnect" :"disconnected" ,"timeout" :"timeout" ,"error" :"error" }.get (finish ,"error" ) 7053self ._terminal_event_locked (request_id ,event ,finish ) 7054if emb : 7055Path (emb ).unlink (missing_ok = True ) 7056for ev in cut (parser .finish (finish )): 7057yield "event" ,ev 7058if parser .rescued or parser .refused : 7059self .totals ["tool_calls_from_reasoning" ]= self .totals .get ("tool_calls_from_reasoning" ,0 )+ parser .rescued 7060f"[strata] tool calls inside the thinking: { parser . rescued } read as calls, { parser . refused } kept as " 7061f"reasoning (quoted, or the turn did not end on a stop)" ,flush = True ) 7062if getattr (parser ,"stray_think" ,0 ): 7063# #4077: the model wrote a closing think tag while thinking; the reasoning after it was sent as the answer 7064self .totals ["stray_think_closers" ]= self .totals .get ("stray_think_closers" ,0 )+ parser .stray_think 7065f"[strata] { parser . stray_think } extra closing think tag(s) in the answer were dropped (the model wrote one " 7066"while thinking, so the rest of its reasoning went out as the answer; a call after it still counts)" ,flush = True ) 7067if getattr (parser ,"notes" ,None ): 7068self .totals ["tool_args_repaired" ]= self .totals .get ("tool_args_repaired" ,0 )+ len (parser .notes ) 7069f"[strata] { len ( parser . notes ) } tool call argument(s) repaired: { '; ' . join ( sorted ( set ( parser . notes ))) } " ,flush = True ) 7070rejected = [] 7071if parser .unread : 7072named = getattr (parser ,"unread_names" ,None ) 7073f"[strata] { parser . unread } <tool_call> block(s) in the answer did not read as a call of a declared " 7074"tool and went back as text (a name the request did not declare, or a form the template does " 7075"not use)" + (f"; the names the model wrote: { ', ' . join ( named ) } " if named else "" ) 7076+ "; the response carries them as strata_rejected_tool_calls, /metrics counts them" ,flush = True ) 7077with self .status_lock : 7078self .totals ["tool_calls_unread" ]= self .totals .get ("tool_calls_unread" ,0 )+ parser .unread 7079# #3796: the same names for the client (a machine-readable marker next to the text, which stays as the model wrote it) 7080rejected = [{"name" :nm ,"reason" :"undeclared" }for nm in named or []] 7081if stops is not None and stops .hit is None and stops .held : 7082yield "event" ,Event ("content" ,stops .flush ())# the held tail was not a stop string after all 7083done = {"finish" :finish ,"completion_tokens" :n ,"reused" : (timings or {}).get ("cache_n" ,0 ), 7084"timings" :timings ,"reasoning_tokens" :thinking_n , 7085"reasoning_recoveries" :recovery_count } 7086if stops is not None and stops .hit is not None : 7087done ["stop_sequence" ]= stops .hit 7088if rejected : 7089done ["rejected_tool_calls" ]= rejected 7090yield "done" ,done 7091 7092 7093def prompt_tokens_seen (prompt_tokens :int ,last :dict )-> int : 7094"""#471: the prompt tokens a request got through - all of them, unless the engine's DONE line says a cancel stopped 7095its prompt read part-way (then the reused ones plus those read). /metrics' history and totals count these, so a 7096cancelled read is neither recorded as the whole prompt nor given a rate from tokens it never read. An engine 7097before 0.1.36 does not say (no `prompt_read`): the whole prompt, as before.""" 7098read = last .get ("prompt_read" ) 7099if read is None or last .get ("finish" )!= "cancel" : 7100return prompt_tokens 7101return min (prompt_tokens ,int (last .get ("reused" )or 0 )+ int (read )) 7102 7103 7104def carry_leg (carry :dict ,leg :dict )-> None : 7105"""#1869: a request that decoded in a batch slot and went back to the solo path ends with the solo path's DONE, which 7106replaces the engine's figures: keep the slot leg's decode time, tokens and prompt figures to add to it.""" 7107for key in ("decode_ms" ,"generated" ): 7108previous ,value = carry .get (key ,0 ),leg .get (key ) 7109carry [key ]= previous + value if previous is not None and value is not None else None 7110carry .setdefault ("prompt_ms" ,float (leg .get ("prompt_ms" )or 0.0 )) 7111if leg .get ("prompt_read" )is not None : 7112carry .setdefault ("prompt_read" ,int (leg ["prompt_read" ])) 7113 7114 7115def add_carry (carry :dict ,last :dict )-> dict : 7116"""The request's totals: the earlier legs' decode time and tokens plus the final one's; the prompt figures of the leg 7117that read the prompt (the solo continuation reads next to nothing).""" 7118out = {** last ,"prompt_ms" :max (float (last .get ("prompt_ms" )or 0.0 ),carry .get ("prompt_ms" ,0.0 ))} 7119for key in ("decode_ms" ,"generated" ): 7120previous ,value = carry .get (key ,0 ),last .get (key ) 7121out [key ]= previous + value if previous is not None and value is not None else None 7122if "prompt_read" in carry : 7123out ["prompt_read" ]= carry ["prompt_read" ] 7124return out 7125 7126 7127def answer_speed (last :dict ,generated :int ,wall_s :float | None = None )-> float | None : 7128"""The one definition of "answer speed": every token the model produced (thinking and answer, the tokens it kept - not 7129the MTP drafts it threw away) over the decode time, first generated token to last. The engine's DONE line holds both 7130numbers; /metrics (`decode_tok_s`), the timings (`predicted_per_second`), the Terminal monitor and the app all use them. 7131Only an engine that sent no DONE falls back to the server's own clock from the first token, and a clock younger than 7132RATE_MIN_SPAN_S says nothing (it printed 1000000 tok/s for a one-token reply). Prompt reading is never in it.""" 7133produced ,decode_ms = last .get ("generated" ),last .get ("decode_ms" ) 7134if produced and produced >= 2 and decode_ms and decode_ms > 0 :# one token has no first-to-last span (a 1-token probe printed 1,250 tok/s) 7135return round (produced / (decode_ms / 1000 ),1 ) 7136if generated and wall_s is not None and wall_s >= RATE_MIN_SPAN_S : 7137return round (generated / wall_s ,1 ) 7138return None 7139 7140 7141def request_timings (prompt_tokens :int ,generated :int ,last :dict )-> dict | None : 7142"""One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clock 7143(StrataEngine.last): prompt_n is what was read, cache_n what the conversation cache already held. None when the 7144engine keeps no clock (MockEngine).""" 7145if last .get ("prompt_ms" )is None : 7146return None 7147cache_n = int (last .get ("reused" )or 0 ) 7148if last .get ("prompt_read" )is not None and last .get ("finish" )!= "cancel" : 7149# #1870: the engine says how many prompt tokens it read: the slot's own session may have held the rest 7150# (not the conversation cache), so the rate is not made of tokens it never read 7151cache_n = max (cache_n ,max (0 ,prompt_tokens - int (last ["prompt_read" ]))) 7152prompt_n ,prompt_ms ,decode_ms = max (0 ,prompt_tokens - cache_n ),float (last ["prompt_ms" ]),last .get ("decode_ms" ) 7153decoded = last .get ("generated" )# explicit zero and missing native work are not the API's output count 7154return {"cache_n" :cache_n ,"prompt_n" :prompt_n ,"prompt_ms" :round (prompt_ms ,1 ), 7155"prompt_per_token_ms" :round (prompt_ms / prompt_n ,3 )if prompt_n else None , 7156"prompt_per_second" :round (prompt_n / (prompt_ms / 1000 ),1 )if prompt_n and prompt_ms > 0 else None , 7157"predicted_n" :generated ,"predicted_ms" :round (decode_ms ,1 )if decode_ms is not None else None , 7158"predicted_per_token_ms" :round (decode_ms / decoded ,3 )if decoded and decode_ms is not None else None , 7159"predicted_per_second" :round (decoded / (decode_ms / 1000 ),1 )if decoded and decode_ms and decode_ms > 0 else None , 7160# the speculative drafts, as llama.cpp names them (from PR #83, @mikicvi): only when the engine reported them 7161** ({"draft_n" :int (last ["drafts_offered" ]),"draft_n_accepted" :int (last ["drafts_accepted" ])} 7162if last .get ("drafts_offered" )is not None else {})} 7163 7164 7165def request_stats (segments :list [dict ])-> dict : 7166"""Keep input/cache accounting at the original API boundary and total native work across continuations.""" 7167if not segments : 7168return {} 7169result = dict (segments [- 1 ]) 7170for key in ("reused" ,"prompt_read" ,"chunk" ): 7171if key in segments [0 ]: 7172result [key ]= segments [0 ][key ] 7173else : 7174result .pop (key ,None ) 7175for key in ("prompt_ms" ,"decode_ms" ,"generated" ,"drafts_offered" ,"drafts_accepted" , 7176"hits" ,"lookups" ,"offloaded" ,"ram_blobs" ,"file_blobs" ,"file_mb" ,"experts_streamed" ): 7177if key in ("decode_ms" ,"generated" )and any (segment .get (key )is None for segment in segments ): 7178result [key ]= None 7179elif any (segment .get (key )is not None for segment in segments ): 7180result [key ]= sum (segment .get (key )or 0 for segment in segments ) 7181return result 7182 7183 7184def prefill_leg_stats (earlier :list [dict ],last :dict ,prompt_tokens :int )-> dict : 7185"""Total yielded reads once, retaining only reuse from before this API request.""" 7186legs = [* earlier ,last ] 7187total = request_stats (legs ) 7188if all (leg .get ("prompt_read" )is not None for leg in legs ): 7189fresh = max (0 ,prompt_tokens - int (total .get ("reused" )or 0 )) 7190total ["prompt_read" ]= min (fresh ,sum (int (leg ["prompt_read" ])for leg in legs )) 7191return total 7192 7193 7194def _debug_req (api ,req ,messages ,tools ,max_new ,thinking ,prompt_tokens ): 7195"""One compact line per request while diagnosing blank/empty turns. Set STRATA_DEBUG=1 to enable.""" 7196if not os .environ .get ("STRATA_DEBUG" ): 7197return 7198last = messages [- 1 ]if messages else {} 7199body = last .get ("content" ) 7200if isinstance (body ,list ): 7201body = " " .join (p .get ("text" ,"" )for p in body if isinstance (p ,dict )) 7202preview = (str (body or "" )[:80 ]).replace ("\n" ," " ) 7203f"[strata] req { api } : msgs= { len ( messages ) } tools= { len ( tools or []) } " 7204f"max_tokens_raw= { req . get ( 'max_tokens' )!r } / { req . get ( 'max_completion_tokens' )!r } " 7205f"max_new= { max_new } thinking= { thinking } stream= { bool ( req . get ( 'stream' )) } " 7206f"prompt_tokens= { prompt_tokens } last= { last . get ( 'role' )!r } : { preview !r } " ,flush = True ) 7207 7208 7209# ------------------------------------------------------------------------------------------------ MCP tool loop 7210def run_with_mcp (svc :Service ,hub ,messages ,tools ,kw ,ids ,thinking ,max_new ,max_req ,sampling ,cancel , 7211mcp_names ): 7212"""Service.run with the MCP tools executed here: the model writes a call to an MCP tool, the server runs it, adds 7213the call and its result to the conversation and lets the model continue - up to `max_rounds` times. Yields what 7214Service.run yields (text, thinking, the request's own tool calls) plus ("mcp", {...}) for the tool activity, and 7215one ("done", ...) at the very end with the output tokens of every round. After the last tool round, one final 7216reply uses the results already obtained, with no tools offered or executed. 7217 7218`mcp_names`: the MCP tools this request offered; any other call is one of the request's own tools and ends the 7219turn as always (the client answers it). MCP calls written in the same answer are then not run (their results 7220could not reach the model before the client's).""" 7221max_rounds = int (hub .settings ["max_rounds" ]) 7222total ,rounds ,done = 0 ,0 ,None 7223finalizing = False 7224messages = list (messages ) 7225while True : 7226text ,reasoning ,calls ,own_calls = [], [], [],0 7227for kind ,x in svc .run (ids ,thinking ,tools ,max_new ,sampling ,cancel ,declared_only = True ): 7228if kind == "done" : 7229done = x 7230continue 7231if kind == "event" : 7232ev :Event = x 7233if ev .call is not None and ev .call .name in mcp_names : 7234if ev .kind == "tool_start" :# the model has started writing a call: say so at once 7235yield "mcp" , {"event" :"start" ,"id" :ev .call .id ,"name" :ev .call .name } 7236elif ev .kind == "tool_call" : 7237calls .append (ev .call ) 7238continue # its argument pieces are not streamed to the client 7239if ev .kind == "tool_call" : 7240own_calls += 1 7241elif ev .kind == "content" : 7242text .append (ev .text ) 7243elif ev .kind == "reasoning" : 7244reasoning .append (ev .text ) 7245yield kind ,x 7246total += done ["completion_tokens" ] 7247run_them = calls and not own_calls and not finalizing and done ["finish" ]== "stop" and not cancel .is_set () 7248if not run_them : 7249for c in calls :# announced, never run: close them in the client's view 7250yield "mcp" , {"event" :"result" ,"id" :c .id ,"ok" :False ,"skipped" :True ,"text" :"not run" , 7251"chars" :0 ,"truncated" :False ,"ms" :0 } 7252break 7253rounds += 1 7254results = [] 7255for c in calls : 7256s ,tool = hub .routes ().get (c .name , (None ,c .name )) 7257yield "mcp" , {"event" :"call" ,"id" :c .id ,"name" :c .name ,"server" :s .name if s else None , 7258"tool" :tool ,"arguments" :c .arguments ,"round" :rounds } 7259# The call runs on a thread while this generator keeps yielding heartbeats: they reach the client as 7260# keep-alives, which is how a client that went away (the web app's Stop) is noticed during a slow tool. 7261box = {} 7262 7263def work (c = c ,box = box ): 7264try : 7265box ["r" ]= hub .call (c .name ,c .arguments ,cancel ) 7266except McpCancelled : 7267box ["cancelled" ]= True 7268worker = threading .Thread (target = work ,daemon = True ) 7269worker .start () 7270try : 7271while worker .is_alive (): 7272worker .join (1.0 ) 7273if worker .is_alive (): 7274yield "ping" ,None 7275except GeneratorExit : 7276cancel .set ()# the client is gone: stop the tool too 7277raise 7278if "r" not in box : 7279break 7280r = box ["r" ] 7281f"[strata] tool { c . name } : { 'ok' if r [ 'ok' ] else 'error' } , { r [ 'chars' ]:, } characters in " 7282f" { r [ 'ms' ] / 1000 :.1f } s { ' (truncated for the model)' if r [ 'truncated' ] else '' } " ,flush = True ) 7283results .append (r .get ("model_content" ,r ["text" ])if svc .vision is not None else r ["text" ]) 7284yield "mcp" , {"event" :"result" ,"id" :c .id , 7285** ({"images" :r ["images" ],"vision" :svc .vision is not None }if r .get ("images" )else {}), 7286** {k :r [k ]for k in ("ok" ,"text" ,"chars" ,"truncated" ,"ms" )}} 7287if cancel .is_set ()or len (results )< len (calls ): 7288done = {** done ,"finish" :"cancel" } 7289break 7290messages .append ({"role" :"assistant" ,"content" :"" .join (text ).strip (), 7291** ({"reasoning_content" :"" .join (reasoning ).strip ()}if reasoning else {}), 7292"tool_calls" : [{"function" : {"name" :c .name ,"arguments" :c .arguments }}for c in calls ]}) 7293messages += [{"role" :"tool" ,"content" :r }for r in results ] 7294if rounds >= max_rounds : 7295finalizing = True 7296tools = None 7297system_end = next ((index for index ,message in enumerate (messages ) 7298if message .get ("role" )not in ("system" ,"developer" )),len (messages )) 7299messages .insert (system_end , {"role" :"system" ,"content" : 7300f"The tool-use limit of { max_rounds } rounds has been reached. No tools are available for this final " 7301"reply. Answer the user's original request in their language using the results already obtained. " 7302"Explain any gaps in the available evidence. Do not request or emit further tool calls." }) 7303yield "mcp" , {"event" :"limit" ,"max_rounds" :max_rounds } 7304try : 7305ids ,thinking ,max_new = svc .prepare (messages ,tools ,kw ,max_req ,cancel = cancel ) 7306except ClientGone :# #1999: the client left while a picture was prepared 7307done = {** done ,"finish" :"cancel" } 7308break 7309yield "done" , {** done ,"completion_tokens" :total ,"prompt_tokens" :len (ids )} 7310 7311 7312# ------------------------------------------------------------------------------------------------ OpenAI 7313# The engine's last PP line stops short of the prompt: up to `--short-read` tokens (generate.cpp's `short_read`, 64 by 7314# default) are read through the verify windows instead of the batched path, so the batched path never reports the whole 7315# prompt. A PP that close to the end says the prompt is read. It matters because a prompt shorter than one `--prefill` 7316# chunk sends exactly one PP, that one: a client would see a bar that appears already full. Such a line is dropped, and 7317# the answer's first token ends the progress for the client anyway. 7318PP_DONE_TAIL = 64 7319 7320 7321 7322class LPLines (collections .deque ): 7323"""One request's LP lines, tagged with its cancel Event (one per request, handed unchanged from the handler 7324through Service.run to Engine.generate). The last events of a request - the parser's and the stop strings' 7325tail - come after it has left the queue, when the next request may already have replaced the engine's lp_lines 7326with its own: LogprobEntries reads only the lines tagged with its own request's Event.""" 7327 7328def __init__ (self ,owner = None ): 7329super ().__init__ () 7330self .owner = owner 7331 7332 7333class LogprobEntries : 7334"""The engine's LP lines as OpenAI's logprobs.content entries. 7335 7336Each token's "token" is the text it completes (an incremental UTF-8 decode, as the reply's 7337text is made), so a character split across tokens lands in the token that finishes it and 7338the tokens, joined, spell the reply. "bytes" are the token's own bytes. The stop token 7339ends the reply and is not listed (OpenAI does not list it either). Tokens that make no 7340text of the reply are left out, because spell() gives each piece of text the tokens that 7341spell it. 7342 7343`allowed_token_ids`: only those ids are kept, and the logprobs are renormalised over them, 7344so a caller asking about specific candidates gets a distribution over exactly those instead 7345of a top-K list it has to hope contains them. vLLM, which named the field, masks generation 7346with these ids instead (every other logit -inf before sampling) and reports the unmasked 7347distribution; here they filter what is reported, so the chosen token can be outside them. 7348 7349On `--parallel`: only a `max_tokens` 1 request gets entries (an admission, decoded through the single-token path 7350that writes an LP line); the slot's `BT` lines carry none, so a longer reply is refused (400) before it starts. 7351""" 7352 7353def __init__ (self ,svc ,allowed = (),owner = None ): 7354self .tok ,self .stop_ids = svc .tok ,svc .stop_ids 7355self .allowed = [i for i in allowed ] 7356self .inc = codecs .getincrementaldecoder ("utf-8" )(errors = "replace" ) 7357self .pending = []# entries read but not yet given to a piece of text 7358self .owner = owner # the request's cancel Event (LPLines) 7359self .lines = None # this request's current LPLines, kept once seen 7360 7361def spell (self ,eng ,text :str )-> list : 7362"""The entries whose tokens spell `text`, the next piece of the reply.""" 7363self .pending += self .take (eng ) 7364at = [0 ] 7365for e in self .pending : 7366at .append (at [- 1 ]+ len (e ["token" ])) 7367joined = "" .join (e ["token" ]for e in self .pending ) 7368i = joined .find (text ) 7369while i >= 0 and text : 7370if i in at : 7371a = at .index (i )# the first token there 7372end = i + len (text ) 7373b = next ((j for j in range (a + 1 ,len (at ))if at [j ]== end ),None ) 7374if b is not None : 7375out ,self .pending = self .pending [a :b ],self .pending [b :] 7376return out 7377i = joined .find (text ,i + 1 ) 7378out ,self .pending = self .pending , [] 7379return out 7380 7381def raw (self ,t ): 7382if hasattr (self .tok ,"token_bytes" ): 7383return self .tok .token_bytes (t ) 7384return self .tok .decode ([t ]).encode ("utf-8" ) 7385 7386def take (self ,eng )-> list : 7387# the engine's current lines are this request's only when they carry its Event (a later generate pass 7388# of the same request makes new ones: the old ones are read to the end first); another request's never are. 7389# A batch admission keeps its own lines on the request's cancel Event: the engine's is one attribute, and 7390# the next request to read control lines may already have replaced it. 7391own = getattr (self .owner ,"_strata_lp_lines" ,None ) 7392cur ,old = (own if own is not None else getattr (eng ,"lp_lines" ,None )),None 7393if cur is not self .lines and getattr (cur ,"owner" ,None )is self .owner : 7394old ,self .lines = self .lines ,cur 7395out = [] 7396for lines in (old ,self .lines ): 7397while lines : 7398t ,line = lines .popleft () 7399if t in self .stop_ids : 7400continue 7401f = line .split () 7402if len (f )< 2 : 7403continue 7404try :# "nan" (no head logits for that window row), "-nan(ind)" 7405lp = float (f [1 ])# (MSVC) or a cut line: no entry for that token 7406alts = [(int (i ),float (v ))for i ,_ ,v in (x .partition (":" )for x in f [2 :])] 7407except ValueError : 7408continue 7409if not math .isfinite (lp )or not all (math .isfinite (v )for _ ,v in alts ): 7410continue 7411b = self .raw (t ) 7412e = {"token" :self .inc .decode (b ),"logprob" :lp ,"bytes" :list (b ), 7413"top_logprobs" : []} 7414if self .allowed : 7415alts = [(i ,v )for i ,v in alts if i in self .allowed ] 7416for i ,v in alts : 7417alt = self .raw (i ) 7418e ["top_logprobs" ].append ({"token" :alt .decode ("utf-8" ,"replace" ), 7419"logprob" :v ,"bytes" :list (alt )}) 7420if self .allowed : 7421e = self ._renormalise (e ,t ,lp ) 7422out .append (e ) 7423return out 7424 7425def _renormalise (self ,e ,t ,lp ): 7426"""Keep only the named ids and normalise over them, so they sum to 1. 7427 7428The line carries the chosen token's own logprob on its head and the named ids after it, and never 7429repeats the chosen one among them. So the chosen token is put back when the caller named it: with 7430`allowed_token_ids` naming only the token the model chose, that token is then the whole distribution, 7431at 1 (logprob 0), which is what vLLM's mask gives -- here it used to leave nothing to normalise over, 7432which returned None, the entry was appended all the same, and the reply failed on e["token"]. A line 7433that carries none of the named ids has nothing to normalise over either: the entry keeps the chosen 7434token and its own logprob, with no alternatives. It is never None and never dropped, because the 7435reply's tokens have to keep spelling its text. 7436""" 7437cand = e ["top_logprobs" ] 7438own = None 7439if t in self .allowed :# named, and not repeated on the line: it is a candidate 7440b = self .raw (t ) 7441own = {"token" :b .decode ("utf-8" ,"replace" ),"logprob" :lp ,"bytes" :list (b )} 7442cand = [own ]+ cand 7443if not cand : 7444return e # no named id observed for this token: its own logprob, no top 7445mx = max (x ["logprob" ]for x in cand ) 7446se = sum (math .exp (x ["logprob" ]- mx )for x in cand ) 7447lse = mx + math .log (se ) 7448for x in cand : 7449x ["logprob" ]-= lse 7450cand .sort (key = lambda x :- x ["logprob" ])# most likely first, as the unfiltered top-k already is 7451e ["top_logprobs" ]= cand 7452if own is not None :# the chosen token is in the distribution: report its own value 7453e ["logprob" ]= own ["logprob" ]# (it used to copy the first alternative's, another token's) 7454return e 7455 7456def prompt_progress (svc :Service ): 7457"""The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the 7458same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a 7459client takes the reused prefix out with `cache` (llama.cpp's rule: the timed progress is 7460`(processed-cache)/(total-cache)`). None when there is nothing to say: no PP yet, or the line that says the prompt 7461is read. An engine too old to print RESUME gives `cache` 0, which only makes a reused prefix count as work.""" 7462engine = svc .engine 7463if getattr (engine ,"batch" ,0 ):# --batch: the engine's progress is one global line, not this request's 7464return None 7465progress = getattr (engine ,"progress" ,None ) 7466if not progress : 7467return None 7468read ,total = progress 7469if total <= 0 or total - read <= PP_DONE_TAIL : 7470return None 7471return {"total" :int (total ),"cache" :int (getattr (engine ,"reused" ,0 )or 0 ),"processed" :int (read ), 7472"time_ms" :int (getattr (engine ,"progress_ms" ,0 )or 0 )} 7473 7474 7475def openai_chunks (svc :Service ,req :dict ,ids ,thinking ,tools ,max_new ,cancel ,run = None ,force = None ): 7476"""`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with 7477an empty delta and a `strata_mcp` field, which only the web app reads. `force`: see Service.run.""" 7478cid ,created = "chatcmpl-" + uuid .uuid4 ().hex [:24 ],int (time .time ()) 7479model = svc .model_for (req ) 7480# llama.cpp's flag, and its default: a client that wants prompt progress asks for it, and nothing changes for one 7481# that does not. Strata already sends a keep-alive comment on every PP line, so this only fills that line in. 7482want_progress = bool (req .get ("return_progress" )) 7483 7484def chunk (delta ,finish = None ): 7485return {"id" :cid ,"object" :"chat.completion.chunk" ,"created" :created ,"model" :model , 7486"choices" : [{"index" :0 ,"delta" :delta ,"finish_reason" :finish }]} 7487 7488yield chunk ({"role" :"assistant" ,"content" :"" }) 7489lp = LogprobEntries (svc ,allowed_ids (req ),cancel )if top_logprobs (req )is not None else None 7490 7491def with_lp (c ,key ): 7492got = lp .spell (svc .engine ,c ["choices" ][0 ]["delta" ][key ])if lp is not None else None 7493if got : 7494c ["choices" ][0 ]["logprobs" ]= {key :got } 7495return c 7496calls = 0 7497streamed = {}# tool call id -> index, for calls sent piece by piece 7498finished = set ()# ... and the ones whose final tool_call came (#211) 7499answered_done = False # the run's own end (its "done" event) arrived 7500born = getattr (svc .engine ,"gen" ,None )# the engine process this request is on (read again with every event: a start inside the run is its own) 7501for kind ,x in run if run is not None else svc .run (ids ,thinking ,tools ,max_new ,req ,cancel ,force = force ,declared_only = True ): 7502born = getattr (svc .engine ,"gen" ,born ) 7503if kind == "ping" : 7504# a PP line: the prompt is being read and there is nothing to say yet. It used to be only the SSE comment; 7505# now it carries the progress when the client asked, and stays the comment when there is nothing to report. 7506pp = prompt_progress (svc )if want_progress else None 7507yield None if pp is None else {** chunk ({}),"prompt_progress" :pp } 7508elif kind == "mcp" : 7509c = chunk ({}) 7510c ["strata_mcp" ]= x 7511yield c 7512elif kind == "event" : 7513ev :Event = x 7514if ev .kind == "reasoning" and ev .text : 7515yield with_lp (chunk ({"reasoning_content" :ev .text }),"reasoning_content" ) 7516elif ev .kind == "content" and ev .text : 7517yield with_lp (chunk ({"content" :ev .text }),"content" ) 7518elif ev .kind == "tool_start" : 7519streamed [ev .call .id ]= calls 7520calls += 1 7521yield chunk ({"tool_calls" : [{"index" :streamed [ev .call .id ],"id" :ev .call .id ,"type" :"function" , 7522"function" : {"name" :ev .call .name ,"arguments" :"" }}]}) 7523elif ev .kind == "tool_args" : 7524yield chunk ({"tool_calls" : [{"index" :streamed [ev .call .id ],"function" : {"arguments" :ev .text }}]}) 7525elif ev .kind == "tool_call" and ev .call .id in streamed : 7526finished .add (ev .call .id ) 7527elif ev .kind == "tool_call" : 7528yield chunk ({"tool_calls" : [{"index" :calls ,"id" :ev .call .id ,"type" :"function" , 7529"function" : {"name" :ev .call .name , 7530"arguments" :json .dumps (ev .call .arguments ,ensure_ascii = False )}}]}) 7531calls += 1 7532else : 7533answered_done = True 7534# a streamed call without its final tool_call is one the output ended inside: not "tool_calls" (#211) 7535whole = calls and streamed .keys ()<= finished 7536finish = "tool_calls" if whole and x ["finish" ]== "stop" else {"cancel" :"stop" }.get (x ["finish" ],x ["finish" ]) 7537last = chunk ({},finish ) 7538pt = x .get ("prompt_tokens" ,len (ids ))# after MCP rounds: the last round's prompt 7539last ["usage" ]= {"prompt_tokens" :pt ,"completion_tokens" :x ["completion_tokens" ], 7540"total_tokens" :pt + x ["completion_tokens" ], 7541# the part of the prompt the conversation cache already held (OpenAI's field) 7542"prompt_tokens_details" : {"cached_tokens" :x .get ("reused" )or 0 }} 7543if x .get ("timings" ): 7544last ["timings" ]= x ["timings" ]# llama.cpp's field: the speed its clients show 7545if x .get ("rejected_tool_calls" ): 7546last ["strata_rejected_tool_calls" ]= x ["rejected_tool_calls" ]# #3796: only when a call was refused as undeclared 7547yield last 7548if not answered_done and not cancel .is_set (): 7549# Every admitted request ends with a "done" event that carries its finish reason. A run that simply stopped (a 200 with one chunk and no 7550# finish_reason, in 0.2 s, while the engine never logged the request: #3961) used to read to the client as an empty answer that worked, and 7551# /health stayed ok. It is an error now, counted in the log, so a client's retry can tell it from an answer. 7552"[strata] a request ended without an answer and without a finish reason; it is answered as an error" ,flush = True ) 7553# the engine is ended so "the next request restarts it" is true - but only that engine process, and only while nobody is on it (the turn is taken 7554# without waiting): this runs after the run released its turn, and a request admitted since must not be killed by it 7555ended = svc .end_engine_if_unchanged (born ) 7556lost = EngineDied ("the engine ended the request without an answer" ) 7557lost .restarts = bool (ended )# "the next request restarts it" only where the engine really was ended (not with batch slots, replicas, another request on it) 7558raise lost 7559 7560 7561def _is_json (text :str )-> bool : 7562try : 7563json .loads (text ) 7564return True 7565except ValueError : 7566return False 7567 7568 7569def openai_collect (chunks )-> dict : 7570content ,reasoning ,by_index ,last ,mcp = [], [], {},None , [] 7571lps = {}# "content" / "reasoning_content" -> logprob entries 7572for c in chunks : 7573if c is None :# a heartbeat 7574continue 7575if c .get ("strata_mcp" ): 7576mcp .append (c ["strata_mcp" ]) 7577for k ,v in (c ["choices" ][0 ].get ("logprobs" )or {}).items (): 7578lps .setdefault (k , []).extend (v ) 7579d = c ["choices" ][0 ]["delta" ] 7580content .append (d .get ("content" )or "" ) 7581reasoning .append (d .get ("reasoning_content" )or "" ) 7582for tc in d .get ("tool_calls" )or []:# streamed calls arrive in pieces: merge them by index 7583cur = by_index .setdefault (tc .get ("index" ,len (by_index )), {"id" :None ,"type" :"function" , 7584"function" : {"name" :"" ,"arguments" :"" }}) 7585cur ["id" ]= tc .get ("id" )or cur ["id" ] 7586fn = tc .get ("function" )or {} 7587cur ["function" ]["name" ]+= fn .get ("name" )or "" 7588cur ["function" ]["arguments" ]+= fn .get ("arguments" )or "" 7589last = c 7590calls = [by_index [i ]for i in sorted (by_index )] 7591if last ["choices" ][0 ]["finish_reason" ]!= "tool_calls" : 7592calls = [c for c in calls if _is_json (c ["function" ]["arguments" ])]# a call the output ended inside (#211) 7593msg = {"role" :"assistant" ,"content" :"" .join (content )or None } 7594if "" .join (reasoning ).strip ()and "" .join (reasoning ).strip ()== "" .join (content ).strip (): 7595reasoning = []# a turn with no </think> (serve/dsml.py): the text is the answer; it is not also reasoning 7596if "" .join (reasoning ): 7597msg ["reasoning_content" ]= "" .join (reasoning ) 7598if calls : 7599msg ["tool_calls" ]= calls 7600if mcp : 7601msg ["strata_mcp" ]= mcp 7602out = {"id" :last ["id" ],"object" :"chat.completion" ,"created" :last ["created" ],"model" :last ["model" ], 7603"choices" : [{"index" :0 ,"message" :msg ,"finish_reason" :last ["choices" ][0 ]["finish_reason" ]}], 7604"usage" :last ["usage" ]} 7605if lps : 7606out ["choices" ][0 ]["logprobs" ]= {"content" :lps .get ("content" , []),"refusal" :None ,** ( 7607 {"reasoning_content" :lps ["reasoning_content" ]}if lps .get ("reasoning_content" )else {})} 7608if last .get ("timings" ): 7609out ["timings" ]= last ["timings" ] 7610if last .get ("strata_rejected_tool_calls" ): 7611out ["strata_rejected_tool_calls" ]= last ["strata_rejected_tool_calls" ] 7612return out 7613 7614 7615def logprob_span (text :str ,part :str ,entries :list ): 7616"""The entries whose tokens spell `part`, a piece of `text`, or None when the tokens do not 7617spell `text` or no token boundary falls at both ends of `part`.""" 7618if "" .join (e ["token" ]for e in entries )!= text : 7619return None 7620start = text .find (part ) 7621if start < 0 : 7622return None 7623at ,first = 0 ,None 7624for i ,e in enumerate (entries ): 7625if at == start and first is None : 7626first = i 7627if at == start + len (part )and first is not None : 7628return entries [first :i ] 7629at += len (e ["token" ]) 7630return entries [first :]if first is not None and at == start + len (part )else None 7631 7632 7633def _same_json (a :str ,b :str )-> bool : 7634"""Are two strings the same JSON value (whitespace and key order aside)? No -> False.""" 7635try : 7636return json .loads (a )== json .loads (b ) 7637except Exception : 7638return False 7639 7640 7641def _structured_logprobs (choice :dict ,content :str ): 7642"""`content`'s logprobs, and the content the tokens actually spell. 7643 7644Returns `(content, logprobs)`: on failure `(the content as validated, None)`. 7645 7646`structured_chunks` returns the canonical JSON the validator produced, which the model never 7647generated, so its tokens do not spell it. Two honest outcomes: 7648 76491. a run of tokens spells what is being returned -> use it as it is; 76502. the tokens spell the model's own JSON, which is the same JSON value (the fenced-with-spaces 7651case, the common one) -> return the model's form, so `''.join(token) == content` again. 7652 7653Neither holds (a rearranged key order, or a reply that is not that JSON at all) and there are no 7654logprobs: a caller that joins the tokens must not silently get something that does not match. 7655""" 7656lps = choice .get ("logprobs" ) 7657if not lps or not lps .get ("content" ): 7658return content ,None 7659raw = choice ["message" ]["content" ]or "" 7660entries = lps ["content" ] 7661if raw == content :# not rewritten: the entries are already its 7662return content ,_with_reasoning (lps ,entries ) 7663span = logprob_span (raw ,content ,entries ) 7664if span is not None : 7665return content ,_with_reasoning (lps ,span ) 7666inner = extract_json (raw ) 7667if inner and _same_json (inner ,content ): 7668span = logprob_span (raw ,inner ,entries ) 7669if span is not None : 7670return inner ,_with_reasoning (lps ,span )# the model's own form: the tokens spell it 7671return content ,None 7672 7673 7674def _with_reasoning (lps :dict ,entries :list )-> dict : 7675out = {"content" :entries } 7676if lps .get ("reasoning_content" ): 7677out ["reasoning_content" ]= lps ["reasoning_content" ] 7678return out 7679 7680 7681def structured_chunks (chunks ,validator ): 7682"""Buffer structured streams so a client never receives unvalidated content.""" 7683buffered = [] 7684heartbeat = time .monotonic () 7685try : 7686for chunk in chunks : 7687progress = chunk is not None and "prompt_progress" in chunk 7688if chunk is not None and not progress : 7689buffered .append (chunk )# a progress chunk carries no content: there is nothing in it to validate 7690if chunk is None or progress or time .monotonic ()- heartbeat >= 1 : 7691heartbeat = time .monotonic () 7692yield chunk if progress else None 7693result = openai_collect (buffered ) 7694choice = result ["choices" ][0 ] 7695content = validated_json (choice ["message" ]["content" ],validator ,choice ["finish_reason" ]) 7696# logprobs: the entries spell what the model wrote, which this function replaces with the 7697# canonical JSON. `_structured_logprobs` gives back the form the tokens spell, or None. 7698content ,logprobs = _structured_logprobs (choice ,content ) 7699yield buffered [0 ] 7700delta = {"content" :content } 7701if choice ["message" ].get ("reasoning_content" ): 7702delta ["reasoning_content" ]= choice ["message" ]["reasoning_content" ] 7703piece = {"index" :0 ,"delta" :delta ,"finish_reason" :None } 7704if logprobs : 7705piece ["logprobs" ]= logprobs 7706yield {** buffered [0 ],"choices" : [piece ]} 7707end = buffered [- 1 ] 7708if end ["choices" ][0 ].get ("logprobs" ): 7709# those entries went out in the piece above (or were dropped with it): the closing 7710# chunk must not carry a second copy 7711end = {** end ,"choices" : [{k :v for k ,v in end ["choices" ][0 ].items ()if k != "logprobs" }]} 7712yield end 7713finally : 7714chunks .close () 7715 7716 7717# ------------------------------------------------------------------------------------------------ Anthropic 7718def anthropic_events (svc :Service ,req :dict ,ids ,thinking ,tools ,max_new ,cancel ,force = None ,deferred = False ): 7719mid = "msg_" + uuid .uuid4 ().hex [:24 ] 7720yield "message_start" , {"type" :"message_start" ,"message" : { 7721"id" :mid ,"type" :"message" ,"role" :"assistant" ,"model" :svc .model_for (req ),"content" : [], 7722"stop_reason" :None ,"stop_sequence" :None ,"usage" : {"input_tokens" :len (ids ),"output_tokens" :0 }}} 7723index ,open_kind ,used_tool = - 1 ,None ,False 7724 7725def close (): 7726return ("content_block_stop" , {"type" :"content_block_stop" ,"index" :index }) 7727 7728streamed ,finished = set (),set ()# calls sent piece by piece; those whose final tool_call came (#211) 7729for kind ,x in svc .run (ids ,thinking ,tools ,max_new ,req ,cancel ,force = force ,declared_only = True , 7730deferred = deferred ): 7731if kind == "ping" : 7732yield None 7733continue 7734if kind == "event" : 7735ev :Event = x 7736if ev .kind == "tool_args" : 7737yield "content_block_delta" , {"type" :"content_block_delta" ,"index" :index , 7738"delta" : {"type" :"input_json_delta" ,"partial_json" :ev .text }} 7739continue 7740if ev .kind == "tool_call" and ev .call .id in streamed : 7741finished .add (ev .call .id ) 7742continue 7743want = {"reasoning" :"thinking" ,"content" :"text" ,"tool_call" :"tool_use" ,"tool_start" :"tool_use" }[ev .kind ] 7744if ev .kind not in ("tool_call" ,"tool_start" )and not ev .text : 7745continue 7746if ev .kind == "tool_start" : 7747streamed .add (ev .call .id ) 7748used_tool = True 7749if open_kind != want or want == "tool_use" : 7750if open_kind is not None : 7751yield close () 7752index += 1 7753open_kind = want 7754block = {"thinking" : {"type" :"thinking" ,"thinking" :"" ,"signature" :"" }, 7755"text" : {"type" :"text" ,"text" :"" }, 7756"tool_use" : {"type" :"tool_use" ,"id" :ev .call .id if ev .call else "" ,"name" : 7757ev .call .name if ev .call else "" ,"input" : {}}}[want ] 7758yield "content_block_start" , {"type" :"content_block_start" ,"index" :index ,"content_block" :block } 7759if want == "thinking" : 7760yield "content_block_delta" , {"type" :"content_block_delta" ,"index" :index , 7761"delta" : {"type" :"thinking_delta" ,"thinking" :ev .text }} 7762elif want == "text" : 7763yield "content_block_delta" , {"type" :"content_block_delta" ,"index" :index , 7764"delta" : {"type" :"text_delta" ,"text" :ev .text }} 7765elif ev .kind == "tool_start" : 7766pass # its input follows as tool_args pieces 7767else : 7768used_tool = True 7769yield "content_block_delta" , {"type" :"content_block_delta" ,"index" :index ,"delta" : { 7770"type" :"input_json_delta" ,"partial_json" :json .dumps (ev .call .arguments ,ensure_ascii = False )}} 7771else : 7772if open_kind is not None : 7773yield close () 7774stop = "stop_sequence" if x .get ("stop_sequence" )is not None else \ 7775"tool_use" if used_tool and streamed <= finished and x ["finish" ]== "stop" else \ 7776 {"stop" :"end_turn" ,"length" :"max_tokens" ,"cancel" :"end_turn" }[x ["finish" ]] 7777# the final counts (message_start could only say the whole prompt): what was read now stays for the next 7778# request, a cache write; input_tokens keeps the last token, as 0 makes Claude Code count the prompt twice (#1013) 7779reused = max (0 ,min (x .get ("reused" )or 0 ,len (ids )- 1 )) 7780read_now = len (ids )- reused 7781delta_event = {"type" :"message_delta" ,"delta" : {"stop_reason" :stop ,"stop_sequence" :x .get ("stop_sequence" )}, 7782"usage" : {"input_tokens" :1 ,"cache_creation_input_tokens" :read_now - 1 , 7783"cache_read_input_tokens" :reused ,"output_tokens" :x ["completion_tokens" ]}} 7784if x .get ("rejected_tool_calls" ): 7785delta_event ["strata_rejected_tool_calls" ]= x ["rejected_tool_calls" ]# #3796 7786yield "message_delta" ,delta_event 7787yield "message_stop" , {"type" :"message_stop" } 7788 7789 7790def anthropic_collect (events )-> dict : 7791msg ,blocks = None , [] 7792for item in events : 7793if item is None :# a heartbeat 7794continue 7795name ,e = item 7796if name == "message_start" : 7797msg = e ["message" ] 7798elif name == "content_block_start" : 7799blocks .append (dict (e ["content_block" ])) 7800elif name == "content_block_delta" : 7801d ,b = e ["delta" ],blocks [- 1 ] 7802if d ["type" ]== "text_delta" : 7803b ["text" ]+= d ["text" ] 7804elif d ["type" ]== "thinking_delta" : 7805b ["thinking" ]+= d ["thinking" ] 7806else :# input_json_delta pieces: parsed when complete 7807b ["_json" ]= b .get ("_json" ,"" )+ d ["partial_json" ] 7808elif name == "content_block_stop" and blocks and "_json" in blocks [- 1 ]: 7809b = blocks [- 1 ] 7810try : 7811b ["input" ]= json .loads (b .pop ("_json" )or "{}" ) 7812except ValueError :# a call the output ended inside (#211): it has no input to give 7813blocks .pop () 7814elif name == "message_delta" : 7815msg ["stop_reason" ]= e ["delta" ]["stop_reason" ] 7816msg ["stop_sequence" ]= e ["delta" ].get ("stop_sequence" ) 7817msg ["usage" ].update (e ["usage" ]) 7818if e .get ("strata_rejected_tool_calls" ): 7819msg ["strata_rejected_tool_calls" ]= e ["strata_rejected_tool_calls" ] 7820for i in range (len (blocks )- 1 ):# a turn with no </think> (serve/dsml.py): the text is the answer; it is not also a thinking block 7821a ,b = blocks [i ],blocks [i + 1 ] 7822if a .get ("type" )== "thinking" and b .get ("type" )== "text" and a .get ("thinking" ,"" ).strip ()== b .get ("text" ,"" ).strip (): 7823del blocks [i ] 7824break 7825msg ["content" ]= blocks 7826return msg 7827 7828 7829# ------------------------------------------------------------------------------------------------ HTTP 7830CHUNKED_BODY_MAX = 256 << 20 # #893: the most a Transfer-Encoding: chunked body may hold (read into memory) 7831 7832 7833def body_limit ()-> int : 7834"""The most a request body may hold, in bytes (read into memory): 256 MiB, which is a million-token conversation 7835with room to spare; STRATA_MAX_BODY_MIB changes it (0 or an unreadable value: the default). A larger one is 7836answered 413 before it is read (a Content-Length of 10 TB used to be read until the client gave up).""" 7837try : 7838mib = int (os .environ .get ("STRATA_MAX_BODY_MIB" ,"0" )) 7839except ValueError : 7840mib = 0 7841return mib << 20 if mib > 0 else CHUNKED_BODY_MAX 7842 7843 7844class BadBody (Exception ): 7845"""A request body that cannot be read (a malformed or oversized chunked body): the status and the sentence.""" 7846 7847def __init__ (self ,status :int ,message :str ): 7848super ().__init__ (message ) 7849self .status = status 7850 7851 7852def make_handler (svc :Service ): 7853class Handler (BaseHTTPRequestHandler ): 7854protocol_version = "HTTP/1.0" # SSE ends by closing the connection 7855 7856record = None # #332: this request's monitor record, if kept 7857watch_done = None # #430 #431: stops this request's disconnect watcher 7858cancel_event = None # active generation owned by this handler 7859body_read = False # whether a handler took this request's body 7860DRAIN_SECONDS = 5 # the longest an unread body is read and dropped 7861 7862def log_message (self ,fmt ,* args ): 7863pass 7864 7865def handle_one_request (self ): 7866self .answer_started = False 7867super ().handle_one_request () 7868self ._drain_body () 7869 7870def send_response (self ,code ,message = None ): 7871self .answer_started = True # a malformed-request answer can only replace one not yet begun 7872super ().send_response (code ,message ) 7873 7874def _chunked (self )-> bool : 7875"""#893: a body sent as Transfer-Encoding: chunked (a relay or proxy that does not buffer it). By RFC 9112 7876it wins over a Content-Length.""" 7877te = self .headers .get ("Transfer-Encoding" ,"" )or "" 7878return te .split ("," )[- 1 ].strip ().lower ()== "chunked" 7879 7880def _read_chunked (self ,limit :int ,keep :bool = True ,deadline :float | None = None )-> bytes : 7881"""Decode a chunked body: at most `limit` bytes (BadBody 413 beyond it - the size is checked before a chunk 7882is read, so a huge announced chunk is never allocated), BadBody 400 for a malformed one. keep=False reads 7883and drops it (the drain); `deadline` (monotonic) ends the read early.""" 7884parts ,total = [],0 7885while True : 7886if deadline is not None : 7887wait = deadline - time .monotonic () 7888if wait <= 0 : 7889return b"" .join (parts ) 7890self .connection .settimeout (wait ) 7891line = self .rfile .readline (1025 ) 7892if not line .endswith (b"\n" ): 7893raise BadBody (400 ,"malformed chunked request body" ) 7894try : 7895size = int (line .split (b";" ,1 )[0 ].strip (),16 ) 7896except ValueError : 7897raise BadBody (400 ,"malformed chunk size in the request body" )from None 7898if size < 0 : 7899raise BadBody (400 ,"malformed chunk size in the request body" ) 7900if size == 0 : 7901for _ in range (64 ):# the trailers, including the final blank line 7902trailer = self .rfile .readline (8193 ) 7903if trailer == b"\r\n" : 7904return b"" .join (parts ) 7905if not trailer .endswith (b"\r\n" ): 7906raise BadBody (400 ,"malformed or incomplete chunked request trailers" ) 7907raise BadBody (400 ,"too many chunked request trailers" ) 7908total += size 7909if total > limit : 7910self .close_connection = True 7911raise BadBody (413 ,f"the request body is larger than { limit >> 20 } MiB" ) 7912left = size 7913while left > 0 : 7914piece = self .rfile .read (min (left ,1 << 20 )) 7915if not piece : 7916raise BadBody (400 ,"the chunked request body ended early" ) 7917left -= len (piece ) 7918if keep : 7919parts .append (piece ) 7920if self .rfile .read (2 )!= b"\r\n" : 7921raise BadBody (400 ,"malformed chunked request body" ) 7922 7923def _body (self )-> bytes : 7924self .body_read = True 7925limit = body_limit () 7926if self ._chunked (): 7927return self ._read_chunked (limit ) 7928try : 7929length = int (self .headers .get ("Content-Length" ,0 )) 7930except ValueError : 7931raise BadBody (400 ,"invalid Content-Length" )from None 7932if length < 0 : 7933raise BadBody (400 ,"invalid Content-Length" ) 7934if length > limit : 7935self .close_connection = True # the body is not read: the connection ends with the answer 7936raise BadBody (413 ,f"the request body is larger than { limit >> 20 } MiB " 7937"(STRATA_MAX_BODY_MIB raises the limit)" ) 7938return self .rfile .read (length ) 7939 7940def _drain_body (self ): 7941"""An answer sent before the body was read (a 401, a 403, /load, a method with no handler) must not close 7942the connection on unread bytes: the close then sends a reset, and a client that sends its body after the 7943headers (http.client, urllib, requests) gets a connection error instead of the answer. So the body is 7944read and dropped here, once, after an answer, in pieces so that its size is never held in memory. What 7945has not arrived DRAIN_SECONDS later is left unread: the limit is time, so that a conversation of many 7946megabytes, at any speed the client has, still gets its answer.""" 7947headers = getattr (self ,"headers" ,None ) 7948if self .body_read or headers is None : 7949return 7950if self ._chunked (): 7951try : 7952self ._read_chunked (body_limit (),keep = False ,deadline = time .monotonic ()+ self .DRAIN_SECONDS ) 7953except (BadBody ,OSError ): 7954self .close_connection = True 7955return 7956try : 7957left = int (headers .get ("Content-Length" ,0 )) 7958except ValueError : 7959return 7960if left <= 0 : 7961return 7962deadline = time .monotonic ()+ self .DRAIN_SECONDS 7963try : 7964while left > 0 and (wait := deadline - time .monotonic ())> 0 : 7965self .connection .settimeout (wait )# a client that never sends what it announced 7966piece = self .rfile .read1 (min (left ,1 << 20 ))# one socket read: read() would wait for it all 7967if not piece : 7968break 7969left -= len (piece ) 7970except OSError : 7971pass 7972 7973def parse_request (self ): 7974"""Without an API key, every request (any method) first passes the Host check: DNS rebinding protection 7975(host_allowed). With a key a rebinding page cannot authenticate, so the check is skipped: tunnels and 7976proxies that pass their own name on keep working.""" 7977if not super ().parse_request (): 7978return False 7979host = self .headers .get ("Host" ) 7980if svc .api_key or host_allowed (host ,svc .host_names ,"*" in svc .allowed_hosts ): 7981return True 7982f"[strata] refused a request for Host { host !r } from { self . client_address [ 0 ] } : not a name this server " 7983f"answers to (add it to \"allowed_hosts\" in the config or STRATA_ALLOWED_HOSTS, or set an API key)" , 7984flush = True ) 7985self ._json (403 , {"error" : {"type" :"forbidden" ,"message" : 7986f"Host { host !r } is not allowed (DNS rebinding protection). Reaching Strata under this " 7987f"name on purpose? Add it to \"allowed_hosts\" in the config (strata-<model>.json) or to " 7988f"the STRATA_ALLOWED_HOSTS environment variable, or set an API key (\"api_key\"), which " 7989f"turns this check off" }}) 7990return False 7991 7992def _foreign_page (self )-> bool : 7993"""Without an API key, a /v1 POST from a browser page of another site (any site can POST text/plain 7994there without a CORS preflight) would burn GPU time: an Origin header must name an allowed page, and 7995then the body must be JSON. No Origin (curl, the SDKs, other servers): any content type, as before.""" 7996origin = self .headers .get ("Origin" ) 7997if svc .api_key or not origin : 7998return False 7999if not origin_allowed (origin ,self .headers .get ("Host" ),svc .host_names , 8000 [* svc .trusted_origins ,* svc .cors_origins ]): 8001f"[strata] refused an API request from the web page { origin !r } (no API key; add its host to " 8002f"\"allowed_hosts\" or its origin to \"cors_origins\" in the config)" ,flush = True ) 8003self ._json (403 , {"error" : {"type" :"forbidden" ,"message" : 8004f"web pages of { origin } may not use this server without an API key; set \"api_key\", " 8005f"or add the page's host to \"allowed_hosts\" (or its origin to \"cors_origins\") " 8006f"in the config" }}) 8007return True 8008if not self .headers .get ("Content-Type" ,"" ).startswith ("application/json" ): 8009self ._json (415 , {"error" : {"message" :"send application/json" }}) 8010return True 8011return False 8012 8013def end_headers (self ): 8014# HTTP/1.0 without keep-alive: the server closes the connection after every response. Say so, or a 8015# client that pools connections (.NET's SocketsHttpHandler) can put its next request on this socket 8016# before the close reaches it, and that request fails with "response ended prematurely" without the 8017# server ever reading it (a .NET agent app, 2026-10-03: 25 of ~1000 requests, 1-24 ms after the previous answer). 8018self .send_header ("Connection" ,"close" ) 8019super ().end_headers () 8020 8021def _watch_client (self ,cancel :threading .Event )-> None : 8022"""#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing 8023until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up 8024usually still succeeds), so a dropped request kept the engine busy until its answer or the whole prompt 8025was done. Every 0.5 s: the socket readable with nothing to read (EOF) means the client closed it. A 8026request is HTTP/1.0 and fully read here, so no later bytes are expected - data is not a hang-up.""" 8027done = self .watch_done = threading .Event () 8028self .cancel_event = cancel 8029with svc .status_lock : 8030svc .active_cancels .add (cancel ) 8031sock = self .connection 8032 8033def watch (): 8034while not done .wait (0.5 )and not cancel .is_set (): 8035try : 8036readable ,_ ,_ = select .select ([sock ], [], [],0 ) 8037gone = bool (readable )and sock .recv (1 ,socket .MSG_PEEK )== b"" 8038except (ConnectionError ,TimeoutError ): 8039gone = True 8040except (OSError ,ValueError ):# the socket was closed here: the request has ended 8041return 8042if gone and not done .is_set (): 8043self ._note (outcome = "disconnected" ) 8044svc .note_client_disconnect (cancel ) 8045return 8046 8047threading .Thread (target = watch ,daemon = True ,name = "strata-client-watch" ).start () 8048 8049def _note (self ,** values ): 8050"""#332: what the monitor shows about this request (nothing when the monitor is off).""" 8051if self .record is not None : 8052with svc .status_lock : 8053self .record .update (values ) 8054 8055def _cors (self ): 8056"""#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing 8057otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools.""" 8058if not svc .cors_origins or not self .path .split ("?" )[0 ].startswith ("/v1/" ): 8059return 8060origin = (self .headers .get ("Origin" )or "" ).rstrip ("/" ) 8061if "*" in svc .cors_origins : 8062allow = "*" 8063elif origin and origin in svc .cors_origins : 8064allow = origin 8065self .send_header ("Vary" ,"Origin" ) 8066else : 8067return 8068self .send_header ("Access-Control-Allow-Origin" ,allow ) 8069self .send_header ("Access-Control-Allow-Methods" ,"GET, POST, OPTIONS" ) 8070# the headers the preflight asks for (SDKs add their own; "*" does not cover Authorization) 8071asked = self .headers .get ("Access-Control-Request-Headers" ) 8072self .send_header ("Access-Control-Allow-Headers" , 8073asked or "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta" ) 8074self .send_header ("Access-Control-Max-Age" ,"600" ) 8075 8076def do_OPTIONS (self ): 8077# a CORS preflight: no credentials come with it, so no API key; the headers only for cors_origins 8078self .send_response (204 ) 8079self ._cors () 8080self .send_header ("Content-Length" ,"0" ) 8081self .end_headers () 8082 8083def _json (self ,code ,obj ,headers = None ,retry_after = None ): 8084if self .record is not None : 8085with svc .status_lock : 8086self .record ["http_status" ]= code 8087raw = json .dumps (obj ,ensure_ascii = False ,indent = 2 ) 8088self .record .update (response = raw [:262144 ],response_truncated = len (raw )> 262144 ) 8089for key in ("error" ,"usage" ,"timings" ): 8090if key in obj : 8091self .record [key ]= obj [key ] 8092body = json .dumps (obj ,ensure_ascii = False ).encode () 8093self .send_response (code ) 8094self .send_header ("Content-Type" ,"application/json" ) 8095for k ,v in (headers or {}).items (): 8096self .send_header (k ,str (v )) 8097if retry_after is not None : 8098self .send_header ("Retry-After" ,str (retry_after )) 8099self ._cors () 8100self .send_header ("Content-Length" ,str (len (body ))) 8101self .end_headers () 8102self .wfile .write (body ) 8103 8104def _authorized (self )-> bool : 8105if not svc .api_key : 8106return True 8107auth = self .headers .get ("Authorization" ,"" ) 8108given = auth [7 :].strip ()if auth .lower ().startswith ("bearer " )else self .headers .get ("x-api-key" ,"" ) 8109if key_matches (given ,svc .api_key ): 8110return True 8111self ._json (401 , {"error" : {"type" :"authentication_error" ,"message" :"missing or wrong API key" }}) 8112return False 8113 8114def _authorized_telemetry (self )-> bool : 8115if not svc .api_key and not svc .telemetry_key : 8116return True 8117auth = self .headers .get ("Authorization" ,"" ) 8118given = auth [7 :].strip ()if auth .lower ().startswith ("bearer " )else self .headers .get ("x-api-key" ,"" ) 8119if (svc .api_key and key_matches (given ,svc .api_key ))or \ 8120 (svc .telemetry_key and key_matches (given ,svc .telemetry_key )): 8121return True 8122self ._json (401 , {"error" : {"type" :"authentication_error" ,"message" :"missing or wrong telemetry key" }}) 8123return False 8124 8125def do_GET (self ): 8126path = self .path .split ("?" )[0 ].rstrip ("/" ) 8127if path .startswith ("/tool-media/" ): 8128if not self ._authorized (): 8129return 8130name = path [len ("/tool-media/" ):] 8131hub = svc .mcp 8132if not re .fullmatch (r"[0-9a-f]{64}\.(png|jpg|webp)" ,name )or not hub or not hub .media_dir : 8133self ._json (404 , {"error" : {"message" :"not found" }}) 8134return 8135file = Path (hub .media_dir )/ name 8136if not file .is_file (): 8137self ._json (404 , {"error" : {"message" :"not found" }}) 8138return 8139body = file .read_bytes () 8140self .send_response (200 ) 8141self .send_header ("Content-Type" , {".png" :"image/png" ,".jpg" :"image/jpeg" ,".webp" :"image/webp" }[file .suffix ]) 8142self .send_header ("Content-Length" ,str (len (body ))) 8143self .send_header ("X-Content-Type-Options" ,"nosniff" ) 8144self .send_header ("Cache-Control" ,"private, max-age=86400" ) 8145self .send_header ("Cross-Origin-Resource-Policy" ,"same-origin" ) 8146self .end_headers () 8147self .wfile .write (body ) 8148return 8149if path .startswith ("/fonts/" ): 8150# the web app's font (Outfit, OFL: serve/web/fonts); the page falls back to the system font 8151name = path [len ("/fonts/" ):] 8152f = ROOT / "serve" / "web" / "fonts" / name 8153if "/" in name or "\\" in name or not name .endswith (".woff2" )or not f .is_file (): 8154self ._json (404 , {"error" : {"message" :"not found" }}) 8155return 8156body = f .read_bytes () 8157self .send_response (200 ) 8158self .send_header ("Content-Type" ,"font/woff2" ) 8159self .send_header ("Cache-Control" ,"max-age=86400" ) 8160self .send_header ("Content-Length" ,str (len (body ))) 8161self .end_headers () 8162self .wfile .write (body ) 8163return 8164sub = web_subtree_file (path ) 8165if path .startswith (("/web/locales/" ,"/web/vendor/" )): 8166# the page's translations (serve/web/locales/<lang>.json) and the vendored KaTeX (serve/web/vendor): 8167# only whitelisted names and types, never a path out of those folders 8168if sub is None : 8169self ._json (404 , {"error" : {"message" :"not found" }}) 8170return 8171body = sub [0 ].read_bytes () 8172self .send_response (200 ) 8173self .send_header ("Content-Type" ,sub [1 ]) 8174self .send_header ("Cache-Control" ,"no-cache" ) 8175self .send_header ("Content-Length" ,str (len (body ))) 8176self .end_headers () 8177self .wfile .write (body ) 8178return 8179if path .startswith ("/web/" ): 8180# the web app's own files (serve/web): styles, script, icon sprite - same origin, no CDN 8181name = path [len ("/web/" ):] 8182types = {".css" :"text/css; charset=utf-8" ,".js" :"text/javascript; charset=utf-8" , 8183".svg" :"image/svg+xml" } 8184f = ROOT / "serve" / "web" / name 8185ext = os .path .splitext (name )[1 ] 8186if "/" in name or "\\" in name or ext not in types or not f .is_file (): 8187self ._json (404 , {"error" : {"message" :"not found" }}) 8188return 8189body = f .read_bytes () 8190self .send_response (200 ) 8191self .send_header ("Content-Type" ,types [ext ]) 8192self .send_header ("Cache-Control" ,"no-cache" ) 8193self .send_header ("Content-Length" ,str (len (body ))) 8194self .end_headers () 8195self .wfile .write (body ) 8196return 8197if path == "/metrics/prometheus" : 8198if self ._authorized (): 8199body = svc .prometheus ().encode () 8200self .send_response (200 ) 8201self .send_header ("Content-Type" ,"text/plain; version=0.0.4; charset=utf-8" ) 8202self .send_header ("Content-Length" ,str (len (body ))) 8203self .end_headers () 8204self .wfile .write (body ) 8205return 8206if path == "/metrics" : 8207from serve import prometheus 8208if prometheus .wants_prometheus (self .headers .get ("Accept" ,"" ),urlsplit (self .path ).query ): 8209if self ._authorized ():# a scraper: the text format, vLLM's names (serve/prometheus.py) 8210body = prometheus .render (svc .metrics (),svc .latencies .snapshot ()).encode () 8211self .send_response (200 ) 8212self .send_header ("Content-Type" ,prometheus .CONTENT_TYPE ) 8213self .send_header ("Content-Length" ,str (len (body ))) 8214self .end_headers () 8215self .wfile .write (body ) 8216return 8217if self ._authorized (): 8218# the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) 8219self ._json (200 ,svc .metrics (all_requests = "requests=all" in self .path )) 8220return 8221if path == "/v1/telemetry" : 8222if self ._authorized_telemetry (): 8223from strata_cli .client import normalize_legacy 8224snapshot = normalize_legacy (svc .metrics (),svc .v1_status ()) 8225snapshot ["source" ]= "server-v1" 8226snapshot ["work" ]["slots_requested" ]= getattr (svc ,"requested_slots" ,None ) 8227# Keep /metrics' established slot shape intact; enrich only this versioned contract. 8228replica_engines = (getattr (svc .engine ,"engines" ,None ) 8229if hasattr (svc .engine ,"replica_view" )else None ) 8230if replica_engines : 8231groups ,live_slots ,replica_by_slot = [], [], [] 8232group_base = 0 8233all_batched = True 8234for replica ,child in enumerate (replica_engines ): 8235count = int (getattr (child ,"batch" ,0 )or 0 ) 8236all_batched = all_batched and count > 0 8237count = max (1 ,count ) 8238child_groups = getattr (child ,"slot_group" , []) 8239child_live = getattr (child ,"slot_live" , []) 8240for local in range (count ): 8241group = child_groups [local ]if local < len (child_groups )else None 8242groups .append (group_base + group if type (group )is int and group >= 0 else None ) 8243live_slots .append (child_live [local ]if local < len (child_live )else None ) 8244replica_by_slot .append (replica ) 8245group_base += int (getattr (child ,"slot_groups" ,0 )or 0 ) 8246snapshot ["work" ]["groups" ]= group_base if all_batched and group_base > 0 else None 8247else : 8248groups = getattr (svc .engine ,"slot_group" , []) 8249live_slots = getattr (svc .engine ,"slot_live" , []) 8250replica_by_slot = [] 8251for slot in snapshot ["work" ]["slots" ]: 8252i = slot .get ("slot" ) 8253if type (i )is int and 0 <= i < len (groups ): 8254slot ["group" ]= groups [i ] 8255if type (i )is int and 0 <= i < len (replica_by_slot ): 8256slot ["replica" ]= replica_by_slot [i ] 8257if type (i )is int and 0 <= i < len (live_slots )and live_slots [i ]: 8258slot ["request_id" ]= live_slots [i ].get ("request_id" ) 8259slot_by_id = {slot .get ("request_id" ):slot for slot in snapshot ["work" ]["slots" ] 8260if slot .get ("request_id" )} 8261with svc .status_lock : 8262active = list (svc .terminal_requests .values ()) 8263snapshot ["activity" ]= {"last_seq" :svc .terminal_event_seq , 8264"events" :list (svc .terminal_events )[- 32 :]} 8265draining = svc .draining 8266admission_reserved = svc .admission_reserved 8267admission_rejected = svc .admission_rejected 8268queue_timeouts = svc .queue_timeouts 8269client_disconnect_cancels = svc .client_disconnect_cancels 8270in_flight_tokens = (sum (max (0 ,int (st .get ("generated" )or 0 )) 8271for st ,_ in svc .live_reqs .values ()) 8272if svc .live_reqs else 8273max (0 ,int (svc .status .get ("generated" )or 0 )) 8274if svc .status .get ("busy" )else 0 ) 8275output_counter = int (svc .totals .get ("output_tokens" )or 0 )+ in_flight_tokens 8276snapshot ["instance" ]["id" ]= svc .instance_id 8277snapshot ["instance" ]["state" ]= "draining" if draining else "ready" 8278if getattr (svc ,"launch_attestation" ,None )is not None : 8279snapshot ["instance" ]["launch_attestation" ]= svc .launch_attestation 8280snapshot ["rates" ]["output_tokens_server_counter" ]= output_counter 8281snapshot ["work" ]["requests_omitted" ]= max (0 ,len (active )- 50 ) 8282snapshot ["work" ].update (max_queue = svc .max_queue ,queue_timeout_s = svc .queue_timeout_s , 8283queue_timeouts = queue_timeouts , 8284client_disconnect_cancels = client_disconnect_cancels , 8285admission_limit = svc .admission_limit (), 8286admission_reserved = admission_reserved , 8287admission_rejected = admission_rejected , 8288oldest_queue_s = max ((max (0 ,time .time ()- row ["queued_at" ]) 8289for row in active if row ["state" ]in ("queued" ,"waiting" )), 8290default = 0 )) 8291snapshot ["work" ]["requests" ]= [ 8292 {** row ,"state" :slot_by_id [row ["id" ]]["state" ]if row ["id" ]in slot_by_id else row ["state" ], 8293"slot" :slot_by_id [row ["id" ]]["slot" ]if row ["id" ]in slot_by_id else None , 8294"group" :slot_by_id [row ["id" ]]["group" ]if row ["id" ]in slot_by_id else None , 8295"replica" :slot_by_id [row ["id" ]]["replica" ]if row ["id" ]in slot_by_id else row .get ("replica" ), 8296"generated" :slot_by_id [row ["id" ]].get ("generated" )if row ["id" ]in slot_by_id else None , 8297"prompt_read" :slot_by_id [row ["id" ]].get ("prompt_read" )if row ["id" ]in slot_by_id else None } 8298for row in active [:50 ]] 8299snapshot ["quality" ]["request_correlation" ]= "reported" 8300batch_sample = (getattr (svc .engine ,"terminal_batch_sample" ,None ) 8301if svc .loaded ()and not replica_engines else None ) 8302if replica_engines : 8303replica_batches = [] 8304for replica ,child in enumerate (replica_engines [:16 ]): 8305row = {"replica" :replica } 8306sample = (getattr (child ,"terminal_batch_sample" ,None ) 8307if child .alive ()else None ) 8308if sample : 8309row .update (batch_sample_windows = sample ["windows" ], 8310batch_sample_rows = sample ["processed_rows" ], 8311batch_sample_active_rows = sample ["active_rows" ], 8312batch_sample_span_s = sample ["elapsed_ms" ]/ 1000.0 , 8313batch_sample_age_s = max (0.0 ,time .monotonic ()- 8314sample ["observed_monotonic" ])) 8315replica_batches .append (row ) 8316snapshot ["work" ]["replica_batches" ]= replica_batches 8317if batch_sample : 8318windows = batch_sample ["windows" ] 8319snapshot ["work" ].update (effective_rows_window = batch_sample ["processed_rows" ]/ windows , 8320batch_active_rows_window = batch_sample ["active_rows" ]/ windows , 8321batch_sample_windows = windows , 8322batch_sample_rows = batch_sample ["processed_rows" ], 8323batch_sample_active_rows = batch_sample ["active_rows" ], 8324batch_sample_span_s = batch_sample ["elapsed_ms" ]/ 1000.0 , 8325batch_sample_age_s = max (0.0 ,time .monotonic ()- 8326batch_sample ["observed_monotonic" ])) 8327snapshot ["quality" ]["batch_window_rows" ]= "measured" 8328snapshot ["quality" ]["batch_window_source" ]= "engine_bstat" 8329stage_sample = (getattr (svc .engine ,"terminal_stage_sample" ,None ) 8330if svc .loaded ()and not replica_engines else None ) 8331if replica_engines : 8332replica_stage_samples = [] 8333for replica ,child in enumerate (replica_engines [:16 ]): 8334row = {"replica" :replica } 8335sample = (getattr (child ,"terminal_stage_sample" ,None ) 8336if child .alive ()else None ) 8337if sample : 8338row .update (stage_sample_elapsed_us = sample ["elapsed_us" ], 8339stage_in_flight_us = sample ["in_flight_us" ], 8340stage_sample_age_s = max (0.0 ,time .monotonic ()- 8341sample ["observed_monotonic" ])) 8342replica_stage_samples .append (row ) 8343snapshot ["work" ]["replica_stage_samples" ]= replica_stage_samples 8344if stage_sample : 8345snapshot ["work" ].update (stage_sample_elapsed_us = stage_sample ["elapsed_us" ], 8346stage_in_flight_us = stage_sample ["in_flight_us" ], 8347stage_sample_age_s = max (0.0 ,time .monotonic ()- 8348stage_sample ["observed_monotonic" ])) 8349snapshot ["quality" ]["stage_in_flight_source" ]= "engine_pstat_host_span" 8350indices = list (getattr (svc ,"gpu_indices" , [])or []) 8351visibility = list (getattr (svc ,"terminal_visibility_order" , [])or []) 8352reported = (list (getattr (svc .engine ,"terminal_stages" , [])or []) 8353if svc .loaded ()and not replica_engines else []) 8354stages = [{** stage ,"device_index" : 8355visibility [stage ["engine_ordinal" ]] 8356if stage ["engine_ordinal" ]< len (visibility )else None } 8357for stage in reported ] 8358snapshot ["topology" ]["selected_devices" ]= indices if replica_engines else visibility or indices 8359replica_devices = getattr (svc ,"replica_gpu_groups" , [])if replica_engines else [] 8360snapshot ["topology" ]["replica_devices" ]= [ 8361 {"replica" :i ,"devices" :list (devices )} 8362for i ,devices in enumerate (replica_devices [:16 ])] 8363replica_stages = [] 8364for replica ,child in enumerate ((replica_engines or [])[:16 ]): 8365child_reported = (list (getattr (child ,"terminal_stages" , [])or []) 8366if child .alive ()else []) 8367spawn = getattr (child ,"spawn" ,None ) 8368child_env = spawn [4 ]if isinstance (spawn ,tuple )and len (spawn )> 4 else None 8369child_visibility = visible_device_order (child_env ,getattr (svc ,"backend" ,None )) 8370configured_cards = (set (replica_devices [replica ]) 8371if replica < len (replica_devices )else set ()) 8372child_stages = [] 8373for stage in child_reported : 8374ordinal = stage ["engine_ordinal" ] 8375card = (child_visibility [ordinal ] 8376if type (ordinal )is int and 0 <= ordinal < len (child_visibility )else None ) 8377child_stages .append ({** stage ,"device_index" :card if card in configured_cards else None }) 8378replica_stages .append ({"replica" :replica ,"stages" :child_stages }) 8379snapshot ["topology" ]["replica_stages" ]= replica_stages 8380snapshot ["topology" ]["mode" ]= ("layer split (engine reported)" if stages else 8381getattr (svc ,"terminal_topology_mode" ,None )) 8382snapshot ["topology" ]["configured_split" ]= getattr (svc ,"terminal_configured_split" ,None ) 8383snapshot ["topology" ]["stages" ]= stages 8384snapshot ["topology" ]["resolved" ]= bool (stages )and all ( 8385stage ["device_index" ]is not None for stage in stages ) 8386snapshot ["topology" ]["source" ]= "engine_start_log" if stages else None 8387snapshot ["quality" ]["placement" ]= ("reported" if snapshot ["topology" ]["resolved" ]else 8388"partial" if stages else "unavailable" ) 8389present = {d .get ("index" )for d in snapshot ["devices" ]} 8390for index in indices : 8391if index not in present : 8392snapshot ["devices" ].append ({"index" :index ,"name" :None ,"mem_used" :None , 8393"mem_total" :None ,"util" :None ,"temp" :None ,"power" :None }) 8394self ._json (200 ,snapshot ) 8395return 8396if path == "/api/requests" and svc .api_monitor : 8397if self ._authorized (): 8398request_id = parse_qs (urlsplit (self .path ).query ).get ("id" , [None ])[0 ] 8399records = svc .request_records (request_id ) 8400self ._json (404 if records is None else 200 , 8401 {"error" : {"message" :"request no longer retained" }}if records is None else 8402records if request_id else {"requests" :records ,"retention" :100 ,"persistent" :False , 8403"loaded" :svc .loaded (),"auto_load" :hasattr (svc .engine ,"restart" )}) 8404return 8405if path == "/settings" : 8406if self ._authorized (): 8407self ._json (200 , {"shared" :bool (svc .shared ),"defaults" :svc .shared }) 8408return 8409if path == "/config" :# #564: the Settings view's keys of the run config 8410if self ._authorized (): 8411self ._config_get () 8412return 8413if path == "/mcp" : 8414# the MCP servers, their state and tools (the web app's switch and Monitor card) 8415if self ._authorized (): 8416self ._json (200 ,svc .mcp .status ()if svc .mcp else {"servers" : [],"tools" :0 }) 8417return 8418if path == "" or (path == "/api-monitor" and svc .api_monitor ): 8419body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html" )).read_bytes () 8420self .send_response (200 ) 8421self .send_header ("Content-Type" ,"text/html; charset=utf-8" ) 8422if not path : 8423# the chat's svg/html preview is a sandboxed frame; this keeps it from navigating away to a web page 8424# (a link or <meta refresh> inside a model's html), which no sandbox flag does (serve/web/preview.js) 8425self .send_header ("Content-Security-Policy" ,PAGE_CSP ) 8426self .send_header ("Content-Length" ,str (len (body ))) 8427self .end_headers () 8428self .wfile .write (body ) 8429elif path in ("/health" ,"/api/health" ): 8430self ._json (200 , {"status" :"ok" ,"max_context" :svc .reported_ctx (),"model" :svc .model , 8431"images" :svc .vision is not None ,"api_key" :bool (svc .api_key ), 8432"image_generation" :svc .images is not None , 8433"loaded" :svc .loaded (),"service" :"strata" }) 8434elif path .startswith ("/v1/images/files/" ): 8435# response_format url: the name (32 random hex digits) is the access, as an OpenAI image URL is 8436f = svc .images .file (path [len ("/v1/images/files/" ):])if svc .images is not None else None 8437if f is None : 8438self ._json (404 , {"error" : {"message" :"not found (the server keeps the newest images only)" }}) 8439return 8440body = f .read_bytes () 8441self .send_response (200 ) 8442self .send_header ("Content-Type" ,"image/png" ) 8443self .send_header ("Cache-Control" ,"private, max-age=86400" ) 8444self .send_header ("Content-Length" ,str (len (body ))) 8445self .end_headers () 8446self .wfile .write (body ) 8447elif path == "/status" : 8448if not self ._authorized ():# #212: it shows the end of the last answer 8449return 8450with svc .status_lock : 8451s = dict (svc .status ) 8452now = time .time () 8453if s .get ("busy" ): 8454s ["elapsed_s" ]= round (now - s ["started" ],1 ) 8455if s .get ("first_token" ): 8456s ["tokens_per_s" ]= round (svc ._tok_s (),1 ) 8457s ["tokens_per_s_mean" ]= round (svc ._tok_s_mean (),1 ) 8458for k in ("started" ,"first_token" ): 8459s .pop (k ,None ) 8460self ._json (200 ,s ) 8461elif path in ("/v1/models" ,"/models" ): 8462if self ._authorized (): 8463loaded = svc .loaded () 8464model = {"id" :svc .model ,"object" :"model" ,"status" : {"value" :"loaded" }, 8465"meta" : {"n_ctx" :svc .reported_ctx ()}, 8466"architecture" : {"input_modalities" : ["text" ,"image" ]if svc .vision is not None else ["text" ], 8467"output_modalities" : ["text" ]}} 8468if not loaded and (svc .idle_unload_s or getattr (svc .engine ,"unloaded" ,False )): 8469model ["status" ]= {"value" :"unloaded" }# like llama-server's router: listed, loads on use 8470loaded = True 8471if svc .aliases :# #297: the aliases, and each one listed under its own id 8472model ["aliases" ]= list (svc .aliases ) 8473data = [model ,* ({** model ,"id" :x ,"alias_of" :svc .model }for x in svc .aliases )] 8474data = data if loaded else [] 8475if svc .images is not None :# the image model: POST /v1/images/generations 8476data .append ({"id" :svc .images .model ,"object" :"model" ,"status" : {"value" :"loaded" }, 8477"architecture" : {"input_modalities" : ["text" ],"output_modalities" : ["image" ]}}) 8478self ._json (200 , {"object" :"list" ,"data" :data }) 8479elif path == "/props" : 8480if self ._authorized (): 8481self ._props () 8482elif path == "/slots" : 8483if self ._authorized (): 8484loaded = not hasattr (svc .engine ,"alive" )or svc .engine .alive () 8485with svc .status_lock : 8486busy = bool (svc .status .get ("busy" )) 8487# llama.cpp's name for what the slot's context holds: the running request's prompt size, 8488# kept after it ends (the conversation cache carries it on). A front-end's context meter 8489# divides it by n_ctx; without the key it reads 0 % against Strata forever (#562). 8490in_use = int (svc .status .get ("prompt_tokens" )or 0 ) 8491if getattr (svc .engine ,"batch" ,0 )and hasattr (svc .engine ,"slots_view" ): 8492# --batch: one entry per slot (the same view /metrics has), not one for the whole engine 8493n_ctx = svc .reported_ctx () 8494slots = [{"id" :s ["slot" ],"n_ctx" :n_ctx ,"is_processing" :s ["state" ]!= "idle" , 8495"n_prompt_tokens" :int (s .get ("prompt_tokens" )or s .get ("held_tokens" )or 0 )} 8496for s in svc .engine .slots_view ()] 8497else : 8498slots = [{"id" :0 ,"n_ctx" :svc .reported_ctx (),"is_processing" :busy , 8499"n_prompt_tokens" :in_use }] 8500self ._json (200 ,slots if loaded else []) 8501elif path == "/v1/status" : 8502if self ._authorized (): 8503self ._json (200 ,svc .v1_status ()) 8504else : 8505self ._json (404 , {"error" : {"message" :"not found" }}) 8506 8507def do_POST (self ): 8508try : 8509self ._post () 8510except BadBody as e :# #893: a malformed or oversized chunked body 8511self ._json (e .status , {"error" : {"type" :"invalid_request_error" ,"message" :str (e )}}) 8512 8513def _post (self ): 8514if not self ._authorized (): 8515return 8516path = self .path .split ("?" )[0 ].rstrip ("/" )# issue #55: Claude Code posts /v1/messages?beta=true 8517path = V1_V1_ALIASES .get (path ,path )# an Anthropic client given ".../v1" as its base posts /v1/v1/messages 8518if path .startswith ("/v1/" )and self ._foreign_page (): 8519return 8520if path == "/settings" : 8521self ._settings () 8522return 8523if path == "/config" : 8524self ._config_post () 8525return 8526if path in ("/unload" ,"/load" )and not self ._control_body (): 8527return 8528# JSON from Strata's own page only, as /settings: else a plain form POST from any site unloads the model 8529if path in ("/unload" ,"/load" )and not self ._own_page ("the model can be loaded or unloaded" ): 8530return 8531# the same for the slot files: else any site could overwrite a saved conversation or replace the live one 8532if path .startswith ("/slots/" )and not self ._own_page ("conversations can be saved or restored" ): 8533return 8534if path == "/unload" :# give the GPU back now (between requests) 8535try : 8536wait_s = unload_wait (parse_qs (urlsplit (self .path ).query ).get ("wait" , [None ])[0 ], 8537svc .UNLOAD_WAIT_S ) 8538r = svc .unload_waiting (wait_s )if wait_s else svc .unload () 8539except EngineStuck as e : 8540self ._json (503 , {"error" : {"type" :"server_error" ,"message" :str (e )}}) 8541return 8542self ._json (409 if r == "busy" else 200 , {"status" :r }) 8543return 8544if path == "/load" :# load now, e.g. ahead of a request 8545try : 8546svc .load () 8547self ._json (200 , {"status" :"loaded" }) 8548except GpuBusy as e : 8549ra = getattr (e ,"retry_after" ,None ) 8550self ._json (503 , {"error" : {"type" :"server_error" ,"message" :str (e )}}, 8551headers = {"Retry-After" :int (ra )}if ra else None ) 8552return 8553reserved = False 8554try : 8555if path in ("/v1/chat/completions" ,"/v1/messages" ,"/v1/responses" ): 8556reserved = svc .reserve_inference () 8557if reserved is None : 8558error = {"type" :"server_error" ,"code" :"server_draining" , 8559"message" :"this instance is draining; retry against the next instance" } 8560body = responses_error_body (error ["message" ],"server_error" ,code = error ["code" ]) \ 8561if path == "/v1/responses" else {"error" :error } 8562self ._json (503 ,body ,retry_after = 1 ) 8563return 8564if not reserved : 8565error = {"type" :"rate_limit_error" ,"code" :"admission_full" , 8566"message" :"the inference admission limit is full; retry later" } 8567body = responses_error_body (error ["message" ],"server_error" ,code = error ["code" ]) \ 8568if path == "/v1/responses" else {"error" :error } 8569self ._json (429 ,body ,retry_after = 1 ) 8570return 8571req = json .loads (self ._body ()or b"{}" ) 8572if not isinstance (req ,dict ): 8573raise ValueError ("send a JSON object" ) 8574if path .startswith ("/v1/responses/" ):# retrieve/delete/cancel/compact: nothing is stored 8575self ._json (404 ,responses_error_body ("this server keeps no responses (stateless); send the " 8576"whole conversation to POST /v1/responses" ,code = "not_found" )) 8577return 8578if path in ("/v1/load" ,"/v1/unload" ): 8579if not self ._own_page ("the model can be loaded or unloaded" ): 8580return 8581if req .get ("model" )not in (None ,svc .model ): 8582self ._json (404 , {"error" : {"message" :"model not found" }}) 8583return 8584if path == "/v1/unload" : 8585wait_s = unload_wait (parse_qs (urlsplit (self .path ).query ).get ("wait" , [None ])[0 ], 8586svc .UNLOAD_WAIT_S ) 8587result = svc .unload_waiting (wait_s )if wait_s else svc .unload () 8588if result == "busy" : 8589raise ModelBusy ("a request is running or queued" ) 8590else : 8591if not svc .fifo .acquire (blocking = False ): 8592raise ModelBusy ("a request is running or queued" ) 8593try : 8594with svc .status_lock : 8595if svc .status .get ("busy" )or svc .status .get ("queued" ): 8596raise ModelBusy ("a request is running or queued" ) 8597svc .ensure_loaded () 8598svc .last_request_at = time .time () 8599finally : 8600svc .fifo .release () 8601result = "loaded" 8602self ._json (200 , {"status" :result ,** svc .v1_status ()}) 8603return 8604if path == "/v1/vram" :# #533: give VRAM back to other programs, or take it 8605if not self ._own_page ("the VRAM reserve can be changed" ): 8606return 8607r = req .get ("reserve_mib" ) 8608if r is not None and (isinstance (r ,bool )or not isinstance (r ,int )or r < 0 ): 8609raise ValueError ("reserve_mib: a whole number of MiB (0 or more), or null for the start's" ) 8610try : 8611self ._json (200 ,svc .vram (r )) 8612except EngineDied as e : 8613self ._json (503 , {"error" : {"type" :"server_error" ,"message" :str (e )}}) 8614return 8615if path in ("/v1/chat/completions" ,"/v1/messages" ,"/v1/responses" ): 8616self .record = svc .begin_request (path ,req ) 8617if path == "/v1/responses" : 8618self ._responses (req ) 8619elif path .startswith ("/slots/" ): 8620query = parse_qs (self .path .partition ("?" )[2 ]) 8621try : 8622code ,body = svc .slot_action (path [len ("/slots/" ):], (query .get ("action" )or ["" ])[0 ], 8623req .get ("filename" )) 8624except EngineDied as e :# EngineSilent included: the engine was ended 8625code ,body = 500 , {"error" : {"code" :500 ,"message" :str (e )+ "; the next request starts " 8626"the engine again" ,"type" :"server_error" }} 8627self ._json (code ,body ) 8628elif path == "/v1/chat/completions" : 8629self ._openai (req ) 8630elif path == "/v1/messages" : 8631self ._anthropic (req ) 8632elif path == "/v1/messages/count_tokens" : 8633self ._count_tokens (req ) 8634elif path == "/v1/images/generations" : 8635self ._images (req ) 8636else : 8637self ._json (404 , {"error" : {"message" :"not found" }}) 8638except EngineNonFinite as e :# #879, twice: not the request's fault 8639f"[strata] 503: { e } " ,flush = True ) 8640self ._json (503 ,responses_error_body (str (e ),"server_error" )if path == "/v1/responses" 8641else {"error" : {"type" :"server_error" ,"message" :str (e )}}) 8642except ValueError as e : 8643f"[strata] 400 invalid request: { e } " ,flush = True ) 8644if path == "/v1/responses" : 8645self ._json (400 ,responses_error_body (str (e ))) 8646else : 8647self ._json (400 , {"error" : {"type" :"invalid_request_error" ,"message" :str (e )}}) 8648except ModelBusy as e : 8649self ._json (409 , {"error" : {"type" :"model_busy" ,"message" :str (e )}}) 8650except QueueWaitExpired as e : 8651error = {"type" :"rate_limit_error" ,"code" :"queue_wait_timeout" ,"message" :str (e )} 8652self ._note (error = error ) 8653body = responses_error_body (str (e ),"server_error" ,code = "queue_wait_timeout" ) \ 8654if path == "/v1/responses" else {"error" :error } 8655self ._json (429 ,body ,retry_after = 1 ) 8656except StructuredOutputError as e : 8657self ._json (502 , {"error" : {"type" :"structured_output_failed" ,"code" :"structured_output_failed" , 8658"message" :str (e )}}) 8659except (GpuBusy ,EngineStarting )as e : 8660ra = getattr (e ,"retry_after" ,None )# #1997 / #1994: a refusal that is worth retrying 8661self ._json (503 , {"error" : {"type" :"server_error" ,"message" :str (e )}}, 8662headers = {"Retry-After" :int (ra )}if ra else None ) 8663except (TypeError ,KeyError ,AttributeError ,IndexError ,UnicodeError )as e : 8664# a body that is JSON but the wrong shape ("messages": 5, a content part that is a number): a 400 that 8665# says so, with the traceback in the log, instead of a dropped connection - unless the answer began 8666if getattr (self ,"answer_started" ,False ): 8667raise 8668import traceback 8669f"[strata] 400 malformed request ( { type ( e ). __name__ } : { e } ):\n" + traceback .format_exc (), 8670flush = True ) 8671body = {"error" : {"type" :"invalid_request_error" , 8672"message" :f"the request is malformed ( { type ( e ). __name__ } : { e } )" }} 8673self ._json (400 ,responses_error_body (body ["error" ]["message" ])if path == "/v1/responses" else body ) 8674except EngineDied as e :# before the answer started (not streamed) 8675self ._json (503 , {"error" : {"type" :"server_error" ,"message" :died_note (e )}}) 8676except EngineStuck as e :# an unload or restart that could not end the engine 8677self ._json (503 , {"error" : {"type" :"server_error" ,"message" :str (e )}}) 8678 8679except ClientGone :# #1999: the client left while the request was prepared 8680self ._note (outcome = "disconnected" ) 8681except OSError : 8682self ._note (outcome = "disconnected" ) 8683raise # as before #332: the server's own handling 8684finally : 8685if reserved : 8686svc .release_inference () 8687svc .drop_embeddings ()# the images' file of a request that never got to run() 8688if self .watch_done is not None : 8689self .watch_done .set () 8690if self .cancel_event is not None : 8691with svc .status_lock : 8692svc .active_cancels .discard (self .cancel_event ) 8693record = self .record 8694if record is not None : 8695with svc .status_lock : 8696record ["wallclock_s" ]= round (time .perf_counter ()- record ["_clock" ],3 ) 8697record ["finished_at" ]= time .time () 8698record ["state" ]= "error" if record .get ("error" )else record .get ("outcome" ,"completed" ) 8699svc .request_trace .record = None 8700 8701def _images (self ,req ): 8702"""POST /v1/images/generations (serve/images.py): one sd-cli job in the GPU's turn.""" 8703gen = svc .images 8704if gen is None : 8705self ._json (404 , {"error" : {"type" :"invalid_request_error" ,"code" :"images_not_set_up" , 8706"message" :"image generation is not set up on this server (run setup " 8707"with --images qwen-image)" }}) 8708return 8709job = images_api .parse_request (req ,gen .cfg )# ImageRequestError (a ValueError): 400 8710svc .last_request_at = time .time () 8711cancel = threading .Event () 8712self ._watch_client (cancel ) 8713f"[strata] image: { job [ 'width' ] } x { job [ 'height' ] } , n= { job [ 'n' ] } , { job [ 'steps' ] } steps, " 8714f"seed { job [ 'seed' ] } " ,flush = True ) 8715try : 8716with images_api .gpu_turn (svc ,gen ,job ,cancel )as policy : 8717images ,figures = gen .run (job ,cancel ) 8718except images_api .ImageJobFailed as e : 8719self ._json (500 , {"error" : {"type" :"server_error" ,"code" :"image_generation_failed" , 8720"message" :str (e )}}) 8721return 8722figures ["gpu_policy" ]= policy 8723f"[strata] image done in { figures [ 'seconds' ]:.1f } s ( { policy } )" ,flush = True ) 8724host = self .headers .get ("Host" )or f" { self . server . server_address [ 0 ] } : { self . server . server_address [ 1 ] } " 8725scheme = "https" if (self .headers .get ("X-Forwarded-Proto" )or "" ).lower ()== "https" else "http" 8726self ._json (200 ,gen .response (images ,job ,figures ,f" { scheme } :// { host } " )) 8727 8728def _props (self ): 8729model = parse_qs (urlsplit (self .path ).query ).get ("model" , [svc .model ])[0 ] 8730if model not in svc .model_names (): 8731self ._json (404 , {"error" : {"message" :"model not found" }}) 8732return 8733if not svc .loaded ()and not getattr (svc .engine ,"unloaded" ,False ): 8734self ._json (503 , {"error" : {"message" :"the engine is not running" }}) 8735return 8736defaults = {** model_card_sampling (svc .model_arch ,True ),** svc .sampling_defaults ,** svc .shared } 8737names = {"repetition_penalty" :"repeat_penalty" ,"penalty_last_n" :"repeat_last_n" } 8738params = {names .get (k ,k ):v for k ,v in defaults .items () 8739if k in ("temperature" ,"top_p" ,"top_k" ,"min_p" ,"seed" ,"repetition_penalty" , 8740"presence_penalty" ,"frequency_penalty" ,"penalty_last_n" )} 8741params ["n_predict" ]= svc .shared .get ("max_tokens" ,- 1 ) 8742props = {"default_generation_settings" : {"n_ctx" :svc .reported_ctx (),"params" :params }, 8743"total_slots" :max (1 ,int (getattr (svc .engine ,"batch" ,0 )or 0 )),# #1004: the batch slots 8744"model_alias" :svc .model ,"chat_template" :svc .template .source , 8745"chat_template_caps" :svc .template .caps , 8746"modalities" : {"vision" :svc .vision is not None },"models_autoload" :hasattr (svc .engine ,"restart" ), 8747"is_sleeping" :not svc .loaded ()} 8748if getattr (svc .engine ,"model_path" ,None ): 8749props ["model_path" ]= svc .engine .model_path 8750version = getattr (svc .engine ,"info" , {}).get ("version" ) 8751if version : 8752props ["build_info" ]= "Strata " + str (version ) 8753self ._json (200 ,props ) 8754 8755def _control_body (self )-> bool : 8756"""Consume the unused control body before replying/closing (Windows otherwise sends a TCP reset).""" 8757if self ._chunked (): 8758self .body_read = True 8759try : 8760self .connection .settimeout (2.0 ) 8761self ._read_chunked (65536 ,keep = False ) 8762except BadBody as e : 8763self ._json (e .status , {"error" : {"message" :f"control request: { e } " }}) 8764return False 8765except OSError : 8766self ._json (400 , {"error" : {"message" :"incomplete control request body" }}) 8767return False 8768return True 8769try : 8770length = int (self .headers .get ("Content-Length" ,"0" )) 8771except ValueError : 8772self ._json (400 , {"error" : {"message" :"invalid Content-Length" }}) 8773return False 8774if not 0 <= length <= 65536 : 8775self ._json (413 , {"error" : {"message" :"control request body is limited to 64 KiB" }}) 8776return False 8777timeout = self .connection .gettimeout () 8778try : 8779self .connection .settimeout (2.0 ) 8780complete = len (self .rfile .read (length ))== length 8781except OSError : 8782complete = False 8783finally : 8784self .connection .settimeout (timeout ) 8785self .body_read = True # nothing left for the drain to wait for (#594) 8786if not complete : 8787self ._json (400 , {"error" : {"message" :"incomplete control request body" }}) 8788return complete 8789 8790def _own_page (self ,what )-> bool : 8791"""Only JSON (a form or a "simple" cross-site request can't send it without a CORS preflight, which this 8792server never grants) and no foreign Origin: a web page elsewhere must not change settings or run tools.""" 8793if not self .headers .get ("Content-Type" ,"" ).startswith ("application/json" ): 8794self ._json (415 , {"error" : {"message" :"send application/json" }}) 8795return False 8796if self ._foreign_origin (): 8797self ._json (403 , {"error" : {"message" :f" { what } only from Strata's own page (or an origin in the " 8798f"config's trusted_origins)" }}) 8799return False 8800return True 8801 8802def _config_get (self ): 8803if not svc .config_path : 8804self ._json (404 , {"error" : {"message" :"this server was started without a run config" }}) 8805return 8806try : 8807cfg = runconfig .load (svc .config_path ) 8808except (OSError ,ValueError )as e : 8809self ._json (500 , {"error" : {"type" :"server_error" ,"message" :f"the run config cannot be read: { e } " }}) 8810return 8811self ._json (200 ,runconfig .view (cfg ,svc .config_path )) 8812 8813def _config_post (self ): 8814"""#564: change a few documented keys of the run config - JSON from Strata's own page only, as 8815/settings (the key is checked before); every other key of the file stays as it is.""" 8816body = self ._body () 8817if not self ._own_page ("the run config can be changed" ): 8818return 8819if not svc .config_path : 8820self ._json (404 , {"error" : {"message" :"this server was started without a run config" }}) 8821return 8822try : 8823req = json .loads (body or b"{}" ) 8824with svc .config_lock : 8825cfg = runconfig .load (svc .config_path ) 8826new ,changed = runconfig .apply (cfg ,req .get ("set" )if isinstance (req ,dict )else None ) 8827if changed : 8828bak = runconfig .save (svc .config_path ,new ) 8829except ValueError as e : 8830self ._json (400 , {"error" : {"type" :"invalid_request_error" ,"message" :str (e )}}) 8831return 8832except OSError as e : 8833self ._json (500 , {"error" : {"type" :"server_error" ,"message" :f"the run config cannot be written: { e } " }}) 8834return 8835if changed : 8836f"[strata] the Settings view changed { ', ' . join ( changed ) } in { Path ( svc . config_path ). name } " 8837f"(the earlier file: { bak . name } ); used from the next start" ,flush = True ) 8838self ._json (200 , {** runconfig .view (new ,svc .config_path ),"changed" :changed }) 8839def _foreign_origin (self )-> bool : 8840"""A web page of another origin sent this. The Origin must be this server's own address (host and port), 8841or an origin the config trusts (trusted_origins: the web app behind a reverse proxy or tunnel); no Origin 8842is a client that is no browser. Headers a proxy adds (X-Forwarded-*, CF-Ray, CF-Connecting-IP) prove 8843nothing about the page that sent the request, so they open nothing.""" 8844origin = (self .headers .get ("Origin" )or "" ).rstrip ("/" ) 8845return bool (origin )and origin .split ("://" ,1 )[- 1 ]!= self .headers .get ("Host" ,"" )and \ 8846origin not in svc .trusted_origins 8847 8848def _no_local_images (self ,messages ): 8849"""A web page of another origin must not have a file on this computer read as an image. Without an 8850api_key, _foreign_page refuses such a page unless cors_origins lets it in - and a page cors_origins lets 8851in (["*"]: every page) could name any file and, CORS allowing, read what the model says about it. data: 8852and http(s) images are the page's own to send; files come from Strata's own page, a trusted origin or a 8853client that is no browser. ValueError (a 400).""" 8854if self ._foreign_origin ()and any (not src .startswith (("data:" ,"http://" ,"https://" )) 8855for src in images_of (messages )): 8856raise ValueError ("a web page of another origin cannot have a file on this computer read as an " 8857"image: send it as a data: URL (or add the page's origin to the config's " 8858"trusted_origins)" ) 8859 8860def _settings (self ): 8861# They change what every client gets, so only the app's own page may set them 8862body = self ._body () 8863if not self ._own_page ("settings can be changed" ): 8864return 8865try : 8866req = json .loads (body or b"{}" ) 8867if not isinstance (req ,dict )or "defaults" not in req : 8868self ._json (400 , {"error" : {"type" :"invalid_request_error" , 8869"message" :'the body must be {"defaults": {...}} to set them, ' 8870'or {"defaults": null} to clear them' }}) 8871return 8872shared = svc .set_shared (req ["defaults" ]) 8873except ValueError as e : 8874self ._json (400 , {"error" : {"type" :"invalid_request_error" ,"message" :str (e )}}) 8875return 8876"[strata] other apps now use the Chat settings: " + ", " .join (f" { k } = { v } " for k ,v in shared .items ()) 8877if shared else "[strata] other apps use their own settings again" ,flush = True ) 8878self ._json (200 , {"shared" :bool (shared ),"defaults" :shared }) 8879 8880def _sse (self ): 8881self ._note (http_status = 200 ) 8882self .send_response (200 ) 8883self .send_header ("Content-Type" ,"text/event-stream" ) 8884self .send_header ("Cache-Control" ,"no-cache" ) 8885self .send_header ("X-Accel-Buffering" ,"no" )# nginx and similar proxies pass each event at once 8886self ._cors () 8887self .end_headers () 8888if STREAM_WRITE_TIMEOUT_S > 0 : 8889try : 8890self .connection .settimeout (STREAM_WRITE_TIMEOUT_S )# (#4271) a stuck write ends as OSError: disconnected 8891except OSError : 8892pass 8893 8894def _capture (self ,items ,api ): 8895"""Retain bounded input/output for the monitor without changing the API response (the items as they 8896are when the monitor is off).""" 8897if self .record is None : 8898return items 8899return self ._captured (items ,api ) 8900 8901def _captured (self ,items ,api ): 8902try : 8903for item in items : 8904if item is not None : 8905if api == "openai" : 8906delta = item ["choices" ][0 ]["delta" ] 8907content ,reasoning = delta .get ("content" ,"" ),delta .get ("reasoning_content" ,"" ) 8908usage ,timings = item .get ("usage" ),item .get ("timings" ) 8909elif api == "responses" : 8910kind = item ["type" ] 8911content = item ["delta" ]if kind == "response.output_text.delta" else "" 8912reasoning = item ["delta" ]if kind == "response.reasoning_text.delta" else "" 8913usage ,timings = (item .get ("response" )or {}).get ("usage" ),None 8914else : 8915_ ,event = item 8916delta = event .get ("delta" , {}) 8917content ,reasoning = delta .get ("text" ,"" ),delta .get ("thinking" ,"" ) 8918usage ,timings = event .get ("usage" ),None 8919with svc .status_lock : 8920for name ,value in (("output" ,content ), ("reasoning" ,reasoning )): 8921if value : 8922combined = self .record [name ]+ value 8923self .record [name ]= combined [:262144 ] 8924self .record [name + "_truncated" ]|= len (combined )> 262144 8925if usage : 8926self .record ["usage" ]= usage 8927if timings : 8928self .record ["timings" ]= timings 8929yield item 8930finally : 8931items .close () 8932 8933def _openai (self ,req ): 8934req = svc .with_shared (req ,"openai" ) 8935bias_api .normalize (req .get ("logit_bias" ),len (getattr (svc .tok ,"tokens" , ()))or None ) 8936messages ,tools ,kw = openai_to_messages (req ) 8937require_messages (messages )# an empty conversation is a 400, as OpenAI answers it, not a reply to nothing 8938self ._no_local_images (messages ) 8939if tool_choice_of (req .get ("tool_choice" ))[0 ]== "none" :# as the Responses route: no tools are offered 8940tools = None 8941force = svc .force_text (forced_call (req .get ("tool_choice" ),tools ))# a bad value is a 400 before anything is sent 8942messages ,validator = prepare_format (req .get ("response_format" ),messages ) 8943if validator is not None and (tools or req .get ("strata_mcp" )): 8944raise ValueError ("structured response_format with tools/MCP is not supported" ) 8945svc .load () 8946max_req = max_new = int (req .get ("max_completion_tokens" )or req .get ("max_tokens" )or 0 )# 0/-1: the rest 8947# No cap of our own on the reply's length when logprobs are asked for: the reply is already bounded by 8948# max_tokens (by the rest of the context when it is not sent), which is the only bound OpenAI and vLLM 8949# put on it either. A reply that is not streamed does hold every entry (its token, bytes and up to 20 8950# alternatives) until it ends, so a long one holds a lot: streaming hands each entry out with its chunk. 8951refuse_for_split (svc .engine ,req )# (before the batch-slot rule below: its message would say to run without --parallel) 8952if top_logprobs (req )is not None and batch_slots_on (svc .engine )and max_req != 1 : 8953# --parallel/--batch: a slot's "BT <slot> <id>" lines carry no LP line, and the batched loop never 8954# calls emit_lp_line (src/program/generate.cpp); an admission -- a max_tokens 1 request -- is read 8955# as GEN 1, which does write them. Past that one token a reply would hold entries for a prefix 8956# only, which a client cannot tell from the model's own answer, so the longer one is refused. 8957raise ValueError ('logprobs is available with "parallel" (batch slots) only for max_tokens 1; ' 8958'run the server without "--parallel" for longer replies' ) 8959n_vocab = len (getattr (svc .tok ,"tokens" , ()))or None 8960if top_logprobs (req )is not None and n_vocab : 8961# emit_lp_line indexes the logits row with each named id as given, so an id past the vocabulary 8962# would read out of bounds: refused here, before anything is sent 8963bad = [i for i in allowed_ids (req )if i >= n_vocab ] 8964if bad : 8965raise ValueError (f"allowed_token_ids: { bad [ 0 ] } is outside the vocabulary " 8966f"(0.. { n_vocab - 1 } )" ) 8967bias_api .validate_request (req ,svc .engine ,len (getattr (svc .tok ,"tokens" , ()))or None ) 8968use_mcp = req .get ("strata_mcp" )is True and svc .mcp is not None # the web app's opt-in (serve/mcp.py) 8969own = {t .get ("name" )for t in tools or []if isinstance (t ,dict )}# #592: a second line of defence 8970if use_mcp : 8971if not self ._own_page ("MCP tools can be used" ):# tools run with the user's rights on this PC 8972return 8973svc .mcp .wait (10 )# servers still starting (only right after start) 8974extra = svc .mcp .template_tools (exclude = own )# the request's own tools win a name clash 8975use_mcp = bool (extra ) 8976tools = (tools or [])+ extra or None 8977if force and use_mcp : 8978raise ValueError ("a forced tool_choice with MCP tools is not supported" ) 8979svc .reasoning_budget (req )# a bad value is a 400 before anything is sent 8980stop_strings (req )# ... and so is a bad stop / stop_sequences 8981check_request_sampling (req )# ... and a sampling field of the wrong type 8982cancel = threading .Event () 8983self ._watch_client (cancel )# #430 #431 (#1999: before prepare, which can take long) 8984ids ,thinking ,max_new = svc .prepare (messages ,tools ,kw ,max_new ,force = force ,req = req ,cancel = cancel ) 8985_debug_req ("openai" ,req ,messages ,tools ,max_new ,thinking ,len (ids )) 8986run = run_with_mcp (svc ,svc .mcp ,messages ,tools ,kw ,ids ,thinking ,max_new ,max_req ,req ,cancel , 8987 {t ["name" ]for t in extra })if use_mcp else None 8988chunks = openai_chunks (svc ,req ,ids ,thinking ,tools ,max_new ,cancel ,run = run ,force = force ) 8989if validator is not None : 8990chunks = structured_chunks (chunks ,validator ) 8991chunks = self ._capture (chunks ,"openai" ) 8992if not req .get ("stream" ): 8993return self ._json (200 ,openai_collect (chunks )) 8994self ._sse () 8995last = time .monotonic () 8996try : 8997for c in chunks : 8998if c is None : 8999# A client whose idle timeout counts chunks (the OpenAI SDK drops SSE comments) would end a 9000# request while a long prompt is read: every 15 s an empty delta tells it the server is working 9001if time .monotonic ()- last >= 15 : 9002beat = {"id" :"chatcmpl-reading" ,"object" :"chat.completion.chunk" ,"created" :int (time .time ()), 9003"model" :req .get ("model" )or "" ,"choices" : [{"index" :0 ,"delta" : {},"finish_reason" :None }]} 9004self .wfile .write (b"data: " + json .dumps (beat ).encode ()+ b"\n\n" ) 9005last = time .monotonic () 9006else : 9007self .wfile .write (b": keep-alive\n\n" )# an SSE comment: clients ignore it 9008else : 9009self .wfile .write (b"data: " + json .dumps (c ,ensure_ascii = False ).encode ()+ b"\n\n" ) 9010last = time .monotonic () 9011self .wfile .flush () 9012self .wfile .write (b"data: [DONE]\n\n" ) 9013except OSError : 9014self ._note (outcome = "disconnected" ) 9015svc .note_client_disconnect (cancel )# client went away: stop the engine 9016chunks .close () 9017except EngineDied as e :# mid-stream: say so, then end the stream properly 9018err = {"error" : {"type" :"server_error" ,"message" :died_note (e )}} 9019self ._note (error = err ["error" ]) 9020self .wfile .write (b"data: " + json .dumps (err ).encode ()+ b"\n\ndata: [DONE]\n\n" ) 9021except QueueWaitExpired as e : 9022err = {"error" : {"type" :"rate_limit_error" ,"code" :"queue_wait_timeout" ,"message" :str (e )}} 9023self ._note (error = err ["error" ]) 9024self .wfile .write (b"data: " + json .dumps (err ).encode ()+ b"\n\ndata: [DONE]\n\n" ) 9025except StructuredOutputError as e : 9026err = {"error" : {"type" :"structured_output_failed" ,"code" :"structured_output_failed" ,"message" :str (e )}} 9027self ._note (error = err ["error" ]) 9028self .wfile .write (b"data: " + json .dumps (err ).encode ()+ b"\n\ndata: [DONE]\n\n" ) 9029except ValueError as e :# the engine's ERR after the stream started: the 9030err = {"error" : {"type" :"server_error" ,"message" :str (e )}}# headers are sent, so no 400 now 9031self ._note (error = err ["error" ]) 9032self .wfile .write (b"data: " + json .dumps (err ).encode ()+ b"\n\ndata: [DONE]\n\n" ) 9033 9034def _responses_ready (self ,req ,events ): 9035"""Send a finished Responses result that did not run on the engine.""" 9036if not req .get ("stream" ): 9037return self ._json (200 ,responses_api .collect (events )) 9038self ._sse () 9039try : 9040for e in events : 9041self .wfile .write (f"event: { e [ 'type' ] } \n" .encode ()+ b"data: " + 9042json .dumps (e ,ensure_ascii = False ).encode ()+ b"\n\n" ) 9043self .wfile .flush () 9044except OSError : 9045self ._note (outcome = "disconnected" ) 9046 9047def _responses (self ,req ): 9048"""#451: POST /v1/responses - OpenAI's Responses API, stateless (serve/responses.py), on the chat path. 9049Errors use the Responses format; once the stream has started they arrive as a response.failed event.""" 9050try : 9051title = (responses_api .thread_title_events (req ,svc .model_for (req )) 9052if svc .codex_thread_titles else None ) 9053except ResponsesError as e : 9054return self ._json (e .status ,e .body ()) 9055if title is not None : 9056return self ._responses_ready (req ,title ) 9057cancel = threading .Event () 9058self ._watch_client (cancel )# #430 #431 (#1999: before prepare, which can take long) 9059try : 9060ids ,thinking ,tools ,max_new ,asm ,validator ,req = self ._responses_prepare (req ,cancel ) 9061except ClientGone : 9062self ._note (outcome = "disconnected" ) 9063return 9064except ResponsesError as e : 9065return self ._json (e .status ,e .body ()) 9066except ModelBusy as e : 9067return self ._json (409 ,responses_error_body (str (e ),"server_error" ,code = "model_busy" )) 9068except (GpuBusy ,EngineStarting ,EngineStuck ,EngineDied )as e : 9069return self ._json (503 ,responses_error_body (str (e ),"server_error" ,code = "server_error" )) 9070 9071def check (text ,finish ): 9072return validated_json (text ,validator ,finish ) 9073 9074def events (): 9075yield from asm .start () 9076done = None 9077for kind ,x in svc .run (ids ,thinking ,tools ,max_new ,req ,cancel ): 9078if kind == "ping" : 9079yield None 9080elif kind == "event" : 9081yield from asm .feed (x ) 9082elif kind == "done" : 9083done = x 9084if done is not None and done ["finish" ]!= "cancel" and not cancel .is_set (): 9085yield from asm .finish (done ,check ) 9086items = self ._capture (events (),"responses" ) 9087if not req .get ("stream" ): 9088try : 9089result = responses_api .collect (items ) 9090except StructuredOutputError as e : 9091return self ._json (502 ,responses_error_body (str (e ),"server_error" , 9092code = "structured_output_failed" )) 9093except QueueWaitExpired as e : 9094return self ._json (429 ,responses_error_body (str (e ),"server_error" , 9095code = "queue_wait_timeout" ),retry_after = 1 ) 9096except EngineDied as e : 9097return self ._json (503 ,responses_error_body (died_note (e ),"server_error" , 9098code = "server_error" )) 9099except EngineNonFinite as e :# #879, twice: not the request's fault 9100return self ._json (503 ,responses_error_body (str (e ),"server_error" ,code = "server_error" )) 9101except ValueError as e :# the engine's ERR line 9102return self ._json (500 ,responses_error_body (str (e ),"server_error" ,code = "server_error" )) 9103return self ._json (200 ,result ) 9104self ._sse () 9105last = time .monotonic () 9106 9107def send (e ): 9108self .wfile .write (f"event: { e [ 'type' ] } \n" .encode ()+ b"data: " + 9109json .dumps (e ,ensure_ascii = False ).encode ()+ b"\n\n" ) 9110 9111try : 9112for e in items : 9113if e is None : 9114# Codex's idle timeout (5 minutes by default) counts events, not SSE comments: while a long 9115# prompt is read, a response.in_progress every 15 s tells it the server is still working 9116if time .monotonic ()- last >= 15 : 9117send (asm .in_progress ()) 9118last = time .monotonic () 9119else : 9120self .wfile .write (b": keep-alive\n\n" ) 9121else : 9122send (e ) 9123last = time .monotonic () 9124self .wfile .flush () 9125except OSError : 9126self ._note (outcome = "disconnected" ) 9127svc .note_client_disconnect (cancel )# client went away: stop the engine 9128items .close () 9129except EngineDied as e :# mid-stream: response.failed, then the stream ends 9130self ._responses_failed (asm ,died_note (e ),"server_error" ,send ) 9131except QueueWaitExpired as e : 9132self ._responses_failed (asm ,str (e ),"queue_wait_timeout" ,send ) 9133except StructuredOutputError as e : 9134self ._responses_failed (asm ,str (e ),"structured_output_failed" ,send ) 9135except ValueError as e :# the engine's ERR after the stream started 9136self ._responses_failed (asm ,str (e ),"server_error" ,send ) 9137 9138def _responses_failed (self ,asm ,message ,code ,send ): 9139e = asm .failed (message ,code ) 9140self ._note (error = e ["response" ]["error" ]) 9141try : 9142send (e ) 9143self .wfile .flush () 9144except OSError : 9145pass 9146 9147def _responses_prepare (self ,req ,cancel = None ): 9148responses_api .check_request (req ) 9149messages = responses_api .input_messages (req ) 9150tools ,names ,skipped = responses_api .request_tools (req ) 9151kw = responses_api .template_kwargs (req , {"reasoning_effort" :svc .effort_default ()}) 9152try : 9153self ._no_local_images (messages )# as on the chat route: no file read for a foreign page 9154except ValueError as e : 9155raise ResponsesError (str (e ),"input" )from None 9156try : 9157messages ,validator = prepare_format (responses_api .text_format (req ),messages ,with_tools = bool (tools )) 9158except ValueError as e : 9159raise ResponsesError (str (e ).replace ("response_format" ,"text.format" ),"text.format" )from None 9160noted = svc .__dict__ .setdefault ("hosted_tools_noted" ,set ())# said once per tool, not per request 9161if set (skipped )- noted : 9162f"[strata] /v1/responses: left out the hosted tools { ', ' . join ( sorted ( set ( skipped ) - noted )) } " 9163f"(this server cannot run them)" ,flush = True ) 9164noted .update (skipped ) 9165if req .get ("max_output_tokens" )is None and "max_tokens" in svc .shared :# the shared Chat settings 9166req = {** req ,"max_output_tokens" :svc .shared ["max_tokens" ]} 9167try : 9168svc .reasoning_budget (req )# a bad value is a 400 before anything is sent 9169except ValueError as e : 9170raise ResponsesError (str (e ),"reasoning_budget_tokens" )from None 9171try : 9172stop_strings (req ) 9173except ValueError as e : 9174raise ResponsesError (str (e ),"stop" )from None 9175try : 9176check_request_sampling (req )# the request is also the sampling dict (see below) 9177except ValueError as e :# its message starts with the field's name: the param 9178raise ResponsesError (str (e ),str (e ).partition (":" )[0 ])from None 9179svc .load () 9180# #924 (opt-in): a Codex compaction request is rendered with its conversation's tools, so its prompt 9181# starts as the cached one did; the parser and the response keep the request's own tools 9182shown = responses_api .prompt_tools (req ,tools )if svc .codex_compaction_cache else tools 9183try : 9184try : 9185ids ,thinking ,max_new = svc .prepare (messages ,shown ,kw ,req .get ("max_output_tokens" )or 0 ,req = req , 9186cancel = cancel ) 9187except ValueError : 9188if shown is tools : 9189raise 9190shown = tools # too long with the kept tools: the request as sent 9191ids ,thinking ,max_new = svc .prepare (messages ,shown ,kw ,req .get ("max_output_tokens" )or 0 ,req = req , 9192cancel = cancel ) 9193except ResponsesError : 9194raise 9195except ValueError as e :# too long for the context, an image without vision 9196raise ResponsesError (str (e ),"input" ,"context_length_exceeded" if "context" in str (e )else None ) \ 9197from None 9198if svc .codex_compaction_cache : 9199responses_api .prompt_made (req ,shown ) 9200_debug_req ("responses" ,req ,messages ,tools ,max_new ,thinking ,len (ids )) 9201include = req .get ("include" )if isinstance (req .get ("include" ),list )else [] 9202asm = responses_api .Assembler (req ,svc .model_for (req ),len (ids ),names , 9203"reasoning.encrypted_content" in include ,validator is not None ) 9204# the request is also the sampling dict, as on the chat path (temperature, top_p, top_k, seed, ...) 9205return ids ,thinking ,tools ,max_new ,asm ,validator ,req 9206 9207def _count_tokens (self ,req ): 9208"""Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would 9209read for the same request, rendered and tokenized - the model does not run.""" 9210req = svc .with_shared (req ,"anthropic" ) 9211messages ,tools ,kw = anthropic_to_messages (req ,svc .anthropic_think_unasked ) 9212stop_strings (req )# the same 400 as the request itself would get 9213check_request_sampling (req )# ... likewise a sampling field of the wrong type 9214self ._json (200 , {"input_tokens" :len (svc .encode_prompt (messages ,tools ,kw ,store = False ))}) 9215 9216def _anthropic (self ,req ): 9217svc .load () 9218req = svc .with_shared (req ,"anthropic" ) 9219messages ,tools ,kw = anthropic_to_messages (req ,svc .anthropic_think_unasked ) 9220self ._no_local_images (messages ) 9221callable_tools ,deferred = anthropic_tools (req )# #4663: the deferred tools are callable, unlisted 9222if tool_choice_of (req .get ("tool_choice" ))[0 ]== "none" :# Anthropic's {"type": "none"}: no tools offered 9223tools = callable_tools = None 9224force = svc .force_text (forced_call (req .get ("tool_choice" ),tools ))# "any" / {"type": "tool", "name": N} 9225max_new = int (req .get ("max_tokens" )or 0 )# 0/-1: the rest of the context 9226svc .reasoning_budget (req )# a bad value is a 400 before anything is sent 9227stop_strings (req )# ... and so is a bad stop / stop_sequences 9228check_request_sampling (req )# ... and a sampling field of the wrong type 9229cancel = threading .Event () 9230self ._watch_client (cancel )# #430 #431 (#1999: before prepare, which can take long) 9231try : 9232ids ,thinking ,max_new = svc .prepare (messages ,tools ,kw ,max_new ,force = force ,req = req ,cancel = cancel ) 9233except ContextOverflow as e : 9234raise ValueError (e .anthropic_text ())from None # #4838: Anthropic's own wording first, Strata's sentence after it 9235_debug_req ("anthropic" ,req ,messages ,tools ,max_new ,thinking ,len (ids )) 9236events = anthropic_events (svc ,req ,ids ,thinking ,callable_tools ,max_new ,cancel ,force = force , 9237deferred = deferred ) 9238events = self ._capture (events ,"anthropic" ) 9239if not req .get ("stream" ): 9240return self ._json (200 ,anthropic_collect (events )) 9241self ._sse () 9242try : 9243for item in events : 9244if item is None : 9245self .wfile .write (b": keep-alive\n\n" ) 9246else : 9247name ,e = item 9248self .wfile .write (f"event: { name } \n" .encode ()+ b"data: " + 9249json .dumps (e ,ensure_ascii = False ).encode ()+ b"\n\n" ) 9250self .wfile .flush () 9251except OSError : 9252self ._note (outcome = "disconnected" ) 9253svc .note_client_disconnect (cancel ) 9254events .close () 9255except EngineDied as e :# mid-stream: Anthropic's error event 9256err = {"type" :"error" ,"error" : {"type" :"api_error" ,"message" :died_note (e )}} 9257self ._note (error = err ["error" ]) 9258self .wfile .write (b"event: error\ndata: " + json .dumps (err ).encode ()+ b"\n\n" ) 9259except QueueWaitExpired as e : 9260err = {"type" :"error" ,"error" : {"type" :"rate_limit_error" ,"code" :"queue_wait_timeout" , 9261"message" :str (e )}} 9262self ._note (error = err ["error" ]) 9263self .wfile .write (b"event: error\ndata: " + json .dumps (err ).encode ()+ b"\n\n" ) 9264except ValueError as e :# the engine's ERR after the stream started 9265err = {"type" :"error" ,"error" : {"type" :"api_error" ,"message" :str (e )}} 9266self ._note (error = err ["error" ]) 9267self .wfile .write (b"event: error\ndata: " + json .dumps (err ).encode ()+ b"\n\n" ) 9268 9269return Handler 9270 9271 9272class Server (ThreadingHTTPServer ): 9273# On Windows SO_REUSEADDR lets a second server bind a port that is already serving, and requests then land on 9274# either one (a forgotten second start of run-<model>.bat). Without it the second start fails loudly instead. 9275allow_reuse_address = os .name != "nt" 9276# socketserver listens with a backlog of 5: a burst of 30-40 clients at once got "connection reset by peer" on the 9277# first ones (measured on 4 x R9700, also with one request at a time); the requests wait in the server, not the kernel 9278# (STRATA_HTTP_BACKLOG overrides it) 9279request_queue_size = max (5 ,int (os .environ .get ("STRATA_HTTP_BACKLOG" )or 256 )) 9280 9281def __init__ (self ,server_address ,RequestHandlerClass ,bind_and_activate = True ): 9282if ":" in server_address [0 ]: 9283self .address_family = socket .AF_INET6 9284super ().__init__ (server_address ,RequestHandlerClass ,bind_and_activate ) 9285 9286def server_bind (self ): 9287# http.server's own server_bind also asks socket.getfqdn(host) for a server_name nothing here reads; on a Mac whose reverse lookup 9288# stalls (GitHub's macOS runner: 35 s on the first lookup of every new process) each start waited that long before it listened 9289socketserver .TCPServer .server_bind (self ) 9290self .server_name ,self .server_port = self .server_address [:2 ] 9291 9292def handle_error (self ,request ,client_address ): 9293if not isinstance (sys .exc_info ()[1 ],ConnectionError ):# a client that hangs up needs no stack trace 9294super ().handle_error (request ,client_address ) 9295 9296def server_close (self ): 9297# the hardware sampler serve() started for this server stops with it (test isolation: every Service a test 9298# started used to leave its sampler running, 21 of them after test_responses, which slowed test_parallel's timing) 9299tel = getattr (getattr (self ,"svc" ,None ),"telemetry" ,None ) 9300if tel is not None and hasattr (tel ,"close" ): 9301tel .close () 9302super ().server_close () 9303 9304 9305def warn_tight_ram (arena_mib )-> None : 9306"""The model's experts live in RAM (INFO arena_mib, engine 0.1.10+). With less than ~6 GB left beside them for the 9307system, the engine and this server, Linux ends the engine mid-answer when memory runs out (issue #27) and Windows 9308pages to disk; say so at start instead of after a lost answer.""" 9309if not isinstance (arena_mib ,int )or arena_mib <= 0 : 9310return 9311try : 9312import psutil 9313total = psutil .virtual_memory ().total 9314except Exception :# noqa: BLE001 - psutil is optional here 9315return 9316left = total / 2 ** 30 - arena_mib / 1024 9317if left < 6 : 9318f"[strata] WARNING: RAM is tight - the model's experts take { arena_mib / 1024 :.1f } GB of this PC's " 9319f" { total / 2 ** 30 :.0f } GB, leaving { left :.1f } GB for everything else. " 9320+ ("Linux may stop the engine in the middle of an answer. " if os .name != "nt" else 9321"Windows will slow down (paging to disk). " ) 9322+ "Close other programs, or run START-HERE --setup and pick a smaller size (Q2_0 / IQ2_XS)." ,flush = True ) 9323 9324 9325def warn_budget_over_ram (args )-> str | None : 9326"""#1080: an explicit `--resident-budget-gib N` bigger than the RAM this PC has free (or than its total beside 9327~6 GB for everything else) pushes experts into swap or the file tier: decode that is "dead slow" until the number is 9328removed. A warning at start, never a refusal (recommend, never force). -> the sentence printed, or None.""" 9329try : 9330budget = float (args [list (args ).index ("--resident-budget-gib" )+ 1 ]) 9331except (ValueError ,IndexError ): 9332return None 9333try : 9334import psutil 9335vm = psutil .virtual_memory () 9336total ,free = vm .total / 2 ** 30 ,vm .available / 2 ** 30 9337except Exception :# noqa: BLE001 - psutil is optional here 9338return None 9339if budget <= free and budget <= total - 6 : 9340return None 9341msg = (f"WARNING: the RAM budget for experts is { budget :g } GiB (--resident-budget-gib), but this PC has " 9342f" { free :.0f } GiB free of { total :.0f } GiB: what does not fit goes to swap or is read from disk, which can make " 9343"decoding very slow. Lower it (setup sizes it for this PC) or remove the argument to let the engine choose." ) 9344"[strata] " + msg ,flush = True ) 9345return msg 9346 9347 9348DESKTOP_FREE_MIB = 2048 # #560 #516: below this, an AMD card that also drives a Linux desktop can run out 9349DESKTOP_RESERVE_MIB = 3072 # what kept KDE/Wayland alive beside a full expert cache in both reports 9350 9351 9352def linux_desktop (env = None )-> bool : 9353"""A graphical session on Linux (Wayland or X): its compositor, browser and apps take VRAM after the model has.""" 9354env = os .environ if env is None else env 9355return os .name != "nt" and sys .platform != "darwin" and bool (env .get ("WAYLAND_DISPLAY" )or env .get ("DISPLAY" )) 9356 9357 9358def desktop_vram_note (backend ,vram_free_mib ,args :list ,desktop :bool )-> str : 9359"""#560 #516: on Linux, when the desktop needs VRAM the AMD card does not have, amdgpu moves GPU memory (the expert 9360cache, ~24 GB) to system RAM, which the experts already fill - the OOM killer then ends the compositor. The 9361default reserve (700 MiB) is sized for a card without a desktop. A recommendation, nothing changes: "" when it 9362does not apply.""" 9363if backend != "hip" or not desktop or not isinstance (vram_free_mib ,int )or vram_free_mib >= DESKTOP_FREE_MIB : 9364return "" 9365try : 9366reserve = int (args [args .index ("--vram-reserve-mib" )+ 1 ])if "--vram-reserve-mib" in args else 700 9367except (ValueError ,IndexError ): 9368reserve = 700 9369if reserve >= DESKTOP_RESERVE_MIB : 9370return "" 9371return (f"[strata] note: { vram_free_mib } MiB of VRAM free with the model loaded. If this AMD card also drives your " 9372"desktop and the desktop or apps crash after the start (the driver moves the expert cache to RAM and " 9373"the OOM killer ends the session), keep more VRAM free: ./setup.sh --vram-reserve-mib " 9374f" { DESKTOP_RESERVE_MIB } (remembered; the expert cache gets " 9375f" { ( DESKTOP_RESERVE_MIB - reserve ) / 1024 :.1f } GB less, a few % of speed)" ) 9376 9377 9378def lan_addresses ()-> list [str ]: 9379"""This PC's IPv4 addresses on its networks (what another device types in), without loopback/link-local.""" 9380import socket 9381first ,ips = None ,set () 9382try :# the address of the default route; sends nothing (UDP) 9383with socket .socket (socket .AF_INET ,socket .SOCK_DGRAM )as s : 9384s .connect (("10.255.255.255" ,1 )) 9385first = s .getsockname ()[0 ] 9386except OSError : 9387pass 9388try : 9389for info in socket .getaddrinfo (socket .gethostname (),None ,socket .AF_INET ): 9390ips .add (info [4 ][0 ]) 9391except OSError : 9392pass 9393ok = lambda ip :ip and not ip .startswith (("127." ,"169.254." ,"0." )) 9394return ([first ]if ok (first )else [])+ sorted (ip for ip in ips if ok (ip )and ip != first ) 9395 9396 9397def host_name (value )-> str : 9398"""The name in a Host header (or an origin's host[:port]): "Example.com:8080" -> "example.com", 9399"[::1]:8095" -> "::1"; "" when it is malformed.""" 9400v = (value or "" ).strip ().lower () 9401if v .startswith ("[" ): 9402name ,sep ,rest = v [1 :].partition ("]" ) 9403return name if sep and (not rest or (rest [:1 ]== ":" and rest [1 :].isdigit ()))else "" 9404if v .count (":" )== 1 : 9405v ,port = v .split (":" ) 9406if not port .isdigit (): 9407return "" 9408elif ":" in v :# a bare IPv6 address (a config entry) 9409return v 9410v = v .rstrip ("." ) 9411return v if v and all (c .isalnum ()or c in "-._" for c in v )else "" 9412 9413 9414def _is_ip (name :str )-> bool : 9415import ipaddress 9416try : 9417ipaddress .ip_address (name ) 9418return True 9419except ValueError : 9420return False 9421 9422 9423def _name_in (name :str ,names )-> bool : 9424"""`name` is one of `names`, or below an entry that starts with a dot (".example.com").""" 9425return name in names or any (n .startswith ("." )and (name .endswith (n )or name == n [1 :])for n in names ) 9426 9427 9428def allowed_hosts_of (value ,env :str = "" )-> list [str ]: 9429"""The config's allowed_hosts (a name or a list) plus $STRATA_ALLOWED_HOSTS (comma-separated): host names, "*" or 9430".example.com" (it and every name below it). A scheme, port or path is dropped ("https://a.example.com:8443/" 9431-> "a.example.com"); a wrong entry stops the start (ValueError).""" 9432items = []if value in (None ,"" )else [value ]if isinstance (value ,str )else value 9433if not isinstance (items ,list )or not all (isinstance (x ,str )for x in items ): 9434raise ValueError ("allowed_hosts: expected a host name or a list of them" ) 9435out = [] 9436for raw in items + [x for x in env .split ("," )if x .strip ()]: 9437x = raw .strip ().lower () 9438if x == "*" : 9439out .append (x ) 9440continue 9441x = x .split ("://" ,1 )[- 1 ].split ("/" ,1 )[0 ] 9442dot = x .startswith ("." ) 9443name = host_name (x [1 :]if dot else x ) 9444if not name : 9445raise ValueError (f"allowed_hosts: { raw !r } is not a host name like strata.example.com" ) 9446out .append ("." + name if dot else name ) 9447return list (dict .fromkeys (out )) 9448 9449 9450def host_names_for (bind_host :str ,allowed_hosts = (),trusted_origins = ())-> set [str ]: 9451"""Every name this server answers to besides an IP address: localhost, the address it listens on, the config's 9452allowed_hosts and trusted_origins' hosts, and - listening beyond this PC (0.0.0.0 or a LAN address) - this PC's 9453name and LAN addresses (the LAN addresses matter for the Origin check, which takes no IP on trust).""" 9454names = set (LOOPBACK_NAMES ) 9455bind = host_name (bind_host ) 9456if bind and bind not in ("0.0.0.0" ,"::" ): 9457names .add (bind ) 9458if bind not in LOOPBACK_NAMES : 9459try : 9460pc = socket .gethostname ().lower () 9461names .update ((pc ,pc + ".local" )) 9462except OSError : 9463pass 9464names .update (("host.docker.internal" ,* lan_addresses ())) 9465names .update (x for x in allowed_hosts if x != "*" ) 9466names .update (filter (None , (host_name (o .split ("://" ,1 )[- 1 ])for o in trusted_origins ))) 9467return names 9468 9469 9470def host_allowed (host ,names ,any_host = False )-> bool : 9471"""DNS rebinding: a web page of another site whose name its DNS points at 127.0.0.1 reaches this server as the 9472same origin, so the browser lets it read every answer. Its requests carry that site's name in Host, so only 9473the names this server answers to pass. An IP address passes (a page served from an IP is that IP's own page; 9474rebinding needs a name), as does "*.localhost" (browsers never ask DNS for it) and a request without a Host 9475header (HTTP/1.0 clients; browsers always send one).""" 9476if any_host or not (host or "" ).strip (): 9477return True 9478name = host_name (host ) 9479return bool (name )and (_is_ip (name )or name == "localhost" or name .endswith (".localhost" ) 9480or _name_in (name ,names )) 9481 9482 9483def key_list (value )-> list [str ]: 9484"""#1344: the keys a server accepts. --api-key / STRATA_API_KEY / "api_key" take llama.cpp's form, several keys 9485separated by commas ("k1,k2"; spaces around each are dropped), or a list in the config ("api_key": ["k1", "k2"], 9486the way to give a key that contains a comma). A list is taken as it is.""" 9487if value is None or value == "" : 9488return [] 9489if isinstance (value , (list ,tuple )): 9490return [str (k )for k in value if str (k )] 9491return [k .strip ()for k in str (value ).split ("," )if k .strip ()] 9492 9493 9494def explicit_no_key (value )-> bool : 9495"""The owner chose to serve without a key: "api_key": "none" in the config, STRATA_API_KEY=none or --api-key none 9496(or --no-api-key, handled by the caller). Never a key called "none".""" 9497return isinstance (value ,str )and value .strip ().lower ()== "none" 9498 9499 9500def open_server_warning (port ,public = False ,tools = False )-> str : 9501"""The one plain warning for a server on the network with no API key (recommend, never force).""" 9502msg = f"no API key: anyone who can reach port { port } can use the model" + (" and its tools" if tools else "" )+ "." 9503if tools : 9504msg += " The tools can read and change files on this computer." 9505if public : 9506msg += " This address is on the public internet, so anyone who finds it can use it." 9507return msg + " Add an API key to keep others out." 9508 9509 9510def api_key_of (value ): 9511"""The key as a client can send it (#725). An HTTP header loses the spaces and line ends around its value, so a 9512key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no 9513request: every client got 401 with the right key. A value that is only such characters raises ValueError, it 9514never means "no key" (#213). #1344: a config list of keys returns the list (each key stripped, none empty); a 9515string stays a string (its commas separate keys, see key_list).""" 9516if isinstance (value , (list ,tuple )): 9517keys = [str (k ).strip ()for k in value ] 9518if not keys or any (not k for k in keys ): 9519raise ValueError ("an API key was given but it is empty" ) 9520return keys 9521key = "" if value is None else str (value ) 9522if key and not key_list (key ): 9523raise ValueError ("an API key was given but it is empty" ) 9524return key .strip () 9525 9526 9527def key_matches (given :str ,key )-> bool : 9528"""given: a header's value as http.server read it, each byte one character. A key with characters outside ASCII 9529arrives as UTF-8 from most clients and as Latin-1 from some; the right key passes in both forms (#725: the 9530bytes were re-encoded before, so a UTF-8 key never matched). Constant-time (#213). #1344: `key` may name several 9531keys (see key_list); the given one must match any, and every key is compared whatever the outcome.""" 9532raw = given .encode ("latin-1" ,"replace" ) 9533ok = False 9534for k in key_list (key ): 9535ok |= hmac .compare_digest (raw ,k .encode ()) 9536try : 9537ok |= hmac .compare_digest (raw ,k .encode ("latin-1" )) 9538except UnicodeEncodeError : 9539pass 9540return ok 9541 9542 9543def origin_allowed (origin :str ,host ,names ,origins = ())-> bool : 9544"""A browser page's Origin that may use the model without an API key: this server's own page (the Origin is the 9545request's own Host), a page on one of the names this server answers to (any port), or an origin the config lists 9546(trusted_origins, cors_origins). Unlike the Host check no IP passes on trust: a page served from any other IP is 9547another site. "null" (a sandboxed frame, a file:// page) does not pass: any site can send it. An origin of another 9548scheme (chrome-extension://, moz-extension://, an Electron app's app://) does: no web site can send one.""" 9549origin = (origin or "" ).strip ().rstrip ("/" ) 9550if origin in origins or "*" in origins :# cors_origins ["*"]: the config lets every page in 9551return True 9552scheme ,sep ,rest = origin .lower ().partition ("://" ) 9553if not sep or not scheme : 9554return False 9555if scheme not in ("http" ,"https" ): 9556return True 9557if host and rest == host .strip ().lower (): 9558return True 9559name = host_name (rest ) 9560return bool (name )and (name in LOOPBACK_NAMES or name .endswith (".localhost" )or _name_in (name ,names )) 9561 9562 9563def serve (svc :Service ,host = "127.0.0.1" ,port = 8095 )-> ThreadingHTTPServer : 9564svc .host_names = host_names_for (host ,svc .allowed_hosts ,svc .trusted_origins ) 9565svc .start_telemetry () 9566httpd = Server ((host ,port ),make_handler (svc )) 9567httpd .svc = svc 9568threading .Thread (target = httpd .serve_forever ,daemon = True ).start () 9569return httpd 9570 9571 9572def origins_of (value ,key :str ,wildcard :bool )-> list [str ]: 9573"""#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path; 9574"*" only where `wildcard` allows it. A wrong entry stops the start rather than opening less or more than meant.""" 9575if value is None or value == "" or value == []: 9576return [] 9577items = [value ]if isinstance (value ,str )else value 9578if not isinstance (items ,list )or not all (isinstance (x ,str )for x in items ): 9579raise SystemExit (f"[strata] { key } : expected an origin or a list of origins" ) 9580out = [] 9581for x in items : 9582x = x .strip ().rstrip ("/" ) 9583if x == "*" and wildcard : 9584out .append (x ) 9585continue 9586scheme ,sep ,rest = x .partition ("://" ) 9587if scheme not in ("http" ,"https" )or not sep or not rest or "/" in rest or "*" in rest : 9588raise SystemExit (f"[strata] { key } : { x !r } is not an origin like https://chat.example.com" 9589+ ("" if wildcard else " (no wildcards here)" )) 9590out .append (x ) 9591return out 9592 9593 9594SHARED_KEYS = ("reasoning_effort" ,"reasoning_budget_tokens" ,"temperature" ,"top_p" ,"top_k" ,"seed" ,"max_tokens" , 9595"experimental_speed_projection" ) 9596 9597 9598def clean_shared_defaults (d )-> dict : 9599"""The Chat settings other apps get (POST /settings): only known keys, each checked; ValueError names a bad one.""" 9600if d is None : 9601return {} 9602if not isinstance (d ,dict ): 9603raise ValueError ("defaults must be an object" ) 9604out = {} 9605for key ,value in d .items (): 9606if value is None or value == "" : 9607continue 9608number = isinstance (value , (int ,float ))and not isinstance (value ,bool ) 9609if key == "reasoning_effort" : 9610if value not in ("none" ,"low" ,"medium" ,"high" ): 9611raise ValueError ("reasoning_effort: none, low, medium or high" ) 9612elif key == "temperature" : 9613if not number or not 0 <= value <= 2 : 9614raise ValueError ("temperature: 0..2" ) 9615elif key == "top_p" : 9616if not number or not 0 < value <= 1 : 9617raise ValueError ("top_p: 0 < top_p <= 1" ) 9618elif key == "top_k" : 9619if not number or value != int (value )or not 1 <= value <= 64 : 9620raise ValueError ("top_k: an integer 1..64" ) 9621value = int (value ) 9622elif key in ("seed" ,"max_tokens" ): 9623if not number or value != int (value )or value <= 0 : 9624raise ValueError (f" { key } : a positive integer" ) 9625value = int (value ) 9626elif key == "reasoning_budget_tokens" :# #123: 0 means no budget, so 0 is allowed here 9627if not number or value != int (value )or value < 0 : 9628raise ValueError ("reasoning_budget_tokens: a whole number of tokens (0: no budget)" ) 9629value = int (value ) 9630elif key == "experimental_speed_projection" : 9631if not isinstance (value ,bool ): 9632raise ValueError ("experimental_speed_projection: true or false" ) 9633else : 9634raise ValueError (f"unknown setting { key !r } " ) 9635out [key ]= float (value )if key in ("temperature" ,"top_p" )else value 9636return out 9637 9638 9639def split_joined_args (cfg :dict )-> None : 9640"""#2267: an engine option written as ONE element of the config's "args" - "--ple-io mmap" or "--ple-io=mmap" - reaches 9641the engine as a single argument ("unknown argument: --ple-io mmap"; the usual form is two elements, "--ple-io", 9642"mmap"). Recommend, never force: such an element is split into the flag and its value, and said at startup. Only an 9643element that starts with a flag name (--letters-digits-dashes) followed by a space or "=" is touched, and never one 9644that sits in the value place of the flag before it.""" 9645args = cfg .get ("args" ) 9646if not isinstance (args ,list ): 9647return 9648out ,changed = [], [] 9649for a in args : 9650m = re .match (r"^(--[A-Za-z0-9][A-Za-z0-9-]*)(?:\s+|=)(\S.*)$" ,a )if isinstance (a ,str )else None 9651prev = out [- 1 ]if out else None 9652in_value_place = isinstance (prev ,str )and re .match (r"^--[A-Za-z0-9][A-Za-z0-9-]*$" ,prev )is not None 9653if m is None or in_value_place : 9654out .append (a ) 9655continue 9656out += [m .group (1 ),m .group (2 ).strip ()] 9657changed .append (a ) 9658if changed : 9659cfg ["args" ]= out 9660"[strata] the config's args hold " + ", " .join (repr (c )for c in changed )+ " as one element each: split into the " 9661'flag and its value (write them as two elements, e.g. "--ple-io", "mmap")' ,flush = True ) 9662 9663 9664def read_config (path )-> dict : 9665"""The run config's JSON. A mistake in it (a missing comma between two args, a trailing comma) is said with its 9666place in the file instead of a traceback (#2267: editing "args" by hand is where it happens).""" 9667return parse_config_text (Path (path ).read_text (encoding = "utf-8-sig" ),path )# Notepad adds a BOM 9668 9669 9670def parse_config_text (text :str ,path )-> dict : 9671"""read_config on text already read (the owner-launched server hashes the bytes it parses, launch attestation).""" 9672try : 9673return json .loads (text ) 9674except json .JSONDecodeError as e : 9675raise SystemExit (f"[strata] { path } is not valid JSON: { e . msg } at line { e . lineno } , column { e . colno } . Check the commas " 9676'between the entries of "args" (each option and each value is its own quoted entry, e.g. ' 9677'"--ple-io", "mmap",) and that no entry is followed by a comma at the end of a list.' )from None 9678 9679 9680def lift_reasoning_effort_arg (cfg :dict )-> None : 9681"""#1641: "--reasoning-effort high" in a config's "args" is meant for the thinking level, which is not an engine 9682option (the engine stopped at the unknown flag). It is the config's "reasoning_effort" (none, low, medium or high: 9683the level for requests that name none), so the flag is taken out of the engine's arguments and becomes that key 9684unless the config already has one; said at startup.""" 9685args = cfg .get ("args" ) 9686if not isinstance (args ,list ): 9687return 9688out ,value ,i = [],None ,0 9689while i < len (args ): 9690a = args [i ] 9691if a == "--reasoning-effort" and i + 1 < len (args ): 9692value ,i = args [i + 1 ],i + 2 9693elif isinstance (a ,str )and a .startswith ("--reasoning-effort=" ): 9694value ,i = a .partition ("=" )[2 ],i + 1 9695else : 9696out .append (a ) 9697i += 1 9698if value is None : 9699return 9700cfg ["args" ]= out 9701if cfg .get ("reasoning_effort" )is None : 9702cfg ["reasoning_effort" ]= value 9703"[strata] '--reasoning-effort' in the config's args is not an engine option: taken out of them. The thinking " 9704"level is the config's 'reasoning_effort' key (outside 'args'); it is used as " + 9705f" { cfg [ 'reasoning_effort' ]!r } " ,flush = True ) 9706 9707 9708# #1819: llama.cpp clients call the repetition penalty and its window repeat_penalty / repeat_last_n; they are the 9709# same settings as repetition_penalty / penalty_last_n (the /props answer already reports them under those names) 9710SAMPLING_ALIASES = {"repeat_penalty" :"repetition_penalty" ,"repeat_last_n" :"penalty_last_n" } 9711 9712 9713def apply_saved_tuning (cfg :dict ,* ,say = None )-> dict : 9714"""The run config with the active saved tuning for its choices put on top (strata_control/presets.py), with no measurement. 9715Every start path runs this (the Terminal, `runtime start`, the app's load, a restart of the app, an unload and a load), so the 9716tuning is applied every time and never re-measured. A tune's own worker sets STRATA_NO_PRESET so that it measures the 9717configuration it was given. Never fails a start: a store that cannot be read means the configuration as it is.""" 9718if os .environ .get ("STRATA_NO_PRESET" ): 9719return cfg 9720say = say or (lambda line :line ,flush = True )) 9721try : 9722from strata_control import presets as _presets 9723out ,applied = _presets .overlay (cfg ) 9724if applied .get ("applied" ): 9725changes = {** (applied .get ("args" )or {}),** (applied .get ("env" )or {})} 9726note = applied .get ("notice" )or "" 9727say (f"[strata] saved tuning ' { applied [ 'preset' ][ 'name' ] } ' applied: " 9728f" { ' ' . join ( f' { k } { v } ' for k , v in changes . items ()) or 'the standard settings (nothing to change)' } " 9729f" { '; ' + note if note and 'identical' not in note else '' } " ) 9730for warning in applied .get ("warnings" )or []:# #3844: outside the range the tuner tries, kept 9731say (f"[strata] warning: { warning } " ) 9732if applied .get ("state" )== "soft" : 9733say ("[strata] this PC or engine changed since it was saved (" + "; " .join (applied ["reasons" ])+ 9734"): a short re-check is available (strata presets recheck)" ) 9735elif applied .get ("why_not" ): 9736say (f"[strata] saved tuning ' { applied [ 'preset' ][ 'name' ] } ' { applied [ 'why_not' ] } ; re-tune with strata tune auto" ) 9737return out 9738except Exception as e :# noqa: BLE001 9739say (f"[strata] saved tuning could not be read ( { type ( e ). __name__ } ); starting with the configuration as it is" ) 9740return cfg 9741 9742 9743def sampling_defaults_from_config (cfg :dict )-> dict : 9744"""The run config's optional `sampling` block: defaults for the sampling fields a request leaves out, so 9745a plain client gets configured sampling instead of greedy. Supported: temperature, top_p, top_k, min_p, 9746presence_penalty, repetition_penalty (also written repeat_penalty), frequency_penalty, penalty_last_n (also 9747repeat_last_n), seed, logit_bias (token id -> bias, e.g. -100 bans a token). The request's own fields 9748always win - an explicit temperature=0 still means greedy, a field set to null falls back to the default. 9749A bad value refuses to start the server (a typo'd config should not quietly change sampling); unknown keys 9750are named at startup and ignored.""" 9751out = {} 9752block = dict (cfg .get ("sampling" )or {}) 9753for alias ,canon in SAMPLING_ALIASES .items ():# #1819: llama.cpp's names for the same two fields 9754if block .get (alias )is not None : 9755if block .get (canon )is not None : 9756raise SystemExit (f"[strata] config sampling: both { alias !r } and { canon !r } are set; they are the same " 9757f"setting, keep one" ) 9758block [canon ]= block .pop (alias ) 9759for key ,value in block .items (): 9760if value is None : 9761continue 9762number = isinstance (value , (int ,float ))and not isinstance (value ,bool ) 9763if key == "temperature" : 9764if not number or value < 0 : 9765raise SystemExit (f"[strata] config sampling.temperature= { value !r } : expected a number >= 0 (0 = greedy)" ) 9766out [key ]= float (value ) 9767elif key == "top_p" : 9768if not number or not 0 < value <= 1 : 9769raise SystemExit (f"[strata] config sampling.top_p= { value !r } : expected 0 < top_p <= 1" ) 9770out [key ]= float (value ) 9771elif key == "min_p" : 9772if not number or not 0 <= value <= 1 : 9773raise SystemExit (f"[strata] config sampling.min_p= { value !r } : expected 0 <= min_p <= 1" ) 9774out [key ]= float (value ) 9775elif key == "top_k" : 9776if not number or value != int (value )or not 1 <= value <= 64 : 9777raise SystemExit (f"[strata] config sampling.top_k= { value !r } : the sampled path takes an integer 1..64" ) 9778out [key ]= int (value ) 9779elif key == "presence_penalty" : 9780if not number or value < 0 : 9781raise SystemExit (f"[strata] config sampling.presence_penalty= { value !r } : expected a number >= 0" ) 9782out [key ]= float (value ) 9783elif key == "frequency_penalty" : 9784if not number or value < 0 : 9785raise SystemExit (f"[strata] config sampling.frequency_penalty= { value !r } : expected a number >= 0" ) 9786out [key ]= float (value ) 9787elif key == "repetition_penalty" : 9788if not number or value <= 0 : 9789raise SystemExit (f"[strata] config sampling.repetition_penalty= { value !r } : expected a number > 0 (1 = off)" ) 9790out [key ]= float (value ) 9791elif key == "penalty_last_n" : 9792if not number or value != int (value )or value < 0 : 9793raise SystemExit (f"[strata] config sampling.penalty_last_n= { value !r } : expected a non-negative integer" ) 9794out [key ]= int (value ) 9795elif key == "seed" : 9796if not number or value != int (value )or value <= 0 : 9797raise SystemExit (f"[strata] config sampling.seed= { value !r } : expected a positive integer" ) 9798out [key ]= int (value ) 9799elif key == "strata_tune" :# a saved tuning's per-request settings (strata_control/presets.py) 9800if not isinstance (value ,dict ): 9801raise SystemExit (f"[strata] config sampling.strata_tune= { value !r } : expected an object" ) 9802out [key ]= {k :v for k ,v in value .items ()if k in ("pcie_frac" ,"spec_min_p" ,"aux_cpus" )} 9803 9804elif key == "logit_bias" : 9805try : 9806out [key ]= bias_api .normalize (value ) 9807except ValueError as e : 9808raise SystemExit (f"[strata] config sampling.logit_bias: { e } " ) 9809elif key == "experimental_speed_projection" : 9810if not isinstance (value ,bool ): 9811raise SystemExit (f"[strata] config sampling.experimental_speed_projection= { value !r } : expected true or " 9812"false (the default for requests that leave it out, when the engine has the vector)" ) 9813out [key ]= value 9814else : 9815f"[strata] config sampling. { key } = { value !r } : unknown key, ignored" ,flush = True ) 9816return out 9817 9818 9819SPLIT_KEYS = ("split_fallback" ,"split_engine_note" ) 9820 9821 9822def start_engine_or_fallback (cfg :dict ,exe :str ,effort_end :list [str ]| None ,env :dict ,lazy :bool ,tok ,* ,offline :bool = False , 9823batch_telemetry = None ): 9824"""Start the run config's engine. A config written for the all-cards split engine (strata_control/split_engine.py) carries the 9825normal layer-split config under "split_fallback": if that engine refuses or fails to come up, say so in one plain line and start the 9826normal one instead, so a start never fails because of the option. Any other config starts exactly as before.""" 9827fb = cfg .get ("split_fallback" ) 9828try : 9829return StrataEngine (exe ,engine_args (cfg ,exe )+ (effort_end or []),cwd = cfg .get ("cwd" ),log = cfg .get ("log" ),env = env ,lazy = lazy , 9830retry_args = mtp_retry_args (cfg ,exe ,effort_end ),retry_vram_args = nodraft_retry_args (cfg ,exe ,effort_end )) 9831except Exception as e : 9832if not isinstance (fb ,dict )or not fb .get ("exe" ): 9833raise 9834msg = str (e ).strip () 9835why = msg .splitlines ()[0 ][:200 ]if msg else type (e ).__name__ 9836# the engine's own reason ("sfnx: failed: ..." in its log tail, which the exception carries) is what a person needs to read 9837own = next ((ln .split ("sfnx: failed: " ,1 )[1 ].strip ()for ln in reversed (msg .splitlines ())if "sfnx: failed: " in ln ),"" ) 9838if own : 9839why = own [:300 ] 9840log = cfg .get ("log" ) 9841if log :# the normal engine writes the same log file: keep the split engine's 9842try : 9843os .replace (log ,str (log )+ ".split-engine" ) 9844except OSError : 9845pass 9846f"[strata] The all-cards split engine could not start ( { why } ). Starting the normal layer split instead." ,flush = True ) 9847cfg2 = {k :v for k ,v in cfg .items ()if k not in SPLIT_KEYS + ("exe" ,"args" ,"env" ,"layer_split" ,"replicas" ,"user_args" ,"drafting" )} 9848cfg2 .update (fb ) 9849cfg2 = with_component_engine (cfg2 ) 9850if engine_component .is_reference (cfg2 ["exe" ]): 9851exe2 = _component_exe (cfg2 ["exe" ],cfg2 ) 9852else : 9853exe2 = cfg2 ["exe" ]if os .path .isabs (cfg2 ["exe" ])else os .path .abspath (os .path .join (cfg2 .get ("cwd" )or "." ,cfg2 ["exe" ])) 9854env2 = child_env (cfg2 ,offline = offline ) 9855configure_batch_telemetry_env (env2 ,cfg2 ,batch_telemetry ) 9856effort2 = effort_end_args (cfg2 ,exe2 ,tok ) 9857engine = StrataEngine (exe2 ,engine_args (cfg2 ,exe2 )+ (effort2 or []),cwd = cfg2 .get ("cwd" ),log = cfg2 .get ("log" ),env = env2 ,lazy = lazy , 9858retry_args = mtp_retry_args (cfg2 ,exe2 ,effort2 ),retry_vram_args = nodraft_retry_args (cfg2 ,exe2 ,effort2 )) 9859engine .info ["split_fallback" ]= True 9860return engine 9861 9862 9863def start_replicas (cfg :dict ,groups :list [list [int ]],exe :str ,effort_end :list [str ],lazy :bool , 9864* ,offline :bool = False ): 9865"""Opt-in data-parallel replicas (serve/replicas.py): one StrataEngine per card group, each with its own cards, log 9866and CPU cores, started together; the ReplicaEngine in front spreads the requests.""" 9867from serve import replicas as rp 9868n = len (groups ) 9869cpus = rp .cpu_sets (n ,cfg .get ("replica_cpus" )is not False ) 9870f"[strata] { n } replicas on the cards { ' | ' . join ( ',' . join ( map ( str , g )) for g in groups ) } " 9871f" { ' (own CPU cores each)' if cpus else '' } : requests go to the least busy one, a conversation back to its own" , 9872flush = True ) 9873engines :list = [None ]* n 9874errors :list = [] 9875arena ,arena_note = rp .shared_arena_plan (cfg ,n )# opt-in: one copy of the experts in RAM for all replicas 9876if arena_note : 9877f"[strata] { arena_note } " ,flush = True ) 9878 9879def one (i :int ): 9880rc = rp .replica_cfg (cfg ,i ,groups [i ]) 9881if arena : 9882rc ["args" ]= list (rc ["args" ])+ ["--shared-expert-arena" ,arena ] 9883try : 9884engines [i ]= StrataEngine (exe ,engine_args (rc ,exe )+ effort_end ,cwd = rc .get ("cwd" ),log = rc .get ("log" ), 9885env = child_env (rc ,offline = offline ),lazy = lazy ,cpus = cpus [i ]if cpus else None , 9886retry_args = mtp_retry_args (rc ,exe ,effort_end ),retry_vram_args = nodraft_retry_args (rc ,exe ,effort_end )) 9887except BaseException as e :# noqa: BLE001 9888errors .append ((i ,e )) 9889rc0 = rp .replica_cfg (cfg ,0 ,groups [0 ]) 9890warn_budget_over_ram (engine_args (rc0 ,announce = False )if "args" in rc0 else []) 9891if os .environ .get ("STRATA_REPLICA_START" ,"" )== "serial" : 9892for i in range (n ): 9893one (i ) 9894else : 9895ts = [threading .Thread (target = one ,args = (i ,))for i in range (n )] 9896for t in ts : 9897t .start () 9898for t in ts : 9899t .join () 9900if errors and arena and len (errors )< n : 9901# a replica that died while it was reading the experts into the shared arena (or any other one that failed) while 9902# another one is up: the living engine took the read over (the state word in the arena), so start the failed ones 9903# once more on the same arena instead of giving up the sharing 9904failed = sorted (i for i ,_ in errors ) 9905errors .clear () 9906f"[strata] replica(s) { ', ' . join ( map ( str , failed )) } did not start; starting again on the shared expert arena" , 9907flush = True ) 9908for i in failed : 9909one (i ) 9910if errors : 9911for e in engines : 9912if e is not None : 9913try : 9914e .close () 9915except Exception :# noqa: BLE001 9916pass 9917rp .remove_arena (arena ) 9918i ,e = errors [0 ] 9919if arena :# a shared arena that could not be made (no room in /dev/shm, a file of another pack): as before 9920f"[strata] replica { i } did not start with the shared expert arena ( { e } ); starting every replica with " 9921"its own copy of the experts instead" ,flush = True ) 9922return start_replicas ({** cfg ,"replica_shared_arena" :False },groups ,exe ,effort_end ,lazy ,offline = offline ) 9923raise SystemExit (f"[strata] replica { i } did not start: { e } " ) 9924load = int (cfg .get ("replica_load_tokens" )or rp .LOAD_TOKENS ) 9925eng = rp .ReplicaEngine (engines ,load_tokens = load ) 9926if arena : 9927eng .__dict__ ["arena_file" ]= arena 9928import atexit 9929atexit .register (rp .remove_arena ,arena )# (a killed server leaves the file: the next start sweeps it) 9930return eng 9931 9932 9933def start_split (cfg :dict ,spec :dict ,exe :str ,effort_end :list [str ],lazy :bool ,* ,offline :bool = False ): 9934"""Opt-in split serving (serve/split.py): a prefill engine and a decode engine, one card each, the same model and the 9935same session settings. Started one after the other, so a shared expert arena is filled once; the SplitEngine in 9936front hands a long prompt from the first to the second.""" 9937from serve import split as sp 9938sp .check_cfg (cfg ,spec ) 9939arena ,arena_note = sp .arena_path (cfg ,spec ) 9940work = sp .session_dir (spec ) 9941f"[strata] split serving: the prompt is read on card { spec [ 'prefill_gpu' ] } , the answer is made on card " 9942f" { spec [ 'decode_gpu' ] } (prompts with { spec [ 'min_prompt_tokens' ] } + new tokens are handed over); { arena_note } " , 9943flush = True ) 9944engines = {} 9945try : 9946for role in ("prefill" ,"decode" ): 9947rc = sp .role_cfg (cfg ,spec ,role ) 9948if arena : 9949rc ["args" ]= list (rc ["args" ])+ ["--shared-expert-arena" ,arena ] 9950if role == "prefill" : 9951warn_budget_over_ram (engine_args (rc ,announce = False )if "args" in rc else []) 9952engines [role ]= StrataEngine (exe ,engine_args (rc ,exe )+ effort_end ,cwd = rc .get ("cwd" ),log = rc .get ("log" ), 9953env = child_env (rc ,offline = offline ),lazy = lazy ,retry_args = mtp_retry_args (rc ,exe ,effort_end ),retry_vram_args = nodraft_retry_args (rc ,exe ,effort_end )) 9954except BaseException : 9955for e in engines .values (): 9956try : 9957e .close () 9958except Exception :# noqa: BLE001 9959pass 9960shutil .rmtree (work ,ignore_errors = True ) 9961raise 9962return sp .SplitEngine (engines ["prefill" ],engines ["decode" ],min_tokens = spec ["min_prompt_tokens" ],work_dir = work , 9963arena_file = arena ) 9964 9965 9966def check_request_sampling (req )-> None : 9967"""A request's sampling field of the wrong JSON type ("temperature": "0.7", "top_k": 40.0, "seed": true) is a 400 9968that names the field, as the same value is through POST /settings or the run config. Unchecked, the value 9969replaced the configured default in run()'s merge and sampling_keys dropped it, so the reply was greedy. Only 9970types are checked: a number (int or float, never bool) for temperature, top_p, min_p and the three penalties; an 9971integer (never bool or float) for top_k, penalty_last_n and seed. Ranges behave as before (a temperature <= 0 is 9972greedy, top_k 0 or above 64 is clamped, a seed <= 0 is unset), and an absent or null field is not checked.""" 9973if isinstance (req ,dict ):# #1819: llama.cpp's names; the OpenAI-style field wins when both are sent 9974if req .get ("repeat_penalty" )is not None and req .get ("repetition_penalty" )is None : 9975req ["repetition_penalty" ]= req ["repeat_penalty" ] 9976rl = req .get ("repeat_last_n" ) 9977if req .get ("penalty_last_n" )is None and isinstance (rl ,int )and not isinstance (rl ,bool )and rl > 0 : 9978req ["penalty_last_n" ]= rl # 0 and -1 (off / the whole context) keep the engine's default window 9979for key ,integer in (("temperature" ,False ), ("top_p" ,False ), ("min_p" ,False ), ("presence_penalty" ,False ), 9980 ("frequency_penalty" ,False ), ("repetition_penalty" ,False ), ("top_k" ,True ), 9981 ("penalty_last_n" ,True ), ("seed" ,True )): 9982value = (req or {}).get (key ) 9983if value is None : 9984continue 9985if isinstance (value ,str )and value .strip ():# some clients send numbers as strings: read and used 9986try : 9987num = float (value ) 9988num = int (num )if integer and num == int (num )else (num if not integer else None ) 9989if integer and num is None : 9990raise ValueError 9991if not integer and re .fullmatch (r"\s*[+-]?\d+\s*" ,value ): 9992num = int (value ) 9993except (ValueError ,OverflowError ): 9994raise ValueError (f" { key } : { 'an integer' if integer else 'a number' } " )from None 9995if num != num or num in (float ("inf" ),float ("-inf" )): 9996raise ValueError (f" { key } : { 'an integer' if integer else 'a number' } " ) 9997req [key ]= value = num 9998if isinstance (value ,bool )or not isinstance (value ,int if integer else (int ,float )): 9999raise ValueError (f" { key } : { 'an integer' if integer else 'a number' } " ) 10000 10001 10002# the API's model name per model family (the GGUF architecture, "arch" in the config) when the config names none 10003FAMILY_MODEL_NAMES = {"qwen4exp" :"qwen3.8-flash-next" ,"qwen35moe" :"qwen3.6-35b-a3b" , 10004"deepseek41" :"deepseek-v4.1-flash" } 10005 10006 10007# The sampling each model card recommends ("Best Practices"), used when neither the request, the Chat settings nor the 10008# run config's `sampling` block says otherwise. Greedy is only for a request or config that asks for temperature 0. 10009# min_p 0, repetition_penalty 1 and presence_penalty 0 are the engine's own "off", so they are not listed. 10010MODEL_CARD_SAMPLING = { 10011# Qwen3.8-Flash-Next (and Gyro, the same base model) 10012"qwen4exp" : {"thinking" : {"temperature" :1.0 ,"top_p" :0.95 ,"top_k" :20 }, 10013"instruct" : {"temperature" :0.7 ,"top_p" :0.8 ,"top_k" :20 ,"presence_penalty" :1.5 }}, 10014# Qwen3.6-35B-A3B: the general-task sets (the card's precise-coding set is temperature 0.6, presence_penalty 0) 10015"qwen35moe" : {"thinking" : {"temperature" :1.0 ,"top_p" :0.95 ,"top_k" :20 ,"presence_penalty" :1.5 }, 10016"instruct" : {"temperature" :0.7 ,"top_p" :0.8 ,"top_k" :20 ,"presence_penalty" :1.5 }}, 10017# DeepSeek-V4.1-Flash: temperature 1.0, top_p 1.0 for local use (thinking or not), no penalties 10018"deepseek41" : {"thinking" : {"temperature" :1.0 ,"top_p" :1.0 },"instruct" : {"temperature" :1.0 ,"top_p" :1.0 }}, 10019} 10020 10021 10022def model_card_sampling (arch ,thinking )-> dict : 10023"""The model card's sampling for the family `arch` and the thinking state ({} for an unknown or unset family).""" 10024sets = MODEL_CARD_SAMPLING .get (arch )if arch else None 10025return dict (sets ["thinking" if thinking else "instruct" ])if sets else {} 10026 10027 10028def arch_from_tokenizer (arch ,pre )-> str | None : 10029"""#4137: the model family a config that names none is served as. A hand-written config (serve/server.py run on its own, a gateway) often leaves 10030"arch" out; for DeepSeek-V4.1 that meant the Qwen defaults: the stop ids of <|im_end|> (the DeepSeek tokenizer splits that into pieces, so a "|" or a 10031">" in the reply ended it: `finish_reason: stop` at token 19 in front of a table), no end token (the raw <|end▁of▁sentence|> came out as text) 10032and no DSML tool calls. The pack's tokenizer says what it is (its pre-tokenizer is "deepseek3"); an arch the config names is never changed.""" 10033if arch : 10034return arch 10035return "deepseek41" if str (pre or "" ).startswith ("deepseek" )else None 10036 10037 10038def default_model_name (cfg :dict )-> str : 10039"""The config's "model_name", else its family's name ("arch": qwen4exp, qwen35moe), else Flash-Next's.""" 10040return cfg .get ("model_name" )or FAMILY_MODEL_NAMES .get (cfg .get ("arch" )or "qwen4exp" ,"qwen3.8-flash-next" ) 10041 10042 10043def with_current_reader (cfg :dict ,package :Path )-> dict : 10044"""The picture reader (vision "exe", "cpu_exe") is written into the run config as an absolute path inside the engine package's folder, 10045and that folder is named after the engine version: after an engine update, or in a container made for another card, the path is gone 10046and the server would stop with "server_exited". Use the same file of the package that is installed now (the reader ships in the package).""" 10047vision = cfg .get ("vision" ) 10048if not isinstance (vision ,dict ): 10049return cfg 10050fixed = dict (vision ) 10051for key in ("exe" ,"cpu_exe" ): 10052old = fixed .get (key ) 10053if isinstance (old ,str )and old and not engine_component .is_reference (old )and os .path .isabs (old ): 10054new = package / old .replace ("\\" ,"/" ).rsplit ("/" ,1 )[- 1 ] 10055gone = not os .path .exists (old ) 10056# #4658: the old engine folder is kept after `strata update`, so the old reader still exists; one in a SIBLING engine folder 10057# (components/engine/<version>-...) is the engine's reader from before the update, and the engine in use has its own 10058older = (not gone and Path (old ).parent != package and Path (old ).parent .parent == package .parent 10059and package .parent .name .lower ()== "engine" ) 10060if (gone or older )and new .is_file (): 10061f"[strata] the picture reader { old } " + ("is not there any more" if gone else "belongs to an older engine" ) 10062+ f"; using { new } from the engine package in use" ,flush = True ) 10063fixed [key ]= str (new ) 10064if fixed == vision : 10065return cfg 10066return {** cfg ,"vision" :fixed } 10067 10068 10069READER_NEEDS_MIB = reader_room .READER_NEEDS_MIB # what the GPU picture reader takes from the card (1,342 MiB measured on an RTX A6000 and an R9700) 10070 10071#: Owner rule 2026-11-01: the picture reader lives in RAM, not VRAM. On an NVIDIA card with one GPU the GPU reader is started by the first 10072#: picture and stopped after vision.elastic_idle_s, inside a reserve of VISION_RESERVE_MIB; a start that finds no room is read by the CPU reader. 10073#: Measured on an RTX A6000 as a 24 GB card (Qwen3.8-Flash-Next IQ3_S, 5 interleaved pairs): the same 20,623 expert slots and the same text speed as 10074#: the reader on the card, 1.3 GB less VRAM in use between pictures. The expert cache that gives its room (vram_elastic) held 8.5% more slots 10075#: and was 2.2% slower in text (4 pairs of 5) in that first measurement; 11-11 it is the default (VISION_NO_RESERVE_BY_DEFAULT): on an RTX 10076#: PRO 5000 held to a 32 GB card (IQ3_S streamed, 5 rotated rounds) its text was level with the processor reader (2K / 8K / 20K 0.998 / 10077#: 0.997 / 0.998) and 2.9% faster than the room held back at 2K (12,719 against 12,022 slots), level when the model fits. 10078VISION_ON_DEMAND_BY_DEFAULT = True 10079#: AMD (HIP): the rule works there (the HIP reader starts on the first picture, +5.4 s on an R9700, and stops when idle) but is OFF by default: with no shrinking 10080#: expert cache on HIP the room has to stay in the reserve, so the engine gets no more slots (R9700, Qwen UD-Q4_K_XL: 7,959 against 7,943 with the reader on the card). 10081#: "elastic": true in the vision section asks for it. Set True if the expert cache can give its room on HIP. 10082VISION_ON_DEMAND_AMD_BY_DEFAULT = False 10083VISION_RESERVE_MIB = 2048 10084#: Owner 11-11: on NVIDIA the on-demand reader holds no room back before the first picture (apply_vision_defaults); the shrinking expert cache 10085#: makes it. In the resident RAM mode, where the cache cannot resize, the engine keeps the reader's room in its reserve itself 10086#: (include/strata/core/reader_room.hpp). 10087VISION_NO_RESERVE_BY_DEFAULT = True 10088_ON_DEMAND_NOT_WITH = ("--kv-grow" ,"--batch" ,"--slots" ,"--peer-device" ,"--expert-cache-device1" ,"--expert-cache-device2" , 10089"--expert-cache-device3" ) 10090 10091 10092def vision_on_demand_by_default (cfg :dict )-> bool : 10093"""True when this config's GPU reader should start on demand without the config saying so: a GPU reader (vision.gpu) of the NVIDIA 10094kind (or AMD's, with its CPU reader) on one GPU, no batch slots, no --kv-grow, no helper caches, and nothing in the vision section that says otherwise. Not DeepSeek 10095(its own tower), not Intel or a Mac (not measured there), not a reader pinned to another card (vision.cuda_device).""" 10096vis = cfg .get ("vision" ) 10097if not VISION_ON_DEMAND_BY_DEFAULT or not isinstance (vis ,dict )or vis .get ("gpu" )is not True or "elastic" in vis : 10098return False 10099if vis .get ("cuda_device" )is not None or sys .platform == "darwin" : 10100return False 10101backend = cfg .get ("backend" ) 10102if (cfg .get ("arch" )or "" )== "deepseek41" or backend not in (None ,"cuda" ,"hip" ): 10103return False 10104args = [str (a )for a in (cfg .get ("args" )or [])] 10105if len (gpu_list (cfg ))> 1 or parallel_slots (cfg )or any (a in args for a in _ON_DEMAND_NOT_WITH ): 10106return False 10107name = re .split (r"[\\/:]" ,str (vis .get ("exe" )or "" ))[- 1 ].lower ()# a path or a "component:..." reference 10108if backend == "hip" :# AMD: the HIP reader, with the CPU reader setup wrote beside it to read when the card has no room 10109return VISION_ON_DEMAND_AMD_BY_DEFAULT and name in (vision_reader .GPU_READER ,vision_reader .GPU_READER + ".exe" )and bool (vis .get ("cpu_exe" )) 10110if vision_reader .shared_memory_nvidia_host ():# a DGX Spark: the reader stays loaded (owner 2026-11-11; vision_reader.shared_memory_nvidia_host) 10111return False 10112return name in (vision_reader .CPU_READER ,vision_reader .CPU_READER + ".exe" ) 10113 10114 10115def apply_vision_defaults (cfg :dict )-> dict : 10116"""cfg with the on-demand reader switched on (vision.elastic) where vision_on_demand_by_default says so; the same dict. 10117NVIDIA (owner 11-11, "picture reader loaded on demand with no memory reserve": Ok): no room is held back for the reader before the first 10118picture. The expert cache is started in segments ("vram_elastic": the engine's --vram-elastic) and makes the reader's room when a picture 10119arrives, then takes it back after vision.elastic_idle_s; the reserve setup wrote (700 MiB, or none) stays as it is. Measured on an RTX A6000 10120(UD-Q4_K_XL partly streamed): 13,526 expert slots before any picture, as with the processor reader, against 13,077 with the room held back. 10121A config that says "vram_elastic" itself, and AMD (no shrinking expert cache on HIP), keep the room in the reserve as before: the reserve 10122setup writes for a GPU reader that stays on the card (700 MiB, or none) becomes VISION_RESERVE_MIB; a reserve the person or the app chose 10123(any other number) is kept.""" 10124if not vision_on_demand_by_default (cfg ): 10125return cfg 10126cfg ["vision" ]= {** cfg ["vision" ],"elastic" :True } 10127if VISION_NO_RESERVE_BY_DEFAULT and cfg .get ("backend" )!= "hip" and "vram_elastic" not in cfg : 10128cfg ["vram_elastic" ]= True # the cache gives the reader its room when a picture comes; nothing is held back before 10129return cfg 10130args = list (cfg .get ("args" )or []) 10131if "--vram-reserve-mib" not in args [:- 1 ]: 10132args += ["--vram-reserve-mib" ,str (VISION_RESERVE_MIB )] 10133elif args [args .index ("--vram-reserve-mib" )+ 1 ]== "700" : 10134args [args .index ("--vram-reserve-mib" )+ 1 ]= str (VISION_RESERVE_MIB ) 10135cfg ["args" ]= args 10136return cfg 10137 10138 10139def with_component_engine (cfg :dict )-> dict : 10140"""A run config that names "component:strata-engine" gets the engine package for this PC: the path in `exe`, and 10141the package's own folder first on the library path (the GPU runtime libraries ship beside the binary).""" 10142if not engine_component .is_reference (cfg .get ("exe" )): 10143return cfg 10144cfg = dict (cfg ) 10145cfg ["exe" ]= _component_exe (cfg ["exe" ],cfg ) 10146cfg ["lib_dirs" ]= [* engine_component .package_lib_dirs (Path (cfg ["exe" ]).parent ),* (cfg .get ("lib_dirs" )or [])] 10147cfg = with_current_reader (cfg ,Path (cfg ["exe" ]).parent ) 10148if cfg .get ("backend" )== "hip" :# AMD: the package's own hipBLASLt tuning table for this card, when its hipBLASLt version matches 10149cfg = hipblaslt_tuning .apply (cfg ,Path (cfg ["exe" ]).parent ,say = lambda line :line ,flush = True )) 10150return cfg 10151 10152 10153def _history_call_names (req )-> list : 10154"""The tool names a request's own conversation called, in order, on any of the three routes: Chat Completions (an assistant 10155message's tool_calls), Anthropic (an assistant message's tool_use blocks) and Responses (function_call / custom_tool_call 10156input items, a namespace in front as `namespace.name`).""" 10157names = [] 10158for message in req .get ("messages" )or []: 10159if not isinstance (message ,dict )or message .get ("role" )!= "assistant" : 10160continue 10161for call in message .get ("tool_calls" )or []: 10162names .append ((call .get ("function" )or {}).get ("name" )if isinstance (call ,dict )else None ) 10163content = message .get ("content" ) 10164for block in content if isinstance (content ,list )else []: 10165if isinstance (block ,dict )and block .get ("type" )== "tool_use" : 10166names .append (block .get ("name" )) 10167items = req .get ("input" ) 10168for item in items if isinstance (items ,list )else []: 10169if isinstance (item ,dict )and item .get ("type" )in ("function_call" ,"custom_tool_call" ): 10170name = item .get ("name" ) 10171if isinstance (name ,str )and name and isinstance (item .get ("namespace" ),str )and item ["namespace" ]: 10172name = f" { item [ 'namespace' ] } . { name } " 10173names .append (name ) 10174return names 10175 10176 10177def with_history_tools (tools ,req )-> list : 10178"""#4663: an agent's tool set changes between turns (deferred tools, MCP servers, a compacted history), and the model calls a tool it used 10179earlier in this conversation that this turn's `tools` no longer lists. That call came back as raw text with finish_reason "stop", and the 10180client took it for prose and stopped. A name the conversation's own assistant turns called is a tool the client has, so it counts as 10181declared (the call comes back as a tool call; the client says what it does with it) - on Chat Completions, Anthropic and Responses. 10182Nothing is added when the request declared no tools at all, or for a name that is already declared.""" 10183if not tools or not isinstance (req ,dict ): 10184return tools 10185try : 10186have = {t .get ("name" )for t in tools if isinstance (t ,dict )} 10187extra = [] 10188for name in _history_call_names (req ): 10189if isinstance (name ,str )and name and name not in have : 10190have .add (name ) 10191extra .append ({"name" :name ,"parameters" : {"type" :"object" ,"properties" : {}}}) 10192return [* tools ,* extra ]if extra else tools 10193except Exception : 10194return tools 10195 10196 10197def _component_exe (reference :str ,cfg :dict )-> str : 10198"""The engine a run config names as "component:strata-engine". No engine for this PC is a clear notice and exit 5; 10199the server never goes looking on the internet for one (strata_control/engine_component.py).""" 10200try : 10201return engine_component .expand (reference ,cfg ) 10202except engine_component .EngineMissing as e : 10203f"[strata] { e } " ,file = sys .stderr ,flush = True ) 10204raise SystemExit (e .exit_code )from None 10205 10206 10207def undeclared_tool_calls_setting (cfg :dict )-> str : 10208"""#4622: the config's "undeclared_tool_calls": "text" (the default, when the config does not name it) keeps a well-formed call of a tool the request 10209did not declare as the text the model wrote, with strata_rejected_tool_calls beside it; "call" returns it as a tool call, for a client that has 10210its own policy for unknown names (it answers the model with the tool names it has). Anything else stops the start.""" 10211mode = cfg .get ("undeclared_tool_calls" ) 10212if mode is None :# the environment names it too (STRATA_UNDECLARED_TOOL_CALLS); the config wins 10213mode = os .environ .get ("STRATA_UNDECLARED_TOOL_CALLS" )or "text" 10214if mode not in ("text" ,"call" ): 10215raise SystemExit (f"[strata] config \"undeclared_tool_calls\" must be \"text\" or \"call\", not { mode !r } " ) 10216return mode 10217 10218 10219def tool_call_recovery_setting (cfg :dict )-> bool : 10220"""The config's "tool_call_recovery" (see OutputParser's recover): ON when the config does not name it (since 0.2.8; 0.2.7 and before: off), 10221"tool_call_recovery": false turns it off. Anything but true or false stops the start.""" 10222recovery = cfg .get ("tool_call_recovery" ,True ) 10223if not isinstance (recovery ,bool ): 10224raise SystemExit (f"[strata] config \"tool_call_recovery\" must be true or false, not { recovery !r } " ) 10225return recovery 10226 10227 10228def main (argv = None ,* ,lifecycle_event = None ,interrupt_exit_code :int = 0 )-> int : 10229"""Serve until stopped. For as long as it runs this server holds the shared activity lease of the runtime folder (the same one `strata serve` and 10230a runtime host take), so `strata update` and a calibration run see an engine that was started by running this file directly - the desktop app's 10231source install does - and wait for it or refuse, instead of test-starting a second copy of the model beside it (#4463). A lease that cannot be 10232taken (an exclusive holder, a runtime folder that is not usable) never stops the server. 10233 10234Its console output goes through a bounded queue (serve/nonblocking_out.py, #4479 / #2481): a console that stops taking output must not hold a 10235request's turn, a cancel or an admission. STRATA_BLOCKING_CONSOLE=1 turns it off (testers).""" 10236quiet_crash_env ()# every child inherits it: no gdb on a user's machine (strata_control/childenv.py) 10237lease = None 10238try : 10239from strata_control import runtime as _runtime 10240lease = _runtime .acquire_activity_lease (shared = True ) 10241except Exception :# noqa: BLE001 - serving never depends on the lease 10242lease = None 10243try : 10244if os .environ .get ("STRATA_BLOCKING_CONSOLE" )== "1" : 10245return _main (argv ,lifecycle_event = lifecycle_event ,interrupt_exit_code = interrupt_exit_code ) 10246from serve .nonblocking_out import decoupled_console 10247with decoupled_console (): 10248return _main (argv ,lifecycle_event = lifecycle_event ,interrupt_exit_code = interrupt_exit_code ) 10249finally : 10250if lease is not None : 10251try : 10252os .close (lease ) 10253except OSError : 10254pass 10255 10256 10257def _main (argv = None ,* ,lifecycle_event = None ,interrupt_exit_code :int = 0 )-> int : 10258try :# files made by a run as administrator still belong to the user 10259from strata_control import private_files as _pf 10260_pf .adopt_user_defaults () 10261except Exception : 10262pass 10263event_sink = lifecycle_event 10264 10265def notify_lifecycle (kind :str ,payload :dict )-> None : 10266nonlocal event_sink 10267if event_sink is None : 10268return 10269try : 10270event_sink (kind ,payload ) 10271except (OSError ,ValueError ): 10272# A closed event consumer must not strand the owned engine or API. 10273event_sink = None 10274 10275ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 10276ap .add_argument ("--engine" ,choices = ["mock" ,"strata" ],default = "mock" ) 10277ap .add_argument ("--config" ,help = "strata engine config (JSON: exe, args, cwd, tokenizer, model_name), " 10278"written by setup.py" ) 10279ap .add_argument ("--host" ,default = None , 10280help = "the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices " 10281"on your network, :: = all IPv6 interfaces (set an API key); also \"host\" in the config" ) 10282ap .add_argument ("--script-cycle" ,action = "store_true" , 10283help = "with --script given more than once: repeat the scripts by position instead of advancing " 10284"to the last one and staying there, so extra requests a harness makes (a session title, " 10285"a re-ask after a tool result) cannot shift the sequence" ) 10286ap .add_argument ("--script-delay" ,type = float ,default = 0.0 , 10287help = "seconds to wait between the mock engine's tokens, so a turn stays live long enough for a " 10288"client to cancel it; the mock honours cancellation between tokens" ) 10289ap .add_argument ("--script" ,action = "append" , 10290help = "the mock engine's answer (default: a short greeting); given more than once, requests get " 10291"them in turn and the last one repeats" ) 10292ap .add_argument ("--port" ,type = int ,default = 8095 ) 10293ap .add_argument ("--ready-file" ,help = "write a JSON instance record once the API is bound and model state is known" ) 10294ap .add_argument ("--owner-fd" ,type = int ,help = argparse .SUPPRESS ) 10295ap .add_argument ("--shutdown-timeout" ,type = float ,default = None , 10296help = "opt-in graceful drain deadline in seconds (0..300) before owned requests are cancelled" ) 10297ap .add_argument ("--parallel" ,type = int ,default = None , 10298help = "request this many simultaneous engine slots without changing the saved config" ) 10299ap .add_argument ("--batch-groups" ,default = None , 10300help = "pipeline groups: auto or a positive integer, without changing the saved config" ) 10301ap .add_argument ("--max-queue" ,type = int ,default = None , 10302help = "maximum inference calls waiting beyond effective engine slots; 0 refuses overload" ) 10303ap .add_argument ("--queue-timeout" ,type = float ,default = None , 10304help = "maximum seconds waiting for the first engine turn (0.1..600; off by default)" ) 10305ap .add_argument ("--batch-telemetry" ,action = argparse .BooleanOptionalAction ,default = None , 10306help = "opt in to low-rate engine decode-window samples for /v1/telemetry" ) 10307ap .add_argument ("--offline" ,action = "store_true" , 10308help = "do not fetch remote image URLs or start MCP/tool subprocesses" ) 10309ap .add_argument ("--gpu" ,help = "the GPU to run on, as nvidia-smi numbers them, or several for a layer split " 10310"(\"0,2\"; also \"gpu\" in the config)" ) 10311ap .add_argument ("--tokenizer" ,default = str (ROOT / "pack/full/tokenizer" ), 10312help = "pack tokenizer directory (falls back to a byte tokenizer if absent)" ) 10313ap .add_argument ("--open" ,action = "store_true" ,help = "open the local page in the browser once the model is ready" ) 10314ap .add_argument ("--fit-max-tokens" ,action = "store_true" , 10315help = "clamp max_tokens to the remaining context instead of rejecting the request " 10316"(the default; kept so older scripts keep working)" ) 10317ap .add_argument ("--no-fit-max-tokens" ,action = "store_true" , 10318help = "answer 400 when prompt + max_tokens does not fit the context, like llama.cpp " 10319"(also \"fit_max_tokens\": false in the config). A prompt that alone does not fit is always 400" ) 10320ap .add_argument ("--api-key" ,default = os .environ .get ("STRATA_API_KEY" ,"" ), 10321help = "require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY. " 10322"Several keys: separate them with commas (key1,key2), as llama.cpp does" ) 10323ap .add_argument ("--no-api-key" ,action = "store_true" , 10324help = "serve on the network without an API key (anyone who can reach the port can use the model; " 10325"also \"api_key\": \"none\" in the config). Warns once, never refuses" ) 10326ap .add_argument ("--mcp-config" ,help = "a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": " 10327"{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " 10328"the config)" ) 10329ap .add_argument ("--lazy" ,action = "store_true" ,help = "start the API unloaded (the engine and the vision encoder start with the first request)" ) 10330ap .add_argument ("--api-monitor" ,action = "store_true" , 10331help = "the API request monitor at /api-monitor: keeps the last 100 requests' prompts and answers in " 10332"memory (also \"api_monitor\": true in the config; off by default)" ) 10333ap .add_argument ("--idle-unload" ,type = float ,default = None ,metavar = "SECONDS" , 10334help = "unload the model after this many seconds without requests, so other programs (games, other " 10335"model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" " 10336"in the config; default: never)" ) 10337ap .add_argument ("--min-free-vram-mib" ,type = int ,default = None , 10338help = "load an unloaded model only when this much VRAM is free, else answer 503 (also " 10339"\"min_free_vram_mib\" in the config; default: always load)" ) 10340ap .add_argument ("--before-load" ,help = "a command run before the model is loaded again (e.g. to unload another " 10341"server's model; also \"before_load\" in the config, a string or a list)" ) 10342ap .add_argument ("--slot-save-path" ,default = None ,metavar = "DIR" , 10343help = "enable POST /slots/0?action=save|restore {\"filename\": NAME} (llama-server's API): the " 10344"conversation the engine holds, to or from DIR/NAME (also \"slot_save_path\" in the config)" ) 10345ap .add_argument ("--replicas" ,type = int ,default = None ,metavar = "N" , 10346help = "data-parallel replicas (opt-in): cut the \"gpu\" list into N equal groups and run one engine on " 10347"each, requests spread over them (also \"replicas\" in the config: a number, or " 10348"[{\"gpus\": [0, 1]}, {\"gpus\": [2, 3]}])" ) 10349ap .add_argument ("--split-serve" ,default = None ,metavar = "PREFILL,DECODE" , 10350help = "split serving (opt-in): one engine on card PREFILL reads the prompt, a second on card DECODE makes " 10351"the answer, the session handed over in RAM (also \"split_serve\" in the config: " 10352"{\"prefill_gpu\": 0, \"decode_gpu\": 1}; docs/SPLIT_SERVE.md)" ) 10353launch_args = list (sys .argv [1 :]if argv is None else argv ) 10354a = ap .parse_args (launch_args ) 10355if a .engine == "strata" and (_rt := rttime_limit_note ()):# #3238: say it before the first unexplained -9 10356"[strata] WARNING: " + _rt ,flush = True ) 10357global OPENS_BROWSER 10358OPENS_BROWSER = bool (a .open ) 10359# Every ordinary way of being asked to stop takes Ctrl+C's path (QUIT to the engine, then exit): SIGTERM (#96 docker 10360# stop; systemd), SIGHUP (the terminal closed, ssh dropped), and on Windows Ctrl+Break and the console's close, 10361# logoff and shutdown events. They are installed before anything slow starts, so one that arrives while the model 10362# loads is not the default "die at once". SIGINT keeps Python's own handler (a second Ctrl+C stops waiting). 10363termination = "sigint" 10364finished = threading .Event ()# set when the clean stop is over (a Windows console handler waits for it) 10365 10366def request_stop (reason :str ): 10367nonlocal termination 10368termination = reason 10369if threading .current_thread ()is threading .main_thread (): 10370raise KeyboardInterrupt 10371import _thread 10372_thread .interrupt_main () 10373lifeline .install_stop_handlers (request_stop ,finished ) 10374if a .owner_fd is not None : 10375try : 10376owner_guard .start (a .owner_fd ,grace = (a .shutdown_timeout or 0 )+ 40 ) 10377except (OSError ,ValueError )as exc : 10378ap .error (str (exc )) 10379if a .shutdown_timeout is not None and not 0 <= a .shutdown_timeout <= 300 : 10380ap .error ("--shutdown-timeout must be in 0..300 seconds" ) 10381config_bytes = Path (a .config ).read_bytes ()if a .config else b"" 10382cfg = parse_config_text (config_bytes .decode ("utf-8-sig" ),a .config )if a .config else {}# Notepad adds a BOM 10383split_joined_args (cfg ) 10384if a .config and a .engine == "strata" : 10385cfg = apply_saved_tuning (cfg ) 10386attestation_key = os .environ .pop ("STRATA_OWNER_ATTEST_KEY" ,None ) 10387launch_attestation = None 10388if a .owner_fd is not None : 10389if attestation_key is None or not re .fullmatch (r"[0-9a-f]{64}" ,attestation_key ): 10390ap .error ("owned server needs a private launch attestation key" ) 10391launch_attestation = launch_identity .attestation (bytes .fromhex (attestation_key ), 10392config_bytes ,launch_args ) 10393if "batch_telemetry" in cfg and type (cfg ["batch_telemetry" ])is not bool : 10394ap .error ("batch_telemetry must be true or false" ) 10395try : 10396ready_path = ready_file .preflight (a .ready_file )if a .ready_file else None 10397except ValueError as e : 10398ap .error (str (e )) 10399max_queue = a .max_queue if a .max_queue is not None else cfg .get ("max_queue" ) 10400if max_queue is not None and (isinstance (max_queue ,bool )or not isinstance (max_queue ,int ) 10401or not 0 <= max_queue <= 4096 ): 10402ap .error ("--max-queue / max_queue must be a whole number in 0..4096" ) 10403queue_timeout = a .queue_timeout if a .queue_timeout is not None else cfg .get ("queue_timeout" ) 10404if queue_timeout is not None and (isinstance (queue_timeout ,bool )or not isinstance (queue_timeout , (int ,float )) 10405or not math .isfinite (queue_timeout )or not 0.1 <= queue_timeout <= 600 ): 10406ap .error ("--queue-timeout / queue_timeout must be finite seconds in 0.1..600" ) 10407if queue_timeout is not None and max_queue is None : 10408ap .error ("--queue-timeout requires --max-queue / max_queue to bound pending calls" ) 10409if a .parallel is not None : 10410if a .parallel < 1 or a .parallel > 1024 : 10411ap .error ("--parallel must be in 1..1024; the engine may reduce it to the supported count" ) 10412if parallel_flag_conflicts (cfg ): 10413ap .error ("--parallel conflicts with an explicit --batch/--slots in the saved engine args" ) 10414cfg ["parallel" ]= a .parallel 10415if a .batch_groups is not None : 10416if a .batch_groups != "auto" and (not a .batch_groups .isdecimal ()or int (a .batch_groups )< 1 ): 10417ap .error ("--batch-groups must be auto or a positive integer" ) 10418if not cfg or "args" not in cfg : 10419ap .error ("--batch-groups needs an engine config" ) 10420if "--batch-groups" in cfg ["args" ]: 10421ap .error ("--batch-groups conflicts with the saved engine args" ) 10422cfg ["args" ]= [* cfg ["args" ],"--batch-groups" ,a .batch_groups ] 10423lift_reasoning_effort_arg (cfg ) 10424if a .replicas is not None : 10425cfg ["replicas" ]= a .replicas 10426if a .split_serve is not None : 10427pair = [x .strip ()for x in a .split_serve .split ("," )] 10428if len (pair )!= 2 or not all (x .isdecimal ()for x in pair ): 10429ap .error ("--split-serve takes two card numbers: PREFILL,DECODE (for example 0,1)" ) 10430cfg ["split_serve" ]= {** (cfg .get ("split_serve" )if isinstance (cfg .get ("split_serve" ),dict )else {}), 10431"prefill_gpu" :int (pair [0 ]),"decode_gpu" :int (pair [1 ])} 10432if a .gpu is not None : 10433cfg ["gpu" ]= int (a .gpu )if a .gpu .strip ().isdigit ()else a .gpu 10434a .host = a .host or cfg .get ("host" )or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can 10435supplied_args = argv if argv is not None else sys .argv [1 :] 10436if ("STRATA_API_KEY" in os .environ and not os .environ ["STRATA_API_KEY" ].strip ())or \ 10437any ((x == "--api-key" and i + 1 < len (supplied_args )and not supplied_args [i + 1 ].strip ())or 10438x .strip ()== "--api-key=" for i ,x in enumerate (supplied_args )): 10439"[strata] an API key was given but it is empty: set a key, or leave it out" ,file = sys .stderr ) 10440return 2 10441raw_key = a .api_key or cfg .get ("api_key" ,"" ) 10442no_key_chosen = bool (getattr (a ,"no_api_key" ,False ))or explicit_no_key (raw_key ) 10443if explicit_no_key (raw_key ): 10444raw_key = "" 10445try : 10446preflight_api_key = api_key_of (raw_key ) 10447except ValueError as e : 10448f"[strata] { e } : set a key, or leave it out" ,file = sys .stderr ) 10449return 2 10450# A key is recommended on a network, never required (owner decision 2026-10-20): the banner below warns once. 10451try :# before the minutes of loading: is the port free? 10452Server ((a .host ,a .port ),BaseHTTPRequestHandler ).server_close () 10453except OSError as e : 10454ap .error (listen_problem (a .host ,a .port ,e )) 10455if cfg .get ("tokenizer" ): 10456a .tokenizer = cfg ["tokenizer" ] 10457tok = ByteTokenizer () 10458tcfg = {} 10459tpath = Path (a .tokenizer ) 10460if a .engine == "strata" and not (tpath / "vocab.json" ).exists (): 10461ap .error (f"the model's tokenizer is missing ( { tpath / 'vocab.json' } ); run setup again" ) 10462if (tpath / "vocab.json" ).exists (): 10463import strata_tokenizer as ST 10464vocab = json .loads ((tpath / "vocab.json" ).read_text (encoding = "utf-8" )) 10465tokens = [None ]* len (vocab ) 10466for t ,i in vocab .items (): 10467tokens [i ]= t 10468merges = (tpath / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ) 10469types = json .loads ((tpath / "token_type.json" ).read_text ()) 10470try :# the pack's pre-tokenizer name and special ids (DeepSeek's differ) 10471tcfg = json .loads ((tpath / "tokenizer.json" ).read_text (encoding = "utf-8" )) 10472except (OSError ,ValueError ): 10473pass 10474try : 10475tok = ST .Tokenizer (tokens ,merges ,types ,tcfg .get ("pre" )or "qwen35" ,tcfg .get ("special_ids" )or None ) 10476except ST .UnknownPreTokenizer as e :# a model with its own splitting rule: stop here, never split with another's 10477ap .error (f"the model's tokenizer ( { tpath } ): { e } " ) 10478if a .engine == "strata" and not cfg .get ("arch" )and arch_from_tokenizer (None ,tcfg .get ("pre" )): 10479cfg ["arch" ]= arch_from_tokenizer (None ,tcfg .get ("pre" )) 10480f"[strata] the config names no \"arch\" and this tokenizer is DeepSeek's: serving it as { cfg [ 'arch' ] } (its end token, DSML tool " 10481f"calls and effort words); add \"arch\": \" { cfg [ 'arch' ] } \" to the config to say it outright" ,flush = True ) 10482hub = hub_from_config (cfg ,a .mcp_config )# before the minutes of loading: a bad entry stops here 10483if a .offline and (hub is not None or cfg .get ("before_load" )or a .before_load ): 10484ap .error ("--offline requires MCP servers and before_load commands to be disabled in this profile" ) 10485if a .offline : 10486# The same decision, reported through the policy module so the two cannot drift: a profile 10487# that permits a network source is refused here rather than on its first request. 10488try : 10489from strata_control import offline as offline_policy 10490blocked = offline_policy .ensure_strictly_offline (cfg ) 10491except ImportError : 10492blocked = [] 10493if blocked : 10494ap .error ("--offline cannot be strict for this profile: " + "; " .join (blocked )) 10495lazy = False 10496if a .engine == "strata" : 10497if not cfg : 10498ap .error ("--engine strata needs --config" ) 10499cfg = apply_vision_defaults (with_component_engine (cfg )) 10500vision = None 10501# The engine's own environment. It carries the offline policy too: an engine that fetched a 10502# missing shard or a plugin would break the promise the flag makes. 10503env = child_env (cfg ,offline = a .offline ) 10504configure_batch_telemetry_env (env ,cfg ,a .batch_telemetry ) 10505sampling_defaults = sampling_defaults_from_config (cfg ) 10506if sampling_defaults : 10507pretty = ", " .join (f" { k } = { v } " for k ,v in sampling_defaults .items ()) 10508f"[strata] sampling defaults from the config: { pretty } " ,flush = True ) 10509lazy = a .lazy or cfg .get ("lazy_load" )is True 10510for line in card_roles_lines (cfg ):# the card roles: said first; every card Off stops here, before anything touches a card 10511line ,flush = True ) 10512if cfg .get ("vision" ): 10513elastic = cfg ["vision" ].get ("elastic" )is True 10514"the vision encoder starts with the first picture (elastic) ..." if elastic else 10515"loading the vision encoder ..." if not lazy else 10516"vision encoder unloaded; it starts with the model ..." ,flush = True ) 10517# relative paths are the config's cwd's, as for the engine below 10518vcfg = {k : (os .path .abspath (os .path .join (cfg .get ("cwd" )or "." ,v )) 10519if k in ("exe" ,"mmproj" ,"model" )and isinstance (v ,str )and not os .path .isabs (v )else v ) 10520for k ,v in cfg ["vision" ].items ()if not (k == "exe" and engine_component .is_reference (v ))} 10521if engine_component .is_reference (cfg ["vision" ].get ("exe" )):# the engine from the component folder 10522vcfg ["exe" ]= _component_exe (cfg ["vision" ]["exe" ],cfg ) 10523if vcfg .get ("elastic" )is True and layer_split_of (cfg ): 10524# the engine turns --vram-elastic off on a layer split (a cache per GPU): the encoder still starts 10525# with the first picture and stops when idle, but its VRAM has to be free already 10526'[strata] images: on a layer split the expert cache cannot make room for the image encoder (the ' 10527'engine turns --vram-elastic off); keep its VRAM free with "--vram-reserve-mib" on the ' 10528"encoder's GPU, or the first picture may not get it" ,flush = True ) 10529vision = Vision (vcfg ,log = open (cfg ["log" ],"a" ,encoding = "utf-8" )if cfg .get ("log" )else None , 10530env = vision_env (cfg ,env ),lazy = lazy ) 10531"model unloaded; the first request loads it ..." if lazy else 10532"loading the model (the first start takes a minute or two) ..." ,flush = True ) 10533warn_budget_over_ram (engine_args (cfg ,announce = False )if "args" in cfg else [])# #1080 10534note = card_note (cfg ,env ) 10535if note : 10536note ,flush = True ) 10537arch_line = engine_arch_note (cfg ) 10538if arch_line : 10539arch_line ,flush = True ) 10540igpu_line = igpu_split_warning (cfg ) 10541if igpu_line : 10542igpu_line ,flush = True ) 10543if layer_split_of (cfg ): 10544try : 10545split = layer_split_value (cfg )# #644: before the (minutes-long) start 10546except ValueError as e : 10547raise SystemExit (f"[strata] config { e } " ) 10548f"[strata] layer split across GPUs { gpu_list ( cfg ) } ( { split } )" ,flush = True ) 10549elif len (gpu_list (cfg ))> 1 : 10550f"[strata] GPUs { gpu_list ( cfg ) } : the later card(s) serve as the peer expert tier (--peer-device)" , 10551flush = True ) 10552# a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing 10553# it is told about (WinError 2), so it is made absolute here 10554if engine_component .is_reference (cfg ["exe" ]):# "component:strata-engine": the engine package for this PC 10555exe = _component_exe (cfg ["exe" ],cfg ) 10556else : 10557exe = cfg ["exe" ]if os .path .isabs (cfg ["exe" ])else os .path .abspath (os .path .join (cfg .get ("cwd" )or "." ,cfg ["exe" ])) 10558try : 10559silence = engine_silence_s (cfg )# #481: checked before the (minutes-long) start 10560apply_ready_timeout (cfg ) 10561except ValueError as e : 10562raise SystemExit (f"[strata] config { e } " ) 10563try : 10564effort_end = effort_end_args (cfg ,exe ,tok )# #458 10565except ValueError as e : 10566raise SystemExit (f"[strata] config { e } " ) 10567from serve import replicas as rp 10568try : 10569groups = rp .gpu_groups (cfg ) 10570except rp .ReplicaConfigError as e : 10571raise SystemExit (f"[strata] config { e } " ) 10572from serve import split as split_mod 10573try : 10574split = split_mod .split_spec (cfg ) 10575if split : 10576split_mod .check_cfg (cfg ,split ) 10577except split_mod .SplitConfigError as e : 10578raise SystemExit (f"[strata] config { e } " ) 10579if groups : 10580engine = start_replicas (cfg ,groups ,exe ,effort_end or [],lazy ,offline = a .offline ) 10581elif split : 10582engine = start_split (cfg ,split ,exe ,effort_end or [],lazy ,offline = a .offline ) 10583else : 10584engine = start_engine_or_fallback (cfg ,exe ,effort_end ,env ,lazy ,tok ,offline = a .offline ,batch_telemetry = a .batch_telemetry ) 10585engine .silence_s = silence # an attribute of its own: restart() keeps it 10586warn_tight_ram (engine .info .get ("arena_mib" )) 10587note = desktop_vram_note (cfg .get ("backend" ),engine .info .get ("vram_free_mib" ),engine .spawn [1 ], 10588linux_desktop ())if not groups and not split else None 10589if note :# #560 #516: before --open starts a browser on that card 10590note ,flush = True ) 10591else : 10592effort_end = None 10593engine ,vision ,sampling_defaults = MockEngine (tok ,a .script or [ 10594"Thinking about it.</think>\n\nHello from the mock engine." ], 10595cycle = getattr (a ,"script_cycle" ,False ), 10596delay_s = getattr (a ,"script_delay" ,0.0 )or 0.0 ),None , {} 10597# the model's own chat template (exported with its tokenizer), else the original model's 10598tpl = tpath / "chat_template.jinja" 10599if (cfg .get ("arch" )or "" )== "deepseek41" : 10600from serve import dsml 10601tpl ,swapped = dsml .pick_template (tpl ) 10602if swapped : 10603"[strata] this pack's chat template spells the tool-call block differently from the V4.1 model's; " 10604"using the V4.1 template so tool calls come back as real calls" ,flush = True ) 10605if vision is None and a .engine == "strata" and (cfg .get ("arch" )or "" )== "deepseek41" : 10606vision = ds4_engine_vision (cfg ,engine ) 10607svc = Service (engine ,tok ,ChatTemplate (tpl if tpl .exists ()else ROOT / "serve/chat_template.jinja" ), 10608model_name = default_model_name (cfg ),vision = vision , 10609sampling_defaults = sampling_defaults , 10610fit_max_tokens = a .fit_max_tokens or (not a .no_fit_max_tokens and cfg .get ("fit_max_tokens" )is not False )) 10611svc .launch_attestation = launch_attestation 10612if (cfg .get ("arch" )or "" )== "deepseek41" and vision is None and a .engine == "strata" : 10613# DeepSeek-V4.1 reads pictures with the engine's own tower (--vision on, the default): no separate reader process. 10614# `--vision off` in the config's args, or a pack without a tower, leaves svc.vision None: pictures are refused with the 400 as before. 10615_dsp = DsPictures .from_config (cfg ,tmp_dir = Path (cfg ["log" ]).parent / "ds-pictures" if cfg .get ("log" )else None ) 10616if _dsp is not None : 10617svc .vision = _dsp 10618"[strata] pictures: on (DeepSeek-V4.1 reads them with the engine's own vision tower; --vision off turns them off)" ,flush = True ) 10619svc .offline = a .offline 10620svc .max_queue = max_queue 10621svc .queue_timeout_s = float (queue_timeout )if queue_timeout is not None else None 10622if a .engine == "strata" :# the model card's sampling when nothing else is said (see MODEL_CARD_SAMPLING) 10623svc .model_arch = cfg .get ("arch" )or "qwen4exp" 10624svc .set_family (svc .model_arch if svc .model_arch == "deepseek41" else None ) 10625requested = cfg .get ("parallel" ) 10626if requested is None : 10627args = cfg .get ("args" , []) 10628for flag in ("--batch" ,"--slots" ): 10629if flag in args and args .index (flag )+ 1 < len (args ): 10630try : 10631requested = int (args [args .index (flag )+ 1 ]) 10632except ValueError : 10633pass 10634per_replica = requested if isinstance (requested ,int )and not isinstance (requested ,bool )and requested > 0 else 1 10635svc .requested_slots = per_replica * len (groups )if groups else per_replica 10636svc .answer_room = cfg .get ("answer_room" )is not False 10637svc .reasoning_close_retry = cfg .get ("reasoning_close_retry" )is True # #1053: opt-in, off by default 10638if cfg .get ("images" ):# image generation (serve/images.py), set up by setup --images 10639icfg = {k : (os .path .abspath (os .path .join (cfg .get ("cwd" )or "." ,v )) 10640if k in ("exe" ,"diffusion_model" ,"vae" ,"llm" ,"out_dir" )and isinstance (v ,str ) 10641and not os .path .isabs (v )else v ) 10642for k ,v in cfg ["images" ].items ()} 10643try : 10644svc .images = images_api .ImageGen (icfg ,log = open (cfg ["log" ],"a" ,encoding = "utf-8" )if cfg .get ("log" )else None ) 10645except ValueError as e : 10646raise SystemExit (f"[strata] config: { e } " ) 10647gone = svc .images .missing () 10648if gone : 10649f"[strata] image generation: missing { ', ' . join ( gone ) } - requests fail until setup --images has run " 10650"again" ,flush = True ) 10651noise_problem = svc .images .noise_problem () 10652if noise_problem : 10653f"[strata] image generation: { noise_problem } " ,flush = True ) 10654vae_problem = svc .images .vae_problem () 10655if vae_problem : 10656f"[strata] image generation: { vae_problem } " ,flush = True ) 10657f"[strata] image generation: { svc . images . model } { icfg . get ( 'quant' ) or '' } on " 10658f" { icfg . get ( 'backend' ) or '?' } (POST /v1/images/generations; GPU policy { svc . images . policy } )" ,flush = True ) 10659if cfg .get ("prevent_sleep" )is not None and not isinstance (cfg ["prevent_sleep" ],bool ): 10660raise SystemExit (f"[strata] config \"prevent_sleep\" must be true or false, not { cfg [ 'prevent_sleep' ]!r } " ) 10661from serve .keepawake import KeepAwake 10662svc .keep_awake = KeepAwake .create (cfg .get ("prevent_sleep" )is True )# #1727: opt-in, Windows only 10663if cfg .get ("reasoning_effort" )is not None :# #1641: the thinking level of requests that name none 10664try : 10665svc .config_effort = clean_shared_defaults ({"reasoning_effort" :cfg ["reasoning_effort" ]}).get ("reasoning_effort" ) 10666except ValueError as e : 10667raise SystemExit (f"[strata] config { e } " ) 10668if svc .config_effort : 10669f"[strata] thinking level: { svc . config_effort } (reasoning_effort in the config; a request, or the " 10670"Chat settings shared with other apps, can set its own)" ,flush = True ) 10671svc .codex_thread_titles = cfg .get ("codex_thread_titles" )is True # #923: opt-in, off by default 10672svc .codex_compaction_cache = cfg .get ("codex_compaction_cache" )is True # #924: opt-in, off by default 10673try : 10674svc .set_aliases (cfg .get ("aliases" ))# #297: other names the model answers to 10675except ValueError as e : 10676raise SystemExit (f"[strata] config { e } " ) 10677if svc .aliases : 10678f"[strata] model aliases: { ', ' . join ( svc . aliases ) } " ,flush = True ) 10679svc .api_key = preflight_api_key 10680try : 10681svc .telemetry_key = api_key_of (os .environ .get ("STRATA_TELEMETRY_KEY" )or cfg .get ("telemetry_read_key" ,"" )) 10682except ValueError as e : 10683f"[strata] invalid telemetry_read_key: { e } " ,file = sys .stderr ) 10684return 2 10685if set (key_list (svc .api_key ))& set (key_list (svc .telemetry_key )): 10686"[strata] telemetry_read_key must differ from every inference API key" ,file = sys .stderr ) 10687return 2 10688if not svc .api_key and "api_key" in cfg and not no_key_chosen :# #569: written, but empty: the server has none (a warning, not a stop) 10689"[strata] the api_key in the config is empty: this server has no API key (anyone who can reach it can " 10690"use it); set one, or leave api_key out" ,file = sys .stderr ,flush = True ) 10691svc .cors_origins = origins_of (cfg .get ("cors_origins" ),"cors_origins" ,wildcard = True ) 10692svc .trusted_origins = origins_of (cfg .get ("trusted_origins" ),"trusted_origins" ,wildcard = False ) 10693try : 10694svc .allowed_hosts = allowed_hosts_of (cfg .get ("allowed_hosts" ),os .environ .get ("STRATA_ALLOWED_HOSTS" ,"" )) 10695except ValueError as e : 10696raise SystemExit (f"[strata] config { e } " ) 10697if svc .allowed_hosts : 10698"[strata] Host check off: any name reaches this server (allowed_hosts \"*\")" if "*" in svc .allowed_hosts 10699else f"[strata] also answers to the host names { ', ' . join ( svc . allowed_hosts ) } (allowed_hosts)" ,flush = True ) 10700svc .api_monitor = a .api_monitor or cfg .get ("api_monitor" )is True 10701if svc .api_monitor : 10702"[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in " 10703"memory" + ("" if svc .api_key else "; anyone who can reach this server can read them (no API key)" ), 10704flush = True ) 10705if svc .cors_origins : 10706f"[strata] CORS on /v1/* for { ', ' . join ( svc . cors_origins ) } " 10707+ ("" if svc .api_key or "*" not in svc .cors_origins else 10708" - WARNING: any web page may use the model (no API key)" ),flush = True ) 10709svc .idle_unload_s = a .idle_unload if a .idle_unload is not None else float (cfg .get ("idle_unload_s" )or 0 ) 10710svc .min_free_vram_mib = a .min_free_vram_mib if a .min_free_vram_mib is not None else \ 10711int (cfg .get ("min_free_vram_mib" )or 0 ) 10712svc .before_load = a .before_load or cfg .get ("before_load" )or None 10713try : 10714svc .before_load_timeout_s = float (cfg .get ("before_load_timeout_s" )or svc .before_load_timeout_s ) 10715except (TypeError ,ValueError ): 10716"[strata] \"before_load_timeout_s\" in the config is not a number; using " 10717f" { svc . before_load_timeout_s :g } s" ,flush = True ) 10718svc .before_load_ignore_failure = cfg .get ("before_load_ignore_failure" )is True 10719svc .before_load_strict = cfg .get ("before_load_strict" )is True 10720# --slot-save-path is relative to the working directory the server was started in; the config's slot_save_path 10721# to the config's "cwd" (the engine's folder) when it has one. Either way the engine gets an absolute path. 10722if a .slot_save_path or cfg .get ("slot_save_path" ): 10723try : 10724svc .slot_save_path = slot_save_dir (a .slot_save_path )if a .slot_save_path else \ 10725slot_save_dir (cfg ["slot_save_path" ],cfg .get ("cwd" )) 10726except (ValueError ,OSError )as e : 10727raise SystemExit (f"[strata] { e } " ) 10728f"[strata] slot save/restore on: { svc . slot_save_path } (session files are kept until deleted: " 10729"about 1.2 GB per 63K-token conversation; restore only files this server wrote)" ,flush = True ) 10730mode = str (cfg .get ("anthropic_thinking" )or "model" )# #278: "on_request" = only when the request asks 10731if mode not in ("model" ,"on_request" ): 10732raise SystemExit (f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not { mode !r } " ) 10733svc .anthropic_think_unasked = mode == "model" 10734svc .tool_call_recovery = tool_call_recovery_setting (cfg ) 10735svc .undeclared_tool_calls = undeclared_tool_calls_setting (cfg ) 10736etu = cfg .get ("env_to_user" ,False )# opt-in: see frontend._env_to_user 10737if not isinstance (etu ,bool ): 10738raise SystemExit (f"[strata] config \"env_to_user\" must be true or false, not { etu !r } " ) 10739import serve .frontend as _frontend 10740_frontend .ENV_TO_USER = etu 10741rs = cfg .get ("repeat_stop_tokens" ,REPEAT_STOP_TOKENS )# #606: opt-out with 0 10742if isinstance (rs ,bool )or not isinstance (rs ,int )or rs < 0 : 10743raise SystemExit (f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not { rs !r } " ) 10744svc .repeat_stop_tokens = rs 10745tl = cfg .get ("thinking_loop_tokens" ,0 )# opt-in: close the thinking on a repeated token and answer 10746if isinstance (tl ,bool )or not isinstance (tl ,int )or tl < 0 : 10747raise SystemExit (f"[strata] config \"thinking_loop_tokens\" must be a whole number >= 0 (0 = off), not { tl !r } " ) 10748svc .thinking_loop_tokens = tl 10749svc .effort_end = bool (effort_end )# #458: "effort_position": "end" with an engine that has it 10750if cfg .get ("reasoning_budget_tokens" )is not None :# #123: a default thinking budget for every request 10751svc .reasoning_budget_configured = True 10752try : 10753svc .reasoning_budget_tokens = cfg ["reasoning_budget_tokens" ] 10754budget = svc .reasoning_budget ({}) 10755except ValueError as e : 10756raise SystemExit (f"[strata] config { e } " ) 10757if budget : 10758f"[strata] thinking budget: { budget } tokens (reasoning_budget_tokens; a request can set its own)" , 10759flush = True ) 10760recovery = cfg .get ("reasoning_loop_recovery" ,False )# #728: false (default) | "stop" | "recover" (true) 10761if recovery is True : 10762recovery = "recover" 10763if recovery is not False and recovery not in ("stop" ,"recover" ): 10764raise SystemExit ("[strata] config \"reasoning_loop_recovery\" must be false, \"stop\" or \"recover\", " 10765f"not { recovery !r } " ) 10766svc .reasoning_loop_recovery = recovery 10767svc .gpu_index = (gpu_list (cfg )or [0 ])[0 ]# the Monitor reads the card the engine runs on (issue #51) 10768svc .gpu_indices = gpu_list (cfg )# ... or every card of a layer split (issue #112) 10769if a .engine == "strata" and groups :# replicas: every card of every group 10770svc .gpu_indices = [c for g in groups for c in g ] 10771svc .gpu_index = svc .gpu_indices [0 ] 10772svc .replica_gpu_groups = groups 10773if a .engine == "strata" and split :# split serving: the two cards (the prefill card first) 10774svc .gpu_indices = [split ["prefill_gpu" ],split ["decode_gpu" ]] 10775svc .gpu_index = split ["decode_gpu" ] 10776svc .terminal_visibility_order = visible_device_order (env ,cfg .get ("backend" ))if a .engine == "strata" else [] 10777svc .terminal_topology_mode = ("replicas (configured)" if a .engine == "strata" and groups 10778else "split serve (configured)" if a .engine == "strata" and split 10779else "layer split (configured)" if a .engine == "strata" and layer_split_of (cfg ) 10780else "single GPU or CPU" if a .engine == "strata" else "mock" ) 10781svc .terminal_configured_split = (layer_split_value (cfg )if a .engine == "strata" and layer_split_of (cfg ) 10782else None ) 10783svc .backend = cfg .get ("backend" )# "hip": the AMD cards' readings come from sysfs (#301) 10784if a .config : 10785svc .config_path = a .config # #564: the web page's Settings view 10786if a .config :# the Chat settings shared with other apps, from last time 10787svc .shared_path = str (Path (a .config ).with_suffix ("" ))+ ".shared-settings.json" 10788try : 10789svc .shared = clean_shared_defaults (json .loads (Path (svc .shared_path ).read_text (encoding = "utf-8" ))) 10790if svc .shared : 10791"[strata] other apps use the Chat settings: " + 10792", " .join (f" { k } = { v } " for k ,v in svc .shared .items ()),flush = True ) 10793except (OSError ,ValueError ): 10794svc .shared = {} 10795if hub is not None : 10796import atexit 10797svc .mcp = hub 10798if hub .settings ["image_results" ]: 10799hub .media_dir = Path (a .config ).with_suffix (".tool-media" )if a .config else Path .cwd ()/ ".tool-media" 10800f"[strata] starting { len ( hub . servers ) } MCP server { 's' * ( len ( hub . servers ) != 1 ) } for the web app's " 10801f"chat: { ', ' . join ( hub . servers ) } " ,flush = True ) 10802hub .start () 10803atexit .register (hub .close )# the servers Strata started end with it 10804httpd = serve (svc ,host = a .host ,port = a .port ) 10805bound_port = httpd .server_address [1 ]# --port 0: report the port the OS actually assigned 10806svc .start_idle_unload () 10807svc .start_vision_idle () 10808here = "[::1]" if a .host == "::" else "127.0.0.1" if a .host in ("0.0.0.0" ,"" )else f"[ { a . host } ]" if ":" in a .host else a .host 10809f"ready: http:// { here } : { bound_port } /v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, " 10810f"context { engine . max_context } tokens { ', images on' if vision else '' } " 10811f" { ', API key required' if svc . api_key else '' } )" ,flush = True ) 10812f" open http:// { here } : { bound_port } / in a browser to chat; close this window to stop the model" ,flush = True ) 10813if a .host not in ("127.0.0.1" ,"localhost" ,"::1" ): 10814# issue #26: reachable from other devices - say at which address, and what can still block it 10815ips = [f"[ { a . host } ]" ]if ":" in a .host and a .host != "::" else []if a .host == "::" else lan_addresses () 10816for ip in ips : 10817f" from other devices: http:// { ip } : { bound_port } / (API: http:// { ip } : { bound_port } /v1)" ,flush = True ) 10818if not ips : 10819address = "[<this PC's IPv6 address>]" if a .host == "::" else "<this PC's IP address>" 10820f" from other devices: http:// { address } : { bound_port } /" ,flush = True ) 10821if not svc .api_key : 10822" WARNING: " + open_server_warning (bound_port ,tools = svc .mcp is not None ), 10823flush = True ) 10824if os .name == "nt" : 10825" nothing arrives? Windows Firewall blocks it until allowed: accept its prompt for Python, or run " 10826"in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str (bound_port )+ "\" " 10827"-Direction Inbound -Protocol TCP -LocalPort " + str (bound_port )+ " -Action Allow -Profile Private\n" 10828" (and set this network to Private in Windows' network settings)" ,flush = True ) 10829if a .open and cfg .get ("open_browser" )is not False :# #609: the config's "open_browser": false wins (an older 10830import webbrowser # run-<model>.bat still passes --open) 10831# on its own thread: webbrowser.open waits for the browser launcher, which on Linux can run for as long as 10832# the browser does, and the main thread must be free to take Ctrl+C and SIGTERM (#1872) 10833threading .Thread (target = webbrowser .open ,daemon = True ,name = "strata-open-browser" , 10834args = (f"http:// { here } : { bound_port } /" ,)).start () 10835if ready_path is not None or event_sink is not None : 10836ready_host = f"[ { here } ]" if ":" in here and not here .startswith ("[" )else here 10837record = {"schema_version" :1 ,"instance_id" :svc .instance_id ,"pid" :os .getpid (), 10838"api_url" :f"http:// { ready_host } : { bound_port } " ,"bound_host" :a .host ,"bound_port" :bound_port , 10839"model_id" :svc .model ,"model_state" :"unloaded" if lazy else "ready" , 10840"api_state" :"ready" ,"created_at" :time .time ()} 10841interrupted = False 10842drained = True 10843try : 10844# inside the try: a SIGTERM that arrives the moment the ready file is visible (a supervisor that reads it and 10845# stops the server at once) takes the clean stop below, not an uncaught KeyboardInterrupt with the file left behind 10846if ready_path is not None : 10847try : 10848ready_file .publish (ready_path ,record ) 10849except OSError as e : 10850f"[strata] could not write ready file ( { type ( e ). __name__ } )" ,file = sys .stderr ) 10851return 6 # the finally below closes everything once 10852if event_sink is not None : 10853notify_lifecycle ("ready" ,record ) 10854while True : 10855time .sleep (1 )# Windows never delivers Ctrl+C to an untimed Event.wait() 10856except KeyboardInterrupt : 10857interrupted = True 10858notify_lifecycle ("stopping" , {"reason" :termination ,"instance_id" :svc .instance_id }) 10859"\n[strata] stopping (Ctrl+C again to end the engine at once) ..." ,flush = True ) 10860finally : 10861cancelled = 0 10862if a .shutdown_timeout is not None : 10863pending = svc .begin_drain () 10864notify_lifecycle ("draining" , {"instance_id" :svc .instance_id , 10865"pending_requests" :pending , 10866"deadline_s" :a .shutdown_timeout }) 10867if pending : 10868f"[strata] draining { pending } inference call(s) for up to { a . shutdown_timeout :g } s ..." , 10869flush = True ) 10870pending = svc .wait_for_drain (a .shutdown_timeout ) 10871if pending : 10872cancelled = svc .cancel_owned_requests () 10873f"[strata] drain deadline expired; cancelling { cancelled } owned request(s) ..." ,flush = True ) 10874svc .wait_for_drain (5 ) 10875drained = False 10876else : 10877# #6055: without --shutdown-timeout there is no wait, but a request that arrives while the engine closes is 10878# still refused (503 server_draining, retry elsewhere) instead of being accepted and cut off with 0 tokens 10879svc .begin_drain () 10880closers = [httpd .shutdown ,getattr (engine ,"close" ,None ),vision .shutdown if vision else None , 10881hub .close if hub is not None else None ] 10882try : 10883for close in filter (None ,closers ): 10884try : 10885close () 10886except KeyboardInterrupt :# a second Ctrl+C: don't wait for the engine to free its memory 10887if getattr (engine ,"proc" ,None ): 10888engine .proc .kill () 10889try : 10890from serve import cache_drop 10891cache_drop .drop_after_exit (engine )# opt-in (STRATA_DROP_CACHE_ON_EXIT=1), default unchanged 10892except Exception as e :# noqa: BLE001 - never block the exit 10893f"[strata] could not release the model files' cache: { e } " ,flush = True ) 10894finally : 10895if ready_path is not None : 10896ready_file .remove_if_owned (ready_path ,svc .instance_id ) 10897finished .set () 10898if interrupted : 10899"[strata] stopped" ,flush = True ) 10900exit_code = (8 if not drained else 10901interrupt_exit_code if interrupted and termination == "sigint" else 0 ) 10902notify_lifecycle ("stopped" , {"instance_id" :svc .instance_id ,"reason" :termination if interrupted else "normal" , 10903"drained" :drained ,"cancelled_requests" :cancelled , 10904"exit_code" :exit_code }) 10905return exit_code 10906 10907 10908if __name__ == "__main__" : 10909sys .exit (main ())