Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Servers: POST /tokenize, token-id prompts on /v1/completions, cache_salt namespaces (Qwen and GLM)

YanissAmz48044ef2b466
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index ff7ab52..622f562 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -139,6 +139,17 @@ Every frame carries `id`, `object: chat.completion.chunk`, `created`, `model`.
Non-streaming returns `chat.completion` with `choices[0].message` holding `content`,
optional `reasoning_content`, optional `tool_calls`, plus `usage`.
+### `POST /tokenize`, `POST /v1/completions`, `cache_salt` (vLLM style)
+`/tokenize` takes `{"prompt" | "messages", "add_special_tokens"}` and returns `{"tokens", "count", "max_model_len"}`.
+`/v1/completions` (stream and non-stream, same queue and `--sessions` as chat) takes `prompt` as text or as a list of token ids
+(`[1, 2, 3]` or `[[1, 2, 3]]`). The prompt is used as sent: no chat template, no BOS, no re-encoding of ids. `usage.prompt_tokens`
+is the count of ids sent, an id outside the vocabulary answers 400, `ignore_eos: true` keeps generating through EOS, `stop` and
+`max_tokens` work as in chat. `usage.prompt_tokens_details.cached_tokens` is on every chat and completions answer.
+`cache_salt` (chat and completions, non-empty string): requests with different salts never share prompt cache. The server keeps
+one salt namespace at a time (requests without a salt are one namespace): when it changes, running requests finish, the whole
+prompt cache is dropped (a fresh Generator over the same cache) and the request starts. The same salt, or no salt at all,
+never drops anything. `chat_template_kwargs` (`reasoning_effort`, `clear_thinking`) is read like the top-level fields and wins.
+
### Thinking
GLM's generation prompt ends with `<think>`, so the model *starts inside* the block.
`opens_thinking()` detects that (`prompt.rstrip().endswith("<think>")`) and the server
@@ -193,7 +204,7 @@ models:
- **Speed.** ~23.8 t/s end-to-end on the lighthouse bench through this server vs ~30.8 t/s
in the standalone MTP bench. The gap is content, not the server: mtp_round on the same prose prompt
gives 24.6 t/s (draft acceptance 0.57) vs 28.2 on chat (0.79); server overhead is ~3%.
-- No auth, no CORS, no `/v1/completions`, no embeddings endpoint. Bind to 127.0.0.1.
+- No auth, no CORS, no embeddings endpoint. Bind to 127.0.0.1.
## Open issues (found while documenting, NOT fixed)
@@ -213,7 +224,7 @@ models:
## Tests
```bash
-python -m pytest -q tools/glm/test_serve.py tools/test_startup_health.py
+python -m pytest -q tools/glm/test_serve.py tools/test_serve_compat.py tools/test_startup_health.py
```
Model-free: a `FakeEngine` emits deterministic GLM XML in 3-character chunks so tags are
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index b8e62ea..0889eed 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -24,6 +24,7 @@ from jinja2.sandbox import ImmutableSandboxedEnvironment
sys.path.append(str(Path(__file__).resolve().parent.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
+import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)
# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py
from serve_metrics import Metrics
from image_cache import ImageEmbeddingCache, digest
@@ -127,6 +128,7 @@ TOOL_CLOSE = "</tool_call>"
# The engine's own default stays greedy; the lane passes the model card's sampling.
# Used when a request omits the field. main() replaces the sampling values with the pack's
# generation_config.json (the model card's recommendation); command-line flags win over both.
+_UNKNOWN_SALT = object() # cache namespace after a failed reset: the next request resets again
SERVE_DEFAULTS: dict[str, Any] = {"temperature": 1.0, "top_p": 0.95, "reasoning_effort": "medium", "max_tokens": None}
# The model's template (levels low, high, max) with a medium level added: the model's "high" plus one instruction line.
DEFAULT_TEMPLATE = Path(__file__).resolve().parent.parent / "lanes" / "assets" / "glm53-template-medium.jinja"
@@ -142,8 +144,13 @@ def pack_sampling(model_dir: str) -> dict[str, float]:
def template_kwargs(body: dict[str, Any]) -> dict[str, Any]:
- kw = {"clear_thinking": body.get("clear_thinking")}
- effort = body.get("reasoning_effort", SERVE_DEFAULTS["reasoning_effort"])
+ """Template variables: chat_template_kwargs (vLLM style) wins over the top-level fields, then the server defaults."""
+ ctk = body.get("chat_template_kwargs") or {}
+ if not isinstance(ctk, dict):
+ raise web.HTTPBadRequest(reason="chat_template_kwargs must be an object")
+ pick = lambda key, default=None: ctk[key] if ctk.get(key) is not None else body.get(key, default)
+ kw = {"clear_thinking": pick("clear_thinking")}
+ effort = pick("reasoning_effort", SERVE_DEFAULTS["reasoning_effort"])
if effort is not None:
kw["reasoning_effort"] = effort
return kw
@@ -376,16 +383,40 @@ class ResidentEngine:
if vision:
self.vision = self._load_vision()
self.supports_vision = self.vision is not None
- self.greedy_generator = Generator(
- model=self.model, cache=self.cache, tokenizer=self.tokenizer,
- draft_model=self.draft_model, draft_cache=self.draft_cache, num_draft_tokens=num_draft or None,
- record_draft_stats=True)
+ self.vocab_size = int(self.config.vocab_size or self.tokenizer.actual_vocab_size) # rows of the embedding table
+ self.Generator = Generator
+ self.greedy_generator = self._make_generator()
# n1f2: one drafted token, fused catch-up variant 2. One Generator only: a second one over the
# same Cache takes ownership and breaks the first. Sampling also goes through MTP: a draft is
# kept only when the independently sampled target token equals it, so outputs follow the target.
GM.MTP_FUSE_CATCHUP = 2
os.environ.setdefault("EXL3_MOE_UNION_V2", "1") # the "+v2" of n1f2+v2
+ def _make_generator(self):
+ return self.Generator(
+ model=self.model, cache=self.cache, tokenizer=self.tokenizer,
+ draft_model=self.draft_model, draft_cache=self.draft_cache, num_draft_tokens=self.num_draft or None,
+ record_draft_stats=True)
+
+ def _rebuild_generator(self) -> None:
+ """A fresh Generator over the same Cache (one at a time: a second one takes the Cache over). It drops the whole prompt
+ cache: page table, recurrent checkpoints, prompt-end checkpoints, CPU tier. The old one is freed first."""
+ import gc
+ self.greedy_generator = None
+ gc.collect()
+ self.torch.cuda.empty_cache()
+ self.greedy_generator = self._make_generator()
+ if getattr(self, "slot_store", None) is not None:
+ self.slot_store.generator = self.greedy_generator
+ self.slot_store.erase()
+
+ async def reset_prefix_cache(self) -> None:
+ """Forget every cached prompt prefix (cache_salt namespace change). The caller has drained the requests."""
+ if self.sessions > 1:
+ await self._post(self._rebuild_generator) # on the driver, between two steps
+ else:
+ await asyncio.get_running_loop().run_in_executor(None, self._rebuild_generator)
+
def _load_vision(self):
"""The vision tower (model.visual.*, fp16) next to the text model; None, with a log line, when the pack has none."""
from exllamav3 import Model
@@ -422,10 +453,15 @@ class ResidentEngine:
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, encode_special_tokens=True).numel())
+ def encode_ids(self, text: str, add_special_tokens: bool = False) -> list[int]:
+ """POST /tokenize: the ids of text (special-token text is encoded as the special token; add_special_tokens adds BOS)."""
+ return [int(t) for t in self.tokenizer.encode(text, add_bos=add_special_tokens, encode_special_tokens=True).flatten().tolist()]
+
async def generate(self, prompt: str, *, max_tokens: int, temperature: float,
top_p: float, stop: list[str], sampler_kw: dict | None = None,
cancel: asyncio.Event | None = None,
- images: list | None = None, stats: dict | None = None) -> AsyncIterator[str]:
+ images: list | None = None, stats: dict | None = None,
+ prompt_ids: list[int] | None = None, ignore_eos: bool = False) -> AsyncIterator[str]:
"""Yield incremental decoded text. With sessions == 1 the caller serializes access to this method; with
sessions > 1 several calls may run at once and the final stats of a request land in `stats`.
@@ -437,7 +473,11 @@ class ResidentEngine:
t0 = time.perf_counter()
probe = getattr(self, "rss_probe", None)
embs = []
- if images:
+ if prompt_ids is not None: # token-id prompt: exactly these ids, no template, no BOS, no re-encoding
+ ids = torch.tensor([prompt_ids], dtype=torch.long)
+ if getattr(self, "slot_store", None) is not None:
+ self.slot_store.note_prompt("", ids)
+ elif images:
if self.sessions > 1: # the tower must not run next to a Generator step: run it on the driver, between steps
embs = await self._post(self._embed, images)
else:
@@ -462,7 +502,7 @@ class ResidentEngine:
else:
sampler = ComboSampler(temperature=max(temperature, 1e-6), top_p=top_p, min_p=0.0, **kw)
generator = self.greedy_generator
- conditions = list(self.config.eos_token_id_list) + stop
+ conditions = ([] if ignore_eos else list(self.config.eos_token_id_list)) + stop
job = self.Job(input_ids=ids, max_new_tokens=max_tokens, sampler=sampler,
stop_conditions=conditions, embeddings=embs or None)
if self.sessions > 1:
@@ -742,7 +782,7 @@ def prime_dense_tune(budget_s: float = 600.0) -> tuple[int, float]:
# Every route of create_app(), for the early /health listener (404 / 405 while loading); a test keeps it in step.
-ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/completion": ("POST",), "/slots/{id}": ("POST",)}
+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",)}
def create_app(engine: Any, model_id: str, template: str) -> web.Application:
@@ -752,11 +792,22 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
sessions = int(getattr(engine, "sessions", 1))
gate = asyncio.Semaphore(sessions) # sessions > 1: one permit per running request; slot actions take them all
slot_lock = asyncio.Lock() # sessions > 1: one slot action at a time
+ salt_state: dict[str, Any] = {"current": None} # cache_salt namespace of the prompt cache (None = requests without a salt)
+ admit_lock = asyncio.Lock() # sessions > 1: serializes admission
processing = 0 # admitted requests; closure, app config is immutable after startup
running = 0 # sessions > 1: requests inside generate()
app = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])
app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())
+ def salt_of(body: dict[str, Any]) -> str | None:
+ try:
+ salt = serve_compat.cache_salt(body)
+ except serve_compat.CompatError as exc:
+ raise web.HTTPBadRequest(reason=str(exc)) from exc
+ if salt is not None and not hasattr(engine, "reset_prefix_cache"):
+ raise web.HTTPBadRequest(reason="cache_salt is not supported by this engine")
+ return salt
+
def observe(st: dict[str, Any], prompt_tokens: int) -> None:
# The MTP window is a fixed num_draft_tokens per round, so rounds = proposed / window
# (exact except for a final window truncated by max_new_tokens). No generator -> no rounds.
@@ -798,6 +849,44 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
for _ in range(got):
gate.release()
+ @contextlib.asynccontextmanager
+ async def admit(salt: str | None):
+ """Permission to run one request. Every running request shares one cache_salt namespace: when the salt changes, the
+ requests in flight finish, the prompt cache is dropped (engine.reset_prefix_cache) and the new request starts alone.
+ The same salt (and traffic with no salt at all) never drops anything."""
+ async def reset() -> None:
+ salt_state["current"] = _UNKNOWN_SALT # a failed reset must not leave the old namespace claimed
+ await engine.reset_prefix_cache()
+ salt_state["current"] = salt
+
+ if sessions == 1:
+ async with lock:
+ if salt != salt_state["current"]:
+ await reset()
+ yield
+ return
+ async with admit_lock:
+ if salt == salt_state["current"]:
+ await gate.acquire()
+ else:
+ async with slot_lock:
+ held = 0
+ try:
+ for _ in range(sessions):
+ await gate.acquire()
+ held += 1
+ await reset()
+ except BaseException:
+ for _ in range(held):
+ gate.release()
+ raise
+ for _ in range(held - 1): # keep the permit of this request
+ gate.release()
+ try:
+ yield
+ finally:
+ gate.release()
+
async def worker() -> None:
nonlocal processing, running
while True:
@@ -810,7 +899,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
store = getattr(engine, "slot_store", None)
processing += 1 # admitted: counted from the dequeue, incl. lock and slot restore
try:
- async with (lock if sessions == 1 else gate):
+ async with admit(body.get("_cache_salt")):
running += 1
if store is not None:
store.busy = True
@@ -822,6 +911,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
max_tokens=token_limit(body), temperature=body.get("temperature", 0.0),
top_p=body.get("top_p", 1.0), stop=body.get("_stop", []),
cancel=body.get("_cancel"), **({"images": body["_images"]} if body.get("_images") else {}),
+ **({"prompt_ids": body["_prompt_ids"]} if body.get("_prompt_ids") is not None else {}),
+ **({"ignore_eos": True} if body.get("_ignore_eos") else {}),
**({"stats": request_stats} if sessions > 1 else {})):
out.put_nowait(delta)
finally:
@@ -896,6 +987,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
body["_prompt_tokens"] = prompt_tokens
body["_room"] = reply_room(engine, prompt_tokens)
body["_prompt"] = prompt
+ body["_cache_salt"] = salt_of(body)
for key in ("temperature", "top_p"):
if body.get(key) is None:
body[key] = SERVE_DEFAULTS[key]
@@ -921,9 +1013,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
return drain(request, cancel, out)
def usage(raw: str) -> dict[str, int]:
- completion_tokens = engine.count_tokens(raw)
- return {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens,
- "total_tokens": prompt_tokens + completion_tokens}
+ return serve_compat.usage(prompt_tokens, engine.count_tokens(raw), int(request_stats.get("cached_tokens") or 0))
def finish_for(message: dict[str, Any], raw: str) -> str:
# A reply cut by max_tokens is "length", not "stop" (clients use it to tell a truncated answer).
@@ -1095,6 +1185,148 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
"timings": {"prompt_n": int(st.get("cached_tokens", 0)),
"predicted_n": int(st.get("new_tokens", 0))}})
+ async def tokenize(request: web.Request) -> web.Response:
+ """vLLM POST /tokenize: {prompt | messages, add_special_tokens?} -> {tokens, count, max_model_len}."""
+ try:
+ body = await request.json()
+ if not isinstance(body, dict):
+ raise web.HTTPBadRequest(reason="body must be a JSON object")
+ if body.get("model", model_id) != model_id:
+ raise web.HTTPBadRequest(reason=f"unknown model; expected {model_id}")
+ if not hasattr(engine, "encode_ids"):
+ raise web.HTTPNotImplemented(reason="this engine cannot tokenize")
+ add_special = body.get("add_special_tokens")
+ if add_special is not None and not isinstance(add_special, bool):
+ raise web.HTTPBadRequest(reason="add_special_tokens must be boolean")
+ if body.get("messages") is not None:
+ if not isinstance(body["messages"], list) or not body["messages"]:
+ raise web.HTTPBadRequest(reason="messages must be a non-empty array")
+ if extract_images(body["messages"]):
+ raise web.HTTPBadRequest(reason="images cannot be tokenized here")
+ text = render_prompt(template, body["messages"], body.get("tools"), **template_kwargs(body))
+ add_special = bool(add_special) # a rendered chat prompt carries its own special tokens
+ else:
+ text = body.get("prompt")
+ if not isinstance(text, str):
+ raise web.HTTPBadRequest(reason="prompt must be a string (or send messages)")
+ add_special = True if add_special is None else add_special
+ ids = engine.encode_ids(text, add_special)
+ except (json.JSONDecodeError, TypeError, ValueError) as exc:
+ raise web.HTTPBadRequest(reason=str(exc)) from exc
+ return web.json_response(serve_compat.tokenize_reply(ids, getattr(engine, "ctx", None)))
+
+ async def v1_completions(request: web.Request) -> web.StreamResponse:
+ """OpenAI POST /v1/completions over the same queue/generator as chat: the prompt (text, or a list of token ids) is
+ used verbatim (no chat template, no BOS added), one prompt, one choice. Streamed with a final `usage`."""
+ try:
+ body = await request.json()
+ if not isinstance(body, dict):
+ raise web.HTTPBadRequest(reason="body must be a JSON object")
+ if body.get("model", model_id) != model_id:
+ raise web.HTTPBadRequest(reason=f"unknown model; expected {model_id}")
+ prompt = body.get("prompt")
+ try:
+ prompt_ids = serve_compat.token_prompt(prompt, getattr(engine, "vocab_size", None))
+ except serve_compat.CompatError as exc:
+ raise web.HTTPBadRequest(reason=str(exc)) from exc
+ if prompt_ids is not None:
+ prompt = ""
+ else:
+ if isinstance(prompt, list) and len(prompt) == 1:
+ prompt = prompt[0]
+ if not isinstance(prompt, str) or not prompt:
+ raise web.HTTPBadRequest(reason="prompt must be a non-empty string or a list of token ids (one prompt per request)")
+ if body.get("n") not in (None, 1) or body.get("echo") or body.get("best_of") not in (None, 1):
+ raise web.HTTPBadRequest(reason="n, best_of and echo are not supported")
+ for key in ("stream", "ignore_eos"):
+ if body.get(key) is not None and not isinstance(body[key], bool):
+ raise web.HTTPBadRequest(reason=f"{key} must be boolean")
+ max_tokens = 16 if body.get("max_tokens") is None else body["max_tokens"]
+ if not isinstance(max_tokens, int) or isinstance(max_tokens, bool) or max_tokens < 1:
+ raise web.HTTPBadRequest(reason="max_tokens must be a positive integer")
+ stops = body.get("stop") or []
+ stops = [stops] if isinstance(stops, str) else stops
+ if not isinstance(stops, list) or not all(isinstance(x, str) for x in stops):
+ raise web.HTTPBadRequest(reason="stop must be a string or a list of strings")
+ prompt_tokens = len(prompt_ids) if prompt_ids is not None else engine.count_tokens(prompt)
+ job = {"_prompt": prompt, "_prompt_ids": prompt_ids, "_ignore_eos": body.get("ignore_eos") is True,
+ "max_tokens": max_tokens, "_room": reply_room(engine, prompt_tokens), "_stop": list(stops),
+ "temperature": float(SERVE_DEFAULTS["temperature"] if body.get("temperature") is None else body["temperature"]),
+ "top_p": float(SERVE_DEFAULTS["top_p"] if body.get("top_p") is None else body["top_p"]),
+ "_cache_salt": salt_of(body)}
+ except (json.JSONDecodeError, TypeError, ValueError) as exc:
+ raise web.HTTPBadRequest(reason=str(exc)) from exc
+
+ limit = token_limit(job)
+ request_id, created = f"cmpl-{uuid.uuid4().hex}", int(time.time())
+ out: asyncio.Queue = asyncio.Queue()
+ request_stats: dict[str, Any] = {}
+ cancel = job["_cancel"] = asyncio.Event()
+ await queue.put((job, out, request_stats))
+
+ def chunk(text: str, finish: str | None) -> dict[str, Any]:
+ return {"id": request_id, "object": "text_completion", "created": created, "model": model_id,
+ "choices": [{"text": text, "index": 0, "logprobs": None, "finish_reason": finish}]}
+
+ def finish_and_usage(text: str, stopped: str | None) -> tuple[str, dict[str, Any]]:
+ n_new = int(request_stats.get("new_tokens") or engine.count_tokens(text))
+ reason = "length" if stopped is None and (request_stats.get("eos_reason") == "max_new_tokens" or n_new >= limit) else "stop"
+ return reason, serve_compat.usage(prompt_tokens, n_new, int(request_stats.get("cached_tokens") or 0))
+
+ hold = max((len(x) for x in job["_stop"]), default=1) - 1
+
+ if body.get("stream", False):
+ response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})
+ await response.prepare(request)
+ try:
+ text, sent, stopped = "", 0, None
+ async for delta in drain(request, cancel, out):
+ text += delta
+ cut, stopped = stop_text(text, job["_stop"])
+ if stopped is not None:
+ cancel.set() # a stop string ended the reply: the rest is not generated
+ text = cut
+ break
+ safe = max(sent, len(text) - hold)
+ if safe > sent:
+ await response.write(sse(chunk(text[sent:safe], None)))
+ sent = safe
+ if len(text) > sent:
+ await response.write(sse(chunk(text[sent:], None)))
+ reason, usage = finish_and_usage(text, stopped)
+ await response.write(sse(chunk("", reason) | {"usage": usage}))
+ await response.write(b"data: [DONE]\n\n")
+ await response.write_eof()
+ except ConnectionResetError:
+ client_left(cancel, "stream")
+ except asyncio.CancelledError:
+ cancel.set()
+ raise
+ except Exception as exc: # noqa: BLE001
+ cancel.set()
+ try:
+ await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
+ await response.write_eof()
+ except ConnectionError:
+ pass
+ return response
+
+ try:
+ raw = ""
+ async for delta in drain(request, cancel, out):
+ raw += delta
+ except ConnectionResetError:
+ return client_left(cancel, "request")
+ except asyncio.CancelledError:
+ cancel.set()
+ raise
+ except Exception:
+ cancel.set()
+ raise
+ text, stopped = stop_text(raw, job["_stop"])
+ reason, usage = finish_and_usage(text, stopped)
+ return web.json_response(chunk(text, reason) | {"usage": usage})
+
async def slots(_: web.Request) -> web.Response:
return web.json_response(engine.slot_store.slots())
@@ -1140,6 +1372,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
app.router.add_get("/metrics", metrics_view)
app.router.add_post("/v1/chat/completions", completions)
app.router.add_post("/apply-template", apply_template)
+ app.router.add_post("/tokenize", tokenize)
+ app.router.add_post("/v1/completions", v1_completions)
app.router.add_post("/completion", completion)
app.on_startup.append(start)
app.on_cleanup.append(close)
diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.py
index 9ac2f9e..c7bd1d7 100644
--- a/tools/glm/test_serve.py
+++ b/tools/glm/test_serve.py
@@ -718,5 +718,160 @@ class SessionsTests(unittest.TestCase):
self.assertEqual(len(gen.cancelled), 1)
+class VllmCompatTests(unittest.TestCase):
+ """POST /tokenize, /v1/completions with token-id prompts, cache_salt (model-free: fake engine)."""
+ template = ServeTests.template
+
+ class Eng(FakeEngine):
+ vocab_size = 1000
+ ctx = 4096
+
+ def __init__(self, output="abc", sessions=1, delay=0.0):
+ super().__init__(output)
+ self.sessions, self.delay, self.resets, self.active, self.calls = sessions, delay, [], 0, []
+
+ def encode_ids(self, text, add_special_tokens=False):
+ return ([0] if add_special_tokens else []) + [len(w) for w in text.split()]
+
+ async def reset_prefix_cache(self):
+ self.resets.append(self.active)
+ await asyncio.sleep(self.delay)
+
+ async def generate(self, prompt, stats=None, **kw):
+ self.active += 1
+ self.calls.append((prompt, kw))
+ try:
+ await asyncio.sleep(self.delay)
+ st = {"cached_tokens": 99, "new_tokens": 3, "prompt_tokens": 3, "eos_reason": "max_new_tokens"}
+ self.last_stats = st
+ if stats is not None:
+ stats.update(st)
+ for ch in self.output:
+ yield ch
+ finally:
+ self.active -= 1
+
+ def call(self, engine, requests):
+ from aiohttp.test_utils import TestClient, TestServer
+
+ async def go():
+ client = TestClient(TestServer(serve.create_app(engine, "m", self.template)))
+ await client.start_server()
+ try:
+ out = []
+ for path, payload in requests:
+ r = await client.post(path, json=payload)
+ out.append((r.status, await r.json() if r.content_type == "application/json" else await r.text()))
+ return out
+ finally:
+ await client.close()
+ return run(go())
+
+ def one(self, engine, path, payload):
+ return self.call(engine, [(path, payload)])[0]
+
+ def test_tokenize_reply_shape_and_errors(self):
+ eng = self.Eng()
+ self.assertEqual(self.one(eng, "/tokenize", {"model": "m", "prompt": "ab cde f", "add_special_tokens": False}),
+ (200, {"count": 3, "max_model_len": 4096, "tokens": [2, 3, 1], "token_strs": None}))
+ self.assertEqual(self.one(eng, "/tokenize", {"prompt": "ab"})[1]["tokens"], [0, 2])
+ self.assertEqual(self.one(eng, "/tokenize", {"messages": [{"role": "user", "content": "hi"}]})[0], 200)
+ for payload in ({"model": "other", "prompt": "x"}, {"prompt": 5}, {}, {"prompt": "x", "add_special_tokens": "no"}):
+ self.assertEqual(self.one(eng, "/tokenize", payload)[0], 400, payload)
+ self.assertEqual(self.one(FakeEngine("x"), "/tokenize", {"prompt": "x"})[0], 501)
+
+ def test_token_id_prompt_reaches_the_engine_untouched(self):
+ for prompt in ([5, 6, 7, 8], [[5, 6, 7, 8]]):
+ eng = self.Eng()
+ st, body = self.one(eng, "/v1/completions", {"model": "m", "prompt": prompt, "max_tokens": 8, "ignore_eos": True,
+ "temperature": 0.0, "add_special_tokens": False, "cache_salt": "s"})
+ self.assertEqual(st, 200)
+ kw = eng.calls[0][1]
+ self.assertEqual((kw["prompt_ids"], kw["ignore_eos"], kw["max_tokens"]), ([5, 6, 7, 8], True, 8))
+ self.assertEqual(body["usage"]["prompt_tokens"], 4)
+ self.assertEqual(body["usage"]["prompt_tokens_details"], {"cached_tokens": 4}) # engine said 99: clamped
+ self.assertEqual((body["choices"][0]["text"], body["choices"][0]["finish_reason"]), ("abc", "length"))
+
+ def test_stream_ends_with_usage_and_done(self):
+ eng = self.Eng()
+ st, raw = self.one(eng, "/v1/completions", {"model": "m", "prompt": [1, 2, 3], "max_tokens": 8, "stream": True,
+ "stream_options": {"include_usage": True}})
+ events = [json.loads(x[6:]) for x in raw.split("\n\n") if x.startswith("data: ") and "[DONE]" not in x]
+ self.assertEqual(st, 200)
+ self.assertTrue(raw.rstrip().endswith("data: [DONE]"))
+ self.assertEqual("".join(e["choices"][0]["text"] for e in events), "abc")
+ self.assertGreater(len([e for e in events if e["choices"][0]["text"]]), 1) # streamed, not buffered
+ self.assertEqual(events[-1]["usage"]["prompt_tokens"], 3)
+ self.assertIn("cached_tokens", events[-1]["usage"]["prompt_tokens_details"])
+
+ def test_stop_string_cuts_text_and_stream(self):
+ eng = self.Eng("one two STOP three")
+ st, body = self.one(eng, "/v1/completions", {"model": "m", "prompt": "go", "stop": ["STOP"], "max_tokens": 50})
+ self.assertEqual((st, body["choices"][0]["text"], body["choices"][0]["finish_reason"]), (200, "one two ", "stop"))
+ st, raw = self.one(eng, "/v1/completions", {"model": "m", "prompt": "go", "stop": "STOP", "max_tokens": 50, "stream": True})
+ events = [json.loads(x[6:]) for x in raw.split("\n\n") if x.startswith("data: ") and "[DONE]" not in x]
+ self.assertEqual("".join(e["choices"][0]["text"] for e in events), "one two ")
+ self.assertEqual(events[-1]["choices"][0]["finish_reason"], "stop")
+
+ def test_validation(self):
+ eng = self.Eng()
+ for bad in ([-1], [1000], [1, True], [1, 2.5], [1, "a"], [[1], [2]], [], [[]]):
+ self.assertEqual(self.one(eng, "/v1/completions", {"model": "m", "prompt": bad})[0], 400, bad)
+ for extra in ({"ignore_eos": "yes"}, {"max_tokens": 0}, {"n": 2}, {"stream": "x"}, {"cache_salt": ""}, {"cache_salt": 3},
+ {"model": "other"}):
+ self.assertEqual(self.one(eng, "/v1/completions", {"model": "m", "prompt": [1]} | extra)[0], 400, extra)
+ self.assertEqual(self.one(eng, "/v1/completions", {"model": "m", "prompt": [1] * 5000})[0], 400)
+ self.assertEqual(eng.calls, [])
+ self.assertEqual(self.one(FakeEngine("x"), "/v1/completions", {"model": "m", "prompt": "hi", "cache_salt": "a"})[0], 400)
+
+ def test_cache_salt_resets_only_when_the_namespace_changes(self):
+ for sessions in (1, 2):
+ eng = self.Eng(sessions=sessions)
+ reqs = [("/v1/completions", {"model": "m", "prompt": [1, 2], "max_tokens": 2} | ({} if s is None else {"cache_salt": s}))
+ for s in (None, None, "a", "a", "a", "b", "a", None, None)]
+ self.assertEqual([c for c, _ in self.call(eng, reqs)], [200] * 9)
+ self.assertEqual(len(eng.resets), 4, sessions) # None -> a, a -> b, b -> a, a -> None
+
+ def test_requests_without_a_salt_never_reset_and_chat_takes_a_salt(self):
+ eng = self.Eng()
+ chat = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
+ self.call(eng, [("/v1/completions", {"model": "m", "prompt": [1]}), ("/v1/chat/completions", chat)])
+ self.assertEqual(eng.resets, [])
+ res = self.call(eng, [("/v1/chat/completions", chat | {"cache_salt": s}) for s in ("x", "x", "y")])
+ self.assertEqual([c for c, _ in res], [200] * 3)
+ self.assertEqual(len(eng.resets), 2)
+
+ def test_chat_usage_reports_cached_tokens(self):
+ eng = self.Eng("hello")
+ st, body = self.one(eng, "/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "one two three"}]})
+ usage = body["usage"]
+ self.assertEqual(usage["prompt_tokens_details"], {"cached_tokens": min(99, usage["prompt_tokens"])})
+
+ def test_salt_change_waits_for_the_running_requests(self):
+ eng = self.Eng(sessions=3, delay=0.05)
+ from aiohttp.test_utils import TestClient, TestServer
+
+ async def go():
+ client = TestClient(TestServer(serve.create_app(eng, "m", self.template)))
+ await client.start_server()
+ try:
+ def req(salt):
+ return client.post("/v1/completions", json={"model": "m", "prompt": [1, 2], "cache_salt": salt})
+ return [r.status for r in await asyncio.gather(req("a"), req("a"), req("b"), req("b"), req("a"))]
+ finally:
+ await client.close()
+ self.assertEqual(run(go()), [200] * 5)
+ self.assertGreaterEqual(len(eng.resets), 2)
+ self.assertEqual(eng.resets, [0] * len(eng.resets))
+
+ def test_chat_template_kwargs_reach_the_template(self):
+ kw = serve.template_kwargs({"chat_template_kwargs": {"reasoning_effort": "low"}, "reasoning_effort": "high"})
+ self.assertEqual(kw["reasoning_effort"], "low")
+ self.assertEqual(serve.template_kwargs({"reasoning_effort": "high"})["reasoning_effort"], "high")
+ self.assertEqual(serve.template_kwargs({"chat_template_kwargs": {"clear_thinking": False}})["clear_thinking"], False)
+ with self.assertRaises(Exception):
+ serve.template_kwargs({"chat_template_kwargs": "x"})
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.md
index 82fe624..def0ba5 100644
--- a/tools/qwen/SERVE.md
+++ b/tools/qwen/SERVE.md
@@ -85,6 +85,15 @@ environment wins. The engine modules read several of these when they are importe
forgets the prompt cache first (cold run), `"return_token_ids": true` adds the generated ids. Switching
speculative mode or `cache_prompt: false` rebuilds the Generator and so drops the prompt cache (400 with `--sessions` > 1).
+- vLLM-style extensions (also used by the RigMark benchmark): `POST /tokenize` (`{"prompt"|"messages", "add_special_tokens"}` ->
+ `{"tokens", "count", "max_model_len"}`); `/v1/completions` takes `prompt` as a list of token ids (`[1, 2, 3]` or `[[1, 2, 3]]`):
+ the ids go to the model as sent (no template, no BOS), `usage.prompt_tokens` is their count, an id outside the vocabulary
+ answers 400, and `ignore_eos: true` keeps generating through the end-of-sequence token. `usage.prompt_tokens_details.cached_tokens`
+ is on every `/v1/completions` and chat answer. `cache_salt` (chat and completions, non-empty string): requests with different
+ salts never share prompt cache. The server keeps one salt namespace at a time (requests without a salt are one namespace):
+ when it changes, running requests finish, the prompt cache is dropped (a fresh Generator, as `cache_prompt: false` does), and the
+ request starts. The same salt, or no salt at all, never drops anything, so only the first request after a change pays the rebuild.
+
## Start-up progress on `/health`
The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok","source":"kyojin"}`
@@ -150,7 +159,7 @@ The server prints this warning at start-up whenever N > 1, and a second one past
## Tests
- python -m pytest tools/test_startup_health.py tools/qwen/test_serve.py tools/qwen/test_guard.py # CPU, fake engine, no GPU (template test needs the pack)
+ python -m pytest tools/test_startup_health.py tools/test_serve_compat.py tools/qwen/test_serve.py tools/qwen/test_guard.py # CPU, fake engine, no GPU (template test needs the pack)
python tools/qwen/serve_check.py http://127.0.0.1:8000 out_dir # live server: chat, thinking, tools, stream, image,
# 3-turn cache, plain vs speculative, warm vs cold
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 7c45b8c..5c711c1 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import argparse
import asyncio
import base64
+import contextlib
import gc
import importlib.util
import io
@@ -40,6 +41,7 @@ sys.path.insert(0, str(HERE))
sys.path.append(str(HERE.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
import image_cache # noqa: E402 (shared bounded LRU of image embeddings; symlink to tools/strix_halo)
+import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)
def _load_mimo():
@@ -64,6 +66,7 @@ FALLBACK_DEFAULTS: dict[str, Any] = {"temperature": 1.0, "top_p": 0.95, "top_k":
# Thinking effort when a request names none. The model's own template defines xhigh and low only;
# chat_template.jinja next to this file is that template plus a medium level.
DEFAULT_EFFORT = "medium"
+_UNKNOWN_SALT = object() # cache namespace after a failed reset: the next request resets again
NO_CTX_REPLY = 32768 # reply budget when the engine reports no context length
DEFAULT_TEMPLATE = Path(__file__).with_name("chat_template.jinja")
# OpenAI effort names -> the Qwen template names (xhigh, medium, low).
@@ -673,6 +676,7 @@ class QwenEngine:
self.vision = None
print(f"qserve: vision tower not loaded ({exc!r}); image input disabled", flush=True)
self.supports_vision = self.vision is not None
+ self.vocab_size = int(self.config.vocab_size or self.tokenizer.actual_vocab_size) # rows of the embedding table
startup_health.stage("engine setup")
self._ngram_resident()
self.generator = self.uninstall = None
@@ -741,6 +745,17 @@ class QwenEngine:
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, add_bos=False, encode_special_tokens=True).numel())
+ def encode_ids(self, text: str, add_special_tokens: bool = False) -> list[int]:
+ """POST /tokenize: the ids of text (special-token text is encoded as the special token; add_special_tokens adds BOS)."""
+ return [int(t) for t in self.tokenizer.encode(text, add_bos=add_special_tokens, encode_special_tokens=True).flatten().tolist()]
+
+ async def reset_prefix_cache(self) -> None:
+ """Forget every cached prompt prefix (page table, recurrent checkpoints, n-gram index): a fresh Generator, the path
+ cache_prompt=false takes. The caller has drained the requests (cache_salt namespace change)."""
+ await self._post(self._build, self.spec_on)
+ if self.slot_store is not None:
+ self.slot_store.erase()
+
def token_str(self, token_id: int) -> str:
return self.tokenizer.tokenizer.decode([int(token_id)], skip_special_tokens=False)
@@ -924,7 +939,7 @@ class QwenEngine:
cancel: asyncio.Event | None = None, seed: int | None = None, reasoning_first: bool = False,
thinking_budget: int | None = None, loop_guard: bool | None = None,
loop_final: bool | None = None, logprobs: int | None = None, stats: dict[str, Any],
- _mine: list) -> AsyncIterator[str]:
+ prompt_ids: list[int] | None = None, ignore_eos: bool = False, _mine: list) -> AsyncIterator[str]:
"""Yield decoded text pieces. Final stats land in `stats`. Every job enqueued is appended to `_mine`.
Final check (on with the guard, loop_final=False turns it off): when the turn ends normally and the visible text
@@ -944,7 +959,10 @@ class QwenEngine:
want_spec = bool(speculative) and self.draft_model is not None
if want_spec != self.spec_on or not cache_prompt:
await self._post(self._build, want_spec)
- ids, embs = await self._post(self._encode, prompt, images or [])
+ if prompt_ids is not None: # token-id prompt: exactly these ids, no template, no BOS, no re-encoding
+ ids, embs = self.torch.tensor([prompt_ids], dtype=self.torch.long), []
+ else:
+ ids, embs = await self._post(self._encode, prompt, images or [])
ctx = getattr(self, "ctx", None)
if ctx: # the chat handler counted a picture as one token; its embeddings take many
room = reply_room(ctx, int(ids.numel()), int(getattr(self.generator, "num_draft_tokens", 0)))
@@ -975,7 +993,7 @@ class QwenEngine:
while True:
job = self.Job(input_ids=job_ids, max_new_tokens=max(max_tokens - generated + discount, 1),
- sampler=self._sampler(sampling), stop_conditions=self.eos + list(stop),
+ sampler=self._sampler(sampling), stop_conditions=([] if ignore_eos else self.eos) + list(stop),
embeddings=embs or None, decode_special_tokens=True, seed=seed,
**({} if logprobs is None else {"return_probs": True, "return_top_tokens": logprobs}))
_mine.append(job)
@@ -1184,7 +1202,7 @@ def format_logprobs(entries: list, token_ids: list[int], token_str, chat: bool)
# Every route of create_app(), for the early /health listener (404 / 405 while loading); a test keeps it in step.
-ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",)}
+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",)}
def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Any] | None = None,
@@ -1196,6 +1214,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
gate = asyncio.Semaphore(sessions) # one permit per running request; slot actions take them all (drain)
lock = asyncio.Lock() # serializes the slot actions
running = 0
+ salt_state: dict[str, Any] = {"current": None} # cache_salt namespace of the prompt cache (None = requests without a salt)
+ admit_lock = asyncio.Lock()
app = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])
app.update(engine=engine, model_id=model_id, template=template, defaults=defaults)
@@ -1212,6 +1232,35 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
return web.json_response({"status": "ok", "source": "kyojin", "model": model_id, "vision": bool(engine.supports_vision), **startup_health.compiler_health(),
**(engine.spec_stats() if hasattr(engine, "spec_stats") else {})})
+ @contextlib.asynccontextmanager
+ async def admit(salt: str | None):
+ """One running-request permit. Every running request shares one cache_salt namespace: when the salt changes, the
+ requests in flight finish, the prompt cache is dropped (engine.reset_prefix_cache) and the new request starts alone.
+ The same salt (and traffic with no salt at all) never drops anything."""
+ async with admit_lock:
+ if salt == salt_state["current"]:
+ await gate.acquire()
+ else:
+ async with lock:
+ held = 0
+ try:
+ for _ in range(sessions):
+ await gate.acquire()
+ held += 1
+ salt_state["current"] = _UNKNOWN_SALT # a failed reset must not leave the old namespace claimed
+ await engine.reset_prefix_cache()
+ salt_state["current"] = salt
+ except BaseException:
+ for _ in range(held):
+ gate.release()
+ raise
+ for _ in range(held - 1): # keep the permit of this request
+ gate.release()
+ try:
+ yield
+ finally:
+ gate.release()
+
async def worker() -> None:
nonlocal running
while True:
@@ -1219,13 +1268,15 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
store = getattr(engine, "slot_store", None)
stats: dict[str, Any] = {}
try:
- async with gate:
+ async with admit(job.get("cache_salt")):
running += 1
if store is not None:
store.busy = True
try:
async for delta in engine.generate(
job["prompt"], stats=stats, max_tokens=job["max_tokens"], sampling=job["sampling"],
+ **({"prompt_ids": job["prompt_ids"]} if job.get("prompt_ids") is not None else {}),
+ **({"ignore_eos": True} if job.get("ignore_eos") else {}),
stop=job["stop"], images=job["images"], speculative=job["speculative"],
cache_prompt=job["cache_prompt"], cancel=job["cancel"],
seed=job.get("seed"), reasoning_first=job.get("reasoning_first", False),
@@ -1261,6 +1312,12 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if sessions > 1 and (not job["cache_prompt"] or (not job["speculative"] and getattr(engine, "spec_on", False))):
raise BadRequest("speculative=false or cache_prompt=false needs a server started with --sessions 1")
+ def salt_of(body: dict[str, Any]) -> str | None:
+ salt = serve_compat.cache_salt(body)
+ if salt is not None and not hasattr(engine, "reset_prefix_cache"):
+ raise BadRequest("cache_salt is not supported by this engine")
+ return salt
+
def prepare(body: Any) -> dict[str, Any]:
"""Validate a request and build the engine job. Raises BadRequest."""
if not isinstance(body, dict):
@@ -1319,6 +1376,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
"reasoning_first": prompt.rstrip().endswith("<think>"), "tools": body.get("tools"),
"return_token_ids": bool(body.get("return_token_ids")), "cancel": asyncio.Event()}
check_sessions(job)
+ job["cache_salt"] = salt_of(body)
return job
async def completions(request: web.Request) -> web.StreamResponse:
@@ -1327,7 +1385,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
job = prepare(body)
except json.JSONDecodeError as exc:
return err(400, f"invalid JSON: {exc}")
- except BadRequest as exc:
+ except (BadRequest, serve_compat.CompatError) as exc:
return err(400, str(exc))
request_id, created = f"chatcmpl-{uuid.uuid4().hex}", int(time.time())
base = {"id": request_id, "object": "chat.completion.chunk", "created": created, "model": model_id}
@@ -1476,6 +1534,39 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
return err(400, str(exc))
return web.json_response({"prompt": prompt})
+ async def tokenize(request: web.Request) -> web.Response:
+ """vLLM POST /tokenize: {prompt | messages, add_special_tokens?} -> {tokens, count, max_model_len}."""
+ try:
+ body = await request.json()
+ if not isinstance(body, dict):
+ raise BadRequest("body must be a JSON object")
+ if body.get("model", model_id) != model_id:
+ raise BadRequest(f"unknown model; expected {model_id}")
+ if not hasattr(engine, "encode_ids"):
+ return err(501, "this engine cannot tokenize")
+ add_special = body.get("add_special_tokens")
+ if add_special is not None and not isinstance(add_special, bool):
+ raise BadRequest("add_special_tokens must be boolean")
+ if body.get("messages") is not None:
+ if not isinstance(body["messages"], list) or not body["messages"]:
+ raise BadRequest("messages must be a non-empty array")
+ if extract_images(body["messages"]):
+ raise BadRequest("images cannot be tokenized here")
+ text = render_prompt(template, normalize_messages(body["messages"]), body.get("tools"),
+ **resolve_template_kwargs(body, defaults))
+ add_special = bool(add_special) # a rendered chat prompt carries its own special tokens
+ else:
+ text = body.get("prompt")
+ if not isinstance(text, str):
+ raise BadRequest("prompt must be a string (or send messages)")
+ add_special = True if add_special is None else add_special
+ ids = engine.encode_ids(text, add_special)
+ except json.JSONDecodeError as exc:
+ return err(400, f"invalid JSON: {exc}")
+ except (BadRequest, ValueError, TypeError, KeyError, AttributeError, jinja2.TemplateError) as exc:
+ return err(400, str(exc))
+ return web.json_response(serve_compat.tokenize_reply(ids, getattr(engine, "ctx", None)))
+
async def completion(request: web.Request) -> web.Response:
"""Minimal llama.cpp POST /completion: prompt used verbatim (no template), same queue and generator."""
try:
@@ -1541,10 +1632,16 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if body.get("model", model_id) != model_id:
raise BadRequest(f"unknown model; expected {model_id}")
prompt = body.get("prompt")
- if isinstance(prompt, list) and len(prompt) == 1:
- prompt = prompt[0]
- if not isinstance(prompt, str) or not prompt:
- raise BadRequest("prompt must be a non-empty string (one prompt per request)")
+ prompt_ids = serve_compat.token_prompt(prompt, getattr(engine, "vocab_size", None))
+ if prompt_ids is not None:
+ prompt = ""
+ else:
+ if isinstance(prompt, list) and len(prompt) == 1:
+ prompt = prompt[0]
+ if not isinstance(prompt, str) or not prompt:
+ raise BadRequest("prompt must be a non-empty string or a list of token ids (one prompt per request)")
+ if body.get("ignore_eos") is not None and not isinstance(body["ignore_eos"], bool):
+ raise BadRequest("ignore_eos must be boolean")
if body.get("n") not in (None, 1) or body.get("echo") or body.get("best_of") not in (None, 1):
raise BadRequest("n, best_of and echo are not supported")
if "stream" in body and not isinstance(body["stream"], bool):
@@ -1566,20 +1663,21 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
lp = logprobs_arg(body.get("logprobs"))
if lp is not None and body.get("stream"):
raise BadRequest("logprobs are returned on non-streaming requests only")
- prompt_tokens = engine.count_tokens(prompt)
+ prompt_tokens = len(prompt_ids) if prompt_ids is not None else engine.count_tokens(prompt)
ctx = getattr(engine, "ctx", None)
if ctx:
room = reply_room(ctx, prompt_tokens, draft_window(engine, body.get("speculative", True) is not False))
if room < 1:
raise BadRequest(f"context length exceeded: prompt is {prompt_tokens} tokens, the server context is {ctx}")
max_tokens = min(max_tokens, room)
- job = {"logprobs": lp, "prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": body.get("speculative", True) is not False, "seed": seed,
+ job = {"cache_salt": salt_of(body), "prompt_ids": prompt_ids, "ignore_eos": body.get("ignore_eos") is True,
+ "logprobs": lp, "prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": body.get("speculative", True) is not False, "seed": seed,
"sampling": sampling_from(body, defaults), "cache_prompt": body.get("cache_prompt", True) is not False,
"loop_guard": body.get("loop_guard"), "cancel": asyncio.Event()}
check_sessions(job)
except json.JSONDecodeError as exc:
return err(400, f"invalid JSON: {exc}")
- except BadRequest as exc:
+ except (BadRequest, serve_compat.CompatError) as exc:
return err(400, str(exc))
request_id, created = f"cmpl-{uuid.uuid4().hex}", int(time.time())
@@ -1589,9 +1687,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
def reason_usage(stats: dict[str, Any], text: str):
n_new = int(stats.get("new_tokens") or engine.count_tokens(text))
- n_prompt = int(stats.get("prompt_tokens") or prompt_tokens)
+ n_prompt = prompt_tokens if prompt_ids is not None else int(stats.get("prompt_tokens") or prompt_tokens)
reason = "length" if stats.get("eos_reason") == "max_new_tokens" else "stop"
- return reason, {"prompt_tokens": n_prompt, "completion_tokens": n_new, "total_tokens": n_prompt + n_new}
+ return reason, serve_compat.usage(n_prompt, n_new, int(stats.get("cached_tokens") or 0))
out: asyncio.Queue = asyncio.Queue()
await queue.put((job, out))
@@ -1698,6 +1796,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
app.router.add_get("/health", health)
app.router.add_post("/v1/chat/completions", completions)
app.router.add_post("/apply-template", apply_template)
+ app.router.add_post("/tokenize", tokenize)
app.router.add_post("/completion", completion)
app.router.add_post("/v1/completions", v1_completions)
if getattr(engine, "slot_store", None) is not None:
diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.py
index af4e2f1..ee53a07 100644
--- a/tools/qwen/test_serve.py
+++ b/tools/qwen/test_serve.py
@@ -788,5 +788,161 @@ class ImageEmbeddingReuseTests(unittest.TestCase):
self.assertEqual(len(calls), 2)
+class VllmCompatTests(unittest.TestCase):
+ """POST /tokenize, token-id prompts on /v1/completions, cache_salt (model-free: fake engine)."""
+
+ class Eng(FakeEngine):
+ vocab_size = 1000
+
+ def __init__(self, output="a b c", sessions=1, delay=0.0):
+ super().__init__(output)
+ self.sessions, self.delay, self.resets, self.active, self.log = sessions, delay, [], 0, []
+
+ def encode_ids(self, text, add_special_tokens=False):
+ return ([0] if add_special_tokens else []) + [len(w) for w in text.split()]
+
+ async def reset_prefix_cache(self):
+ self.resets.append(self.active)
+ await asyncio.sleep(self.delay)
+
+ async def generate(self, prompt, **kw):
+ self.active += 1
+ self.log.append(kw.get("prompt_ids"))
+ try:
+ await asyncio.sleep(self.delay)
+ async for piece in super().generate(prompt, **kw):
+ yield piece
+ finally:
+ self.active -= 1
+
+ def post(self, engine, path, payload):
+ async def fn(client):
+ r = await client.post(path, json=payload)
+ return r.status, await r.json() if r.content_type == "application/json" else await r.text()
+ return with_client(engine, fn)
+
+ def test_tokenize_reply_shape(self):
+ eng = self.Eng()
+ st, body = self.post(eng, "/tokenize", {"model": "m", "prompt": "ab cde f", "add_special_tokens": False})
+ self.assertEqual((st, body), (200, {"count": 3, "max_model_len": 4096, "tokens": [2, 3, 1], "token_strs": None}))
+ self.assertEqual(self.post(eng, "/tokenize", {"prompt": "ab"})[1]["tokens"], [0, 2]) # vLLM default: special tokens on
+ st, body = self.post(eng, "/tokenize", {"messages": [{"role": "user", "content": "hi"}]})
+ self.assertEqual(st, 200)
+ self.assertGreater(body["count"], 0)
+
+ def test_tokenize_bad_requests(self):
+ eng = self.Eng()
+ for payload in ({"model": "other", "prompt": "x"}, {"prompt": 5}, {}, {"prompt": "x", "add_special_tokens": "no"},
+ {"messages": []}):
+ self.assertEqual(self.post(eng, "/tokenize", payload)[0], 400, payload)
+ self.assertEqual(self.post(FakeEngine(""), "/tokenize", {"prompt": "x"})[0], 501)
+
+ def test_token_id_prompt_reaches_the_engine_untouched(self):
+ for prompt in ([5, 6, 7, 8], [[5, 6, 7, 8]]):
+ eng = self.Eng()
+ st, body = self.post(eng, "/v1/completions", {"model": "m", "prompt": prompt, "max_tokens": 8, "ignore_eos": True,
+ "temperature": 0.0, "add_special_tokens": False, "cache_salt": "s1"})
+ self.assertEqual(st, 200)
+ self.assertEqual(eng.log, [[5, 6, 7, 8]])
+ self.assertIs(eng.calls[0][1]["ignore_eos"], True)
+ self.assertEqual(body["usage"]["prompt_tokens"], 4) # the ids sent, not the engine's count
+ self.assertEqual(body["usage"]["prompt_tokens_details"], {"cached_tokens": 4}) # clamped to prompt_tokens
+
+ def test_token_id_prompt_stream_ends_with_usage_and_done(self):
+ eng = self.Eng("abcdef")
+ st, raw = self.post(eng, "/v1/completions", {"model": "m", "prompt": [1, 2, 3], "max_tokens": 8, "stream": True,
+ "stream_options": {"include_usage": True}})
+ events = sse_events(raw)
+ self.assertEqual(st, 200)
+ self.assertTrue(raw.rstrip().endswith("data: [DONE]"))
+ self.assertEqual("".join(e["choices"][0]["text"] for e in events), "abcdef")
+ self.assertEqual(events[-1]["usage"]["prompt_tokens"], 3)
+ self.assertEqual(events[-1]["usage"]["prompt_tokens_details"]["cached_tokens"], 3)
+ self.assertIsNone(eng.calls[0][1].get("ignore_eos"))
+
+ def test_text_prompt_and_unknown_fields_still_accepted(self):
+ eng = self.Eng()
+ st, body = self.post(eng, "/v1/completions", {"model": "m", "prompt": "hello there", "max_tokens": 3, "seed": 7,
+ "user": "u", "add_special_tokens": False, "stream_options": {"include_usage": True}})
+ self.assertEqual(st, 200)
+ self.assertEqual(body["usage"]["prompt_tokens"], 11)
+ self.assertEqual(eng.log, [None])
+
+ def test_token_id_prompt_validation(self):
+ eng = self.Eng()
+ for bad in ([-1], [1000], [1, True], [1, 2.5], [1, "a"], [[1], [2]], [[1], 2], [], [[]]):
+ self.assertEqual(self.post(eng, "/v1/completions", {"model": "m", "prompt": bad})[0], 400, bad)
+ self.assertEqual(eng.log, []) # nothing reached the engine
+ self.assertEqual(self.post(eng, "/v1/completions", {"model": "m", "prompt": [1], "ignore_eos": "yes"})[0], 400)
+ self.assertEqual(self.post(eng, "/v1/completions", {"model": "m", "prompt": [1] * 5000})[0], 400) # longer than ctx
+
+ def test_cache_salt_resets_only_when_the_namespace_changes(self):
+ eng = self.Eng()
+
+ async def fn(client):
+ codes = []
+ for salt in (None, None, "a", "a", "a", "b", "a", None, None):
+ payload = {"model": "m", "prompt": [1, 2], "max_tokens": 2} | ({} if salt is None else {"cache_salt": salt})
+ codes.append((await client.post("/v1/completions", json=payload)).status)
+ return codes
+ self.assertEqual(with_client(eng, fn), [200] * 9)
+ self.assertEqual(len(eng.resets), 4) # None -> a, a -> b, b -> a, a -> None
+
+ def test_requests_without_a_salt_never_reset(self):
+ eng = self.Eng()
+
+ async def fn(client):
+ await client.post("/v1/completions", json={"model": "m", "prompt": [1, 2]})
+ await client.post("/v1/completions", json={"model": "m", "prompt": "x y"})
+ await client.post("/v1/chat/completions", json={"model": "m", "messages": [{"role": "user", "content": "hi"}]})
+ with_client(eng, fn)
+ self.assertEqual(eng.resets, [])
+
+ def test_chat_accepts_cache_salt_too(self):
+ eng = self.Eng()
+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
+
+ async def fn(client):
+ return [(await client.post("/v1/chat/completions", json=body | {"cache_salt": s})).status for s in ("x", "x", "y")]
+ self.assertEqual(with_client(eng, fn), [200] * 3)
+ self.assertEqual(len(eng.resets), 2)
+
+ def test_salt_change_waits_for_the_running_requests(self):
+ eng = self.Eng(sessions=3, delay=0.05)
+
+ async def fn(client):
+ def req(salt):
+ return client.post("/v1/completions", json={"model": "m", "prompt": [1, 2], "cache_salt": salt})
+ rs = await asyncio.gather(req("a"), req("a"), req("b"), req("b"), req("a"))
+ return [r.status for r in rs]
+ self.assertEqual(with_client(eng, fn), [200] * 5)
+ self.assertGreaterEqual(len(eng.resets), 2)
+ self.assertEqual(eng.resets, [0] * len(eng.resets)) # no request was running when the cache was dropped
+
+ def test_failed_reset_is_retried_by_the_next_request(self):
+ class Flaky(self.Eng):
+ fail = True
+
+ async def reset_prefix_cache(self):
+ await super().reset_prefix_cache()
+ if Flaky.fail:
+ Flaky.fail = False
+ raise RuntimeError("boom")
+ eng = Flaky()
+
+ async def fn(client):
+ body = {"model": "m", "prompt": [1, 2], "cache_salt": "a"}
+ return [(await client.post("/v1/completions", json=body)).status for _ in range(2)]
+ st = with_client(eng, fn)
+ self.assertEqual(st[0], 500)
+ self.assertEqual((st[1], len(eng.resets)), (200, 2))
+
+ def test_cache_salt_validation(self):
+ eng = self.Eng()
+ for bad in ("", 5, ["a"], True):
+ self.assertEqual(self.post(eng, "/v1/completions", {"model": "m", "prompt": [1], "cache_salt": bad})[0], 400, bad)
+ self.assertEqual(self.post(FakeEngine("x"), "/v1/completions", {"model": "m", "prompt": "hi", "cache_salt": "a"})[0], 400)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/serve_compat.py b/tools/serve_compat.py
new file mode 100644
index 0000000..53729d9
--- /dev/null
+++ b/tools/serve_compat.py
@@ -0,0 +1,55 @@
+"""vLLM-style request helpers shared by tools/qwen/serve.py and tools/glm/serve.py (pure Python, no engine import).
+
+- token-id prompts for POST /v1/completions (`prompt` = [int, ...] or [[int, ...]])
+- the `cache_salt` request field
+- the POST /tokenize reply
+- the `usage` object with `prompt_tokens_details.cached_tokens`
+"""
+from __future__ import annotations
+
+from typing import Any
+
+
+class CompatError(ValueError):
+ """A request field is malformed (the servers answer 400)."""
+
+
+def cache_salt(body: dict[str, Any]) -> str | None:
+ """The request's `cache_salt`: None when absent. Requests with different salts never share prompt cache."""
+ salt = body.get("cache_salt")
+ if salt is None:
+ return None
+ if not isinstance(salt, str) or not salt:
+ raise CompatError("cache_salt must be a non-empty string")
+ return salt
+
+
+def token_prompt(prompt: Any, vocab_size: int | None) -> list[int] | None:
+ """The token ids of a prompt given as ids, None when it is text. `[int, ...]` and a single `[[int, ...]]` are
+ accepted. An id outside 0 <= id < vocab_size is refused: the embedding lookup of the model would read out of bounds."""
+ if isinstance(prompt, list) and len(prompt) == 1 and isinstance(prompt[0], list):
+ prompt = prompt[0]
+ if not isinstance(prompt, list) or not prompt or all(isinstance(x, str) for x in prompt):
+ return None # text, or a batch of texts (the servers take one prompt)
+ if any(isinstance(x, list) for x in prompt):
+ raise CompatError("one prompt per request: a list of token id lists must hold exactly one list")
+ for x in prompt:
+ if isinstance(x, bool) or not isinstance(x, int):
+ raise CompatError("prompt token ids must be integers")
+ if x < 0 or (vocab_size is not None and x >= vocab_size):
+ raise CompatError(f"prompt token id {x} is outside the vocabulary (0..{(vocab_size or 0) - 1})")
+ return list(prompt)
+
+
+def tokenize_reply(ids: list[int], max_model_len: int | None) -> dict[str, Any]:
+ """vLLM POST /tokenize reply."""
+ return {"count": len(ids), "max_model_len": max_model_len, "tokens": ids, "token_strs": None}
+
+
+def usage(prompt_tokens: int, completion_tokens: int, cached_tokens: int | None = None) -> dict[str, Any]:
+ """OpenAI usage object. cached_tokens is clamped to 0..prompt_tokens; None leaves `prompt_tokens_details` out."""
+ out: dict[str, Any] = {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens,
+ "total_tokens": prompt_tokens + completion_tokens}
+ if cached_tokens is not None:
+ out["prompt_tokens_details"] = {"cached_tokens": max(0, min(int(cached_tokens), prompt_tokens))}
+ return out
diff --git a/tools/test_serve_compat.py b/tools/test_serve_compat.py
new file mode 100644
index 0000000..1d55298
--- /dev/null
+++ b/tools/test_serve_compat.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python3
+"""Shared vLLM-style helpers, and RigMark's own request builders and parsers driven against both servers.
+
+The RigMark part runs bench.py (read-only, outside this repo) over real HTTP against qwen/serve.py and glm/serve.py with a
+fake engine that keeps a whole-prompt cache and drops it in reset_prefix_cache(). Model-free, CPU only. It is skipped when
+the RigMark source is not at $RIGMARK_SRC (default ~/hermes-work/rigmark/src).
+"""
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import json
+import os
+import sys
+import threading
+import unittest
+import zlib
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE))
+import serve_compat
+
+RIGMARK = Path(os.environ.get("RIGMARK_SRC", os.path.expanduser("~/hermes-work/rigmark/src")))
+
+
+class HelperTests(unittest.TestCase):
+ def test_cache_salt(self):
+ self.assertIsNone(serve_compat.cache_salt({}))
+ self.assertEqual(serve_compat.cache_salt({"cache_salt": "s"}), "s")
+ for bad in ("", 1, [], True):
+ with self.assertRaises(serve_compat.CompatError):
+ serve_compat.cache_salt({"cache_salt": bad})
+
+ def test_token_prompt(self):
+ self.assertEqual(serve_compat.token_prompt([1, 2], 10), [1, 2])
+ self.assertEqual(serve_compat.token_prompt([[1, 2]], 10), [1, 2])
+ self.assertIsNone(serve_compat.token_prompt("text", 10))
+ self.assertIsNone(serve_compat.token_prompt(["a"], 10))
+ self.assertIsNone(serve_compat.token_prompt([], 10))
+ self.assertEqual(serve_compat.token_prompt([9], None), [9]) # no vocabulary known: only the sign is checked
+ for bad in ([-1], [10], [True], [1.0], [[1], [2]], [1, [2]]):
+ with self.assertRaises(serve_compat.CompatError, msg=bad):
+ serve_compat.token_prompt(bad, 10)
+
+ def test_usage_and_tokenize_reply(self):
+ self.assertEqual(serve_compat.usage(4, 2), {"prompt_tokens": 4, "completion_tokens": 2, "total_tokens": 6})
+ self.assertEqual(serve_compat.usage(4, 2, 9)["prompt_tokens_details"], {"cached_tokens": 4})
+ self.assertEqual(serve_compat.usage(4, 2, -1)["prompt_tokens_details"], {"cached_tokens": 0})
+ self.assertEqual(serve_compat.tokenize_reply([1], 8), {"count": 1, "max_model_len": 8, "tokens": [1], "token_strs": None})
+
+
+def load(name: str, path: Path):
+ sys.path.insert(0, str(path.parent))
+ spec = importlib.util.spec_from_file_location(name, path)
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[name] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+class SimEngine:
+ """Fake engine with a whole-prompt cache: a prompt seen since the last reset reports cached_tokens == its length."""
+ ctx = 20000
+ vocab_size = 1000
+ supports_vision = False
+ spec_on = True
+ sessions = 1
+
+ def __init__(self):
+ self.cache, self.resets, self.salted_seen = set(), 0, []
+ self.last_stats = {}
+
+ def encode_ids(self, text, add_special_tokens=False):
+ return [1 + zlib.crc32(w.encode()) % 900 for w in text.split()]
+
+ def count_tokens(self, text):
+ return len(self.encode_ids(text))
+
+ def spec_stats(self):
+ return {}
+
+ async def reset_prefix_cache(self):
+ self.cache.clear()
+ self.resets += 1
+
+ async def generate(self, prompt, stats=None, prompt_ids=None, ignore_eos=False, **kw):
+ ids = tuple(prompt_ids) if prompt_ids is not None else tuple(self.encode_ids(prompt))
+ cached = len(ids) if ids in self.cache else 0
+ self.cache.add(ids)
+ st = {"cached_tokens": cached, "prompt_tokens": len(ids), "new_tokens": 6, "eos_reason": "stop_token" if not ignore_eos else "max_new_tokens",
+ "time_prefill": 0.01, "time_generate": 0.05}
+ self.last_stats = st
+ if stats is not None:
+ stats.update(st)
+ for piece in ("one ", "two ", "three ", "four ", "five ", "six"):
+ await asyncio.sleep(0.01)
+ yield piece
+
+
+class Live:
+ """An aiohttp app on 127.0.0.1 in its own thread, for the urllib client of RigMark."""
+
+ def __init__(self, app):
+ from aiohttp import web
+ self.loop = asyncio.new_event_loop()
+ self.runner = web.AppRunner(app)
+ self.loop.run_until_complete(self.runner.setup())
+ site = web.TCPSite(self.runner, "127.0.0.1", 0)
+ self.loop.run_until_complete(site.start())
+ self.port = site._server.sockets[0].getsockname()[1]
+ self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)
+ self.thread.start()
+
+ def close(self):
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ self.thread.join(5)
+ self.loop.run_until_complete(self.runner.cleanup())
+ self.loop.close()
+
+
[email protected]((RIGMARK / "bench.py").exists(), "RigMark source not found (set RIGMARK_SRC)")
+class RigmarkDriveTests(unittest.TestCase):
+ """RigMark's own prefill, decode and concurrency code against each server."""
+
+ @classmethod
+ def setUpClass(cls):
+ sys.path.insert(0, str(RIGMARK))
+ cls.bench = load("rigmark_bench", RIGMARK / "bench.py")
+ cls.prompts, _ = cls.bench.load_prompts(RIGMARK / "prompts.json")
+ cls.template = "{% for m in messages %}{{ m.content }} {% endfor %}answer:"
+
+ def servers(self):
+ qwen = load("qwen_serve", HERE / "qwen" / "serve.py")
+ glm = load("glm_serve", HERE / "glm" / "serve.py")
+ return {"qwen": qwen.create_app, "glm": glm.create_app}
+
+ def run_server(self, name, fn):
+ engine = SimEngine()
+ live = Live(self.servers()[name](engine, "m", self.template))
+ try:
+ client = self.bench.Client(f"http://127.0.0.1:{live.port}", "", 60)
+ return fn(client, engine)
+ finally:
+ live.close()
+
+ def test_prefill_phase_cold_then_replay_per_salt(self):
+ for name in ("qwen", "glm"):
+ def go(client, engine):
+ return self.bench.run_prefill(client, "m", self.prompts, [512, 1024], 2, "cmp-test"), engine
+ result, engine = self.run_server(name, go)
+ for depth in ("512", "1024"):
+ for cold, warm in zip(result[depth]["cold"]["runs"], result[depth]["warm_replay"]["runs"]):
+ self.assertEqual(cold["prompt_tokens"], int(depth), name)
+ self.assertEqual(cold["requested_prompt_tokens"], int(depth), name)
+ self.assertEqual(cold["cached_prompt_tokens"], 0, name)
+ self.assertEqual(warm["cached_prompt_tokens"], int(depth), name)
+ self.assertEqual(len(cold["cache_salt_sha256"]), 64)
+ self.assertEqual(engine.resets, 4, name) # one reset per cold request (a new salt), none for a replay
+
+ def test_prefill_without_a_salt_would_hit_the_cache(self):
+ """Control: the same ids twice under one salt do hit; RigMark's cold check is what the salt reset satisfies."""
+ for name in ("qwen", "glm"):
+ def go(client, engine):
+ ids = self.bench.exact_token_ids(client, "m", 600, self.prompts["prefill_unit"], "n1")
+ a = self.bench.prefill_once(client, "m", ids, "same")
+ b = self.bench.prefill_once(client, "m", ids, "same")
+ c = self.bench.prefill_once(client, "m", ids, "other")
+ return a, b, c
+ a, b, c = self.run_server(name, go)
+ self.assertEqual((a["cached_prompt_tokens"], b["cached_prompt_tokens"], c["cached_prompt_tokens"]), (0, 600, 0), name)
+
+ def test_decode_and_concurrency_fields_are_accepted(self):
+ extra = {"chat_template_kwargs": {"enable_thinking": False, "reasoning_effort": "low"}}
+ for name in ("qwen", "glm"):
+ def go(client, engine):
+ dec = self.bench.run_decode(client, "m", self.prompts, 1, 64, 20260905, extra, "cmp-test")
+ con = self.bench.run_concurrency(client, "m", self.prompts, [1, 2], 1, 32, 20260905, extra, "code", "cmp-test")
+ return dec, con
+ dec, con = self.run_server(name, go)
+ for workload in dec.values():
+ row = workload["runs"][0]
+ self.assertEqual(row["finish_reason"], "stop", name)
+ self.assertTrue(row["stream_done_marker"], name)
+ self.assertGreater(row["prompt_tokens"], 0)
+ self.assertEqual(sorted(con), ["1", "2"])
+
+ def test_rigmark_payload_fields_pass_both_chat_endpoints(self):
+ payload = self.bench.build_chat_payload("m", "sys", "hi", 16, 1, {"chat_template_kwargs": {"enable_thinking": False}})
+ for name in ("qwen", "glm"):
+ def go(client, engine):
+ return client.stream("/v1/chat/completions", payload)
+ row = self.run_server(name, go)
+ self.assertEqual(row["finish_reason"], "stop", name)
+
+
+if __name__ == "__main__":
+ unittest.main()