serve: the thinking budget's hold on --batch engines (BGEN slots)

P2 ended the budget's first pass exactly at the budget for a solo request; a --batch engine kept the old behaviour (the server sent no hold to it), so there the second pass still read the whole reasoning again in 8-9 of 21-24 budget turns (p1004, --batch 2: base 9 of 24, head 8 of 21, PERF-AUDIT's R9700 and l620 runs the same shape).

Engine (src/program/generate.cpp, include/strata/core/serve_stop_bound.hpp): a slot carries the hold (SlotHold: on / n / id). BGEN hold=N:ID is parsed by the GEN path the admission runs; at the handover the slot takes the hold unless the admission's one token was </think>, and an admission whose hold is that one token ends there (DONE hold, no slot). In the slot windows the rows a window may commit stop at the hold (slot_cap(), in the MTP window, the pipelined MTP window's proposal count and the DFlash2 draft count), a slot ends with BDONE hold after exactly N emitted tokens unless ID was emitted first, and its sessions then hold exactly the tokens it fed, as in the solo case. The cap is the conservative one for a window that might emit ID: it stops at the hold and the next window goes on. READY says "stop hold holdb"; "holdb" is a protocol token only (no user-visible line, no setting).

Server (serve/server.py): the budget sends the hold to a --batch engine only when its READY says holdb (can_hold_batch); generate_batched adds the key per leg with the tokens the pass has already sent taken off (a solo leg promoted to a slot continues with hold=N-k, none once </think> was sent), and a leg that ends with finish "hold" ends the pass.

Tests: tests/core/serve_stop_bound_test.cpp (slot windows of changing width against a per-token reference over a whole reply: 75,360 cases; same tokens, same finish, no row committed past what was emitted, the hold ending at exactly N unless ID came first); serve/test_thinking_hold_batch.py (a fake --batch engine with the hold: solo path, a request admitted into a slot, a solo leg promoted to a slot with the count falling, first-N tokens of the unheld reply for N = 1 ... 53, hold ended by its token); serve/test_thinking_hold.py (stub engine with holdb).

The slot-model case failed on its first run (first=0 hold=1 max_new=3 id_at=0: got 7777 101 103, reference 7777 101 102). The test model was wrong, not the engine: it read a window's rows with `produced`, which it increments while the window is emitted, so it skipped a row; the engine emits from fixed arrays (outb[first + j]). Fixed in the test with a base index; the engine code was not changed by that run.

Mixed versions, both covered: new server + old engine (an engine without hold, and one with hold but no holdb, get no key when they run --batch; the budget cuts and STOPs as before) in test_thinking_hold.py, and old server + new engine (the extra READY tokens change nothing it reads, a request without a key runs as before through the solo path and through a slot) in test_thinking_hold_batch.py. Real-engine cross runs of P2 (head engine + base server, base engine + head server) were done on p1004 before this commit.

Lane AGENT-TURN, P2b.
This commit is contained in:
Niko1221 committed 2026-11-11 21:22:34 +01:00
1 parent 77c344bdd0
commit b92075d924
6 files changed
+351 -15

No files matched your search

+28
View File
@@ -29,6 +29,34 @@ int64_t serve_hold_remaining(int accepted, int64_t produced, int64_t max_new, in
return cap;
}
// --batch slot (P2b): the same hold for one slot of the batch windows. A slot emits through windows of its own (one row, or one
// row plus its accepted proposals), so the hold is a per-slot state: on until ID is emitted, n = the emitted tokens (counted from
// the request's start, the admission's first token included) after which the slot ends with finish "hold" and its sessions at exactly
// what it fed (all emitted tokens but the last). The cap below is conservative for a window that might emit ID: the rows of that window
// stop at the hold, and the next window (hold off) goes on - never more rows than the unconditional cap, never fewer than one.
struct SlotHold {
bool on = false;
int64_t n = 0;
int64_t id = -1;
};
inline SlotHold slot_hold_from(long long hold_n, long long hold_id, bool on) {
SlotHold h;
h.on = on && hold_n > 0 && hold_id >= 0;
h.n = hold_n;
h.id = hold_id;
return h;
}
// the tokens a slot may emit in all before its next window decides again (max_new, or the hold while it is on)
inline int64_t slot_cap(int64_t max_new, const SlotHold& h) { return h.on ? std::min(max_new, h.n) : max_new; }
// a token y was emitted: the hold is over when it is ID
inline void slot_hold_emitted(SlotHold& h, int64_t y) {
if (h.on && y == h.id) h.on = false;
}
// the slot reached its hold (ID not emitted, max_new not reached): BDONE says "hold"
inline bool slot_hold_reached(const SlotHold& h, int64_t produced, int64_t max_new) {
return h.on && produced >= h.n && produced < max_new;
}
// #4677: the bound is on by default on every backend; STRATA_SERVE_STOP_BOUND=0 (the variable's value, passed in)
// turns it off. It only limits which accepted rows enter the cached conversation: the tokens a request emits are the
// same either way.
+19 -8
View File
@@ -1166,6 +1166,7 @@ class StrataEngine:
self.max_context = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 4096
self.can_stop = False # the engine honours a STOP line mid-request (READY <ctx> stop)
self.can_hold = False # the engine takes GEN hold=N:ID (READY <ctx> ... hold)
self.can_hold_batch = False # ... and its --batch slots end at the hold too, BDONE hold (READY ... holdb)
self.last = {}
self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)
self.terminal_stages: list[dict] = [] # final layer ranges from this engine start's bounded stderr log
@@ -1250,6 +1251,7 @@ class StrataEngine:
self.max_context = int(f[1])
self.can_stop = "stop" in f[2:]
self.can_hold = "hold" in f[2:]
self.can_hold_batch = "holdb" in f[2:]
self.multi = next((int(x[6:]) for x in f[2:] if x.startswith("multi=") and x[6:].isdigit()), 0)
break
loading.set()
@@ -2254,7 +2256,8 @@ class StrataEngine:
raise EngineDied("the engine is unavailable; this request was not sent")
self.progress, self.progress_ms, self.reused = None, 0, 0
born = self.gen # the engine process this request is sent to
keys = self.sampling_keys(sampling or {})
hold = (sampling or {}).get(HOLD_KEY) # the thinking budget's hold (P2b): the reasoning tokens left when this pass starts, and </think>'s id
keys0 = self.sampling_keys({k: v for k, v in (sampling or {}).items() if k != HOLD_KEY}) # (the hold's key goes on per leg: leg_keys below)
# logprobs: only an admission's token can have an LP line here (the slot's "BT" lines carry none), so the
# server refuses these requests unless max_tokens is 1. The lines go to the request itself, through its
# cancel Event: several requests read control lines at once, and the engine's lp_lines is one attribute.
@@ -2264,6 +2267,13 @@ class StrataEngine:
out: list[int] = []
pending: list[int] = []
prompt, left = list(ids), int(max_new)
def leg_keys() -> str:
"""The budget's hold counts what this pass still has: a leg that starts after `out` tokens of it holds the rest (at least one);
once </think> is in `out` the hold is over and no key goes."""
if isinstance(hold, tuple) and len(hold) == 2 and hold[0] > 0 and hold[1] >= 0 and hold[1] not in out:
return keys0 + f" hold={max(1, hold[0] - len(out))}:{hold[1]}"
return keys0
orig_len = len(prompt) # a leg that continues (prompt + what it generated) names where the reply began: pen_from, the penalty window's start
reused0 = None # the first read's reused tokens: a continued leg's count includes this request's own output
carry = {} # #1869: the figures of the legs that ended in a hand-back to the solo path (the final DONE adds to them)
@@ -2298,7 +2308,7 @@ class StrataEngine:
alone = not any(self.slot_busy) and self.waiting == 0
if alone and left > 1:
pf = self.pen_from_key(orig_len, len(prompt))
head = f"GENI {left}{keys}{pf} {embeddings}" if embeddings else f"GEN {left}{keys}{pf}"
head = f"GENI {left}{leg_keys()}{pf} {embeddings}" if embeddings else f"GEN {left}{leg_keys()}{pf}"
self._last_done = None # (#879: this request's DONE decides below)
deadline = getattr(cancel, "_strata_queue_deadline", None)
if deadline is not None and time.monotonic() >= deadline:
@@ -2355,8 +2365,8 @@ class StrataEngine:
if slot is None:
finish = (self.last or {}).get("finish") if isinstance(self.last, dict) else None
left = int(max_new) - len(out)
if cancel.is_set() or left <= 0 or finish in ("stop", "length") or (out and out[-1] in EOS_IDS):
return
if cancel.is_set() or left <= 0 or finish in ("stop", "length", "hold") or (out and out[-1] in EOS_IDS):
return # ("hold": the budget's cut: the caller wraps up or asks for more)
if reused0 is None:
reused0 = (self.last or {}).get("reused")
carry_leg(carry, self.last) # #1869: the solo leg's figures; the slot's admission (a copy of
@@ -2432,7 +2442,7 @@ class StrataEngine:
while not sq[slot].empty():
sq[slot].get_nowait()
pf = self.pen_from_key(orig_len, len(prompt))
head = f"BGENI {slot} {left}{keys}{pf} {embeddings}" if embeddings else f"BGEN {slot} {left}{keys}{pf}"
head = f"BGENI {slot} {left}{leg_keys()}{pf} {embeddings}" if embeddings else f"BGEN {slot} {left}{leg_keys()}{pf}"
live = {"slot": slot, "request_id": getattr(cancel, "_strata_request_id", None),
"state": "reading", "prompt_tokens": len(prompt), "prompt_read": 0, "generated": 0,
"started": time.time(), "first_token": None}
@@ -6489,10 +6499,11 @@ class Service:
before = getattr(self.engine, "last", None)
last_print = time.time()
prompt, thought = ids, 0 # thought: the reasoning tokens so far (the budget's count)
# the engine stops at the budget itself (HOLD_KEY), when it can and </think> is one token: one engine
# at a time (a --batch engine's slots and a multi engine take no hold)
# the engine stops at the budget itself (HOLD_KEY), when it can and </think> is one token: a --batch engine
# only when its slots say they hold too (READY holdb); a multi engine takes no hold
hold_end = None
if (budget and getattr(self.engine, "can_hold", False) is True and not getattr(self.engine, "batch", 0)
if (budget and getattr(self.engine, "can_hold", False) is True
and (not getattr(self.engine, "batch", 0) or getattr(self.engine, "can_hold_batch", False) is True)
and not getattr(self.engine, "multi", 0)):
te = self.tok.encode(THINK_END, parse_special=True)
hold_end = te[0] if len(te) == 1 else None
+31 -2
View File
@@ -31,10 +31,11 @@ class WindowEngine:
THOUGHT = "Let me think step by step about two plus two. " * 4
ANSWER = "The answer is 4."
def __init__(self, tok, windows=(3, 2, 4), overrun=True, can_hold=True, honours_hold=True, thought=None):
def __init__(self, tok, windows=(3, 2, 4), overrun=True, can_hold=True, honours_hold=True, thought=None, can_hold_batch=False):
self.tok, self.max_context = tok, 4096
self.windows, self.overrun = windows, overrun
self.can_hold, self.honours_hold = can_hold, honours_hold
self.can_hold_batch = can_hold_batch # READY says holdb: the --batch slots end at the hold too (P2b)
self.batch = self.multi = 0
self.thought = thought if thought is not None else self.THOUGHT
self.start = tok.encode("<|im_start|>", parse_special=True)[0]
@@ -216,12 +217,40 @@ class ThinkingHold(HoldCase):
self.assertEqual(len(self.engine.passes), 1)
self.assertIsNone(self.engine.passes[0]["hold"])
def test_a_batch_engine_gets_no_hold(self):
def test_a_batch_engine_whose_slots_do_not_say_holdb_gets_no_hold(self):
self.start()
self.engine.batch = 4
self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
self.assertTrue(all(p["hold"] is None for p in self.engine.passes))
def test_new_server_old_engine_no_token_no_hold_for_a_batch_engine(self):
"""Mixed versions, new server + old engine: an engine that says neither hold nor holdb (before P2), and one that says hold but
not holdb (P2 without P2b), get no key when they run --batch; the budget then cuts and STOPs as it always did."""
for kw in ({"can_hold": False}, {"can_hold": True}, {"can_hold": False, "can_hold_batch": True}):
with self.subTest(**kw):
self.start(**kw)
self.engine.batch = 4
self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
self.assertTrue(all(p["hold"] is None for p in self.engine.passes))
def test_a_batch_engine_that_says_holdb_gets_the_hold(self):
"""P2b: a --batch engine whose slots end at the hold (READY holdb) gets the key like a solo engine: the second pass reads the last
reasoning token and the wrap-up, as in the solo case."""
self.start(can_hold_batch=True)
self.engine.batch = 4
self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
passes = self.engine.passes
self.assertEqual(len(passes), 2)
self.assertEqual(passes[0]["hold"], (20, self.tok.encode("</think>", parse_special=True)[0]))
wrap = len(self.tok.encode(REASONING_WRAP_UP, parse_special=True))
self.assertEqual((passes[1]["reused"], passes[1]["read"]), (passes[0]["prompt"] + 20 - 1, 1 + wrap))
def test_holdb_does_not_matter_without_batch_and_a_multi_engine_gets_none(self):
self.start(can_hold_batch=True)
self.engine.multi = 2
self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
self.assertTrue(all(p["hold"] is None for p in self.engine.passes))
class HoldKey(unittest.TestCase):
def test_the_gen_key(self):
+184
View File
@@ -0,0 +1,184 @@
"""The thinking budget's hold on a --batch engine (lane AGENT-TURN, P2b): GEN / BGEN hold=N:ID reaches the batch slots too.
The fake engine of test_parallel.py (a script speaking GEN / BGEN / T / DONE / BADM / BT / BDONE / BSTOP) is given the engine's side of the
hold, as generate.cpp has it: READY says "hold holdb"; a solo GEN ends after N emitted tokens unless token ID came first (DONE hold); a BGEN's
admission token counts toward N and its slot ends with BDONE hold at exactly N; once ID is emitted the hold is over. What is tested is the
server: the key's count falls by what an earlier leg of the same pass already sent (the solo leg promoted to a slot), the finish "hold" ends
the pass, no key goes to an engine whose READY lacks holdb, and the tokens of a held pass are exactly the first N of the unheld reply."""
from __future__ import annotations
import sys
import threading
import time
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from serve.server import HOLD_KEY # noqa: E402
from serve.test_parallel import FAKE_BATCH, FakeEngineCase # noqa: E402
def with_hold(script: str, says_holdb: bool = True) -> str:
"""FAKE_BATCH with the engine's hold (every replaced text must be there once: a change of the fake fails loudly here)."""
def swap(text, old, new):
assert text.count(old) == 1, old
return text.replace(old, new)
s = swap(script, 'print("READY 4096 stop", flush=True)', 'print("READY 4096 stop hold%s", flush=True)' % (" holdb" if says_holdb else ""))
s = swap(s, ' ids = f[-1].split(",")\n',
' ids = f[-1].split(",")\n'
' hold = next(((int(x[5:].split(":")[0]), int(x[5:].split(":")[1])) for x in f if x.startswith("hold=")), None)\n')
s = swap(s, 'log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)}\\n"); log.flush()',
'log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)} hold={hold[0] if hold else None}:{hold[1] if hold else None}\\n"); log.flush()')
s = swap(s, " out = 0\n for t in toks[:n]:\n if stop.is_set():\n break\n print(f\"T {t}\", flush=True)\n out += 1\n time.sleep(STEP)\n"
" fin = \"stop\" if out and toks[out - 1] == 257 else (\"cancel\" if stop.is_set() else \"length\")\n",
" out = 0\n hold_on = hold is not None\n for t in toks[:n]:\n if stop.is_set():\n break\n"
" if hold_on and out >= hold[0]:\n break\n"
" print(f\"T {t}\", flush=True)\n out += 1\n if hold_on and t == hold[1]:\n hold_on = False\n time.sleep(STEP)\n"
" fin = \"stop\" if out and toks[out - 1] == 257 else (\"cancel\" if stop.is_set() else "
"\"hold\" if hold_on and out >= hold[0] and (out < n or slot is not None) else \"length\")\n")
s = swap(s, " active[slot] = [toks[1:], max_new, 1]\n", " active[slot] = [toks[1:], max_new, 1, hold, hold_on]\n")
s = swap(s, " left, max_new, produced = active[b]\n", " left, max_new, produced, hold, hold_on = active[b]\n")
s = swap(s, " print(f\"BT {b} {t}\", flush=True)\n if t == 257 or produced >= max_new:\n"
" fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length'\n",
" print(f\"BT {b} {t}\", flush=True)\n if hold_on and t == hold[1]:\n hold_on = False\n"
" if t == 257 or produced >= max_new or (hold_on and produced >= hold[0]):\n"
" fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length' if produced >= max_new else 'hold'\n")
s = swap(s, " active[b] = [left, max_new, produced]\n", " active[b] = [left, max_new, produced, hold, hold_on]\n")
return s
REPLY = list(b"ok, " + b"la " * 15 + b"done.") + [257] # what the fake engine says to a prompt with LONGREPLY in it (then <|im_end|>)
NO_ID = 199 # a token the reply never has: the hold stays on
COMMA = ord(",") # the reply's third token: the hold ends there
class HoldBatchCase(FakeEngineCase):
def start_hold(self, slots=2, says_holdb=True, **kw):
import serve.test_parallel as tp
old = tp.FAKE_BATCH
tp.FAKE_BATCH = with_hold(FAKE_BATCH, says_holdb)
try:
self.start(slots, **kw)
finally:
tp.FAKE_BATCH = old
def run_pass(self, text, max_new, hold):
"""One engine pass through generate (the real StrataEngine.generate -> generate_batched): -> (tokens, finish)"""
ids = list(text.encode())
cancel = threading.Event()
sampling = {HOLD_KEY: hold} if hold else {}
out = [t for t in self.engine.generate(ids, max_new, sampling, cancel) if t is not None]
return out, (self.engine.last or {}).get("finish")
def requests(self):
return [ln.split() for ln in self.log.read_text().splitlines()] if self.log.exists() else []
class SoloAndSlots(HoldBatchCase):
def test_a_batch_engine_says_holdb_in_ready(self):
self.start_hold()
self.assertTrue(self.engine.can_hold)
self.assertTrue(self.engine.can_hold_batch)
def test_an_engine_without_holdb_says_so(self):
self.start_hold(says_holdb=False)
self.assertTrue(self.engine.can_hold)
self.assertFalse(self.engine.can_hold_batch)
def test_old_server_new_engine_the_tokens_are_ignored_and_no_key_means_no_hold(self):
"""Mixed versions, old server + new engine: the server before P2 reads READY with `"stop" in f[2:]` and sends no hold key. The new
engine's extra READY tokens change nothing it reads (can_stop, the context), and a request with no key runs as it always did,
through the solo path and through a slot."""
self.start_hold()
self.assertTrue(self.engine.can_stop)
self.assertEqual(self.engine.max_context, 4096)
results = {}
def first():
results["first"] = self.run_pass("LONGREPLY first", 64, None)
t = threading.Thread(target=first)
t.start()
time.sleep(0.15)
results["second"] = self.run_pass("LONGREPLY second", 64, None) # admitted into a slot
t.join(30)
self.assertEqual(results["first"][0], REPLY)
self.assertEqual(results["second"][0], REPLY)
self.assertEqual({results["first"][1], results["second"][1]}, {"stop"})
self.assertTrue(any(r[0] == "BGEN" for r in self.requests()))
self.assertTrue(all(r[-1] == "hold=None:None" for r in self.requests()))
def test_alone_the_solo_path_ends_at_the_hold(self):
self.start_hold()
got, finish = self.run_pass("LONGREPLY please", 64, (12, NO_ID))
self.assertEqual(got, REPLY[:12])
self.assertEqual(finish, "hold")
gen = [r for r in self.requests() if r[0] == "GEN"]
self.assertEqual(len(gen), 1)
self.assertEqual(gen[0][-1], "hold=12:%d" % NO_ID)
def test_the_hold_ends_when_its_token_comes_first(self):
self.start_hold()
got, finish = self.run_pass("LONGREPLY please", 64, (12, COMMA))
self.assertEqual(got, REPLY) # </think> came at the third token: the pass runs on to its own end
self.assertEqual(finish, "stop")
def test_no_hold_no_key(self):
self.start_hold()
got, finish = self.run_pass("LONGREPLY please", 64, None)
self.assertEqual(got, REPLY)
self.assertTrue(all(r[-1] == "hold=None:None" for r in self.requests()))
def test_a_request_that_goes_to_a_slot_ends_at_the_hold(self):
"""Another request holds the solo path: this one is admitted into a slot (BGEN) and its slot ends with BDONE hold at exactly N."""
self.start_hold()
results = {}
def first():
results["first"] = self.run_pass("LONGREPLY first", 64, None)
t = threading.Thread(target=first)
t.start()
time.sleep(0.15)
got, finish = self.run_pass("LONGREPLY second", 64, (20, NO_ID))
t.join(30)
self.assertEqual(got, REPLY[:20])
self.assertEqual(finish, "hold")
self.assertEqual(results["first"][0], REPLY)
bgen = [r for r in self.requests() if r[0] == "BGEN" and r[-1].startswith("hold=20")]
self.assertEqual(len(bgen), 1, self.requests())
def test_a_solo_leg_promoted_to_a_slot_holds_what_is_left(self):
"""The pass starts alone (GEN, hold=N), another request arrives, the pass is stopped and goes on in a slot: its key counts the tokens
the solo leg already sent, and the pass still ends at exactly N tokens in all."""
self.start_hold()
results = {}
def first():
results["first"] = self.run_pass("LONGREPLY first", 64, (40, NO_ID))
t = threading.Thread(target=first)
t.start()
time.sleep(0.15)
other = self.run_pass("LONGREPLY other", 64, None)
t.join(30)
got, finish = results["first"]
self.assertEqual(got, REPLY[:40])
self.assertEqual(finish, "hold")
self.assertEqual(other[0], REPLY)
keys = [r[-1] for r in self.requests() if r[0] in ("GEN", "BGEN") and r[-1] != "hold=None:None"]
self.assertEqual(keys[0], "hold=40:%d" % NO_ID)
legs = [int(k.split("=")[1].split(":")[0]) for k in keys]
self.assertTrue(all(n <= 40 for n in legs) and legs == sorted(legs, reverse=True), keys)
def test_the_tokens_of_a_held_pass_are_the_first_n_of_the_unheld_reply(self):
self.start_hold()
for n in (1, 2, 3, 10, 30, 53):
with self.subTest(n=n):
got, finish = self.run_pass("LONGREPLY please", 64, (n, NO_ID))
self.assertEqual(got, REPLY[:n])
self.assertEqual(finish, "hold")
if __name__ == "__main__":
unittest.main()
+14 -5
View File
@@ -14115,7 +14115,7 @@ int main(int argc, char** argv) {
strata::core::pin_sim_report("at READY");
strata::core::pin_reserve_release_hard(); // the load is over: nothing else needs the headroom
strata::core::manifest::instance().write("ready"); // STRATA_MANIFEST (a no-op unless it is set)
std::printf("READY %lld stop hold\n", (long long) o.max_context); // "stop": this engine honours STOP; "hold": GEN hold=N:ID
std::printf("READY %lld stop hold holdb\n", (long long) o.max_context); // "stop": this engine honours STOP; "hold": GEN hold=N:ID; "holdb": the --batch slots end at the hold too (BDONE hold)
std::fflush(stdout);
std::string line;
int64_t rounds = 0;
@@ -14307,6 +14307,7 @@ int main(int argc, char** argv) {
int n_drafts = 1; ///< STRATA_PIPED_MTP: how many of `draft` its next window checks
int64_t p = 0; ///< its position
int64_t produced = 0, max_new = 0;
strata::core::SlotHold hold; ///< GEN / BGEN hold=N:ID (the server's thinking budget): the slot ends with BDONE "hold" after N emitted tokens unless ID came first
Clock::time_point t0;
// the slot's own conversation cache: the tokens its sessions hold (the prompt, then every token a window
// fed). Kept when the request ends (`cached`), so the next turn of that conversation continues from it
@@ -14630,7 +14631,7 @@ int main(int argc, char** argv) {
const BSlot& q = bs[(size_t) act_ids[k]];
int want = spare / nact + (k < spare % nact ? 1 : 0);
want = std::min(want, (int) strata::core::Dflash2Drafter::kDrafts);
want = std::min<int>(want, (int) std::max<int64_t>(0, q.max_new - q.produced - 1));
want = std::min<int>(want, (int) std::max<int64_t>(0, strata::core::slot_cap(q.max_new, q.hold) - q.produced - 1));
want = std::min<int>(want, (int) std::max<int64_t>(0, (int64_t) o.max_context - q.p - 2));
want = std::min(want, df2_cap);
if (q.draft_ready && df2_conf > 0.0) { // a draft row is worth its cost where the chain so far is likely: the product of the selector's probabilities
@@ -14761,7 +14762,7 @@ int main(int argc, char** argv) {
int kp = 1; // the proposals the target picked, in order: row j + 1 stands when the target's pick after row j is its token and nothing ended
while (batch_mtp && kp < nrow[a] && outb[i + kp - 1] == tok[i + kp] && !sl.stop &&
std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outb[i + kp - 1]) == o.eos_ids.end() &&
sl.produced + kp + 1 <= sl.max_new && sl.p + kp + 2 <= o.max_context)
sl.produced + kp + 1 <= strata::core::slot_cap(sl.max_new, sl.hold) && sl.p + kp + 2 <= o.max_context)
++kp;
keep[b] = kp;
}
@@ -14801,8 +14802,10 @@ int main(int argc, char** argv) {
sl.ids.push_back(tok[first[t] + j]);
std::printf("BT %d %d\n", b, (int) y);
++sl.produced;
strata::core::slot_hold_emitted(sl.hold, (int64_t) y);
const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
: strata::core::slot_hold_reached(sl.hold, sl.produced, sl.max_new) ? "hold"
: sl.p + 2 > o.max_context ? "length" : nullptr;
if (fin != nullptr) {
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
@@ -15106,7 +15109,9 @@ int main(int argc, char** argv) {
++sl.produced;
++bt_rows;
++pipe_rows;
strata::core::slot_hold_emitted(sl.hold, (int64_t) y);
const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
: strata::core::slot_hold_reached(sl.hold, sl.produced, sl.max_new) ? "hold"
: sl.p + 2 > o.max_context ? "length" : nullptr;
sl.ids.push_back(G.tok[blk.f + j]);
if (fin != nullptr) {
@@ -15250,8 +15255,10 @@ int main(int argc, char** argv) {
++sl.produced;
++bt_rows;
++pipe_rows;
strata::core::slot_hold_emitted(sl.hold, (int64_t) y);
const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
: strata::core::slot_hold_reached(sl.hold, sl.produced, sl.max_new) ? "hold"
: sl.p + 2 > o.max_context ? "length" : nullptr;
sl.ids.push_back(sl.x);
if (fin != nullptr) {
@@ -15323,7 +15330,7 @@ int main(int argc, char** argv) {
G.pos[G.S] = sl.p;
++G.S;
int nd = sl.draft_ready && !sl.stop ? sl.n_drafts : 0;
nd = (int) std::min<int64_t>(nd, std::min<int64_t>(sl.max_new - sl.produced - 1,
nd = (int) std::min<int64_t>(nd, std::min<int64_t>(strata::core::slot_cap(sl.max_new, sl.hold) - sl.produced - 1,
o.max_context - sl.p - 2));
for (int j = 0; j < nd; ++j) {
G.rows[G.S] = b;
@@ -19510,7 +19517,8 @@ int main(int argc, char** argv) {
p += a + 1;
}
// GEN hold=N:ID reached (ID not emitted): the server wraps up the thinking or asks for more
if (hold_on && std::strcmp(finish, "length") == 0 && produced_n >= req_hold_n && produced_n < max_new) finish = "hold";
// (a --batch admission is a GEN of one token whose hold may be that one token: the slot must not start then)
if (hold_on && std::strcmp(finish, "length") == 0 && produced_n >= req_hold_n && (produced_n < max_new || admit_slot >= 0)) finish = "hold";
if (!keep_sync()) { std::printf("ERR %s\n", err.c_str()); return 1; }
const double decode_ms = std::chrono::duration<double, std::milli>(Clock::now() - d0).count();
if (use_df2 && o.draft_auto && bandit_key != 0 && produced_n >= 48 && decode_ms > 0.0) {
@@ -19777,6 +19785,7 @@ int main(int argc, char** argv) {
sl.p = p;
sl.produced = 1;
sl.max_new = admit_max_new;
sl.hold = strata::core::slot_hold_from(req_hold_n, req_hold_id, hold_on); // the thinking budget goes on in the slot's windows (hold_on: the first token was not ID)
sl.t0 = Clock::now();
sl.ids = live;
{ // the penalty window of the slot's decode: the reply, from the last prompt token (the first window fed it), as the solo loop counts it
+75
View File
@@ -3,6 +3,7 @@
#include "strata/core/serve_stop_bound.hpp"
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
int main() {
@@ -64,6 +65,80 @@ int main() {
++hold_cases;
}
std::cout << "SUMMARY hold cases=" << hold_cases << " passed\n";
// --batch slots (P2b): the slot's windows (SlotHold helpers) against an independent per-token reference, over a whole reply
// of several windows of changing width: same tokens, same finish, the commit never past what was emitted, the hold ending at
// exactly N unless ID came first. (A window may stop at the hold while ID is still in its rows: the next window goes on.)
int slot_cases = 0;
const int widths[4] = {1, 3, 2, 4};
for (int first = 0; first < 4; ++first)
for (int hold = 1; hold <= 10; ++hold)
for (int max_new = 1; max_new <= 12; ++max_new)
for (int id_at = -1; id_at < 12; ++id_at)
for (int eos = -1; eos < 12; ++eos) {
if (eos >= 0 && eos == id_at) continue;
if (hold > 12) continue;
std::vector<int> stream(14);
for (int i = 0; i < 14; ++i) stream[i] = i == eos ? -1 : i == id_at ? ID : 100 + i;
// reference: one token at a time
std::vector<int> ref;
std::string ref_fin;
{
bool on = true;
for (int i = 0; i < 14; ++i) {
ref.push_back(stream[i]);
if (stream[i] == ID) on = false;
const int produced = static_cast<int>(ref.size());
if (stream[i] == -1) { ref_fin = "stop"; break; }
if (produced >= max_new) { ref_fin = "length"; break; }
if (on && produced >= hold) { ref_fin = "hold"; break; }
}
}
// the slot: windows of widths[...] rows, the cap per window as generate.cpp has it
strata::core::SlotHold h = strata::core::slot_hold_from(hold, ID, true);
std::vector<int> got;
std::string fin;
int64_t produced = 0, committed_rows = 0;
for (int w = first; fin.empty() && produced < 14; ++w) {
const int nrow = widths[w % 4];
int kp = 1; // the proposals the target picked, in order (here: all of them), and nothing ended
while (kp < nrow && produced + kp < 14 && stream[produced + kp - 1] != -1 &&
produced + kp + 1 <= strata::core::slot_cap(max_new, h))
++kp;
committed_rows += kp;
const int64_t base = produced; // (the window's rows start here; `produced` counts on while they are emitted)
for (int j = 0; j < kp; ++j) {
const int y = stream[base + j];
got.push_back(y);
++produced;
strata::core::slot_hold_emitted(h, y);
if (y == -1) fin = "stop";
else if (produced >= max_new) fin = "length";
else if (strata::core::slot_hold_reached(h, produced, max_new)) fin = "hold";
if (!fin.empty()) break;
}
}
if (got != ref || fin != ref_fin) {
std::cerr << "MISMATCH first=" << first << " hold=" << hold << " max_new=" << max_new << " id_at=" << id_at << " eos=" << eos
<< " got:";
for (int y : got) std::cerr << ' ' << y;
std::cerr << " (" << fin << ") ref:";
for (int y : ref) std::cerr << ' ' << y;
std::cerr << " (" << ref_fin << ")\n";
}
assert(got == ref);
assert(fin == ref_fin);
assert(committed_rows == static_cast<int64_t>(got.size())); // not one row committed past what was emitted
if (fin == "hold") {
assert(static_cast<int>(got.size()) == hold);
for (int y : got) assert(y != ID);
}
// no hold: the hold helpers change nothing
assert(strata::core::slot_cap(max_new, strata::core::SlotHold{}) == max_new);
++slot_cases;
}
assert(!strata::core::slot_hold_from(5, -1, true).on && !strata::core::slot_hold_from(0, ID, true).on &&
!strata::core::slot_hold_from(5, ID, false).on && strata::core::slot_hold_from(5, ID, true).on);
std::cout << "SUMMARY slot hold cases=" << slot_cases << " passed\n";
// on unless the variable is exactly "0" (every backend, since the bound left HIP-only)
assert(strata::core::serve_stop_bound_on(nullptr));
assert(strata::core::serve_stop_bound_on("1"));