Files
strata/serve/test_replicas.py
T
lask3802 f332a85570 Non-finite logits (#879): a guard with self-healing
Rarely a window's logits become NaN and the reply degenerates into token 0
('!') repeated (#606); the poison sits in the conversation's K/V and
recurrent state, so with the prompt cache every later turn stays poisoned
until it is read again from token 0. The q8_1 clamps (2b726ba, f6601bf,
7a0e302) remove the overflows found so far; this guard catches whatever
cause is left, and drops the poisoned state instead of serving it again.

On by default, as a fix: STRATA_NAN_GUARD=0 turns it off. It only reads
flags, so an answer without a NaN is the one the engine gives with the
guard off (compared byte for byte on a GPU, below).

Engine:
- every verify-window graph checks its head logits beside the greedy pick
  (logits_nonfinite_rows: 16 blocks a row, one flag word each, into mapped
  memory); Verifier::note_nonfinite reads them after the sync the window
  already does (run, run_slot_rows, batch_poll, pl_finish). No extra sync.
  With STRATA_NAN_GUARD=0 no kernel is recorded.
- --serve: a flagged window emits none of its tokens, one stderr line names
  the position and row, and the request ends with `DONE ... nonfinite` (a
  batch slot: `BDONE <slot> <n> nonfinite`; an admission: BADM <slot> 0).
  The next request first drops the live session, every checkpoint, every
  parked conversation (ConversationCache::clear) and every idle slot, and
  reads its prompt from token 0; a slot still running then finishes its
  reply and is not kept as a cache after it. A request that ends on it does
  not keep its conversation live (#1620's cancelled-read path is skipped
  for it).
  Covered: the serial decode loop (one GPU or a layer split), the
  --pipeline-windows decode loop of a layer split, the prompt's short tail
  (read_windows, and read_windows_pl with --pipeline-windows), and both
  batch-slot loops (run_slot_rows, and the --batch-groups pipeline's
  batch_poll). Not covered: the one-shot command line (no --serve) and the
  SYCL port in sycl/, which has its own verify.cpp and generate.cpp.
- STRATA_NAN_INJECT=<n>[,<n>...] (debug): the n-th window the guard checks
  reports row 0 as non-finite.

Server: EngineNonFinite on that finish. A request that has sent nothing yet
is sent again once (its usage is the retry's: the failed pass's DONE is
dropped); a reply that had started ends as "length"; a second fire on the
retry ends with an error (503 before an answer, an error event in a
stream). With replicas the router forgets what that replica held.
repeat_stop_tokens stays as the backstop.

Checks: serve tests (python -m unittest discover -s serve -t . -p
"test_*.py": 697 tests, OK, 11 skipped; NonFiniteLogits,
test_nonfinite_in_batch_mode and test_nonfinite_forgets_the_replica are
new). ctest with CUDA_VISIBLE_DEVICES=-1: 24 pass (conversation_cache_test
with clear() among them), 3 skip for want of a GPU, and the 43 GPU parity
tests were not run on a GPU. Built for CUDA 13.0 on Linux (GCC, sm_75 +
sm_86); generate.cpp, verify.cpp and verify_kernels.cu compile with
MSVC 2022 + CUDA 13.0, and conversation_cache_test and conv_cache_test
pass there; built for HIP (ROCm 7.0, gfx1100, compile only) and SYCL
(oneAPI 2026.1.1; it takes only the new declaration in verify_kernels.hpp
and the new inline ConversationCache::clear(), and calls neither).

On a GPU (RTX 3080, RVN IQ3_S, strata.service's one-GPU config):
- Answers, guard on vs STRATA_NAN_GUARD=0, at fixed expert sets
  (--pcie-frac 0 --adapt-every 0 --adapt-swaps 0 --mtp-max-t 1
  --suffix-draft 0, STRATA_IQ_MT_MIN=1 STRATA_PREFILL_CPU_SHARE=0), a chat
  replay of 2 x 4 turns on a 16K-token system prompt: byte-identical in 3
  pairs (one with STRATA_ROUTE_TAIL_SKIP=0, one with STRATA_SH_STREAM=0),
  and two guard-on runs 8 of 8. One more guard-off run differed from every
  other run from its first answer, and a second guard-off run matched the
  guard-on runs: a difference between runs of this config, not the guard.
- Cost, Nsight Systems: logits_nonfinite_kernel 424 launches, 4.77 us on
  average (7.78 us at most), 2.0 ms against 21.6 s of decode: 0.009%.
- STRATA_NAN_INJECT=1,60: the first window of a new chat flagged, the
  server sent the request again from token 0 and the client saw one normal
  answer; the 60th, mid-reply in the next turn, ended that reply as
  "length" after 58 tokens; the turn after it reused 0 cached tokens and
  answered normally. The engine logged exactly the two injected windows.
2026-10-11 12:01:22 +02:00

246 lines
10 KiB
Python

"""Data-parallel replicas (serve/replicas.py): the config, the router, and the real Service over HTTP with two fake
engines (the fake of test_parallel.py) behind a ReplicaEngine."""
import json
import sys
import tempfile
import threading
import unittest
import urllib.request
from pathlib import Path
from unittest import mock
from serve.frontend import ChatTemplate
from serve.replicas import BLOCK, ReplicaConfigError, ReplicaEngine, Router, cpu_sets, gpu_groups, replica_cfg
from serve.server import ByteTokenizer, Service, StrataEngine, serve
from serve.test_parallel import FAKE_BATCH
class Config(unittest.TestCase):
def test_a_number_cuts_the_gpu_list(self):
self.assertEqual(gpu_groups({"gpu": [0, 1, 2, 3], "replicas": 2}), [[0, 1], [2, 3]])
self.assertEqual(gpu_groups({"gpu": "0,1,2,3", "replicas": 4}), [[0], [1], [2], [3]])
self.assertEqual(gpu_groups({"gpu": [0, 1], "replicas": 1}), [])
self.assertEqual(gpu_groups({"gpu": [0, 1]}), [])
def test_named_groups(self):
self.assertEqual(gpu_groups({"replicas": [{"gpus": [0, 1]}, {"gpus": [2]}]}), [[0, 1], [2]])
self.assertEqual(gpu_groups({"replicas": [{"gpus": [0, 1]}]}), [])
def test_mistakes_are_said(self):
for cfg in ({"gpu": [0, 1, 2], "replicas": 2}, {"replicas": 2}, {"replicas": "2"},
{"replicas": [{"gpus": [0, 1]}, {"gpus": [1, 2]}]}, {"replicas": [{"gpus": []}, {"gpus": [1]}]}):
with self.assertRaises(ReplicaConfigError, msg=cfg):
gpu_groups(cfg)
def test_replica_cfg(self):
cfg = {"gpu": [0, 1, 2, 3], "args": ["--x"], "log": "/l/strata.log", "hip_ordinal": 1, "env": {"A": "1"},
"expert_profile_save": "/p/prof.bin",
"replicas": [{"gpus": [0, 1], "env": {"B": 2}}, {"gpus": [2, 3], "args": ["--y"]}]}
a, b = replica_cfg(cfg, 0, [0, 1]), replica_cfg(cfg, 1, [2, 3])
self.assertEqual((a["gpu"], b["gpu"]), ([0, 1], [2, 3]))
self.assertEqual((a["log"], b["log"]), ("/l/strata.r0.log", "/l/strata.r1.log"))
self.assertEqual(a["env"], {"A": "1", "B": "2"})
self.assertEqual(b["args"], ["--x", "--y"])
self.assertNotIn("replicas", a)
self.assertNotIn("hip_ordinal", a)
self.assertEqual(a["expert_profile_save"], "/p/prof.r0.bin")
self.assertEqual(cfg["args"], ["--x"]) # the original is untouched
self.assertEqual(replica_cfg({"gpu": [0, 1], "args": []}, 0, [3])["gpu"], 3)
def test_cpu_sets_off(self):
self.assertIsNone(cpu_sets(2, enabled=False))
self.assertIsNone(cpu_sets(1))
class Routing(unittest.TestCase):
def test_matched_prefix_per_replica(self):
r = Router(3)
a = list(range(BLOCK * 4))
r.note(0, a)
r.note(1, a[:BLOCK * 2])
self.assertEqual(r.matched(a + [9] * 70), [BLOCK * 4, BLOCK * 2, 0])
self.assertEqual(r.matched([7] * 200), [0, 0, 0])
r.forget(0)
self.assertEqual(r.matched(a), [0, BLOCK * 2, 0])
def test_the_index_is_bounded(self):
r = Router(2, cap=10)
for i in range(50):
r.note(i % 2, [i] * (BLOCK * 2))
self.assertLessEqual(len(r.blocks), 10)
class FakeEngine:
def __init__(self, n=4):
self.batch, self.up = n, True
self.max_context = 4096
self.info = {}
self.last = {}
def alive(self):
return self.up
class RouteChoice(unittest.TestCase):
def test_least_loaded_then_affinity(self):
e = ReplicaEngine([FakeEngine(), FakeEngine()], load_tokens=3000)
picks = [e.route([i] * 100) for i in range(4)] # nothing cached: spread
self.assertEqual(sorted(picks), [0, 0, 1, 1])
ids = list(range(BLOCK * 8))
e.inflight = [0, 0]
k = e.route(ids)
e.router.note(k, ids)
e.inflight = [0, 0]
self.assertEqual(e.route(ids + [5] * 10), k) # the conversation goes back
e.inflight = [0, 0]
e.inflight[k] = 1 # 512 tokens held < 3000 per running request
self.assertNotEqual(e.route(ids + [5] * 10), k)
def test_a_long_prefix_outweighs_load(self):
e = ReplicaEngine([FakeEngine(), FakeEngine()], load_tokens=3000)
ids = list(range(BLOCK * 200)) # 12,800 tokens held on replica 0
e.router.note(0, ids)
e.inflight = [2, 0]
self.assertEqual(e.route(ids + [1]), 0)
e.inflight = [5, 0]
self.assertEqual(e.route(ids + [1]), 1)
def test_a_dead_replica_is_skipped(self):
a, b = FakeEngine(), FakeEngine()
e = ReplicaEngine([a, b])
e.heal = lambda: None
ids = list(range(BLOCK * 3))
e.router.note(0, ids)
a.up = False
self.assertEqual(e.route(ids), 1)
b.up = False
self.assertEqual(e.route(ids), -1)
def test_nonfinite_forgets_the_replica(self):
"""#879: after DONE ... nonfinite the engine holds no conversation: the router forgets that replica."""
from serve.server import EngineNonFinite
class NonFinite(FakeEngine):
def generate(self, ids, max_new, sampling, cancel):
yield 7
raise EngineNonFinite("the engine's logits became non-finite (#879)")
e = ReplicaEngine([NonFinite(), NonFinite()])
other, ids = [9] * (BLOCK * 4), list(range(BLOCK * 3))
e.router.note(0, other)
e.router.note(1, other)
k = 0
e.inflight[k] += 1 # as route() counts it
with mock.patch.object(e, "route", return_value=k):
with self.assertRaises(EngineNonFinite):
list(e.generate(ids, 10, {}, threading.Event()))
self.assertEqual(e.router.matched(ids)[k], 0)
self.assertEqual(e.router.matched(other)[k], 0) # its older conversations too
self.assertEqual(e.router.matched(other)[1 - k], len(other))
self.assertEqual(e.inflight[k], 0)
def test_batch_is_the_sum(self):
self.assertEqual(ReplicaEngine([FakeEngine(4), FakeEngine(4)]).batch, 8)
self.assertEqual(ReplicaEngine([FakeEngine(0), FakeEngine(0)]).batch, 2)
class ReplicaService(unittest.TestCase):
def start(self, slots=4, n=2):
import serve.server as server
self.tmp = tempfile.TemporaryDirectory()
script = Path(self.tmp.name) / "fake_strata.py"
script.write_text(FAKE_BATCH, encoding="utf-8")
real = server.subprocess.Popen
self.logs = [Path(self.tmp.name) / f"r{i}.log" for i in range(n)]
engines = []
for i in range(n):
extra = (["--batch", str(slots)] if slots else []) + ["--log", str(self.logs[i])]
with mock.patch.object(server.subprocess, "Popen",
lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
engines.append(StrataEngine("strata", extra))
self.engine = ReplicaEngine(engines)
self.svc = Service(self.engine, ByteTokenizer(), ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
self.httpd = serve(self.svc, port=0)
self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
def tearDown(self):
if getattr(self, "httpd", None):
self.httpd.shutdown()
self.httpd.server_close()
if getattr(self, "engine", None):
self.engine.unload()
if getattr(self, "tmp", None):
self.tmp.cleanup()
def post(self, messages, max_tokens=64):
body = {"messages": messages, "max_tokens": max_tokens, "reasoning_effort": "none"}
req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read().decode())["choices"][0]["message"]["content"]
def chat(self, text, max_tokens=64):
return self.post([{"role": "user", "content": text}], max_tokens)
def served(self):
return [sum(1 for l in p.read_text().splitlines() if l.split()[0] in ("GEN", "BGEN")) if p.exists() else 0
for p in self.logs]
def burst(self, prompts):
out = [None] * len(prompts)
def one(i):
out[i] = self.chat(prompts[i])
ts = [threading.Thread(target=one, args=(i,)) for i in range(len(prompts))]
for t in ts:
t.start()
for t in ts:
t.join()
return out
def test_requests_spread_over_both_and_answers_are_the_solo_answer(self):
self.start()
solo = self.chat("hello there")
before = self.served()
out = self.burst([f"request number {i} " + "x" * 300 for i in range(6)])
got = [b - a for a, b in zip(before, self.served())]
self.assertTrue(all(g >= 2 for g in got), got)
self.assertEqual(set(out), {solo})
def test_metrics_and_status_see_all_slots(self):
self.start()
self.assertEqual(self.svc.v1_status()["concurrency"]["serving"], 8)
m = self.svc.metrics()
self.assertEqual(len(m["live"]["slots"]), 8)
self.assertEqual([r["replica"] for r in m["live"]["replicas"]], [0, 1])
self.assertEqual(m["engine"]["replicas"], 2)
def test_engines_without_slots_run_one_each_at_once(self):
self.start(slots=0)
out = self.burst(["a" * 40, "b" * 40])
self.assertEqual(self.served(), [1, 1])
self.assertEqual(len(set(out)), 1)
def test_a_conversation_goes_back_to_its_replica(self):
self.start()
first = "begin " + "lorem ipsum " * 40
reply = self.chat(first)
k = self.served().index(1)
self.post([{"role": "user", "content": first}, {"role": "assistant", "content": reply},
{"role": "user", "content": "and then?"}], 16)
self.assertEqual(self.served()[k], 2)
def test_a_replica_that_died_is_skipped(self):
self.start()
self.engine.heal = lambda: None
self.engine.engines[0].proc.kill()
self.engine.engines[0].proc.wait()
self.assertTrue(self.engine.alive())
for i in range(3):
self.assertIn("ok, done.", self.chat(f"after the loss {i}"))
self.assertEqual(self.served()[1], 3)
if __name__ == "__main__":
unittest.main()