The three adapters reduce pictures to a Responses input_image, the prompt renderer writes the template's picture items and returns their sources in prompt order, and the request path encodes them (in turn with the engine), expands every image pad to its token count and sends GENI with the combined SVE1 file. The encoder is configured by a top-level vision section, stops with the engine and starts before it. Goldens recorded from the Python handlers cover fourteen Chat and Messages requests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
618 lines
34 KiB
Python
618 lines
34 KiB
Python
"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only).
|
|
|
|
Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables
|
|
of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of
|
|
`crates/serving-policy` compare against these files.
|
|
|
|
python3 -I control-plane/tests/golden/gen_goldens.py [section ...]
|
|
|
|
Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them.
|
|
Sections: gen_lines, shared, props_slots, cors, ...
|
|
"""
|
|
import json
|
|
import os
|
|
import queue
|
|
import sys
|
|
import threading
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
REPO = os.path.normpath(os.path.join(HERE, "..", "..", ".."))
|
|
ENGINE = os.path.join(REPO, "engine", "strata")
|
|
sys.path.insert(0, ENGINE)
|
|
sys.path.insert(0, os.path.join(ENGINE, "tools"))
|
|
|
|
OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden")
|
|
OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures")
|
|
|
|
|
|
def write(name, obj, dest="control"):
|
|
out = OUT_POLICY if dest == "policy" else OUT_CONTROL
|
|
os.makedirs(out, exist_ok=True)
|
|
path = os.path.join(out, name + ".json")
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False)
|
|
f.write("\n")
|
|
print("wrote", os.path.relpath(path, REPO), file=sys.stderr)
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ gen_lines
|
|
def gen_lines():
|
|
from serve.server import StrataEngine
|
|
|
|
class Pipe:
|
|
def __init__(self):
|
|
self.sent = []
|
|
|
|
def write(self, text):
|
|
self.sent.append(text)
|
|
|
|
def flush(self):
|
|
pass
|
|
|
|
def capture(ids, max_new, sampling, embeddings=None):
|
|
eng = object.__new__(StrataEngine)
|
|
eng.proc = type("P", (), {"stdin": Pipe()})()
|
|
eng.lines = queue.Queue()
|
|
eng.lines.put("DONE 1 1 1.0 1.0 stop\n")
|
|
eng.can_stop = False
|
|
eng.progress = None
|
|
eng.prefill_tok_s_mean = None
|
|
eng.last = {}
|
|
list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings))
|
|
return "".join(eng.proc.stdin.sent)
|
|
|
|
cases = []
|
|
sampling_tables = [
|
|
{},
|
|
{"temperature": 0.0},
|
|
{"temperature": 0.7},
|
|
{"temperature": 0.7, "top_p": 0.9},
|
|
{"temperature": 1, "top_p": 1.0},
|
|
{"temperature": 0.8, "top_k": 40, "min_p": 0.05},
|
|
{"temperature": 0.8, "top_k": 0},
|
|
{"temperature": 0.8, "top_k": 1000},
|
|
{"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0},
|
|
{"repetition_penalty": 1.1},
|
|
{"repetition_penalty": 1.1, "penalty_last_n": 256},
|
|
{"presence_penalty": 0.5, "frequency_penalty": 0.25},
|
|
{"presence_penalty": -0.5},
|
|
{"frequency_penalty": 1.5, "penalty_last_n": 0},
|
|
{"temperature": 0.7, "seed": 42},
|
|
{"temperature": 0.7, "seed": 0},
|
|
{"temperature": 0.7, "seed": 18446744073709551615},
|
|
{"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05,
|
|
"presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7},
|
|
{"strata_tune": {"pcie_frac": 0.0}},
|
|
{"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}},
|
|
{"strata_tune": {"spec_min_p": 1.0}},
|
|
{"experimental_speed_projection": True},
|
|
{"experimental_speed_projection": False},
|
|
{"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False},
|
|
]
|
|
for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None),
|
|
([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")):
|
|
for sampling in sampling_tables:
|
|
cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling,
|
|
"line": capture(ids, max_new, sampling, emb)})
|
|
write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases})
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ shared
|
|
def shared():
|
|
from serve.server import clean_shared_defaults, sampling_defaults_from_config
|
|
|
|
clean_cases = [
|
|
None, {}, [], "x", 5,
|
|
{"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5},
|
|
{"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"},
|
|
{"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False},
|
|
{"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"},
|
|
{"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615},
|
|
{"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"},
|
|
{"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"},
|
|
{"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3},
|
|
{"experimental_speed_projection": True}, {"experimental_speed_projection": False},
|
|
{"experimental_speed_projection": 1},
|
|
{"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1},
|
|
{"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100,
|
|
"reasoning_effort": "medium", "experimental_speed_projection": False},
|
|
]
|
|
clean = []
|
|
for case in clean_cases:
|
|
try:
|
|
clean.append({"input": case, "ok": clean_shared_defaults(case)})
|
|
except ValueError as e:
|
|
clean.append({"input": case, "error": str(e)})
|
|
|
|
config_cases = [
|
|
None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True},
|
|
{"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2},
|
|
{"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5},
|
|
{"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25},
|
|
{"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0},
|
|
{"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5},
|
|
{"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"},
|
|
{"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"},
|
|
{"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3},
|
|
{"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1,
|
|
"frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9},
|
|
]
|
|
import contextlib
|
|
import io
|
|
config = []
|
|
for case in config_cases:
|
|
out = io.StringIO()
|
|
try:
|
|
with contextlib.redirect_stdout(out):
|
|
ok = sampling_defaults_from_config({"sampling": case} if case is not None else {})
|
|
config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines()
|
|
if "unknown key" in ln]})
|
|
except SystemExit as e:
|
|
config.append({"input": case, "error": str(e)})
|
|
write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)",
|
|
"clean": clean, "config": config}, dest="policy")
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ reasoning
|
|
def reasoning():
|
|
import random
|
|
from serve.frontend import OutputParser
|
|
from serve.server import Detokenizer, Service, ByteTokenizer
|
|
|
|
class BytesTok:
|
|
"""Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer."""
|
|
def __init__(self, table):
|
|
self.table = table
|
|
|
|
def token_bytes(self, t):
|
|
return self.table[t]
|
|
|
|
pieces = [b"a", b"b", b" so ", b"think", b"</", b"/think>", b"</think>", b"</thi", b"nk>", b"<", b"/", b"\n",
|
|
b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"<t",
|
|
b"hink>", b"x"]
|
|
rng = random.Random(1234)
|
|
seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0],
|
|
[3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
|
|
for _ in range(120):
|
|
seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))])
|
|
cases = []
|
|
for seq in seqs:
|
|
row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}}
|
|
for budget in (1, 2, 3, 5, 8):
|
|
parser = OutputParser(thinking=True, tools=None, stream_tools=True)
|
|
detok = Detokenizer(BytesTok(pieces))
|
|
thought, wrap_at = 0, None
|
|
for i, t in enumerate(seq):
|
|
parser.feed(detok.push(t))
|
|
if parser.state == "reasoning":
|
|
thought += 1
|
|
if thought >= budget and not parser.buf and not detok.pending():
|
|
wrap_at = i
|
|
break
|
|
row["wrap_at"][str(budget)] = wrap_at
|
|
cases.append(row)
|
|
|
|
parse = []
|
|
svc = Service.__new__(Service)
|
|
for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0),
|
|
({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50),
|
|
({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0),
|
|
({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0),
|
|
({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]:
|
|
svc.reasoning_budget_tokens = default
|
|
try:
|
|
parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)})
|
|
except ValueError as e:
|
|
parse.append({"request": req, "default": default, "error": str(e)})
|
|
from serve.server import REASONING_WRAP_UP
|
|
write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real "
|
|
"Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases,
|
|
"parse": parse}, dest="policy")
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ http
|
|
def http_surface():
|
|
"""The operational HTTP surface of the real Python server, scenario by scenario (fake resident engine)."""
|
|
import http.client
|
|
from pathlib import Path
|
|
from serve.frontend import ChatTemplate
|
|
from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve
|
|
|
|
class Resident(StrataEngine):
|
|
def __init__(self, tok, loaded, max_context):
|
|
self.reply = MockEngine(tok, "Hello.", max_context=max_context)
|
|
self.max_context, self.info, self.last = max_context, {"version": "9.9.9"}, {}
|
|
self.loaded, self.unloaded, self.progress = loaded, not loaded, None
|
|
|
|
def alive(self):
|
|
return self.loaded
|
|
|
|
def exit_code(self):
|
|
return None
|
|
|
|
def restart(self):
|
|
self.loaded, self.unloaded = True, False
|
|
|
|
def close(self):
|
|
self.loaded = False
|
|
|
|
def unload(self):
|
|
self.close()
|
|
self.unloaded = True
|
|
|
|
def generate(self, *args, **kwargs):
|
|
yield from self.reply.generate(*args, **kwargs)
|
|
|
|
def run(setup, steps):
|
|
tok = ByteTokenizer()
|
|
engine = Resident(tok, setup.get("loaded", True), setup.get("max_context", 4096))
|
|
svc = Service(engine, tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
|
|
model_name=setup.get("model", "strata-test"),
|
|
sampling_defaults=setup.get("config_sampling") or {})
|
|
svc.set_aliases(setup.get("aliases"))
|
|
svc.api_key = setup.get("api_key", "")
|
|
svc.cors_origins = setup.get("cors_origins", [])
|
|
svc.trusted_origins = setup.get("trusted_origins", [])
|
|
if setup.get("shared"):
|
|
svc.shared = dict(setup["shared"])
|
|
svc.idle_unload_s = setup.get("idle_unload_s", 0)
|
|
for key, value in (setup.get("status") or {}).items():
|
|
svc.status[key] = value
|
|
httpd = serve(svc, port=0)
|
|
port = httpd.server_address[1]
|
|
out = []
|
|
try:
|
|
for step in steps:
|
|
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
|
|
headers = dict(step.get("headers") or {})
|
|
body = step.get("body")
|
|
if body is not None and not isinstance(body, str):
|
|
body = json.dumps(body)
|
|
headers.setdefault("Content-Type", "application/json")
|
|
if body is not None:
|
|
headers.setdefault("Content-Length", str(len(body.encode())))
|
|
conn.request(step["method"], step["path"], body=body.encode() if body is not None else None,
|
|
headers=headers)
|
|
response = conn.getresponse()
|
|
raw = response.read().decode()
|
|
selected = {k.lower(): v for k, v in response.getheaders()
|
|
if k.lower().startswith("access-control-") or k.lower() == "vary"}
|
|
try:
|
|
parsed = json.loads(raw) if raw else None
|
|
except ValueError:
|
|
parsed = raw
|
|
out.append({"request": {"method": step["method"], "path": step["path"],
|
|
"headers": step.get("headers") or {}, "body": step.get("body")},
|
|
"status": response.status, "headers": selected, "body": parsed,
|
|
"state": {"loaded": engine.loaded, "shared": svc.shared}})
|
|
conn.close()
|
|
finally:
|
|
httpd.shutdown()
|
|
httpd.server_close()
|
|
return {"setup": setup, "steps": out}
|
|
|
|
scenarios = {}
|
|
# ---- CORS
|
|
cors_steps = [
|
|
{"method": "OPTIONS", "path": "/v1/chat/completions",
|
|
"headers": {"Origin": "https://a.example", "Access-Control-Request-Headers": "authorization,content-type"}},
|
|
{"method": "OPTIONS", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
|
|
{"method": "OPTIONS", "path": "/v1/models"},
|
|
{"method": "OPTIONS", "path": "/health", "headers": {"Origin": "https://a.example"}},
|
|
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://a.example/"}},
|
|
{"method": "GET", "path": "/v1/status?x=1", "headers": {"Origin": "https://b.example"}},
|
|
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
|
|
{"method": "GET", "path": "/v1/models"},
|
|
{"method": "GET", "path": "/health", "headers": {"Origin": "https://a.example"}},
|
|
{"method": "GET", "path": "/props", "headers": {"Origin": "https://a.example"}},
|
|
{"method": "GET", "path": "/v1/nothing", "headers": {"Origin": "https://a.example"}},
|
|
]
|
|
for name, origins in (("off", []), ("any", ["*"]), ("listed", ["https://a.example", "https://b.example"])):
|
|
scenarios[f"cors_{name}"] = run({"cors_origins": origins}, cors_steps)
|
|
# (an unknown path answers 404 before authentication in the Python server; the Rust server
|
|
# authenticates every path first, so that one step is left out here)
|
|
scenarios[f"cors_{name}_with_key"] = run({"cors_origins": origins, "api_key": "k" * 40}, cors_steps[:-1])
|
|
# ---- own page
|
|
page = {"defaults": {"temperature": 0.5}}
|
|
own = [
|
|
{"method": "POST", "path": "/settings", "body": page},
|
|
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "http://127.0.0.1:1"}},
|
|
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example"}},
|
|
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com/"}},
|
|
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com",
|
|
"Host": "proxy.internal"}},
|
|
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example",
|
|
"X-Forwarded-Host": "evil.example",
|
|
"CF-Ray": "1"}},
|
|
{"method": "POST", "path": "/settings", "body": json.dumps(page), "headers": {"Content-Type": "text/plain"}},
|
|
{"method": "POST", "path": "/settings", "body": json.dumps(page),
|
|
"headers": {"Content-Type": "application/x-www-form-urlencoded"}},
|
|
{"method": "POST", "path": "/settings", "body": json.dumps(page),
|
|
"headers": {"Content-Type": "application/json; charset=utf-8"}},
|
|
{"method": "GET", "path": "/settings"},
|
|
]
|
|
scenarios["own_page"] = run({"trusted_origins": ["https://strata.example.com"]}, own)
|
|
# ---- settings
|
|
settings = [
|
|
{"method": "GET", "path": "/settings"},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.7, "top_k": 40, "seed": 3}}},
|
|
{"method": "GET", "path": "/settings"},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 9}}},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"nonsense": 1}}},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_p": 0, "temperature": 1}}},
|
|
{"method": "GET", "path": "/settings"},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"max_tokens": 128, "reasoning_effort": "low",
|
|
"experimental_speed_projection": True}}},
|
|
{"method": "GET", "path": "/settings"},
|
|
{"method": "POST", "path": "/settings", "body": [1, 2]},
|
|
{"method": "GET", "path": "/settings"},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.5}}},
|
|
{"method": "POST", "path": "/settings", "body": {}},
|
|
{"method": "GET", "path": "/settings"},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": 5}},
|
|
]
|
|
scenarios["settings"] = run({}, settings)
|
|
scenarios["settings_with_key"] = run({"api_key": "k" * 40}, [
|
|
{"method": "GET", "path": "/settings"},
|
|
{"method": "GET", "path": "/settings", "headers": {"Authorization": "Bearer " + "k" * 40}},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}},
|
|
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}},
|
|
"headers": {"Authorization": "Bearer " + "k" * 40}},
|
|
])
|
|
# ---- props, slots, health, status
|
|
reads = [
|
|
{"method": "GET", "path": "/props"},
|
|
{"method": "GET", "path": "/props?model=strata-test"},
|
|
{"method": "GET", "path": "/props?model=alias-one"},
|
|
{"method": "GET", "path": "/props?model=nope"},
|
|
{"method": "GET", "path": "/props?model="},
|
|
{"method": "GET", "path": "/slots"},
|
|
{"method": "GET", "path": "/api/health"},
|
|
{"method": "GET", "path": "/v1/status"},
|
|
]
|
|
scenarios["reads_loaded"] = run({"aliases": ["alias-one", "alias-two"]}, reads)
|
|
scenarios["reads_loaded_with_defaults"] = run(
|
|
{"config_sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.2,
|
|
"repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 8},
|
|
"shared": {"temperature": 0.9, "max_tokens": 256}, "max_context": 32768}, reads)
|
|
scenarios["reads_unloaded"] = run({"loaded": False, "aliases": ["alias-one"]}, reads)
|
|
scenarios["reads_busy"] = run({"status": {"busy": True, "queued": 2}}, [
|
|
{"method": "GET", "path": "/slots"}, {"method": "GET", "path": "/v1/status"}])
|
|
scenarios["reads_with_key"] = run({"api_key": "k" * 40}, [
|
|
{"method": "GET", "path": "/props"}, {"method": "GET", "path": "/slots"},
|
|
{"method": "GET", "path": "/v1/status"}, {"method": "GET", "path": "/api/health"},
|
|
{"method": "GET", "path": "/health"}])
|
|
# ---- load / unload
|
|
lifecycle = [
|
|
{"method": "POST", "path": "/unload"},
|
|
{"method": "POST", "path": "/unload"},
|
|
{"method": "GET", "path": "/slots"},
|
|
{"method": "POST", "path": "/load"},
|
|
{"method": "POST", "path": "/load"},
|
|
{"method": "POST", "path": "/v1/unload", "body": {}},
|
|
{"method": "POST", "path": "/v1/unload", "body": {}},
|
|
{"method": "POST", "path": "/v1/load", "body": {"model": "other-model"}},
|
|
{"method": "POST", "path": "/v1/load", "body": {"model": "strata-test"}},
|
|
{"method": "POST", "path": "/v1/load", "body": {}},
|
|
{"method": "POST", "path": "/v1/load", "body": "{}", "headers": {"Content-Type": "text/plain"}},
|
|
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Origin": "https://other.example"}},
|
|
{"method": "POST", "path": "/v1/unload", "body": [1]},
|
|
{"method": "POST", "path": "/v1/unload", "body": "not json", "headers": {"Content-Type": "application/json"}},
|
|
{"method": "POST", "path": "/v1/unload", "body": {"model": None}},
|
|
{"method": "GET", "path": "/props"},
|
|
]
|
|
scenarios["lifecycle"] = run({}, lifecycle)
|
|
scenarios["lifecycle_busy"] = run({"status": {"queued": 1}}, [
|
|
{"method": "POST", "path": "/v1/unload", "body": {}},
|
|
{"method": "POST", "path": "/v1/load", "body": {}},
|
|
{"method": "POST", "path": "/unload"},
|
|
{"method": "POST", "path": "/load"},
|
|
])
|
|
scenarios["lifecycle_unloaded_then_busy"] = run({"loaded": False, "status": {"busy": True}}, [
|
|
{"method": "POST", "path": "/v1/load", "body": {}},
|
|
{"method": "POST", "path": "/unload"},
|
|
{"method": "POST", "path": "/load"},
|
|
])
|
|
scenarios["lifecycle_with_key"] = run({"api_key": "k" * 40}, [
|
|
{"method": "POST", "path": "/unload"},
|
|
{"method": "POST", "path": "/v1/unload", "body": {}},
|
|
{"method": "POST", "path": "/v1/unload", "body": {},
|
|
"headers": {"Authorization": "Bearer " + "k" * 40, "Origin": "https://other.example"}},
|
|
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Authorization": "Bearer " + "k" * 40}},
|
|
{"method": "POST", "path": "/load", "headers": {"x-api-key": "k" * 40}},
|
|
])
|
|
write("http_surface", {"source": "serve/server.py Handler (real code, resident fake engine)",
|
|
"scenarios": scenarios})
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ timings
|
|
def timings():
|
|
from serve.server import ByteTokenizer, MockEngine, Service, request_timings
|
|
from serve.frontend import ChatTemplate
|
|
from pathlib import Path
|
|
|
|
cases = []
|
|
lasts = [
|
|
{"prompt_ms": 250.0, "decode_ms": 1000.0, "generated": 50, "reused": 60},
|
|
{"prompt_ms": 0.0, "decode_ms": 0.0, "generated": 0, "reused": 0},
|
|
{"prompt_ms": 12.34567, "decode_ms": 98.7654, "generated": 7, "reused": None},
|
|
{"prompt_ms": 0.25, "decode_ms": 0.05, "generated": 3},
|
|
{"prompt_ms": 2.675, "decode_ms": 1234.55, "generated": 11, "reused": 5, "drafts_offered": 20, "drafts_accepted": 15},
|
|
{"prompt_ms": 100.0, "decode_ms": 333.3333, "generated": 0, "reused": 200},
|
|
{"prompt_ms": 1e-9, "decode_ms": 5e-5, "generated": 9, "reused": 0, "drafts_offered": 0, "drafts_accepted": 0},
|
|
{"prompt_ms": 12345.678, "decode_ms": 87654.321, "generated": 4096, "reused": 1},
|
|
]
|
|
for last in lasts:
|
|
for prompt_tokens, generated in ((300, last.get("generated") or 5), (10, 10), (0, 0), (50, 7)):
|
|
cases.append({"last": last, "prompt_tokens": prompt_tokens, "generated": generated,
|
|
"timings": request_timings(prompt_tokens, generated, last)})
|
|
cases.append({"last": {}, "prompt_tokens": 5, "generated": 5, "timings": request_timings(5, 5, {})})
|
|
aliases = []
|
|
tok = ByteTokenizer()
|
|
for value in (None, [], ["a"], [" a ", "a", "", "m", "b"], "a, b ,a,,m", ["a", 1], 5, {"a": 1}, "", [""]):
|
|
svc = Service(MockEngine(tok, "x"), tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
|
|
model_name="m")
|
|
try:
|
|
svc.set_aliases(value)
|
|
aliases.append({"input": value, "ok": svc.aliases})
|
|
except ValueError as e:
|
|
aliases.append({"input": value, "error": str(e)})
|
|
write("timings", {"source": "serve/server.py request_timings + Service.set_aliases (real code)",
|
|
"timings": cases, "aliases": aliases}, dest="policy")
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ vision
|
|
def vision():
|
|
import base64
|
|
import tempfile
|
|
from pathlib import Path
|
|
from serve.frontend import ChatTemplate, _image_source, images_of, openai_to_messages
|
|
from serve.server import IMAGE_PAD, VISION_START, ByteTokenizer, MockEngine, Service, Vision
|
|
|
|
# base64 as Vision.load decodes data: URLs
|
|
b64 = []
|
|
for text in ["QQ==", "QUI=", "QUJD", "QU\nJD", "", "QQ", "Q", "QUJDRA==", "QUJDRA=", "QUJDRA", "QU JD", "QQ==QQ==",
|
|
"Q=Q=", "!!!!", "QUJD\n", "//8=", "-_8=", "QUJD=", "====", "QUJDREVG", "QUJDREVGRw", "QUJDREVGRw=="]:
|
|
try:
|
|
b64.append({"text": text, "ok": Vision.load("data:image/png;base64," + text).hex()})
|
|
except Exception as e: # binascii.Error and friends
|
|
b64.append({"text": text, "error": type(e).__name__ + ": " + str(e)})
|
|
|
|
sources = [
|
|
{"type": "image_url", "image_url": {"url": "https://x/y.png"}}, {"type": "image_url", "image_url": "data:abc"},
|
|
{"type": "input_image", "image_url": "file:///a.png"}, {"type": "image_url"}, {"type": "image_url", "image_url": {}},
|
|
{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}},
|
|
{"type": "image", "source": {"type": "base64", "data": "QQ=="}},
|
|
{"type": "image", "source": {"type": "url", "url": "http://u"}}, {"type": "image", "source": {"path": "/p.png"}},
|
|
{"type": "image", "source": {"url": "", "path": "/q.png"}}, {"type": "image"}, {"type": "image", "source": None},
|
|
]
|
|
src = [{"part": part, "source": _image_source(part)} for part in sources]
|
|
|
|
tok = ByteTokenizer()
|
|
|
|
class FakeVision:
|
|
def __init__(self, counts):
|
|
self.counts, self.dir = counts, Path(tempfile.mkdtemp(prefix="strata-golden-"))
|
|
|
|
def encode(self, source):
|
|
path = self.dir / (str(abs(hash(source)) % 10**8) + ".sve")
|
|
path.write_bytes(source.encode())
|
|
return path, self.counts[source]
|
|
|
|
template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja")
|
|
prepared = []
|
|
cases = [
|
|
([{"role": "user", "content": "hello"}], {}),
|
|
([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "A"}}]}],
|
|
{"A": 3}),
|
|
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}},
|
|
{"type": "image_url", "image_url": {"url": "B"}},
|
|
{"type": "text", "text": "compare"}]}], {"A": 2, "B": 5}),
|
|
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}]},
|
|
{"role": "assistant", "content": "ok"},
|
|
{"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": "C"}}]}],
|
|
{"A": 1, "C": 4}),
|
|
([{"role": "user", "content": [{"type": "text", "text": "literal " + IMAGE_PAD + " in text"},
|
|
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
|
|
([{"role": "user", "content": "just text " + IMAGE_PAD + " again"}], {}),
|
|
([{"role": "user", "content": [{"type": "text", "text": VISION_START + IMAGE_PAD + " fake"},
|
|
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
|
|
]
|
|
for messages, counts in cases:
|
|
req = {"messages": messages}
|
|
norm, tools, kw = openai_to_messages(req)
|
|
prompt = template.render(norm, tools=tools, **kw)
|
|
ids_before = tok.encode(prompt, parse_special=True)
|
|
svc = Service(MockEngine(tok, "x", max_context=100000), tok, template, vision=FakeVision(counts) if counts else None)
|
|
entry = {"messages": messages, "counts": counts, "ids_before": ids_before,
|
|
"images": images_of(norm), "pad": tok.encode(IMAGE_PAD, parse_special=True)[0],
|
|
"start": tok.encode(VISION_START, parse_special=True)[0],
|
|
"literal": tok.encode(IMAGE_PAD, parse_special=False)}
|
|
try:
|
|
ids, thinking, max_new = svc.prepare(norm, tools, kw, 10)
|
|
entry["ids_after"] = ids
|
|
entry["combined_hex"] = Path(svc.embeddings.path).read_bytes().hex() if getattr(svc.embeddings, "path", None) else None
|
|
except ValueError as e:
|
|
entry["error"] = str(e)
|
|
prepared.append(entry)
|
|
write("vision", {"source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)",
|
|
"base64": b64, "sources": src, "prepare": prepared}, dest="policy")
|
|
|
|
|
|
def vision_dialects():
|
|
"""Chat and Messages requests that carry pictures, through the real `openai_to_messages` / `anthropic_to_messages`
|
|
and the real chat template: the prompt text and the picture sources in prompt order."""
|
|
import base64
|
|
from pathlib import Path
|
|
from serve.frontend import ChatTemplate, anthropic_to_messages, images_of, openai_to_messages
|
|
|
|
template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja")
|
|
counter = iter(range(1, 250))
|
|
|
|
def url():
|
|
# a PNG signature and one tag byte: the tests find the picture again by its last byte
|
|
return "data:image/png;base64," + base64.b64encode(b"\x89PNG\r\n\x1a\n" + bytes([next(counter)])).decode()
|
|
|
|
def chat(messages):
|
|
return {"dialect": "chat", "request": {"messages": messages, "reasoning_effort": "none"}}
|
|
|
|
def claude(messages, system=None):
|
|
request = {"messages": messages, "thinking": {"type": "disabled"}}
|
|
if system:
|
|
request["system"] = system
|
|
return {"dialect": "messages", "request": request}
|
|
|
|
def b64(media="image/png"):
|
|
data = url().split(",", 1)[1]
|
|
return {"type": "image", "source": {"type": "base64", "media_type": media, "data": data}}
|
|
|
|
cases = [
|
|
chat([{"role": "user", "content": [{"type": "text", "text": "what is this?"},
|
|
{"type": "image_url", "image_url": {"url": url(), "detail": "high"}}]}]),
|
|
chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}]),
|
|
chat([{"role": "user", "content": [{"type": "image_url", "image_url": url()}, {"type": "text", "text": "after"}]}]),
|
|
chat([{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": url()}},
|
|
{"type": "text", "text": "b"}, {"type": "image_url", "image_url": url()},
|
|
{"type": "text", "text": "c"}]}]),
|
|
chat([{"role": "system", "content": "be brief"},
|
|
{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "x"}]}]),
|
|
chat([{"role": "user", "content": "first"}, {"role": "assistant", "content": "ok"},
|
|
{"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": url()}}]}]),
|
|
chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]},
|
|
{"role": "assistant", "content": "a cat"},
|
|
{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "and?"}]}]),
|
|
chat([{"role": "user", "content": [{"type": "text", "text": "the docs say <|image_pad|> marks an image"},
|
|
{"type": "image_url", "image_url": {"url": url()}}]}]),
|
|
claude([{"role": "user", "content": [b64(), {"type": "text", "text": "describe"}]}]),
|
|
claude([{"role": "user", "content": [{"type": "text", "text": "describe"}, b64("image/jpeg")]}], system="be brief"),
|
|
claude([{"role": "user", "content": [b64(), b64(), {"type": "text", "text": "compare"}]}]),
|
|
claude([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image", "source": {"type": "url", "url": url()}}]}]),
|
|
claude([{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": url()}}]}]),
|
|
claude([{"role": "user", "content": "first"}, {"role": "assistant", "content": [{"type": "text", "text": "ok"}]},
|
|
{"role": "user", "content": [b64(), {"type": "text", "text": "now this"}]}]),
|
|
]
|
|
out = []
|
|
for case in cases:
|
|
req = case["request"]
|
|
if case["dialect"] == "chat":
|
|
messages, tools, kw = openai_to_messages(req)
|
|
else:
|
|
messages, tools, kw = anthropic_to_messages(req)
|
|
out.append({**case, "prompt": template.render(messages, tools=tools, **kw), "images": images_of(messages)})
|
|
write("vision_dialects", {"source": "serve/frontend.py openai_to_messages / anthropic_to_messages + chat_template.jinja",
|
|
"cases": out})
|
|
|
|
|
|
SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface,
|
|
"timings": timings, "vision": vision, "vision_dialects": vision_dialects}
|
|
|
|
|
|
def main(argv):
|
|
names = argv or list(SECTIONS)
|
|
for name in names:
|
|
SECTIONS[name]()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|