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.
This commit is contained in:
lask3802 authored and Niko1221 committed 2026-10-11 12:01:22 +02:00
1 parent 248dbee5b8
commit f332a85570
13 files changed
+536 -13

No files matched your search

+26
View File
@@ -743,6 +743,32 @@ print(r.choices[0].message.content)
server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a broken
state that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` in
`strata-<model>.json` sets the run length; `0` turns it off (for a request that really wants one token many times).
- **Non-finite logits end the request and drop the cached state (#879, on by default).** 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 of that conversation stays poisoned. The q8_1 clamps
of 0.1.39 and later remove the overflows found so far; this guard catches whatever cause is left. Every verify window
of `--serve` (the decode windows, the `--pipeline-windows` decode windows of a layer split, the prompt's short
tail, batch slots) checks its head logits on the GPU beside the greedy pick (one small kernel into mapped flags, read
after the sync the window already does). A flagged window emits none of its tokens, the engine prints one
`non-finite logits (#879)` line with the position, ends the request with `DONE ... nonfinite` (a slot:
`BDONE <slot> <n> nonfinite`), and the next request first drops the live session, every checkpoint, every parked
conversation and every idle slot (a slot still running finishes its reply and is not kept after it) and reads its
prompt from token 0. The server retries a request that had sent nothing yet once, transparently; a reply that had
started ends as `"length"` with a line in the server window; a second fire on the retry ends the request with an
error (503 before an answer, an error event in a stream). With replicas, the server forgets what that replica held.
`repeat_stop_tokens` stays as the backstop. The kernel writes only its flags and the host only reads them, so an
answer without a NaN is the one the engine gives with `STRATA_NAN_GUARD=0`, which records no kernel: on an RTX
3080 with the RVN IQ3_S config at fixed expert sets (a chat replay of 8 turns on a 16K-token system prompt), the
guard on and off gave byte-identical answers in 3 pairs (one of them with `STRATA_ROUTE_TAIL_SKIP=0`, one with
`STRATA_SH_STREAM=0`); one more guard-off run differed from all the others from its first answer on, while a second
guard-off run matched the guard-on runs, so that was a difference between runs, not the guard. Its cost there: 4.8 us of GPU time a window on average (7.8 us at most), 0.009% of the decode
time (Nsight Systems, 424 windows). The one-shot command line (`strata` without `--serve`) and the Intel (SYCL) port
in `sycl/` do not check.
Debug switch: `STRATA_NAN_INJECT=<n>[,<n>...]` reports the n-th window the guard checks in the engine process
(counted from 1 over prompt-tail, decode and batch windows) as non-finite, to exercise the whole path without a real
fire. With `=1,60` on that 3080: a new chat's first window was flagged and the server sent the request again from
token 0 (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.
- **Repeated reasoning (opt-in, #728).** The single-token guard above does not see a model that repeats whole
passages. `"reasoning_loop_recovery"` in `strata-<model>.json` is `false` (the default), `"stop"` or `"recover"`
(`true` means `"recover"`). Every 512 output tokens, at a complete character and parser boundary, the reasoning is
@@ -289,6 +289,16 @@ public:
return true;
}
// #879: every parked conversation (pinned ones too) and the retained K/V go - after non-finite logits any of them
// may carry the poison. Returns how many were parked.
size_t clear() {
const size_t n = entries_.size();
entries_.clear();
bytes_ = 0;
reuse_ = {};
return n;
}
// The slot count, so a caller that evicts in a loop has a bound it did not invent.
size_t slots() const { return slots_; }
+20
View File
@@ -97,6 +97,21 @@ public:
/// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run().
bool copy_logits(int t, float* host) const;
int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; }
/// #879 GUARD: the first row of the last finished window (run, run_slot_rows, batch_poll, pl_finish) whose head
/// logits held a NaN or an infinity, else -1; nonfinite_pos() is that row's position. Every window graph
/// checks its T rows on the device beside the greedy pick (logits_nonfinite_rows into mapped flags, read after
/// the sync the window already does: no extra sync). On the stage with the head (a layer split asks the last
/// stage). STRATA_NAN_GUARD=0: off (always -1). STRATA_NAN_INJECT=<n>[,<n>...] (debug): the n-th window the
/// guard checks in this process (counted from 1 over every stage-with-head verifier: prompt-tail windows, decode
/// windows and batch windows alike) reports row 0 as non-finite, so the whole response can be tested.
int nonfinite_row() const { return next_ != nullptr && !last_stage() ? next_->nonfinite_row() : nf_row_; }
int64_t nonfinite_pos() const { return next_ != nullptr && !last_stage() ? next_->nonfinite_pos() : nf_pos_; }
/// Row t of the last window (a batch window: each slot's own rows) held a non-finite logit.
bool nonfinite_in(int t) const {
if (next_ != nullptr && !last_stage()) return next_->nonfinite_in(t);
return t >= 0 && t < 32 && ((nf_mask_ >> t) & 1u) != 0;
}
static bool nan_guard_on();
/// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per
/// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its
/// parameters would otherwise be baked forever - so this can change between requests freely.
@@ -442,6 +457,11 @@ private:
int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}]
float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd
int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids
uint32_t* h_nf_ = nullptr; uint32_t* m_nf_ = nullptr; // #879: kVerifyMaxT * kNonfiniteBlocks flags
int nf_row_ = -1; ///< nonfinite_row()
int64_t nf_pos_ = -1; ///< nonfinite_pos()
uint32_t nf_mask_ = 0; ///< nonfinite_in(): bit t = row t
void note_nonfinite(int T, const int64_t* pos_b); ///< the window's flags (+ STRATA_NAN_INJECT) -> nf_row_
float* h_x_ = nullptr; float* m_x_ = nullptr; // doorbell payload: T * n_embd
int32_t* h_ids_ = nullptr; int32_t* m_ids_ = nullptr; // T * k
float* h_w_ = nullptr; float* m_w_ = nullptr; // T * k
@@ -129,6 +129,11 @@ void argmax_rows(const float* logits, int n_rows, int n, void* scratch, int32_t*
uint64_t row_top_prob_scratch_bytes(int n_rows);
void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* scratch,
void* stream);
/// #879 guard: flags[t * kNonfiniteBlocks + b] = 1 when slice b of row t (n floats a row) holds a NaN or an infinity,
/// else 0, for n_rows rows. Every word is written on every launch (nothing to clear between windows), so `flags` can
/// be mapped host memory read after the window's own sync. Graph-capturable; CUDA and HIP.
inline constexpr int kNonfiniteBlocks = 16;
void logits_nonfinite_rows(const float* logits, int n_rows, int n, uint32_t* flags, void* stream);
/// True where row_top_prob_split runs as its own kernel (CUDA; AMD keeps the one-block row_top_prob, so it calls
/// that). STRATA_MULTI_BLOCK_ARGMAX=0: off.
bool multi_block_head_ops();
+8 -2
View File
@@ -382,7 +382,7 @@ class ReplicaEngine:
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
# imported here: serve.server imports this module
from serve.server import EngineDied
from serve.server import EngineDied, EngineNonFinite
k = self.route(ids)
if k < 0:
raise EngineDied("no replica is running; this request was not sent")
@@ -390,6 +390,7 @@ class ReplicaEngine:
self.tl.cur = e
produced: list[int] = []
held = False
nonfinite = False
try:
self.router.note(k, ids)
if not int(getattr(e, "batch", 0) or 0): # no slots: this replica takes one request at a time
@@ -406,10 +407,15 @@ class ReplicaEngine:
if t is not None:
produced.append(t)
yield t
except EngineNonFinite:
nonfinite = True
raise
finally:
if held:
self.run_locks[k].release()
with self.lock:
self.inflight[k] -= 1
if produced:
if nonfinite: # #879: the engine dropped every cached conversation
self.router.forget(k)
elif produced:
self.router.note(k, list(ids) + produced)
+58
View File
@@ -315,6 +315,13 @@ class EngineSilent(EngineDied):
EngineDied, so the request ends with an error and the next one starts the engine again."""
class EngineNonFinite(ValueError):
"""#879: the engine's DONE (or a slot's BDONE) said `nonfinite`: a window's logits held a NaN or an infinity. The
engine wrote none of that window's tokens and drops every cached state that may carry the poison, so its next
request reads the prompt from token 0. Service.run sends a request that had produced nothing yet once more, and
ends one that had started (as "length"). A ValueError, so a stream that has started reports it as an error event."""
class SessionRefused(ValueError):
"""Disk sessions: the engine refused or failed a SAVE / RESTORE and is still in step (`SERR <kind> <published>
<reason>`). `kind` is the engine's category - invalid (400), storage (507), memory (503), io (500); `published`:
@@ -1091,6 +1098,11 @@ class StrataEngine:
self._ctl_result = ("done", None)
return
def _done_finish(self) -> str | None:
"""The finish field of the DONE line the control lines read last (None: none since it was cleared)."""
f = (getattr(self, "_last_done", None) or "").split()
return f[5] if len(f) > 5 else None
def _drain_control(self, until: str, timeout: float = 300.0, born: int | None = None):
"""After a consumer left early: read the control lines up to the next `until` line (DONE or BADM) so the next
request does not read this one's leftovers. Returns that line (None: the engine ended or never answered).
@@ -1169,6 +1181,8 @@ class StrataEngine:
except (IndexError, ValueError):
tail = []
if line.startswith("BDONE "):
if line.split()[3:4] == ["nonfinite"]: # #879: the engine dropped the slot's state
tail = []
break
held[slot] = tail[:-1] if stream and tail else []
with self.slot_cv:
@@ -1302,6 +1316,7 @@ class StrataEngine:
alone = not any(self.slot_busy) and self.waiting == 0
if alone and left > 1:
head = f"GENI {left}{keys} {embeddings}" if embeddings else f"GEN {left}{keys}"
self._last_done = None # (#879: this request's DONE decides below)
self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
phase = "solo"
self._ctl_mode, self._ctl_result, self._yielded = "solo", None, None
@@ -1330,6 +1345,8 @@ class StrataEngine:
t = pending.pop(0)
out.append(t)
yield t
if self._done_finish() == "nonfinite": # #879 (never promoted to a slot)
raise EngineNonFinite("the engine's logits became non-finite (#879)")
if self._yielded is not None and reserved is not None and self._yielded[0] == reserved:
slot, reserved = reserved, None # gave way: the read goes on in that slot (below)
elif reserved is not None: # it did not give way: the slot is free again
@@ -1410,6 +1427,7 @@ class StrataEngine:
live = {"slot": slot, "state": "reading", "prompt_tokens": len(prompt), "generated": 0,
"started": time.time(), "first_token": None}
self.slot_live[slot] = live
self._last_done = None # (#879: this admission's DONE decides below)
self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
self.slot_held[slot] = [] # the admission overwrites what the slot held
phase = "admit"
@@ -1433,6 +1451,8 @@ class StrataEngine:
t = pending.pop(0)
out.append(t)
yield t
if not cont and self._done_finish() == "nonfinite": # #879
raise EngineNonFinite("the engine's logits became non-finite (#879)")
if not cont and self._yielded is not None and self._yielded[0] == slot and not cancel.is_set():
continue # gave way: again once the shorter request is in
break
@@ -1475,6 +1495,9 @@ class StrataEngine:
self._apply_bdone(f)
# what the slot's sessions hold now: the prompt and every token fed (all but the last one)
self.slot_held[slot] = list(prompt) + out[gen0:-1] if len(out) > gen0 else []
if f[3:4] == ["nonfinite"]: # #879: the engine dropped the slot's state
self.slot_held[slot] = []
raise EngineNonFinite("the engine's logits became non-finite (#879)")
if (going_solo and f[3:4] == ["cancel"] and not cancel.is_set() and len(out) < int(max_new)
and not (out and out[-1] in EOS_IDS)):
# the solo path continues it: the engine copies the slot's sessions back (all but the
@@ -1690,6 +1713,8 @@ class StrataEngine:
elif line.startswith("DONE"):
self._parse_done(line)
done = True
if self.last.get("finish") == "nonfinite": # #879
raise EngineNonFinite("the engine's logits became non-finite (#879)")
return
elif line.startswith("ERR"):
done = True
@@ -3692,6 +3717,7 @@ class Service:
opening, force = parser.feed(force), None
tail = "" # the last characters written (the newlines before a call)
answered, close_retried = False, False # #1053: content or a call came out; the thinking was closed
nf_retried = False # #879: the request was sent again after non-finite logits
timings, before = None, None # this request's timings; the engine's `last` before it
recovery_count, reasoning_text, repeat_coverage = 0, "", 0.0
looped, next_loop_check = False, LOOP_CHECK_EVERY # #728: reasoning that repeats whole passages
@@ -3780,10 +3806,12 @@ class Service:
yield "event", ev
while True:
segment_before = getattr(self.engine, "last", None)
segments_before = len(segments) # (#879: a pass sent again leaves no segment)
gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \
else self.engine.generate(prompt, max_new - n, sampling, cancel)
recover_prompt = None
seg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closed
nonfinite = False # #879: the engine ended this pass on non-finite logits
opens = False # the thinking is over: write the forced call's opening
try:
# A value the frontend holds back (a tool call's array or object argument is sent
@@ -3860,6 +3888,8 @@ class Service:
elif parser.state == "content" and not parser.buf and not detok.pending():
opens = True
break
except EngineNonFinite:
nonfinite = True
except EngineDied as e:
finish = "error"
self._say_died(e)
@@ -3884,6 +3914,28 @@ class Service:
segment_done = getattr(self.engine, "last", None)
if segment_done is not None and segment_done is not segment_before:
segments.append(dict(segment_done))
if nonfinite and not cancel.is_set():
# #879: the engine emitted none of the poisoned window's tokens and reads its next prompt
# from token 0. Nothing sent yet: the same request once more, unseen by the client
if n == 0 and not nf_retried:
nf_retried = True
# the retry reads from token 0: its DONE, not this one's, says what was reused
del segments[segments_before:]
print("[strata] the engine's logits became non-finite before the first token (#879); it "
"dropped its cached state: sending the request again once", flush=True)
continue
if n == 0:
finish = "error"
print("[strata] the engine's logits became non-finite again on the retry (#879): the "
"request ends with an error", flush=True)
raise EngineNonFinite("the model's output became non-finite (NaN) twice in a row "
"(#879); the engine has dropped its cached state - send the "
"request again")
print(f"[strata] the engine's logits became non-finite after {n} tokens (#879): the reply "
"ends here as \"length\"; the engine dropped its cached state, so the next request "
"reads its prompt from the start", flush=True)
finish = "length"
break
if recover_prompt is not None and not cancel.is_set() and n < max_new:
recovery_count += 1
# Only the two settings that keep the same words coming are raised (temperature to at
@@ -5035,6 +5087,10 @@ def make_handler(svc: Service):
self._count_tokens(req)
else:
self._json(404, {"error": {"message": "not found"}})
except EngineNonFinite as e: # #879, twice: not the request's fault
print(f"[strata] 503: {e}", flush=True)
self._json(503, responses_error_body(str(e), "server_error") if path == "/v1/responses"
else {"error": {"type": "server_error", "message": str(e)}})
except ValueError as e:
print(f"[strata] 400 invalid request: {e}", flush=True)
if path == "/v1/responses":
@@ -5404,6 +5460,8 @@ def make_handler(svc: Service):
except EngineDied as e:
return self._json(503, responses_error_body(f"{e}; the next request restarts it", "server_error",
code="server_error"))
except EngineNonFinite as e: # #879, twice: not the request's fault
return self._json(503, responses_error_body(str(e), "server_error", code="server_error"))
except ValueError as e: # the engine's ERR line
return self._json(500, responses_error_body(str(e), "server_error", code="server_error"))
return self._json(200, result)
+50
View File
@@ -53,12 +53,20 @@ def reply(ids): # the rest of the reply after what the prompt already
return R[k:]
active = {} # slot -> [tokens left, max_new, produced]
stopped = set() # BSTOPped slots: they end "cancel"
# #879: a prompt with NFSOLO / NFADMIT ends its first GEN / BGEN with DONE ... nonfinite (nothing emitted); one with
# NFSLOT ends its slot with BDONE ... nonfinite after its second token
fired, nf_slots = set(), set()
def window(): # one batch window: every active slot one token
if fail and len(active) >= 2: # as the engine: the reason on stdout, then exit code 1
print("ERR verify batch: layer 34 never rang (graph finished)", flush=True)
sys.exit(1)
for b in sorted(active):
left, max_new, produced = active[b]
if b in nf_slots and produced >= 2:
nf_slots.discard(b)
print(f"BDONE {b} {produced} nonfinite 1.0", flush=True)
del active[b]
continue
t = left.pop(0) if left else 257
produced += 1
print(f"BT {b} {t}", flush=True)
@@ -99,6 +107,16 @@ while True:
continue
if log:
log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)}\n"); log.flush()
pb = bytes(int(x) & 255 for x in ids)
mark = b"NFSOLO" if f[0] == "GEN" else b"NFADMIT"
if mark in pb and mark not in fired:
fired.add(mark)
print(f"DONE 0 {len(ids)} 5.0 0.0 nonfinite 0 0 0", flush=True)
if slot is not None:
print(f"BADM {slot} 0", flush=True)
continue
if slot is not None and b"NFSLOT" in pb:
nf_slots.add(slot)
toks = reply(ids)
stop.clear()
# the prompt read: CH tokens a chunk, a PP line each; a BYIELD <s> gives way at a chunk boundary
@@ -548,6 +566,38 @@ class ParallelService(unittest.TestCase):
self.assertIn("exited (code 1)", note)
self.assertIn("verify batch: layer 34 never rang (graph finished)", note)
def test_nonfinite_in_batch_mode(self):
"""#879 in --batch mode: DONE ... nonfinite on the solo path or at an admission (nothing emitted yet) sends the
request again once; BDONE ... nonfinite in a slot ends the reply that had started, as "length"."""
self.start(2)
self.assertEqual(self.chat("NFSOLO alone")["choices"][0]["message"]["content"], "ok, done.")
gens = [x for x in self.log.read_text().splitlines() if x.startswith("GEN")]
self.assertEqual(len(gens), 2, gens) # sent again once
res = self.race("first question LONGREPLY", "NFADMIT second")
self.assertEqual(res["NFADMIT second"][0], "ok, done.")
self.assertEqual(res["first question LONGREPLY"][0], "ok, " + "la " * 15 + "done.")
self.assertTrue(any(x.startswith("BGEN") for x in self.log.read_text().splitlines()))
out = {}
def go(t):
body = {"messages": [{"role": "user", "content": t}], "max_tokens": 64, "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:
out[t] = json.loads(r.read().decode())["choices"][0]
a = threading.Thread(target=go, args=("third question LONGREPLY",))
a.start()
time.sleep(0.15)
go("NFSLOT fourth")
a.join(30)
c = out["NFSLOT fourth"]
self.assertEqual((c["message"]["content"], c["finish_reason"]), ("ok", "length"))
self.assertEqual(out["third question LONGREPLY"]["message"]["content"], "ok, " + "la " * 15 + "done.")
# the engine dropped that slot's state: the server does not route the conversation's next turn to it
self.assertFalse([h for h in self.engine.slot_held if bytes(t & 255 for t in h).find(b"NFSLOT") >= 0])
with self.svc.status_lock:
self.assertEqual(self.svc.live_reqs, {})
def test_a_continued_request_reports_its_own_prompt_reuse(self):
"""A request STOPped on the solo path and continued in a slot (or back on the solo path) is sent again as its
prompt + what it generated, and the engine holds all of that: the usage must still split the request's OWN
+23
View File
@@ -116,6 +116,29 @@ class RouteChoice(unittest.TestCase):
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)
+125 -1
View File
@@ -22,7 +22,8 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from serve.frontend import ChatTemplate, literal_tags, mark_think_literals, unmark_think_literals # noqa: E402
from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, PP_DONE_TAIL, Service, # noqa: E402
from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, EngineNonFinite, GpuBusy, MockEngine, # noqa: E402
PP_DONE_TAIL, Service,
StrataEngine, api_key_of, engine_args, key_matches, layer_split_value, prompt_progress,
prompt_tokens_seen,
request_timings, serve, start_failure_hint)
@@ -2086,6 +2087,129 @@ class RepeatStop(unittest.TestCase):
self.assertEqual(done["finish"], "stop")
class NonFiniteEngine(MockEngine):
"""#879: each pass ends on the engine's `DONE ... nonfinite` after plan[i] tokens (None, or no plan left: the
script runs whole), as StrataEngine.generate raises it. A pass that ends on it had reused all but the last
prompt token; the next one reads from token 0, as the engine does."""
def __init__(self, *a, plan=(), **kw):
super().__init__(*a, **kw)
self.plan, self.calls = list(plan), []
self.last, self.flushed = None, False
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
self.calls.append(list(ids))
cut = self.plan.pop(0) if self.plan else None
# (set before the tokens: the service closes a pass at its end-of-turn token, before the code after the loop)
self.last = {"prompt_tokens": len(ids), "reused": 0 if self.flushed else len(ids) - 1,
"finish": "nonfinite" if cut is not None else "stop"}
self.flushed = False
for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)):
if cut is not None and i >= cut:
break
yield t
if cut is not None:
self.flushed = True
raise EngineNonFinite("the engine's logits became non-finite (#879)")
class NonFiniteLogits(unittest.TestCase):
"""#879: non-finite logits before the first token -> the same request once more; after tokens went out -> the
reply ends as "length"; again on the retry -> an error, no loop."""
def run_reply(self, plan):
tok = ByteTokenizer()
eng = NonFiniteEngine(tok, "hello", max_context=CTX, plan=plan)
svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
ids = tok.encode("hi")
events, done, error = [], None, None
with contextlib.redirect_stdout(io.StringIO()) as out:
try:
for kind, x in svc.run(ids, False, None, 100, {}, threading.Event()):
if kind == "done":
done = x
elif kind == "event":
events.append(x)
except EngineNonFinite as e:
error = e
text = "".join(ev.text or "" for ev in events if ev.kind == "content")
return eng, svc, ids, done, error, text, out.getvalue()
def test_nothing_emitted_is_retried_once(self):
eng, svc, ids, done, error, text, log = self.run_reply([0])
self.assertIsNone(error)
self.assertEqual(eng.calls, [ids, ids]) # the same request, once more
self.assertEqual(done["finish"], "stop")
self.assertEqual(text, "hello")
self.assertIn("non-finite before the first token", log)
self.assertEqual(svc.metrics()["requests"][0]["finish"], "stop")
self.assertEqual(svc.metrics()["requests"][0]["reused"], 0) # the retry's DONE, not the failed pass's
def test_mid_reply_ends_without_retry(self):
eng, svc, ids, done, error, text, log = self.run_reply([3]) # "hel"
self.assertIsNone(error)
self.assertEqual(len(eng.calls), 1)
self.assertEqual((done["finish"], done["completion_tokens"]), ("length", 3))
self.assertEqual(text, "hel")
self.assertIn("non-finite after 3 tokens", log)
def test_twice_is_an_error(self):
eng, svc, ids, done, error, text, log = self.run_reply([0, 0, 0])
self.assertIsNotNone(error)
self.assertIn("twice in a row", str(error))
self.assertEqual(eng.calls, [ids, ids]) # one retry, no loop
self.assertEqual(eng.plan, [0])
self.assertIsNone(done)
self.assertEqual(svc.metrics()["requests"][0]["finish"], "error")
def test_twice_over_http(self):
tok = ByteTokenizer()
svc = Service(NonFiniteEngine(tok, "ok", max_context=CTX, plan=[0, 0]), tok,
ChatTemplate(ROOT / "serve/chat_template.jinja"))
httpd = serve(svc, port=0)
base = f"http://127.0.0.1:{httpd.server_address[1]}"
try:
for path, stream in (("/v1/chat/completions", False), ("/v1/chat/completions", True),
("/v1/responses", False)):
svc.engine.plan = [0, 0]
body = {"model": "m", "max_tokens": 20, "stream": stream, "messages": [{"role": "user", "content": "hi"}]}
if path == "/v1/responses":
body = {"model": "m", "max_output_tokens": 20, "input": "hi"}
req = urllib.request.Request(base + path, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
with contextlib.redirect_stdout(io.StringIO()):
try:
with urllib.request.urlopen(req, timeout=30) as r:
code, text = r.status, r.read().decode()
except urllib.error.HTTPError as e:
with e:
code, text = e.code, e.read().decode()
self.assertEqual(code, 200 if stream else 503, text)
self.assertIn("twice in a row", text)
self.assertIn("server_error", text)
finally:
httpd.shutdown()
httpd.server_close()
def test_engine_done_line_raises(self):
"""StrataEngine.generate: `DONE ... nonfinite` raises EngineNonFinite after the tokens before it."""
import queue as queue_
eng = object.__new__(StrataEngine)
eng.lines = queue_.Queue()
for line in ("T 5", "T 6", "DONE 2 3 1.0 2.0 nonfinite 0 0 0"):
eng.lines.put(line)
eng.proc = SimpleNamespace(stdin=io.StringIO())
eng.alive = lambda: True
eng.silence_s, eng.can_stop, eng.last = 0, True, None
got = []
with self.assertRaises(EngineNonFinite):
for t in eng.generate([1, 2, 3], 10, {}, threading.Event()):
got.append(t)
self.assertEqual(got, [5, 6])
self.assertEqual(eng.last["finish"], "nonfinite")
self.assertNotIn("STOP", eng.proc.stdin.getvalue()) # the DONE was read: nothing to stop or drain
class LayerSplit(unittest.TestCase):
"""#644: "layer_split" is the first layer of each later GPU; a list is accepted, counts per card are not."""
+11
View File
@@ -128,6 +128,17 @@ int main() {
cache.put(image({9, 8, 7}));
check(cache.evict_oldest() && cache.size() == 1, "the oldest unpinned conversation went (the pinned one is older)");
check(!cache.evict_oldest() && cache.size() == 1, "only a pinned one is left: nothing more can go");
// #879: after non-finite logits every parked conversation goes, the pinned one too
cache.put(image({4, 5, 6}));
std::vector<ConversationKv> kv(1);
kv[0].cells = 3;
kv[0].k.resize(64, 1);
cache.retain(std::move(kv), 3);
check(cache.retained_bytes() > 0, "a retained K/V before clear()");
check(cache.clear() == 2, "clear() reports how many were parked");
check(cache.size() == 0 && cache.bytes() == 0 && cache.retained_bytes() == 0, "clear() leaves nothing parked");
check(cache.best(std::vector<int64_t>{1, 2, 3, 4}, {}, true).tokens == 0, "a cleared cache matches nothing");
check(cache.clear() == 0, "clear() on an empty cache");
}
{
auto s = image({1, 2, 3});
+61 -1
View File
@@ -513,7 +513,7 @@ Verifier::~Verifier() {
if (e) cudaEventDestroy(e);
if (arena_) cudaFree(arena_);
void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,
h_flagA_, h_plan_, h_flagB_, h_plan_err_};
h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_};
for (void* h : hosts)
if (h) cudaFreeHost(h);
}
@@ -609,6 +609,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
mapped((2 + T) * 4 + 16, (void**) &h_commit_, (void**) &m_commit_) &&
mapped(T * N * 4, (void**) &h_ple_, (void**) &m_ple_) &&
mapped(T * 4 + 16, (void**) &h_out_, (void**) &m_out_) &&
mapped((size_t) strata::kernels::kVerifyMaxT * strata::kernels::kNonfiniteBlocks * 4, (void**) &h_nf_,
(void**) &m_nf_) &&
mapped(T * N * 4, (void**) &h_x_, (void**) &m_x_) &&
mapped(T * K * 4, (void**) &h_ids_, (void**) &m_ids_) &&
mapped(T * K * 4, (void**) &h_w_, (void**) &m_w_) &&
@@ -1789,6 +1791,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
sp.temperature = 0.0f;
sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs);
}
// #879: whether each row's logits are all finite, beside the pick (read after the window's own sync)
if (nan_guard_on()) strata::kernels::logits_nonfinite_rows(head_logits_, T, (int) n_vocab_, m_nf_, cs);
}
stamp(g.n_layers, 1, 0);
return true;
@@ -2336,6 +2340,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
}
}
for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
note_nonfinite(T, nullptr);
if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) { // debug: the first non-finite head
static bool reported = false;
if (!reported) {
@@ -2869,6 +2874,7 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons
if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);
if (!sample_rows(S, err)) return false;
for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
note_nonfinite(S, last_pos_b_);
progress_at("decode");
progress_beat();
return true;
@@ -2932,6 +2938,7 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons
if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);
if (!sample_rows(S, err)) return false;
for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
note_nonfinite(S, last_pos_b_);
progress_at("decode");
progress_beat();
return true;
@@ -3088,6 +3095,7 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
if (last_stage()) {
if (!sample_rows(S, err)) { b_running_ = false; return -1; }
for (int t = 0; t < S; ++t) b_out_[t] = ((volatile int32_t*) h_out_)[t];
note_nonfinite(S, last_pos_b_);
}
++windows;
b_running_ = false;
@@ -3095,6 +3103,57 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
return 1;
}
// #879: STRATA_NAN_GUARD=0 turns the guard off (no kernel is recorded; the graphs are captured once, so it is read once)
bool Verifier::nan_guard_on() {
static const bool on = [] {
const char* v = std::getenv("STRATA_NAN_GUARD");
return v == nullptr || std::atoi(v) != 0;
}();
return on;
}
namespace {
// STRATA_NAN_INJECT=<n>[,<n>...] (debug): the windows (counted from 1 over the process) the guard reports as non-finite
const std::vector<long long>& nan_inject_list() {
static const std::vector<long long> list = [] {
std::vector<long long> v;
if (const char* e = std::getenv("STRATA_NAN_INJECT"))
for (const char* q = e; *q != 0;) {
char* end = nullptr;
const long long n = std::strtoll(q, &end, 10);
if (end == q) break;
if (n > 0) v.push_back(n);
q = *end == ',' ? end + 1 : end;
}
return v;
}();
return list;
}
std::atomic<long long> g_nf_windows{0};
} // namespace
void Verifier::note_nonfinite(int T, const int64_t* pos_b) {
nf_row_ = -1;
nf_pos_ = -1;
nf_mask_ = 0;
if (!nan_guard_on() || h_nf_ == nullptr || !last_stage()) return; // (a stage without the head checks nothing)
const volatile uint32_t* f = h_nf_;
for (int t = 0; t < T && t < strata::kernels::kVerifyMaxT; ++t)
for (int b = 0; b < strata::kernels::kNonfiniteBlocks; ++b)
if (f[t * strata::kernels::kNonfiniteBlocks + b] != 0) { nf_mask_ |= 1u << t; break; }
const std::vector<long long>& inject = nan_inject_list();
if (!inject.empty()) {
const long long k = g_nf_windows.fetch_add(1) + 1;
if (nf_mask_ == 0 && std::find(inject.begin(), inject.end(), k) != inject.end()) {
nf_mask_ = 1u;
std::fprintf(stderr, "strata verify: STRATA_NAN_INJECT: window %lld reported as non-finite\n", k);
}
}
for (int t = 0; t < T && nf_row_ < 0; ++t)
if ((nf_mask_ >> t) & 1u) nf_row_ = t;
if (nf_row_ >= 0) nf_pos_ = pos_b != nullptr ? pos_b[nf_row_] : last_pos0_ + nf_row_;
}
bool Verifier::copy_logits(int t, float* host) const {
if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage
if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false;
@@ -3354,6 +3413,7 @@ bool Verifier::pl_finish(int32_t* out, std::string& err) {
}
if (out != nullptr)
for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
note_nonfinite(T, nullptr);
progress_beat();
return true;
}
+23
View File
@@ -853,6 +853,29 @@ void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int3
}
#endif
namespace {
// grid (kNonfiniteBlocks, rows): block b of row t scans [b * per_block, +per_block) and writes its own word. The
// test is on the bits (exponent all ones), so --use_fast_math cannot fold it away.
__global__ void logits_nonfinite_kernel(const float* __restrict__ logits, int n, int per_block, uint32_t* flags) {
const int row = (int) blockIdx.y, b = (int) blockIdx.x;
const float* l = logits + (size_t) row * n;
const int lo = b * per_block, hi = min(n, lo + per_block);
int bad = 0;
for (int v = lo + (int) threadIdx.x; v < hi; v += (int) blockDim.x)
bad |= (__float_as_uint(l[v]) & 0x7f800000u) == 0x7f800000u;
bad = __syncthreads_or(bad);
if (threadIdx.x == 0) flags[row * kNonfiniteBlocks + b] = bad ? 1u : 0u;
}
} // namespace
void logits_nonfinite_rows(const float* logits, int n_rows, int n, uint32_t* flags, void* stream) {
if (n_rows <= 0 || n <= 0) return;
const int per_block = (n + kNonfiniteBlocks - 1) / kNonfiniteBlocks;
logits_nonfinite_kernel<<<dim3((unsigned) kNonfiniteBlocks, (unsigned) n_rows), 256, 0, (cudaStream_t) stream>>>(
logits, n, per_block, flags);
check("logits_nonfinite_rows");
}
bool multi_block_head_ops() {
#if defined(__HIPCC__)
return false;
+116 -9
View File
@@ -6194,9 +6194,14 @@ int main(int argc, char** argv) {
//
// and each generated token is written to stdout as `T <id>` as soon as its verify window is done, followed by
//
// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <stop|length|cancel> <drafts accepted>
// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <stop|length|cancel|nonfinite> <drafts accepted>
// <drafts offered> <prompt tokens reused> ... <prompt tokens read> (see the DONE line below; #471)
//
// `nonfinite` (#879): a window's head logits held a NaN or an infinity (Verifier::nonfinite_row). None of that
// window's tokens was written; every state that may carry the poison (the live session, the checkpoints, the
// parked conversations, the idle batch slots) is dropped at the next request's start, which reads its prompt from
// token 0. A batch slot ends the same way: `BDONE <slot> <n> nonfinite`.
//
// Before that, `RESUME <n>` (n prompt tokens are not read again), `PP <position> <prompt_tokens> <ms> <tok/s>`
// after every prompt chunk, and `REUSED <n>` once the prompt is read. (`ERR <message>` instead when a request
// cannot run; `STOP` ends the running request at its next step; `QUIT` ends the process.) A request continues
@@ -7712,6 +7717,8 @@ int main(int argc, char** argv) {
std::vector<int32_t> live;
std::vector<ImgKey> live_imgs, req_imgs;
bool live_ok = false;
// #879: a window met non-finite logits: the next request drops every cached state first and reads from token 0
bool nan_flush = false;
std::vector<ConvCheckpoint> checks;
uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it
int64_t tail_ckpt_len = -1; // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none)
@@ -7972,6 +7979,20 @@ int main(int argc, char** argv) {
// failed): a request cancelled here keeps them as the live conversation instead of dropping what it restored
bool pp_exact = false;
Clock::time_point pp_t0 = Clock::now();
// #879: this request met a window whose head logits were not all finite (nonfinite_hit): it ends with
// DONE ... nonfinite, emitting none of that window's tokens
bool nf_hit = false;
auto nonfinite_hit = [&](const strata::core::Verifier& v, const char* what) -> bool {
const int row = v.nonfinite_row();
if (row < 0) return false;
std::fprintf(stderr, "strata serve: non-finite logits (#879) in a %s window at position %lld (row %d): its "
"tokens are not emitted, the request ends (DONE nonfinite) and the next request reads "
"its prompt from token 0\n", what, (long long) v.nonfinite_pos(), row);
std::fflush(stderr);
nf_hit = true;
nan_flush = true;
return true;
};
auto imgs_below = [&](const std::vector<ImgKey>& all, int64_t L) {
std::vector<ImgKey> v;
for (const ImgKey& k : all) if (k.start < L) v.push_back(k);
@@ -9183,6 +9204,9 @@ int main(int argc, char** argv) {
// a prompt read that gave way to a waiting request (BYIELD): `ids` is the part read so far, and the same
// request continues from it (the read goes on with the same chunks; `from0`: it had started at token 0)
bool partial = false, partial_from0 = false;
// #879: it was running when non-finite logits dropped the cached state; its state may have started from
// that state (a checkpoint, a parked conversation), so it is not kept as a cache when it ends
bool tainted = false;
};
std::vector<BSlot> bs((size_t) std::max(o.batch, 0));
// timing of the batch windows since the slots were last all idle (one stderr line then)
@@ -9405,6 +9429,20 @@ int main(int argc, char** argv) {
for (int t = 0; t < A; ++t) {
const int b = active[t];
BSlot& sl = bs[(size_t) b];
bool nf = false; // #879: a row of this slot held non-finite logits: the slot ends, nothing emitted
for (int r = first[t]; r < first[t] + (batch_mtp ? 2 : 1); ++r) nf = nf || ver.nonfinite_in(r);
if (nf) {
std::fprintf(stderr, "strata batch: non-finite logits (#879) in slot %d at position %lld: it ends "
"(BDONE nonfinite) and the next request reads its prompt from token 0\n", b,
(long long) pos[first[t]]);
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
std::printf("BDONE %d %lld nonfinite %.1f\n", b, (long long) sl.produced, ms);
sl.active = false;
sl.cached = false;
sl.checks.clear();
nan_flush = true;
continue;
}
for (int j = 0; j < keep[b]; ++j) {
const int32_t y = outb[first[t] + j];
sl.ids.push_back(tok[first[t] + j]);
@@ -9417,7 +9455,7 @@ int main(int argc, char** argv) {
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms);
sl.active = false;
sl.cached = o.prompt_cache > 0 && !sl.img;
sl.cached = o.prompt_cache > 0 && !sl.img && !sl.tainted;
break;
}
sl.x = y;
@@ -9551,6 +9589,18 @@ int main(int argc, char** argv) {
for (int t = 0; t < G.S; ++t) {
BSlot& sl = bs[(size_t) (gi * GS + t)];
if (!sl.active) continue;
if (vk.nonfinite_in(t)) { // #879: the slot ends, nothing emitted
std::fprintf(stderr, "strata batch: non-finite logits (#879) in slot %d at position %lld: it "
"ends (BDONE nonfinite) and the next request reads its prompt from token 0\n",
gi * GS + t, (long long) sl.p);
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
std::printf("BDONE %d %lld nonfinite %.1f\n", gi * GS + t, (long long) sl.produced, ms);
sl.active = false;
sl.cached = false;
sl.checks.clear();
nan_flush = true;
continue;
}
const int32_t y = outb[t];
std::printf("BT %d %d\n", gi * GS + t, (int) y);
++sl.produced;
@@ -9566,7 +9616,7 @@ int main(int argc, char** argv) {
// a pipelined slot is a cache again (#857: a request left alone in its slot goes back to the solo path with its
// drafts): its state is final once its last window has left the last stage. A later group window whose pad
// row writes this slot clears the flag (below, where the group starts), so a stale state is never reused
sl.cached = o.prompt_cache > 0 && !sl.img;
sl.cached = o.prompt_cache > 0 && !sl.img && !sl.tainted;
} else {
sl.x = y;
sl.p += 1;
@@ -9923,6 +9973,13 @@ int main(int argc, char** argv) {
for (const ConvCheckpoint& c : checks) check_clock = std::max(check_clock, c.used);
cvec_cached = image.cvec;
live_ok = true;
if (nan_flush) { // #879: the file replaced the poisoned session; the parked ones go (no slots here)
nan_flush = false;
const size_t n_parked = conversations.clear();
std::fprintf(stderr, "strata serve: after non-finite logits (#879): the restored session "
"replaces the live one; dropped %zu parked conversation%s\n", n_parked,
n_parked == 1 ? "" : "s");
}
std::fprintf(stderr, "strata serve: session restored %zu tokens, %zu checkpoints, %zu bytes from %s "
"in %.1f ms (read+check %.1f ms)\n", live.size(), checks.size(), bytes, path.c_str(),
ms(), read_ms);
@@ -10157,6 +10214,34 @@ int main(int argc, char** argv) {
return 1;
}
}
nf_hit = false;
// #879: an earlier window met non-finite logits. The poison sits in a conversation's K/V and recurrent
// state, so nothing that may hold it is continued: the live session, every checkpoint, every parked
// conversation and every idle batch slot go, and this prompt is read from token 0 (resume == 0 below)
if (nan_flush) {
nan_flush = false;
const size_t n_checks = checks.size();
live_ok = false;
checks.clear();
tail_ckpt_len = -1;
const size_t n_parked = conversations.clear();
size_t n_slots = 0, n_running = 0;
for (BSlot& sl : bs)
if (sl.active) { // a running slot finishes its reply, but is not kept as a cache after it
sl.tainted = true;
++n_running;
} else if (sl.cached) {
sl.cached = false;
sl.partial = false;
sl.checks.clear();
++n_slots;
}
std::fprintf(stderr, "strata serve: after non-finite logits (#879): dropped the live session, %zu "
"checkpoint%s, %zu parked conversation%s and %zu idle slot%s (%zu running slot%s "
"not kept after their reply); reading this prompt from token 0\n", n_checks,
n_checks == 1 ? "" : "s", n_parked, n_parked == 1 ? "" : "s", n_slots,
n_slots == 1 ? "" : "s", n_running, n_running == 1 ? "" : "s");
}
int64_t resume = 0;
bool from_live = false;
if (o.prompt_cache > 0 && want_cvec == cvec_cached) {
@@ -10528,6 +10613,7 @@ int main(int argc, char** argv) {
if (v.service(win_pool_fn, PSD[f1 & 1], e) < 0) return fail(e);
if (v.done(e)) {
if (!v.pl_finish(nullptr, e)) return fail(e);
if (nonfinite_hit(v, "prompt")) return fail("non-finite logits (#879)");
const Win& w = wins[f1];
for (int t = 0; t < w.T; ++t) nx[(size_t) t] = (int32_t) cur[(size_t) (w.q + t + 1)];
if (!mtp.prefill(v.final_R(0), nx.data(), w.T, w.q, e, false)) return fail(e);
@@ -10580,6 +10666,10 @@ int main(int argc, char** argv) {
if (drive.d.failed && drive.d.fail) e = drive.d.fail;
return false;
}
if (nonfinite_hit(ver, "prompt")) { // (its commit is not needed: the next request reads from 0)
e = "non-finite logits (#879)";
return false;
}
// STRATA_LOGPOS=<path>: the teacher-forced log-probability of every token read here (every
// token is committed and nxt[t] is the prompt's own next token), appended to <path>; the last
// column is the log-probability of STRATA_LOGPOS_EXTRA (default 248046, <|im_end|>), so the
@@ -10962,6 +11052,10 @@ int main(int argc, char** argv) {
std::chrono::duration<double, std::milli>(Clock::now() - tsp).count());
std::fflush(stderr);
}
if (!sp_ok && nf_hit) { // #879: DONE nonfinite (the lent slots are refilled below)
cancelled = true;
break;
}
if (!sp_ok) {
if (yielded_at < 0 && (batch_fatal || !stop_req.load())) {
std::fprintf(stderr, "strata serve: %s\n", err.c_str());
@@ -11054,7 +11148,7 @@ int main(int argc, char** argv) {
const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;
const int64_t offload0 = drive.d.offload_entries; // #588
pcie_auto.mark(drive.d.ms_run, drive.d.multi_misses); // the prompt's windows are not the decode's
if (cancelled) finish = "cancel";
if (cancelled) finish = nf_hit ? "nonfinite" : "cancel";
// ======== --pipeline-windows 2: the decode windows with the two cards overlapped ========
// Stage 0 (the first card) runs window K+1 while stage 1 verifies window K, on the guess that K is accepted
// whole and that its bonus token is the drafter's. The drafter, teacher-forced through K+1's drafts,
@@ -11565,8 +11659,9 @@ int main(int argc, char** argv) {
if (drive.d.fs) drive.d.fs->completed.fetch_add(1, std::memory_order_release);
++dec_windows;
dec_T += A.T;
const bool nf = nonfinite_hit(V1(A), "decode"); // #879: none of its tokens goes out
bool eos = false;
for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) {
for (int i = 0; !nf && i <= a && produced_n < max_new && !eos; ++i) {
std::printf("T %d\n", (int) outp[(size_t) i]);
strata::core::progress_beat();
++produced_n;
@@ -11574,10 +11669,11 @@ int main(int argc, char** argv) {
eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outp[(size_t) i]) != o.eos_ids.end();
}
std::fflush(stdout);
if (eos) finish = "stop";
if (nf) finish = "nonfinite";
else if (eos) finish = "stop";
else if (stop_req.load()) finish = "cancel";
const bool last = eos || produced_n >= max_new || stop_req.load();
const bool on = B.launched && a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1];
const bool last = nf || eos || produced_n >= max_new || stop_req.load();
const bool on = !nf && B.launched && a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1];
if (B.made) { // the gate's calibration: would B have been on the path, by its estimate p_on
const bool would = a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1];
const int bin = std::min(9, std::max(0, (int) (B.p_on * 10.0f)));
@@ -11837,6 +11933,15 @@ int main(int argc, char** argv) {
std::printf("ERR %s\n", err.c_str());
return 1;
}
if (nonfinite_hit(ver, first_window ? "first decode" : "decode")) { // #879: none of its tokens goes out
if (adapt_thr.joinable()) adapt_thr.join();
if (!adapt_ok) {
std::printf("ERR an adaptive refill failed\n");
return 1;
}
finish = "nonfinite";
break;
}
// the window's first a + 1 tokens are in the session now (the last output is not: it is next x)
for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]);
draft_offered += T - 1;
@@ -11948,7 +12053,9 @@ int main(int argc, char** argv) {
live.swap(consumed);
live_imgs = imgs_below(req_imgs, (int64_t) live.size());
live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830)
} else if (pp_exact && pp_reached > 0 && o.prompt_cache > 0 && req_ckpt && pp_reached <= (int64_t) cur.size()) {
if (nf_hit) live_ok = false; // #879 (the next request's start drops the rest)
} else if (!nf_hit && pp_exact && pp_reached > 0 && o.prompt_cache > 0 && req_ckpt &&
pp_reached <= (int64_t) cur.size()) {
// #1620: stopped between two windows (or before the first token was read): the session is exactly at
// pp_reached, so it stays the live conversation - the next request continues from it or parks it.
// Without this a cancelled request that had restored a parked conversation dropped it.