serve: the thinking budget's hold (GEN hold=N:ID), so the wrap-up pass continues from the live session

At the thinking budget the server cut the stream, STOPped the engine and sent a second engine request: the same prompt + the tokens it kept + the wrap-up. The engine sees STOP only at a window's end and commits each window before sending it, so it often held one or more tokens past the cut; its live session was then not a prefix of the second request, which fell back to the checkpoint before the assistant turn, parked the live branch and read the whole reasoning again (lane PERF-AUDIT, R9700 0.1.59: 4 of 9 budget turns, 535 tokens, 849-1000 ms against 85-96 ms).

Engine: GEN key hold=N:ID ends the request after N emitted tokens unless token ID (</think>) came first; the commit is capped there (serve_hold_remaining() + serve_stop_bound(), tested against the emission loop in serve_stop_bound_test), DONE finish "hold", READY says "stop hold". Without the key nothing changes; an older engine skips the key.
Server: sends hold=<budget - thought>:<</think> id> (HOLD_KEY, its own key, never a client's) only to an engine that says hold in READY, has no --batch slots and is not a multi engine, and only when </think> is one token. At DONE hold it wraps up if the point is clean; if not (a character split across tokens, a tag held back) one more pass from the live session with a hold of the tokens left (at least one). The second pass then reads the last token and the wrap-up only. Tested with a windowed stub engine in serve/test_thinking_hold.py: the answer is the same with and without the hold for every budget; an engine that does not say hold gets no key; one that says it but ignores it gives the same answer.
--batch engines (BGEN slots) are a separate path: not covered here, no hold is sent to them.

Lane AGENT-TURN, P2.
This commit is contained in:
Niko1221 committed 2026-11-11 16:18:59 +01:00
1 parent 5e41f69844
commit be101072ba
5 files changed
+358 -15

No files matched your search

+15
View File
@@ -14,6 +14,21 @@ int serve_stop_bound(int accepted, int64_t remaining, const Token* outputs, IsEo
return count;
}
// GEN hold=N:ID (the server's thinking budget): the request ends after N emitted tokens unless token ID (</think>) came
// first, and the session keeps exactly what it emitted, so the server's next pass - the same prompt plus those tokens plus
// its wrap-up - continues from the live session instead of a checkpoint before the reasoning. The rows a window may still
// emit (`remaining` for serve_stop_bound): up to the hold, unless ID is among the outputs before it, else up to max_new.
// hold_n <= 0 or hold_id < 0: no hold. `produced`: the tokens this request emitted before the window.
template<class Token>
int64_t serve_hold_remaining(int accepted, int64_t produced, int64_t max_new, int64_t hold_n, int64_t hold_id,
const Token* outputs) {
if (hold_n <= 0 || hold_id < 0) return max_new - produced;
const int64_t cap = std::min(max_new, hold_n) - produced;
for (int64_t i = 0; i < accepted && i < cap; ++i)
if (static_cast<int64_t>(outputs[i]) == hold_id) return max_new - produced;
return cap;
}
// #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.
+32 -2
View File
@@ -230,6 +230,11 @@ ANSWER_RESERVE_MIN = 512 # #984: the tokens kept for the answer when a think
# and no call, is continued once with the thinking closed (the same way the budget's wrap-up closes it)
REASONING_CLOSE = "\n</think>\n\n"
REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n"
# The budget's pass to an engine that says "hold" in READY carries GEN hold=N:ID (N: the reasoning tokens left, ID: the one
# token of </think>): the engine stops there with its session at exactly the tokens it sent, so the next pass (+ the wrap-up)
# continues from the live session. Without it the engine ran a window or two past the cut, and the next pass read the
# whole reasoning again from the checkpoint before it. The server's own key in `sampling`, never a client's.
HOLD_KEY = "_strata_hold"
# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see).
# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the
# low-effort instruction in place of the xhigh one. Both off by default.
@@ -1160,6 +1165,7 @@ class StrataEngine:
self.ended, self.unloaded = True, True
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.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
@@ -1243,6 +1249,7 @@ class StrataEngine:
f = line.split()
self.max_context = int(f[1])
self.can_stop = "stop" in f[2:]
self.can_hold = "hold" 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()
@@ -1702,6 +1709,11 @@ class StrataEngine:
ac = tune.get("aux_cpus")
if isinstance(ac, bool) or (isinstance(ac, (int, float)) and ac in (0, 1)):
keys += f" aux_cpus={int(ac)}"
# the thinking budget's hold (HOLD_KEY): set by the server for an engine that says "hold", never by a client
hold = sampling.get(HOLD_KEY)
if (isinstance(hold, tuple) and len(hold) == 2 and all(isinstance(x, int) and not isinstance(x, bool) for x in hold)
and hold[0] > 0 and hold[1] >= 0):
keys += f" hold={hold[0]}:{hold[1]}"
# "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request
# extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before.
if sampling.get("strata_checkpoint") is False:
@@ -6477,13 +6489,24 @@ 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)
hold_end = None
if (budget and getattr(self.engine, "can_hold", False) is True and not getattr(self.engine, "batch", 0)
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
for ev in opening:
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)
pass_sampling = {k: v for k, v in (sampling or {}).items() if k != HOLD_KEY}
held = hold_end is not None and budget is not None
if held: # the reasoning tokens left before the budget (at least one: a cut not yet clean)
pass_sampling[HOLD_KEY] = (max(1, int(budget) - thought), int(hold_end))
gen = self.engine.generate(prompt, max_new - n, pass_sampling, cancel, embeddings=emb) if emb \
else self.engine.generate(prompt, max_new - n, pass_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
@@ -6664,6 +6687,13 @@ class Service:
prompt = prompt + seg + extra
finish = "length"
continue
if (held and not (wrap or opens) and not cancel.is_set() and finish != "stop" and not repeated
and not looped and n < max_new and segments and segments[-1].get("finish") == "hold"
and len(segments) > segments_before):
# the engine stopped at the hold but the cut is not clean yet (a character split across
# tokens, a tag held back) or the reasoning count is short: on from the live session
prompt = prompt + seg
continue
if not (wrap or opens) or cancel.is_set():
break
# #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a
+237
View File
@@ -0,0 +1,237 @@
"""The thinking budget's hold (GEN hold=N:ID, lane AGENT-TURN P2): the budget's second engine pass continues from the
live session instead of reading the whole reasoning again.
The stub engine below behaves like the real one where it matters: it decodes in windows of several tokens, commits a
window before it sends its tokens, sees a STOP only at a window's end (and can run one more window before it does), and
keeps as its live session the prompt plus every token it sent but the last. A prompt that the live session is not a
prefix of falls back to the checkpoint at the previous prompt's last <|im_start|>. With the hold it stops exactly at
the hold and commits nothing past it, as serve_hold_remaining() does in the engine."""
from __future__ import annotations
import json
import sys
import unittest
import urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from serve.frontend import ChatTemplate # noqa: E402
from serve.server import HOLD_KEY, REASONING_WRAP_UP, ByteTokenizer, Service, StrataEngine, serve # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
class ThinkTokenizer(ByteTokenizer):
"""The byte tokenizer with <think> / </think> as one token each, as the real tokenizer has them."""
SPECIALS = ByteTokenizer.SPECIALS + ["<think>", "</think>"]
ALWAYS = ("<think>", "</think>")
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):
self.tok, self.max_context = tok, 4096
self.windows, self.overrun = windows, overrun
self.can_hold, self.honours_hold = can_hold, honours_hold
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]
self.think_end = tok.encode("</think>", parse_special=True)[0]
self.end = tok.encode("<|im_end|>", parse_special=True)
self.wrap = tok.encode(REASONING_WRAP_UP, parse_special=True)
self.live: list[int] = []
self.checkpoints: list[int] = []
self.turn: list[int] | None = None
self.last: dict = {}
self.passes: list[dict] = []
def _model(self, ids):
"""The tokens the model writes after `ids` (greedy, deterministic)."""
full = self.tok.encode(self.thought + "</think>\n\n" + self.ANSWER, parse_special=True) + self.end
if self.turn is not None and ids[:len(self.turn)] == self.turn:
so_far = ids[len(self.turn):]
if so_far[-len(self.wrap):] == self.wrap:
return self.tok.encode(self.ANSWER) + self.end
if full[:len(so_far)] == so_far:
return full[len(so_far):]
self.turn = list(ids)
return full
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
ids = list(ids)
if self.live and len(self.live) <= len(ids) - 1 and ids[:len(self.live)] == self.live:
reused = len(self.live)
else:
reused = max([c for c in self.checkpoints if c <= len(ids) - 1 and c <= len(self.live)
and ids[:c] == self.live[:c]] or [0])
hold = (sampling or {}).get(HOLD_KEY) if self.honours_hold else None
row = {"prompt": len(ids), "reused": reused, "read": len(ids) - reused, "hold": hold}
self.passes.append(row)
last_start = max(i for i, t in enumerate(ids) if t == self.start)
out = self._model(ids)
hold_n = hold[0] if hold else -1
sent: list[int] = []
finish = "length"
w = 0
try:
k = 0
while k < len(out):
cap = min(max_new, hold_n) if hold_n > 0 else max_new
if len(sent) >= cap:
break
window = out[k:k + self.windows[w % len(self.windows)]]
w += 1
if hold_n > 0: # the engine's bound: rows up to the hold unless </think> comes first
room = cap - len(sent)
if self.think_end in window[:room]:
room = max_new - len(sent)
window = window[:room]
else:
window = window[:max_new - len(sent)]
k += len(window)
pending = list(window)
while pending:
if cancel.is_set():
finish = "cancel"
return
t = pending.pop(0)
sent.append(t)
if t == self.think_end:
hold_n = -1
if t in self.end:
finish = "stop"
return
yield t
if hold_n > 0 and len(sent) >= hold_n and len(sent) < max_new:
finish = "hold"
except GeneratorExit:
# the STOP is seen at the window's end: the window was committed and sent whole, and one more window may
# have run before the STOP arrived
sent.extend(pending)
if self.overrun and k < len(out):
more = out[k:k + self.windows[w % len(self.windows)]]
if hold_n > 0: # with the hold the engine never runs past it (its bound ends the request there)
more = more[:max(0, hold_n - len(sent))]
sent.extend(more)
finish = "hold" if hold_n > 0 and len(sent) >= hold_n else "cancel"
raise
finally:
self.live = ids + sent[:-1] if sent else ids[:-1]
if last_start not in self.checkpoints:
self.checkpoints.append(last_start)
row.update(sent=len(sent), finish=finish)
self.last = {"finish": finish, "reused": reused, "prompt_read": len(ids) - reused, "generated": len(sent)}
class HoldCase(unittest.TestCase):
def start(self, **kw):
self.tok = ThinkTokenizer()
self.engine = WindowEngine(self.tok, **kw)
svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
self.httpd = serve(svc, port=0)
self.addCleanup(self.httpd.server_close)
self.addCleanup(self.httpd.shutdown)
self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
def chat(self, **extra):
body = {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], "max_tokens": 400, **extra}
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=30) as r:
msg = json.loads(r.read().decode())["choices"][0]["message"]
return msg.get("reasoning_content"), msg.get("content")
def reply(self, budget, **kw):
self.start(**kw)
return self.chat(reasoning_budget_tokens=budget), self.engine.passes
def expected(self, budget, thought=WindowEngine.THOUGHT):
return thought[:budget] + REASONING_WRAP_UP.split("</think>")[0], WindowEngine.ANSWER
class ThinkingHold(HoldCase):
def test_without_the_hold_the_second_pass_reads_the_reasoning_again(self):
"""Today's behaviour, kept for an engine that does not say "hold": the engine ran past the cut, so the second
pass falls back to the checkpoint before the assistant turn and reads the reasoning again."""
got, passes = self.reply(20, can_hold=False)
self.assertEqual(got, self.expected(20))
self.assertEqual(len(passes), 2)
self.assertIsNone(passes[0]["hold"])
wrap = len(self.tok.encode(REASONING_WRAP_UP, parse_special=True))
self.assertGreater(passes[1]["read"], 20 + wrap)
def test_the_hold_makes_the_second_pass_continue_from_the_live_session(self):
got, passes = self.reply(20)
self.assertEqual(got, self.expected(20))
self.assertEqual(len(passes), 2)
think_end = self.tok.encode("</think>", parse_special=True)[0]
self.assertEqual(passes[0]["hold"], (20, think_end))
self.assertEqual((passes[0]["sent"], passes[0]["finish"]), (20, "hold"))
wrap = len(self.tok.encode(REASONING_WRAP_UP, parse_special=True))
# all but the last reasoning token is reused; the read is that token and the wrap-up
self.assertEqual(passes[1]["reused"], passes[0]["prompt"] + 20 - 1)
self.assertEqual(passes[1]["read"], 1 + wrap)
self.assertIsNone(passes[1]["hold"]) # the budget is spent: the answer pass has none
def test_same_answer_with_and_without_the_hold_for_every_budget(self):
for budget in (1, 2, 5, 19, 20, 21, 100, 183):
with self.subTest(budget=budget):
got_hold, _ = self.reply(budget)
got_old, _ = self.reply(budget, can_hold=False)
self.assertEqual(got_hold, got_old)
self.assertEqual(got_hold, self.expected(budget))
def test_a_cut_that_is_not_clean_at_the_hold_takes_one_more_matching_pass(self):
"""A character split across tokens at the hold: the server does not wrap there; the next pass (a hold of one
more token) continues from the live session, and the wrap-up comes at the same clean point as without the hold."""
thought = "Two plus two: " + "é" * 10 + " is four. " * 8 # two bytes per e-acute
budget = len("Two plus two: ".encode()) + 3 # inside the third e-acute
got_hold, passes = self.reply(budget, thought=thought)
got_old, _ = self.reply(budget, thought=thought, can_hold=False)
self.assertEqual(got_hold, got_old)
self.assertEqual(len(passes), 3)
self.assertEqual(passes[0]["finish"], "hold")
self.assertEqual(passes[1]["hold"][0], 1)
self.assertEqual(passes[1]["reused"], passes[0]["prompt"] + passes[0]["sent"] - 1)
self.assertEqual(passes[1]["read"], 1)
self.assertEqual(passes[2]["reused"], passes[1]["prompt"] + passes[1]["sent"] - 1)
def test_thinking_that_ends_before_the_budget_runs_in_one_pass(self):
got, passes = self.reply(500)
self.assertEqual(got, (WindowEngine.THOUGHT, WindowEngine.ANSWER))
self.assertEqual(len(passes), 1)
self.assertEqual(passes[0]["finish"], "stop")
def test_an_engine_that_says_hold_but_ignores_it_gives_the_same_answer(self):
"""A new server with an engine that does not act on the key: the server cuts and STOPs as before."""
got, passes = self.reply(20, honours_hold=False)
self.assertEqual(got, self.expected(20))
self.assertEqual(len(passes), 2)
def test_no_budget_no_hold(self):
self.start()
self.assertEqual(self.chat(), (WindowEngine.THOUGHT, WindowEngine.ANSWER))
self.assertEqual(len(self.engine.passes), 1)
self.assertIsNone(self.engine.passes[0]["hold"])
def test_a_batch_engine_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))
class HoldKey(unittest.TestCase):
def test_the_gen_key(self):
self.assertEqual(StrataEngine.sampling_keys({HOLD_KEY: (512, 248069)}), " hold=512:248069")
def test_only_the_servers_own_value_is_sent(self):
for v in ([512, 1], (0, 1), (5, -1), (5,), ("5", 1), (True, 1), None, 7):
with self.subTest(v=v):
self.assertNotIn("hold=", StrataEngine.sampling_keys({HOLD_KEY: v}))
if __name__ == "__main__":
unittest.main()
+37 -13
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\n", (long long) o.max_context); // "stop": this engine honours STOP
std::printf("READY %lld stop hold\n", (long long) o.max_context); // "stop": this engine honours STOP; "hold": GEN hold=N:ID
std::fflush(stdout);
std::string line;
int64_t rounds = 0;
@@ -15860,6 +15860,10 @@ int main(int argc, char** argv) {
// a parked conversation holding it stays parked) and a later request that resumes from it does not park the
// branch it leaves: N queries cost one prefix, not N. Absent = as before.
int64_t req_pin = 0;
// hold=N:ID (the server's thinking budget, GEN only): end the request after N emitted tokens unless token ID
// (</think>) came first, with the session at exactly what was emitted (serve_hold_remaining); DONE says "hold".
// Absent = as before. An older engine skips the key (unknown keys are skipped), and says no "hold" in READY.
long long req_hold_n = -1, req_hold_id = -1;
// tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of
// the missed experts and the draft-probability floor, for this request only
double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p;
@@ -15890,6 +15894,15 @@ int main(int argc, char** argv) {
else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0;
else if (key == "prefill") req_prefill_only = std::atoi(tok.c_str() + eq + 1) != 0;
else if (key == "pin") req_pin = std::max<long long>(0, std::atoll(tok.c_str() + eq + 1));
else if (key == "hold") {
char* he = nullptr;
const long long hn = std::strtoll(tok.c_str() + eq + 1, &he, 10);
if (he != nullptr && *he == ':' && hn > 0) {
char* ie = nullptr;
const long long hid = std::strtoll(he + 1, &ie, 10);
if (ie != he + 1 && *ie == '\0' && hid >= 0) { req_hold_n = hn; req_hold_id = hid; }
}
}
else if (key == "temperature") req_temperature = fv;
else if (key == "top_p") req_top_p = fv;
else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1);
@@ -18245,6 +18258,9 @@ int main(int argc, char** argv) {
size_t pen_gen0 = strata::kernels::penalty_window_from(consumed.size(), pen_prompt);
if (req_pen_from >= 0 && !pen_prompt) pen_gen0 = std::min<size_t>(pen_gen0, (size_t) req_pen_from); // a continued request: its reply began earlier
const char* finish = "length";
// GEN hold=N:ID: on until ID is emitted; meanwhile the request's cap is min(max_new, N)
bool hold_on = req_hold_n > 0 && req_hold_id >= 0;
auto cap_now = [&]() -> int64_t { return hold_on ? std::min<int64_t>(max_new, req_hold_n) : (int64_t) max_new; };
const Clock::time_point d0 = Clock::now();
// STRATA_DECODE_TIMING=1: where a request's decode time goes (one line per request)
static const bool dec_timing = std::getenv("STRATA_DECODE_TIMING") != nullptr;
@@ -18289,7 +18305,7 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata serve: --pipeline-windows: a request with %s decodes serially\n",
pl_serial);
}
if (pl_want && pl_serial == nullptr && !cancelled && produced_n < max_new) {
if (pl_want && pl_serial == nullptr && !cancelled && produced_n < cap_now()) {
pl_ran = true;
if (!pl_prepare(err)) {
std::printf("ERR %s\n", err.c_str());
@@ -18772,8 +18788,10 @@ int main(int argc, char** argv) {
chain_kind = 0;
int a = 0;
while (a < A.T - 1 && A.tok[a + 1] == outp[(size_t) a]) ++a;
if (stop_bound)
a = strata::core::serve_stop_bound(a + 1, max_new - produced_n, outp.data(), [&](int32_t y) {
if (stop_bound || hold_on) // (a hold always bounds the commit: the server's next pass continues from it)
a = strata::core::serve_stop_bound(a + 1, strata::core::serve_hold_remaining(a + 1, produced_n, max_new,
hold_on ? req_hold_n : -1, req_hold_id, outp.data()),
outp.data(), [&](int32_t y) {
return std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
}) - 1;
if (!V1(A).pl_commit_async(a + 1, err)) return die(err);
@@ -18786,8 +18804,9 @@ int main(int argc, char** argv) {
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; !nf && i <= a && produced_n < max_new && !eos; ++i) {
for (int i = 0; !nf && i <= a && produced_n < cap_now() && !eos; ++i) {
std::printf("T %d\n", (int) outp[(size_t) i]);
if (hold_on && (int64_t) outp[(size_t) i] == req_hold_id) hold_on = false;
if (req_logprobs >= 0) emit_lp_line(V1(A), i, outp[(size_t) i], req_logprobs, req_allowed);
strata::core::progress_beat();
++produced_n;
@@ -18798,7 +18817,7 @@ int main(int argc, char** argv) {
if (nf) finish = "nonfinite";
else if (eos) finish = "stop";
else if (stop_req.load()) finish = "cancel";
const bool last = nf || eos || produced_n >= max_new || stop_req.load();
const bool last = nf || eos || produced_n >= cap_now() || 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];
@@ -18978,7 +18997,7 @@ int main(int argc, char** argv) {
auto draft_df2 = [&](int) -> bool { return false; };
#endif
if (df2_trace != nullptr) std::fprintf(df2_trace, "# request prompt %lld df2 %d spec %d\n", (long long) n, req_df2 ? 1 : 0, S_mtp);
while (!pl_ran && !cancelled && produced_n < max_new) {
while (!pl_ran && !cancelled && produced_n < cap_now()) {
int T = 1;
policy.set_context(p);
const bool merged = first_window && merge_T > 0; // the prompt's last tokens and the first token
@@ -19314,8 +19333,10 @@ int main(int argc, char** argv) {
}
// A merged window contains prompt rows: every one must still be committed.
// Otherwise do not cache accepted rows whose outputs this request cannot emit.
if (stop_bound && !merged)
a = strata::core::serve_stop_bound(a + 1, max_new - produced_n, outv.data(), [&](int32_t y) {
if ((stop_bound || hold_on) && !merged)
a = strata::core::serve_stop_bound(a + 1, strata::core::serve_hold_remaining(a + 1, produced_n, max_new,
hold_on ? req_hold_n : -1, req_hold_id, outv.data()),
outv.data(), [&](int32_t y) {
return std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
}) - 1;
if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }
@@ -19378,8 +19399,9 @@ int main(int argc, char** argv) {
const bool initial_round = first_window; // a single-row window: no proposal to learn from
first_window = false;
bool eos = false;
for (int i = merged ? a : 0; i <= a && produced_n < max_new && !eos; ++i) { // (merged: row T-1 only)
for (int i = merged ? a : 0; i <= a && produced_n < cap_now() && !eos; ++i) { // (merged: row T-1 only)
std::printf("T %d\n", (int) outv[(size_t) i]);
if (hold_on && (int64_t) outv[(size_t) i] == req_hold_id) hold_on = false;
if (req_logprobs >= 0) emit_lp_line(ver, i, outv[(size_t) i], req_logprobs, req_allowed);
strata::core::progress_beat();
++produced_n;
@@ -19393,20 +19415,20 @@ int main(int argc, char** argv) {
const Clock::time_point tw2 = Clock::now();
// coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's
// commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will
if (use_mtp && hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new)
if (use_mtp && hist_n > 0 && mtp.coupled() && !eos && produced_n < cap_now())
mtp.set_draft_history(consumed.data() + pen_gen0, (int64_t) (consumed.size() - pen_gen0), outv[(size_t) a]);
generation = {}; // a skipped or failed production must not expose an older q view
#if defined(STRATA_HAVE_DFLASH2)
// The request ends here, so no draft follows and the window's committed rows would never reach the drafter's ring or its log: every turn would
// leave a hole of a + 1 positions behind it, which a later turn that resumes after this one finds blank (and cannot rebuild). Update them now.
static const bool df2_end_update = std::getenv("STRATA_DF2_END_UPDATE") == nullptr || std::getenv("STRATA_DF2_END_UPDATE")[0] != '0'; // =0: the pre-fix behaviour (diagnostics)
if (df2_end_update && use_df2 && req_df2 && !merged && (eos || produced_n >= max_new)) {
if (df2_end_update && use_df2 && req_df2 && !merged && (eos || produced_n >= cap_now())) {
const float* tp_end = df2_win_taps(a + 1, err); // (on a layer split: every stage's taps gathered onto the drafter's card)
if (tp_end == nullptr || !df2.context(tp_end, a + 1, p, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); return 1; }
}
#endif
const GatedDraftLimit draft_limit(mtp, gated_proposal, S_mtp, p + a + 1, o.max_context);
const bool drafted = !draft_on || eos || produced_n >= max_new ||
const bool drafted = !draft_on || eos || produced_n >= cap_now() ||
(req_df2 ? ((!merged && defer_df2(a)) || draft_df2(a)) : mtp.draft_long(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p,
nullptr, gated_proposal ? &generation : nullptr));
{
@@ -19484,6 +19506,8 @@ int main(int argc, char** argv) {
x = outv[(size_t) a];
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";
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) {
+37
View File
@@ -27,6 +27,43 @@ int main() {
++cases;
}
assert(strata::core::serve_stop_bound(4, 0, static_cast<const int*>(nullptr), [](int) { return false; }) == 0);
// GEN hold=N:ID: against the emission loop with the hold (stop after N emitted tokens unless ID came first; EOS and
// max_new as before), for every window shape, start, hold, max_new and place of ID / EOS in the window
int hold_cases = 0;
const int ID = 7777; // a real token id (a negative one means "no hold")
for (int accepted = 1; accepted <= 8; ++accepted)
for (int produced = 0; produced <= 6; ++produced)
for (int hold = 1; hold <= 10; ++hold)
for (int max_new = produced + 1; max_new <= 12; ++max_new)
for (int id_at = -1; id_at < accepted; ++id_at)
for (int eos = -1; eos < accepted; ++eos) {
if (eos >= 0 && eos == id_at) continue;
if (produced >= hold) continue; // a hold the request already reached has ended it
std::vector<int> outputs(accepted);
for (int i = 0; i < accepted; ++i) outputs[i] = i == eos ? -1 : i == id_at ? ID : 100 + i;
std::vector<int> reference;
bool on = true;
int64_t done = produced;
for (int i = 0; i < accepted; ++i) {
const int64_t cap = on ? std::min(max_new, hold) : max_new;
if (done >= cap) break;
reference.push_back(outputs[i]);
++done;
if (outputs[i] == ID) on = false;
if (outputs[i] == -1) break;
}
const int64_t rem = strata::core::serve_hold_remaining(accepted, produced, max_new, hold, ID,
outputs.data());
const int kept = strata::core::serve_stop_bound(accepted, rem, outputs.data(),
[](int t) { return t == -1; });
assert(kept == static_cast<int>(reference.size()));
assert(std::vector<int>(outputs.begin(), outputs.begin() + kept) == reference);
// no hold: exactly the max_new bound
assert(strata::core::serve_hold_remaining(accepted, produced, max_new, -1, ID, outputs.data()) ==
max_new - produced);
++hold_cases;
}
std::cout << "SUMMARY hold cases=" << hold_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"));