radiance 1.2.0

- MXFP4 weights: block-fp8 Qwen3.5/3.6/3.8 dense models serve OCP-MXFP4 linears (e2m1, an E8M0
  exponent per 32) at 4-bit weights against E4M3 activations. New libr4d rows: the decode GEMM
  (M <= 128, split-K with a fused last-arriver reduction) and the prefill GEMM on a fragment-tiled
  activation. Qwen3.8-27B MXFP4 (AMD Quark AWQ) is in the model table.
- Cards without peer-to-peer access serve: every collective has a host-memory twin; --p2p
  auto|on|off.
- Stop strings apply to the answer, not to the reasoning block a reply starts in.
- A prefix hit ends one drafter window before the prompt's end, so a windowed block drafter
  (DFlash2) drafts from the first token of a follow-up turn.
This commit is contained in:
Deadcode committed 2026-10-06 21:36:24 +02:00
1 parent 7001841e45
commit e95d397288
47 files changed
+2611 -219

No files matched your search

+10
View File
@@ -39,6 +39,9 @@ static const Flag g_flags[] = {
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
"none at 8" },
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
"asks the driver, on requires peer access and stops without\n"
"it, off exchanges through pinned host memory" },
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
@@ -362,6 +365,13 @@ int config_parse(int argc, char** argv, Config* c) {
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; }
}
else if (S("--p2p")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO;
else if (!std::strcmp(v, "on")) c->p2p = RAD_P2P_ON;
else if (!std::strcmp(v, "off")) c->p2p = RAD_P2P_OFF;
else { RAD_ERR("--p2p takes auto, on or off, not '%s'", v); return RAD_E_INVAL; }
}
else if (S("--tp-wire-min-kb")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); }
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
+22 -7
View File
@@ -3028,9 +3028,11 @@ int Engine::start() {
/* PEER ACCESS, MEASURED BEFORE ANYTHING IS SELECTED. A kernel that reads or writes another
* card's memory says so with a constraint on device.p2p (rad_types.h), and the selector reads
* it from here: on a machine where some pair of the ranks' cards cannot reach each other such a
* kernel is not selected, and declare names the constraint instead of the all-reduce faulting
* or hanging on its first message. Every ordered pair, because access is granted one way at a
* time. */
* kernel is not selected, and one that exchanges through host memory takes the op instead (or
* declare names the constraint) rather than the all-reduce faulting or hanging on its first
* message. Every ordered pair, because access is granted one way at a time. --p2p overrides the
* answer in one direction each way (Config::p2p): off turns it down whatever the driver says,
* on refuses to start without it. */
{
long long p2p = 1;
std::string blocked;
@@ -3048,14 +3050,27 @@ int Engine::start() {
blocked += fmt("%s%d->%d", blocked.empty() ? "" : ", ", devs[i], devs[j]);
}
}
if (cfg_.tp > 1 && cfg_.p2p == RAD_P2P_ON && !p2p) {
RAD_ERR("device: --p2p on, but the driver reports no peer-to-peer access between cards "
"%s. IOMMU settings and the PCIe topology decide this, not radiance; --p2p auto "
"serves through host memory instead", blocked.c_str());
return RAD_E_UNSUPPORTED;
}
const bool forced_off = cfg_.p2p == RAD_P2P_OFF;
if (forced_off) p2p = 0;
rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p);
if (cfg_.tp > 1) {
if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to "
"peer)", cfg_.tp);
else RAD_WARN("device: no peer-to-peer access between cards %s. A kernel that needs "
"it (device.p2p == 1) is not selected; if nothing else implements its "
"op, startup stops below naming it. IOMMU settings and the PCIe "
"topology decide this, not radiance", blocked.c_str());
else if (forced_off)
RAD_INFO("device: --p2p off: the collectives exchange through pinned host memory%s",
blocked.empty() ? " although the driver reports peer-to-peer access"
: "");
else RAD_WARN("device: no peer-to-peer access between cards %s. The collectives "
"exchange through pinned host memory instead, and a kernel that needs "
"peer access (device.p2p == 1) is not selected; if nothing else "
"implements its op, startup stops below naming it. IOMMU settings and "
"the PCIe topology decide this, not radiance", blocked.c_str());
}
}
+40 -16
View File
@@ -224,7 +224,8 @@ void PrefixCache::touch(const BlockHash& h) const {
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out) const {
std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const {
CacheHit hit;
if (blocks_out) { blocks_out->assign(groups_.size(), {}); }
if (!enabled_ || tokens.empty()) return hit;
@@ -261,6 +262,43 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
* forward pass. */
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
* at or below `limit` is found by asking each snapshot whether this chain passes through it:
* its key is the chained hash at its own position, which matches only on the same prefix. The
* index holds a few hundred snapshots against tens of thousands of block positions. */
auto deepest = [&](int64_t limit) {
auto best = ck_by_prefix_.end();
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
const Ckpt& c = it->second;
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
c.pos % block_size_ != 0)
continue;
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
best = it;
}
return best;
};
/* What a hit of `m` blocks lets a sequence skip: all of it, or with recurrent state only up
* to the deepest checkpoint under it (Scheduler::admit_one resumes there). */
auto reusable = [&](int64_t m) -> int64_t {
if (!has_linear_) return m * block_size_;
const auto b = deepest(m * block_size_);
return b == ck_by_prefix_.end() ? 0 : b->second.pos;
};
if (cap && matched > cap->tokens / block_size_) {
const int64_t whole = reusable(matched);
if (whole > cap->tokens) {
const int64_t m = cap->tokens > 0 ? cap->tokens / block_size_ : 0;
const int64_t lost = whole - reusable(m);
if (lost <= cap->max_give_back) {
matched = m;
hit.given_back = (int32_t)lost;
}
}
}
for (int64_t b = 0; b < matched; ++b) {
touch(hs[(size_t)b]);
if (!blocks_out) continue;
@@ -287,21 +325,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
hit.n_linear_tokens = hit.n_attn_tokens;
return hit;
}
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
* under the hit is found by asking each snapshot whether this chain passes through it: its
* key is the chained hash at its own position, which matches only on the same prefix. The
* index holds a few hundred snapshots against tens of thousands of block positions. */
auto best = ck_by_prefix_.end();
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
const Ckpt& c = it->second;
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > hit.n_attn_tokens ||
c.pos % block_size_ != 0)
continue;
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
best = it;
}
const auto best = deepest(hit.n_attn_tokens);
if (best == ck_by_prefix_.end()) {
++stats_.ckpt_misses;
return hit;
+15 -2
View File
@@ -108,6 +108,18 @@ struct CacheHit {
int32_t n_attn_tokens = 0; /* attention KV reused directly, always a whole block multiple */
int32_t n_linear_tokens = 0; /* linear state reused; <= n_attn_tokens, a checkpoint multiple */
int32_t checkpoint_slot = -1; /* the snapshot holding that state, -1 if none */
int32_t given_back = 0; /* reusable tokens a HitCap took off the whole hit */
};
/* A HIT ENDED EARLY ON PURPOSE. The hit ends no later than `tokens` -- at a block and, for a model
* with recurrent state, at the deepest checkpoint at or below it -- unless that gives back more
* than `max_give_back` of what the whole hit would reuse, in which case the whole hit stands. It
* exists for a drafter whose own KV the cache does not hold (Scheduler::init, --draft-refill):
* recomputing the prompt's tail gives it context, and a cap whose nearest checkpoint is far below
* would recompute far more than that tail. */
struct HitCap {
int64_t tokens = 0;
int64_t max_give_back = 0;
};
/* ------------------------------------------------------------------ retention policy */
@@ -181,10 +193,11 @@ public:
*
* NEVER returns the whole prompt: at least one token must remain for the step to compute a
* logit from, so a full hit is backed off by one block. That is not a subtlety the caller
* should have to know. */
* should have to know. `cap`, when given, ends the hit early (HitCap). */
CacheHit lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out = nullptr) const;
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
const HitCap* cap = nullptr) const;
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
+11
View File
@@ -583,6 +583,9 @@ struct Request {
/* ================================================================== engine config */
/* --p2p: whether the collectives use the cards' peer access. */
enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
struct Config {
std::string model; /* path to the .rad */
std::string radiance_home;
@@ -609,6 +612,14 @@ struct Config {
* floor that compresses everything which benefits while leaving single-sequence decode
* exact. */
int64_t tp_wire_min_kb = 128; /* --tp-wire-min-kb */
/* HOW THE COLLECTIVES REACH THE OTHER CARDS. Auto asks the driver, for every ordered pair of
* the ranks' cards, whether one can address the other's memory, and takes the P2P kernels only
* if every pair can. A driver can answer yes on a board where peer traffic is broken or slower
* than going through host memory, and that is what `off` is for: it takes the host-mailbox
* collectives whatever the driver says. `on` takes the P2P kernels and stops startup naming
* the pairs the driver refuses, rather than falling back -- a deployment that was measured on
* P2P should not quietly serve on something else. */
int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */
int64_t max_tok = 8192; /* --max-num-batched-tokens */
int64_t max_seqs = 256;
int64_t max_ctx = 0; /* 0 = the model's training context */
+6 -5
View File
@@ -148,8 +148,9 @@ struct IPrefixCache {
/* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */
virtual void release(const Request&) {}
virtual CacheHit lookup(const Request& r,
std::vector<std::vector<int32_t>>* blocks_out) const = 0;
/* `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
virtual CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const = 0;
virtual const std::vector<int32_t>& cached_groups() const = 0;
/* PUBLISH what this sequence computed, so the next request sharing the prefix can adopt it.
@@ -335,10 +336,10 @@ struct PCBinding final : IPrefixCache {
mutable std::vector<MMContentKey> mm_;
explicit PCBinding(PC* p) : m(p) {}
CacheHit lookup(const Request& r,
std::vector<std::vector<int32_t>>* out) const override {
CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* out,
const HitCap* cap) const override {
media_keys(r, &mm_);
return m->lookup(r.prompt, mm_, out);
return m->lookup(r.prompt, mm_, out, cap);
}
/* Installed by the engine when the idle tiers are on; empty otherwise. */
+4
View File
@@ -123,6 +123,10 @@ struct SchedMetrics {
/* Speculation (§10). */
int64_t draft_tokens = 0;
int64_t draft_accepted = 0;
/* Prefix hits ended early so a windowed block drafter has context (Scheduler::draft_refill_),
* and the reusable tokens they gave back to be recomputed. */
int64_t draft_refills = 0;
int64_t draft_refill_tokens = 0;
float draft_acceptance = 0.0f;
int draft_depth = 0; /* what the controller would choose right now */
/* Per draft POSITION, so a cliff can be told from a decay: `reached` is how often every
+17 -1
View File
@@ -87,6 +87,13 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
n_paged, pc->cached_groups().size(),
hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole");
}
draft_refill_ = 0;
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
hit_holes_draft_) {
draft_refill_ = prog.drafter.window;
RAD_INFO("draft refill: a prefix hit ends %lld tokens before the prompt's end, so the "
"drafter's window is recomputed", (long long)draft_refill_);
}
DraftController::Params dp;
dp.max_depth = cfg.n_spec;
@@ -788,7 +795,16 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
* context back instead of re-prefilling it: it costs a copy, and the alternative
* costs a prefill. */
if (pc_->restore(r) == IPrefixCache::Restore::Wait) return kAdmitWait;
CacheHit h = pc_->lookup(r, &hit_blocks_);
HitCap cap;
if (draft_refill_ > 0) {
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
cap.max_give_back = 2 * draft_refill_;
}
const CacheHit h = pc_->lookup(r, &hit_blocks_, draft_refill_ > 0 ? &cap : nullptr);
if (h.given_back > 0) {
m_.draft_refill_tokens += h.given_back;
++m_.draft_refills;
}
int32_t reuse = h.n_attn_tokens;
if (geo_.checkpoints() && h.n_linear_tokens < reuse) {
/* A hit landing between checkpoints reuses the attention blocks and must replay the
+9
View File
@@ -472,6 +472,15 @@ private:
* also skips on a block-size mismatch. A bound like this lives in exactly one place; a second
* copy is free to drift out of step with the first. */
bool hit_holes_draft_ = true;
/* DRAFT REFILL. Where a hit leaves a hole in a WINDOWED block drafter's cache, the drafter is
* declined until its window has slid past the hole, which on the follow-up turn of a chat --
* the turn a prefix hit is for -- is most or all of the reply. So the hit is ended one window
* before the end of the prompt (HitCap): the trunk recomputes that window, the drafter's
* context pass covers it, and the sequence drafts from its first decode step. Output is
* unchanged; only which tokens are recomputed moves. A hit whose nearest checkpoint below
* that point would give back more than two windows is kept whole. The drafter's window, or 0
* where no hit can leave such a hole. */
int64_t draft_refill_ = 0;
BatchBuilder builder_;
DraftController draft_;
+2
View File
@@ -268,6 +268,7 @@ public:
o.draft_acceptance = m.draft_acceptance;
o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens;
o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted;
o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens;
o.linear_hit_rate = m.linear_hit_rate;
o.attn_cached_tokens = m.attn_cached_tokens;
o.linear_cached_tokens = m.linear_cached_tokens;
@@ -311,6 +312,7 @@ public:
std::string push(int32_t t) override { return d_.push(t); }
std::string flush() override { return d_.flush(); }
bool stopped() const override { return d_.stopped(); }
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
private:
Detokenizer d_;
};
+6
View File
@@ -102,6 +102,9 @@ struct SchedMetrics {
/* The exact pair the ratio is computed from, for the same reason. */
int64_t draft_tokens = 0;
int64_t draft_accepted = 0;
/* Prefix hits ended early for a windowed block drafter, and the tokens they gave back. */
int64_t draft_refills = 0;
int64_t draft_refill_tokens = 0;
/* THE PER-POSITION DRAFT HAZARD. `draft_acceptance` above is pooled over the whole window and
* cannot distinguish a drafter that decays with depth from one whose later rounds are broken:
* both read as one small number. These carry the conditional rate at each position -- of the
@@ -299,6 +302,9 @@ public:
* search text that can no longer contain what it is searching for, and the generation would
* run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
virtual bool stopped() const { return false; }
/* Match the stop strings only after `marker` has been generated (core/text Detokenizer::
* defer_stops_until): the reply starts inside its reasoning block. */
virtual void defer_stops_until(const std::string& /*marker*/) {}
};
class ITokenizer {
+9
View File
@@ -160,6 +160,9 @@ void Metrics::sample(const SchedMetrics& m) {
c_decode_tokens_.inc(std::max(0.0, (double)m.decode_tokens - c_decode_tokens_.get()));
c_draft_tokens_.inc(std::max(0.0, (double)m.draft_tokens - c_draft_tokens_.get()));
c_draft_accepted_.inc(std::max(0.0, (double)m.draft_accepted - c_draft_accepted_.get()));
c_draft_refills_.inc(std::max(0.0, (double)m.draft_refills - c_draft_refills_.get()));
c_draft_refill_tokens_.inc(
std::max(0.0, (double)m.draft_refill_tokens - c_draft_refill_tokens_.get()));
c_attn_cached_.inc(std::max(0.0, (double)m.attn_cached_tokens - c_attn_cached_.get()));
c_linear_cached_.inc(std::max(0.0, (double)m.linear_cached_tokens - c_linear_cached_.get()));
c_checkpoints_.inc(std::max(0.0, (double)m.checkpoints_written - c_checkpoints_.get()));
@@ -345,6 +348,12 @@ std::string Metrics::render() const {
w.counter("radiance:draft_accepted_total",
"Speculative tokens accepted; the pair the acceptance ratio is computed from.",
L, c_draft_accepted_.get());
w.counter("radiance:draft_refills_total",
"Prefix hits ended a drafter window early so a windowed block drafter has context.",
L, c_draft_refills_.get());
w.counter("radiance:draft_refill_tokens_total",
"Cached prompt tokens those hits gave back to be recomputed.",
L, c_draft_refill_tokens_.get());
/* PREFIX CACHING, DECOUPLED (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the ATTENTION one,
* because that is what vLLM's single number has always meant. The linear side hits at a
+1
View File
@@ -144,6 +144,7 @@ private:
* answers "how much between these two scrapes", and only the second survives a comparison
* between two runs that settled into different mixes. */
Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
Counter c_draft_refills_, c_draft_refill_tokens_;
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Gauge g_linear_hit_;
+6
View File
@@ -1456,6 +1456,12 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
if (std::find(out->stop.begin(), out->stop.end(), s) == out->stop.end())
out->stop.push_back(s);
/* A reply that starts inside the reasoning block: its stop strings are the answer's, so they
* apply only after the block's closer (Detokenizer::defer_stops_until). The chat format says
* whether the rendered prompt leaves the block open and what closes it. */
if (render.think_starts_open && !render.think_close.empty())
out->stops_after = render.think_close;
/* Checked HERE, where the answer is still a 400. The grammar being validated may be the
* caller's, or one the template produced for its own tool-call syntax; either way the first
* moment it can fail is when the automaton is built, and building it on the step path would
+3
View File
@@ -77,6 +77,9 @@ struct OaiRequest {
SamplingParams sp;
int32_t max_tokens = 0;
std::vector<std::string> stop;
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
std::string stops_after;
/* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */
bool ignore_eos = false;
int priority = 0;
+25 -2
View File
@@ -30,6 +30,10 @@ struct Server::Generation {
Finish finish = Finish::None;
bool closed = false; /* the server has decided this choice is over */
size_t scanned = 0; /* how far the stop-string scan has reached */
/* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
* has been generated) and how far the search for it has reached. */
size_t stops_floor = std::string::npos;
size_t closer_scanned = 0;
size_t stop_cut = std::string::npos;
size_t emitted = 0; /* streaming: text already handed to the delta stream */
bool retired = false; /* reap() has been said for this id, at most once */
@@ -330,6 +334,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
*err = err_not_implemented("the tokenizer did not supply an incremental decoder");
return RAD_E_UNSUPPORTED;
}
if (!r.stops_after.empty()) g.detok->defer_stops_until(r.stops_after);
Request rq;
rq.prompt = r.prompts[p].tokens;
@@ -338,7 +343,9 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
* Offsetting is enough: the sampler's stream is seeded, not chained. */
rq.sp.seed = r.sp.seed + (uint64_t)k;
rq.max_tokens = r.max_tokens;
rq.stop = r.stop;
/* With the stop strings deferred past the reasoning block, the scheduler -- which
* cannot tell reasoning from answer -- gets none; the decoder and pump() cut. */
rq.stop = r.stops_after.empty() ? r.stop : std::vector<std::string>{};
rq.ignore_eos = r.ignore_eos;
rq.priority = r.priority;
rq.stream = r.stream;
@@ -429,8 +436,24 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
* string straddles token boundaries and only the detokenised text can be searched, so the
* authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous
* end so a match spanning two drains is still found. */
if (maxstop && g.stop_cut == std::string::npos && !g.text.empty()) {
/* Stop strings deferred past the reasoning block match only after its closer. The closer
* is searched for incrementally, from (closer length - 1) bytes behind the previous end,
* so a reply that thinks for a long time is not rescanned from its start every drain. */
size_t floor = 0;
if (!r.stops_after.empty()) {
if (g.stops_floor == std::string::npos) {
const size_t n = r.stops_after.size();
const size_t from = g.closer_scanned >= n ? g.closer_scanned - n + 1 : 0;
const size_t m = g.text.find(r.stops_after, from);
g.closer_scanned = g.text.size();
if (m != std::string::npos) g.stops_floor = m + n;
}
floor = g.stops_floor;
}
if (maxstop && floor != std::string::npos && g.stop_cut == std::string::npos &&
!g.text.empty()) {
size_t start = g.scanned >= maxstop ? g.scanned - maxstop + 1 : 0;
if (start < floor) start = floor;
for (const auto& s : r.stop) {
if (s.empty()) continue;
size_t at = g.text.find(s, start);
+21 -2
View File
@@ -1606,13 +1606,32 @@ std::string Detokenizer::push(int32_t token) {
all_ += p;
pending_ += p;
/* Inside the reasoning block no stop string applies (defer_stops_until). The closer is
* searched for incrementally in all_, from (closer length - 1) bytes behind the previous end.
* Once it has been generated, matching starts in the text AFTER it: the closer may still be in
* pending_, and nothing before its end may count. */
size_t from = 0;
if (!armed_) {
const size_t n = arm_after_.size();
const size_t start = arm_scanned_ >= n ? arm_scanned_ - n + 1 : 0;
const size_t m = all_.find(arm_after_, start);
arm_scanned_ = all_.size();
if (m == std::string::npos) {
from = std::string::npos;
} else {
armed_ = true;
const size_t pending_at = all_.size() - pending_.size();
from = m + n > pending_at ? m + n - pending_at : 0;
}
}
/* A complete stop string inside pending_ ends the stream. Everything before it is emitted;
* the stop string and anything after it never is. */
if (!stops_.empty()) {
if (!stops_.empty() && from != std::string::npos) {
size_t best = std::string::npos;
const std::string* which = nullptr;
for (const std::string& s : stops_) {
const size_t m = pending_.find(s);
const size_t m = pending_.find(s, from);
if (m != std::string::npos && m < best) { best = m; which = &s; }
}
if (which) {
+16
View File
@@ -247,6 +247,19 @@ public:
bool stopped() const { return stopped_; }
const std::string& stop_hit() const { return stop_hit_; }
/* STOP STRINGS ARE THE ANSWER'S, NOT THE REASONING'S. A generation that starts inside its
* reasoning block is matched against its stop strings only after `marker` -- the block's
* closer -- has been generated, and only in the text after it. Otherwise a stop string the
* model happens to write while thinking ends the request with the reasoning cut short and no
* answer at all: a few-shot harness that stops on "Q:" loses every reply whose reasoning
* restates the question. "" = match from the first token, the behaviour of every request that
* does not start in a block. */
void defer_stops_until(std::string marker) {
arm_after_ = std::move(marker);
armed_ = arm_after_.empty();
arm_scanned_ = 0;
}
/* Everything pushed so far, stop string included. The scheduler wants this to decide whether
* a request finished on a stop or on a length limit. */
const std::string& text() const { return all_; }
@@ -264,6 +277,9 @@ private:
std::string stop_hit_;
size_t max_stop_ = 0;
bool first_ = true;
std::string arm_after_; /* see defer_stops_until */
bool armed_ = true;
size_t arm_scanned_ = 0; /* how far into all_ the search for arm_after_ has reached */
Tokenizer tok_; /* over v_, set up by the first push */
bool tok_ready_ = false;