Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+3
-131
@@ -1,11 +1,6 @@
|
||||
/* accept.cpp -- greedy and rejection-sampling acceptance for speculative decoding. See accept.h
|
||||
* for which rule is correct when, and for why `n_accepted` is a read offset and not a recompute.
|
||||
/* accept.cpp -- acceptance for speculative decoding. See accept.h for why the rule is exact.
|
||||
*/
|
||||
#include "accept.h"
|
||||
#include "host_ref.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -19,134 +14,11 @@ int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
|
||||
if (draft[i] != target[i]) break;
|
||||
out[i] = draft[i];
|
||||
}
|
||||
/* The bonus token. Whether every draft token was accepted or the run stopped at i, the
|
||||
* target's own answer AT position i is correct to emit -- on a full run that is the free
|
||||
* extra token speculation buys, and on a rejection it is the correction. One code path for
|
||||
* both, which is what stops the bonus from being an off-by-one nobody notices until the
|
||||
* acceptance rate looks a percent low. */
|
||||
/* The target's token at position i is correct to emit either way: the bonus token on a full
|
||||
* run, the correction on a rejection. */
|
||||
out[i] = target[i];
|
||||
*n_accepted = i;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Draw from a distribution given as a callable over token ids, walking in ASCENDING TOKEN ID.
|
||||
* Any fixed order samples correctly; a distribution over the whole vocabulary has no candidate
|
||||
* order to follow, and ascending id is the one that needs no sort to be a total order.
|
||||
*
|
||||
* Two passes over the vocabulary and NO intermediate array: the residual after a rejection would
|
||||
* otherwise be a 151K-float allocation on the step path, which the arena discipline (spec §3.1)
|
||||
* exists to forbid. Returns -1 if the total mass is zero. */
|
||||
template <class Weight>
|
||||
static int32_t draw_from(Weight w, int64_t n, float u) {
|
||||
double total = 0.0;
|
||||
for (int64_t v = 0; v < n; ++v) {
|
||||
const float x = w(v);
|
||||
if (x > 0.0f) total += (double)x;
|
||||
}
|
||||
if (!(total > 0.0)) return -1;
|
||||
|
||||
const double want = (double)u * total;
|
||||
double acc = 0.0;
|
||||
int32_t last = -1;
|
||||
for (int64_t v = 0; v < n; ++v) {
|
||||
const float x = w(v);
|
||||
if (!(x > 0.0f)) continue;
|
||||
last = (int32_t)v;
|
||||
acc += (double)x;
|
||||
if (acc >= want) return (int32_t)v;
|
||||
}
|
||||
/* Float drift can leave the walk a hair short at the very top of the range; the last token
|
||||
* with mass is the right answer there, not token 0. */
|
||||
return last;
|
||||
}
|
||||
|
||||
int accept_stochastic(const SpecAcceptParams& p, const int32_t* draft,
|
||||
const float* target_probs, const float* draft_probs,
|
||||
int32_t* out, int32_t* n_accepted) {
|
||||
if (!target_probs || !out || !n_accepted) return RAD_E_INVAL;
|
||||
if (p.n_draft < 0 || p.n_vocab <= 0) return RAD_E_INVAL;
|
||||
if (p.n_draft > 0 && !draft) return RAD_E_INVAL;
|
||||
|
||||
const int64_t V = p.n_vocab;
|
||||
|
||||
for (int i = 0; i < p.n_draft; ++i) {
|
||||
const int32_t x = draft[i];
|
||||
if (x < 0 || x >= V) return RAD_E_INVAL;
|
||||
|
||||
const float* prow = target_probs + (int64_t)i * V;
|
||||
const float px = prow[x];
|
||||
/* A greedy drafter is a point mass: q(x) = 1, q(everything else) = 0. Passing null for
|
||||
* `draft_probs` says so, and it is the case worth being fast at -- every MTP head that
|
||||
* ships inside a target checkpoint drafts greedily. */
|
||||
const float qx = draft_probs ? draft_probs[(int64_t)i * V + x] : 1.0f;
|
||||
|
||||
const float u = rng_uniform(p.seed, p.pos + (uint64_t)i, RAD_RNG_ACCEPT);
|
||||
const bool accept = !(qx > 0.0f) || (double)u < (double)px / (double)qx;
|
||||
|
||||
if (accept) { out[i] = x; continue; }
|
||||
|
||||
/* Rejected. The emitted token comes from the residual norm(max(0, p - q)); anything else
|
||||
* -- re-sampling p, or emitting the target's argmax -- changes the distribution the
|
||||
* scheme emits, which is the one property speculative decoding is supposed to preserve. */
|
||||
const float* qrow = draft_probs ? draft_probs + (int64_t)i * V : nullptr;
|
||||
auto resid = [&](int64_t v) -> float {
|
||||
const float q = qrow ? qrow[v] : (v == x ? 1.0f : 0.0f);
|
||||
const float r = prow[v] - q;
|
||||
return r > 0.0f ? r : 0.0f;
|
||||
};
|
||||
|
||||
const int32_t tok =
|
||||
draw_from(resid, V, rng_uniform(p.seed, p.pos + (uint64_t)i, RAD_RNG_RESID));
|
||||
if (tok < 0) {
|
||||
/* The residual is empty: the target has no mass the drafter did not already claim,
|
||||
* and the uniform landed on the acceptance boundary anyway. Accepting is the correct
|
||||
* answer there -- the drafted token is in the target's support by construction -- so
|
||||
* take it and carry on rather than emitting nothing. */
|
||||
out[i] = x;
|
||||
continue;
|
||||
}
|
||||
out[i] = tok;
|
||||
*n_accepted = i;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Every draft token accepted: the bonus position is an ordinary pick from the target's own
|
||||
* distribution, drawn on the ORDINARY pick stream at its own output position, so it is the
|
||||
* same token a non-speculative step would have produced there for this seed. */
|
||||
const float* brow = target_probs + (int64_t)p.n_draft * V;
|
||||
const int32_t bonus =
|
||||
draw_from([&](int64_t v) { return brow[v]; }, V,
|
||||
rng_uniform(p.seed, p.pos + (uint64_t)p.n_draft, RAD_RNG_PICK));
|
||||
if (bonus < 0) {
|
||||
RAD_ERR("speculative accept: target distribution at the bonus position has no mass "
|
||||
"(a grammar admitting nothing); the request cannot be continued");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
out[p.n_draft] = bonus;
|
||||
*n_accepted = p.n_draft;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int accept_sequence(const SpecAcceptParams& p, const int32_t* draft,
|
||||
const int32_t* target_argmax,
|
||||
const float* target_probs, const float* draft_probs,
|
||||
int32_t* out, int32_t* n_accepted) {
|
||||
if (p.greedy) {
|
||||
if (!target_argmax) {
|
||||
RAD_ERR("speculative accept: greedy acceptance was asked for without the target's "
|
||||
"argmax; a silent switch to rejection sampling would change the output "
|
||||
"distribution and nothing would say so");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return accept_greedy(draft, p.n_draft, target_argmax, out, n_accepted);
|
||||
}
|
||||
if (!target_probs) {
|
||||
RAD_ERR("speculative accept: rejection sampling was asked for without target "
|
||||
"probabilities");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return accept_stochastic(p, draft, target_probs, draft_probs, out, n_accepted);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+35
-79
@@ -1,49 +1,24 @@
|
||||
/* accept.h -- speculative acceptance. Verification is a declared op; ACCEPTANCE IS CORE SAMPLER
|
||||
* LOGIC (spec §10), which is why it lives here beside the chain that produced the distributions
|
||||
* it compares.
|
||||
/* accept.h -- speculative acceptance. Verification is a declared op; acceptance is core sampler
|
||||
* logic (spec §10), so it lives beside the chain that produced the distributions it compares.
|
||||
*
|
||||
* Three rules, and the cheapest one is exact everywhere.
|
||||
* Agreement with the target's own token. A drafted token is accepted when it equals the token the
|
||||
* target produced at that position: the argmax at temperature 0, the target's sampled draw above
|
||||
* it. Both are exact, provided each verified position draws from its own RNG coordinate
|
||||
* (`p.pos = n_out + k` in sampler.cpp): the first emitted token is the target's draw whether the
|
||||
* draft agreed or not, and every later position is conditioned on a prefix accepted only because
|
||||
* it matched. Exact given the same logits; a verify step computes logits at a different M than a
|
||||
* decode step, so text matches a non-speculative run exactly at temperature 0 and mostly above it
|
||||
* (see Engine::collect_step). The cost is acceptance rate, P(y == x) instead of rejection
|
||||
* sampling's min(1, p/q), and no probability planes are needed.
|
||||
*
|
||||
* AGREEMENT WITH THE TARGET'S OWN TOKEN -- what accept_greedy below actually implements, and what
|
||||
* this engine uses. A drafted token is accepted when it equals the token the target produced at
|
||||
* that position. At temperature 0 that token is the argmax, which is where the name came from.
|
||||
* ABOVE ZERO IT IS THE TARGET'S SAMPLED DRAW, AND ACCEPTING ON IT IS STILL EXACT -- provided each
|
||||
* verified position draws from its own RNG coordinate, which core/sample/sampler.cpp guarantees
|
||||
* (`p.pos = n_out + k`). Then the target's draw at position k is the one its own distribution
|
||||
* specifies there, the first emitted token is that draw whether the draft agreed or not, and every
|
||||
* later position is conditioned on a prefix accepted only because it matched. The emitted sequence
|
||||
* is a draw from the target, not an approximation of one.
|
||||
* Accepting on argmax at a positive temperature is not exact: it replaces the target's
|
||||
* distribution with its mode. Do not conflate it with the rule above.
|
||||
*
|
||||
* Exact given the same logits -- which is not the same as byte-identical to a non-speculative run,
|
||||
* because a verify step's logits are computed at a different M than a decode step's. The text
|
||||
* matches exactly at temperature 0 and mostly above it. See Engine::collect_step.
|
||||
*
|
||||
* What it costs is acceptance RATE: P(y == x) rather than the optimal min(1, p/q). What it costs
|
||||
* in machinery is nothing, which is why the engine computes no probability planes for it.
|
||||
*
|
||||
* ACCEPTING ON ARGMAX AT A POSITIVE TEMPERATURE is the rule that is NOT exact -- it replaces the
|
||||
* target's distribution with its mode. That is a different thing from the above, and the two are
|
||||
* easy to conflate.
|
||||
*
|
||||
* REJECTION SAMPLING. At temperature > 0 the drafted token x is accepted with probability
|
||||
* min(1, p(x)/q(x)) where p is the target's filtered distribution and q the drafter's. On
|
||||
* rejection the emitted token is drawn from the residual, norm(max(0, p - q)), which is what
|
||||
* makes the whole scheme emit exactly the target's distribution. With a GREEDY DRAFTER q is a
|
||||
* point mass, so the accept probability collapses to p(x) and the residual is p with x removed
|
||||
* and the rest renormalised -- which is the case the fast path is written for.
|
||||
*
|
||||
* Worth stating plainly because it looks like a regression and is not: acceptance FALLS relative
|
||||
* to greedy-against-greedy, because a proposal the target agrees with is still only accepted with
|
||||
* probability p(x) rather than always. That is the price of emitting the target's true
|
||||
* distribution.
|
||||
*
|
||||
* WHAT THE ANSWER IS FOR. `n_accepted` is consumed by two components that do different things
|
||||
* with it. The scheduler frees paged KV blocks past the accepted position -- a slot-table edit.
|
||||
* The linear-attention kernels do NOT recompute: the recurrent state and the conv window have
|
||||
* already absorbed the rejected tokens, and libr4d handles that by treating the conv state cache
|
||||
* as a rolling window of `conv_width-1 + n_spec` entries and READING AT THE SLOT THE LAST
|
||||
* ACCEPTED TOKEN LEFT. A rejection is a change of read offset, not a recompute, and `num_accepted`
|
||||
* is a required operand of `gdn_conv_update` and `gdn_recurrent_update` for exactly that reason
|
||||
* Consumers of `n_accepted`: the scheduler frees paged KV blocks past the accepted position. The
|
||||
* linear-attention kernels do not recompute: the recurrent state and conv window have absorbed the
|
||||
* rejected tokens, and libr4d keeps the conv state as a rolling window of `conv_width-1 + n_spec`
|
||||
* entries read at the slot the last accepted token left. A rejection is a read-offset change, which
|
||||
* is why `num_accepted` is an operand of `gdn_conv_update` and `gdn_recurrent_update`
|
||||
* (docs/OPS.md, spec §10).
|
||||
*/
|
||||
#pragma once
|
||||
@@ -53,46 +28,27 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct SpecAcceptParams {
|
||||
int n_draft = 0; /* draft tokens proposed for this sequence */
|
||||
int64_t n_vocab = 0; /* row stride of the probability planes */
|
||||
uint64_t seed = 0; /* the request's seed */
|
||||
uint64_t pos = 0; /* output position of draft token 0 */
|
||||
bool greedy = false; /* temperature 0: argmax acceptance instead of rejection */
|
||||
};
|
||||
|
||||
/* Acceptance by agreement, over precomputed target tokens. `target` is [n_draft+1] -- the token
|
||||
* the target model produced at each verified position, including the bonus position past the last
|
||||
* draft token, which is why the buffer is one longer than the draft. That token is the argmax at
|
||||
* temperature 0 and the target's own sampled draw above it; both are exact, for the reason at the
|
||||
* top of this file. The name describes the temperature-0 case; the rule is correct above it too.
|
||||
/* Acceptance by agreement over precomputed target tokens. `target` is [n_draft+1]: the token the
|
||||
* target produced at each verified position plus the bonus position past the last draft token.
|
||||
* It is the argmax at temperature 0 and the sampled draw above it; the name describes the
|
||||
* temperature-0 case, but the rule is exact for both (see the file header).
|
||||
*
|
||||
* Writes n_accepted+1 tokens into `out` (capacity n_draft+1) and sets *n_accepted. Returns
|
||||
* RAD_OK. Always emits at least one token: the position after the last accepted one is the
|
||||
* target's own answer, which is always correct to emit. */
|
||||
* RAD_OK. Always emits at least one token: the target's own token after the last accepted one. */
|
||||
int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
|
||||
int32_t* out, int32_t* n_accepted);
|
||||
|
||||
/* Rejection sampling. `target_probs` is [(n_draft+1) * n_vocab], each row a NORMALISED
|
||||
* distribution as the sampler chain left it -- filtered, renormalised over the survivors, zero
|
||||
* elsewhere. `draft_probs` is [n_draft * n_vocab] on the same terms, or null for a greedy drafter
|
||||
* (a point mass on the drafted token), which is the common case and the cheap one.
|
||||
*
|
||||
* Writes n_accepted+1 tokens into `out` and sets *n_accepted. Returns RAD_OK, or RAD_E_INVAL on
|
||||
* a malformed argument. A target row that sums to zero -- everything masked out by a grammar --
|
||||
* is RAD_E_STATE: there is no token to emit and the request must fail rather than receive one. */
|
||||
int accept_stochastic(const SpecAcceptParams& p, const int32_t* draft,
|
||||
const float* target_probs, const float* draft_probs,
|
||||
int32_t* out, int32_t* n_accepted);
|
||||
|
||||
/* The one a caller reaches for: dispatches on p.greedy. The greedy path needs `target_argmax`
|
||||
* (which the `sample_argmax` op already produced) and ignores the probability planes; the
|
||||
* stochastic path needs the planes and ignores the argmax. Passing the wrong one for the mode is
|
||||
* RAD_E_INVAL rather than a quiet fallback, because a verify step that silently switched
|
||||
* acceptance rules would change the output distribution and nothing would say so. */
|
||||
int accept_sequence(const SpecAcceptParams& p, const int32_t* draft,
|
||||
const int32_t* target_argmax,
|
||||
const float* target_probs, const float* draft_probs,
|
||||
int32_t* out, int32_t* n_accepted);
|
||||
/* Where a verify step's emission ends: at the first end-of-generation token among `out`'s
|
||||
* n_accepted + 1 tokens (accept_greedy's output), which is emitted, or after all of them. Returns
|
||||
* the number of accepted drafts to commit, at most `n_accepted`. A drafter that predicts the stop
|
||||
* token agrees with the target, so without the cut the run would continue into the next turn.
|
||||
* The card's acceptance (sched/advance_impl.h, ADV_ACCEPT) applies the same rule, and the engine
|
||||
* refuses a step where the two disagree. */
|
||||
template <class IsEog>
|
||||
inline int32_t accept_cut_at_eog(const int32_t* out, int32_t n_accepted, IsEog&& is_eog) {
|
||||
for (int32_t j = 0; j <= n_accepted; ++j)
|
||||
if (is_eog(out[j])) return j;
|
||||
return n_accepted;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+172
-217
@@ -8,7 +8,6 @@
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
@@ -138,14 +137,10 @@ PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start,
|
||||
|
||||
/* ================================================================== the per-vocabulary cache
|
||||
*
|
||||
* EVERYTHING GBNF DERIVES FROM A VOCABULARY, IN ONE OBJECT WHOSE LIFETIME IS THE VOCABULARY'S.
|
||||
* The vocabulary index (gbnf_mask.cpp) and the programs compiled against it are kept on the
|
||||
* VocabView itself rather than in a process-global table keyed on its POINTER. A pointer is not
|
||||
* an identity: a view destroyed and another constructed in the same storage answers to the same
|
||||
* key, and the second one is served the first one's work -- a mask over a vocabulary it is not
|
||||
* sampling from, which admits the wrong token set or none at all with nothing anywhere reporting
|
||||
* it. Hanging it off the view makes that unaskable, and it makes the program cap mean thirty-two
|
||||
* schemas PER VOCABULARY rather than thirty-two shared between every vocabulary a process holds.
|
||||
* Everything GBNF derives from a vocabulary (the vocabulary index and the programs compiled
|
||||
* against it) lives on the VocabView itself, with the vocabulary's lifetime. A global table keyed
|
||||
* on the view's pointer would serve a stale index or program to a new view allocated at the same
|
||||
* address, silently admitting the wrong token set. It also makes the program cap per vocabulary.
|
||||
*/
|
||||
struct GbnfProgram;
|
||||
|
||||
@@ -154,13 +149,10 @@ struct VocabGbnf {
|
||||
std::shared_ptr<const gbnf::VocabIndex> index;
|
||||
double index_ms = 0.0;
|
||||
|
||||
/* One program per (text, root). The cache PINS the most recently used ones -- capped, because
|
||||
* the key comes from client requests and a caller sending a thousand distinct schemas must
|
||||
* not be able to grow it without bound -- and REMEMBERS every other one that is still alive.
|
||||
* A program is kept alive by every request compiled against it (SamplingParams holds it from
|
||||
* admission on), so a request is always served the program it was admitted with, however
|
||||
* many other grammars were compiled in between, and the scheduler thread never recompiles
|
||||
* one. */
|
||||
/* One program per (text, root). The cache pins the most recently used ones (capped, since
|
||||
* keys come from clients) and remembers every other one still alive. Each request holds its
|
||||
* program from admission on (SamplingParams), so it always runs the program it was admitted
|
||||
* with and the scheduler thread never recompiles. */
|
||||
struct Cached {
|
||||
std::shared_ptr<const GbnfProgram> pinned;
|
||||
std::weak_ptr<const GbnfProgram> alive;
|
||||
@@ -170,10 +162,8 @@ struct VocabGbnf {
|
||||
uint64_t clock = 0;
|
||||
};
|
||||
|
||||
/* Created on first use under one process-wide lock; read under the cache's own. Two locks rather
|
||||
* than one because the outer one is taken once per grammar and the inner one is taken for the
|
||||
* duration of a vocabulary index build, which on a quarter-million-piece vocabulary is not
|
||||
* brief. */
|
||||
/* Created on first use under a process-wide lock; contents are guarded by the cache's own lock,
|
||||
* which is held for a whole vocabulary index build (slow on a quarter-million-piece vocabulary). */
|
||||
static VocabGbnf& gbnf_cache_for(const VocabView* v) {
|
||||
static std::mutex m;
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
@@ -211,6 +201,20 @@ int gbnf_prepare_vocab(const VocabView* vocab, GbnfVocabInfo* info) {
|
||||
|
||||
/* ================================================================== lexing helpers */
|
||||
|
||||
/* Where a parse error is, for its message: the rest of the line, at most 40 bytes. Not the rest
|
||||
* of the grammar, which can be megabytes for a generated one. The cut backs up to a character
|
||||
* boundary: the message reaches a JSON error body, whose encoder refuses broken UTF-8. */
|
||||
static std::string where(const char* p) {
|
||||
size_t n = 0;
|
||||
while (p[n] && p[n] != '\n' && p[n] != '\r' && n < 40) ++n;
|
||||
const bool cut = p[n] && p[n] != '\n' && p[n] != '\r';
|
||||
if (cut)
|
||||
while (n > 0 && ((unsigned char)p[n] & 0xC0u) == 0x80u) --n;
|
||||
std::string s(p, n);
|
||||
if (cut) s += "...";
|
||||
return s;
|
||||
}
|
||||
|
||||
static bool is_digit_char(char c) { return '0' <= c && c <= '9'; }
|
||||
static bool is_word_char(char c) {
|
||||
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '-' || is_digit_char(c);
|
||||
@@ -229,7 +233,7 @@ static std::pair<uint32_t, const char*> parse_hex(const char* src, int size) {
|
||||
else break;
|
||||
}
|
||||
if (pos != end)
|
||||
throw std::runtime_error("expecting " + std::to_string(size) + " hex chars at " + src);
|
||||
throw std::runtime_error("expecting " + std::to_string(size) + " hex chars at " + where(src));
|
||||
return { value, pos };
|
||||
}
|
||||
|
||||
@@ -246,20 +250,20 @@ static const char* parse_space(const char* src, bool newline_ok) {
|
||||
static const char* parse_name(const char* src) {
|
||||
const char* pos = src;
|
||||
while (is_word_char(*pos)) pos++;
|
||||
if (pos == src) throw std::runtime_error(std::string("expecting name at ") + src);
|
||||
if (pos == src) throw std::runtime_error(std::string("expecting name at ") + where(src));
|
||||
return pos;
|
||||
}
|
||||
|
||||
static const char* parse_int(const char* src) {
|
||||
const char* pos = src;
|
||||
while (is_digit_char(*pos)) pos++;
|
||||
if (pos == src) throw std::runtime_error(std::string("expecting integer at ") + src);
|
||||
if (pos == src) throw std::runtime_error(std::string("expecting integer at ") + where(src));
|
||||
return pos;
|
||||
}
|
||||
|
||||
/* The repetition count written in [src, end), which parse_int has checked is digits. A count past
|
||||
* 2^64 - 2 is refused here; any smaller one is the compile budget's to judge, by what it expands
|
||||
* to (handle_repetitions). UINT64_MAX itself is reserved for "no maximum". */
|
||||
/* The repetition count in [src, end), already checked to be digits. A count past 2^64 - 2 is
|
||||
* refused here (UINT64_MAX means "no maximum"); smaller ones are judged by the compile budget in
|
||||
* handle_repetitions. */
|
||||
static uint64_t parse_count(const char* src, const char* end) {
|
||||
uint64_t v = 0;
|
||||
for (const char* p = src; p < end; ++p)
|
||||
@@ -282,7 +286,7 @@ static std::pair<uint32_t, const char*> parse_char(const char* src) {
|
||||
case '\\': case '"': case '[': case ']':
|
||||
return { (uint32_t)(uint8_t)src[1], src + 2 };
|
||||
default:
|
||||
throw std::runtime_error(std::string("unknown escape at ") + src);
|
||||
throw std::runtime_error(std::string("unknown escape at ") + where(src));
|
||||
}
|
||||
} else if (*src) {
|
||||
return decode_utf8(src);
|
||||
@@ -291,10 +295,10 @@ static std::pair<uint32_t, const char*> parse_char(const char* src) {
|
||||
}
|
||||
|
||||
/* `<[id]>` is a literal token id; `<text>` resolves through the vocabulary and must tokenise to
|
||||
* exactly one token, because a rule element is one terminal. */
|
||||
* exactly one token, since a rule element is one terminal. */
|
||||
static std::pair<uint32_t, const char*> parse_token(const VocabView* vocab, const char* src) {
|
||||
const char* pos = src;
|
||||
if (*pos != '<') throw std::runtime_error(std::string("expecting '<' at ") + pos);
|
||||
if (*pos != '<') throw std::runtime_error(std::string("expecting '<' at ") + where(pos));
|
||||
pos++;
|
||||
|
||||
if (*pos == '[') {
|
||||
@@ -302,17 +306,17 @@ static std::pair<uint32_t, const char*> parse_token(const VocabView* vocab, cons
|
||||
const char* int_end = parse_int(pos);
|
||||
const uint32_t id = (uint32_t)std::stoul(std::string(pos, (size_t)(int_end - pos)));
|
||||
pos = int_end;
|
||||
if (*pos != ']') throw std::runtime_error(std::string("expecting ']' at ") + pos);
|
||||
if (*pos != ']') throw std::runtime_error(std::string("expecting ']' at ") + where(pos));
|
||||
pos++;
|
||||
if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + pos);
|
||||
if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + where(pos));
|
||||
pos++;
|
||||
return { id, pos };
|
||||
}
|
||||
|
||||
if (!vocab) throw std::runtime_error(std::string("no vocabulary to parse token at ") + src);
|
||||
if (!vocab) throw std::runtime_error(std::string("no vocabulary to parse token at ") + where(src));
|
||||
|
||||
while (*pos != 0 && *pos != '>') pos++;
|
||||
if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + pos);
|
||||
if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + where(pos));
|
||||
pos++;
|
||||
|
||||
std::vector<int32_t> toks;
|
||||
@@ -324,11 +328,11 @@ static std::pair<uint32_t, const char*> parse_token(const VocabView* vocab, cons
|
||||
|
||||
/* ================================================================== the parser */
|
||||
|
||||
/* What a symbol costs beyond its name: the map node that holds it and the rule slot it owns. */
|
||||
/* Bytes a symbol costs beyond its name: its map node and its rule slot. */
|
||||
static constexpr uint64_t kSymbolOverhead = 64 + sizeof(GbnfRule);
|
||||
|
||||
/* Saturating: `bytes` may be a count from the grammar text times a size, and a sum that wrapped
|
||||
* would pass. budget_used_ never exceeds the budget, so the comparison cannot overflow. */
|
||||
/* Written as a subtraction so a huge `bytes` (a client count times a size) cannot wrap the sum;
|
||||
* budget_used_ never exceeds the budget, so the subtraction cannot underflow. */
|
||||
void GbnfParser::charge(uint64_t bytes) {
|
||||
if (bytes > kMaxCompileBytes - budget_used_)
|
||||
throw std::runtime_error("the grammar expands past " +
|
||||
@@ -344,8 +348,8 @@ uint32_t GbnfParser::get_symbol_id(const char* src, size_t len) {
|
||||
return r.first->second;
|
||||
}
|
||||
|
||||
/* A generated name repeats its base, so a long rule name times many generated rules is an
|
||||
* amplification the text does not pay for; it is charged like any other. */
|
||||
/* A generated name repeats its base, so many generated rules under a long name amplify the text;
|
||||
* charged accordingly. */
|
||||
uint32_t GbnfParser::generate_symbol_id(const std::string& base) {
|
||||
charge(base.size() + 12 + kSymbolOverhead);
|
||||
const uint32_t next_id = (uint32_t)symbol_ids_.size();
|
||||
@@ -377,26 +381,23 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
size_t last_sym_start = rule.size();
|
||||
const char* pos = src;
|
||||
|
||||
/* S{m,n} is rewritten into rules rather than counted at match time, which is what keeps the
|
||||
* state machine a pushdown automaton with no counters in it:
|
||||
/* S{m,n} is rewritten into rules rather than counted at match time, so the machine stays a
|
||||
* pushdown automaton without counters:
|
||||
* S{m,n} -> S S ... (m times) S'(n-m), S'(x) ::= S S'(x-1) |
|
||||
* S{m,} -> S S ... (m times) S', S' ::= S S' |
|
||||
* S* -> S{0,} S+ -> S{1,} S? -> S{0,1}
|
||||
*
|
||||
* WHAT BOUNDS THE EXPANSION IS ITS SIZE, charged to the compile budget before any of it is
|
||||
* made, and not a count of repetitions. Upstream refuses any count past 2000, and a JSON
|
||||
* schema's `maxLength: 8000` -- an ordinary bound on a tool's free-text argument -- failed
|
||||
* every request carrying the tool. The expansion is linear in the count: each optional link
|
||||
* is a rule of a few elements and a generated name, and nothing after the parse is worse than
|
||||
* linear in the rules (find_left_recursion, and the mask plan, which gives every link past
|
||||
* the longest token one class). So `[^"]{0,8000}` costs about a megabyte and compiles to the
|
||||
* plan `[^"]{0,1999}` does, and a count the budget cannot hold is refused naming its rule. */
|
||||
* The expansion is bounded by its size, charged to the compile budget before it is built, not
|
||||
* by a repetition count (upstream's cap of 2000 rejects ordinary schemas such as
|
||||
* `maxLength: 8000`). It is linear in the count, and nothing after the parse is worse than
|
||||
* linear in the rules; the mask plan gives every link past the longest token one class. So
|
||||
* `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`. */
|
||||
auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
|
||||
const bool no_max = max_times == UINT64_MAX;
|
||||
if (last_sym_start == rule.size())
|
||||
throw std::runtime_error(std::string("expecting preceding item to */+/?/{ at ") + pos);
|
||||
throw std::runtime_error(std::string("expecting preceding item to */+/?/{ at ") + where(pos));
|
||||
|
||||
/* `n_opt` below is max - min, which a reversed range would wrap to about 1.8e19 rules. */
|
||||
/* `n_opt` below is max - min, which a reversed range would wrap to ~1.8e19 rules. */
|
||||
if (!no_max && max_times < min_times)
|
||||
throw std::runtime_error("repetition {" + std::to_string(min_times) + "," +
|
||||
std::to_string(max_times) + "} has its minimum above its "
|
||||
@@ -404,14 +405,12 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
|
||||
const GbnfRule prev_rule(rule.begin() + (std::ptrdiff_t)last_sym_start, rule.end());
|
||||
|
||||
/* A refusal names the repetition: the count is what a client wrote. */
|
||||
/* A refusal names the repetition the client wrote. */
|
||||
try {
|
||||
/* The copies about to be made: the operand once per required count beyond the
|
||||
* first, and once more in each optional rule with its reference, ALT and END. The
|
||||
* counts are the grammar's own, up to 2^64 - 2, so the arithmetic saturates where it
|
||||
* would wrap: a count past the budget is refused here, before the loops below start.
|
||||
* Each generated rule's name and slot are charged again as it is made
|
||||
* (generate_symbol_id). */
|
||||
/* Charge the copies up front: the operand once per required count beyond the first,
|
||||
* and once per optional rule plus its reference, ALT and END. Counts reach 2^64 - 2,
|
||||
* so overflow saturates and is refused before the loops run. Each generated rule's
|
||||
* name and slot are charged again in generate_symbol_id. */
|
||||
{
|
||||
const uint64_t w = prev_rule.size();
|
||||
const uint64_t n_rest = no_max ? 1 : max_times - min_times;
|
||||
@@ -506,7 +505,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
--depth_;
|
||||
last_sym_start = rule.size();
|
||||
rule.push_back({ GRE_RULE_REF, sub_rule_id });
|
||||
if (*pos != ')') throw std::runtime_error(std::string("expecting ')' at ") + pos);
|
||||
if (*pos != ')') throw std::runtime_error(std::string("expecting ')' at ") + where(pos));
|
||||
pos = parse_space(pos + 1, is_nested);
|
||||
} else if (*pos == '.') { /* any char */
|
||||
last_sym_start = rule.size();
|
||||
@@ -524,7 +523,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
} else if (*pos == '{') {
|
||||
pos = parse_space(pos + 1, is_nested);
|
||||
if (!is_digit_char(*pos))
|
||||
throw std::runtime_error(std::string("expecting an int at ") + pos);
|
||||
throw std::runtime_error(std::string("expecting an int at ") + where(pos));
|
||||
const char* int_end = parse_int(pos);
|
||||
const uint64_t min_times = parse_count(pos, int_end);
|
||||
pos = parse_space(int_end, is_nested);
|
||||
@@ -540,10 +539,10 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
max_times = parse_count(pos, e);
|
||||
pos = parse_space(e, is_nested);
|
||||
}
|
||||
if (*pos != '}') throw std::runtime_error(std::string("expecting '}' at ") + pos);
|
||||
if (*pos != '}') throw std::runtime_error(std::string("expecting '}' at ") + where(pos));
|
||||
pos = parse_space(pos + 1, is_nested);
|
||||
} else {
|
||||
throw std::runtime_error(std::string("expecting ',' at ") + pos);
|
||||
throw std::runtime_error(std::string("expecting ',' at ") + where(pos));
|
||||
}
|
||||
handle_repetitions(min_times, max_times);
|
||||
} else {
|
||||
@@ -561,12 +560,11 @@ const char* GbnfParser::parse_rule(const char* src) {
|
||||
const std::string name(src, name_len);
|
||||
|
||||
if (!(pos[0] == ':' && pos[1] == ':' && pos[2] == '='))
|
||||
throw std::runtime_error(std::string("expecting ::= at ") + pos);
|
||||
throw std::runtime_error(std::string("expecting ::= at ") + where(pos));
|
||||
pos = parse_space(pos + 3, true);
|
||||
|
||||
/* An error inside a rule names the rule. A grammar written from a JSON schema or a tool list
|
||||
* names its rules after the tool and the property, so this is what tells a client which part
|
||||
* of its request the grammar could not hold. */
|
||||
/* An error inside a rule names the rule. Grammars generated from a schema or tool list name
|
||||
* rules after the tool and property, so this points the client at the failing part. */
|
||||
try {
|
||||
pos = parse_alternates(pos, name, rule_id, false);
|
||||
} catch (const std::runtime_error& ex) {
|
||||
@@ -575,7 +573,7 @@ const char* GbnfParser::parse_rule(const char* src) {
|
||||
|
||||
if (*pos == '\r') pos += pos[1] == '\n' ? 2 : 1;
|
||||
else if (*pos == '\n') pos++;
|
||||
else if (*pos) throw std::runtime_error(std::string("expecting newline or end at ") + pos);
|
||||
else if (*pos) throw std::runtime_error(std::string("expecting newline or end at ") + where(pos));
|
||||
return parse_space(pos, true);
|
||||
}
|
||||
|
||||
@@ -587,8 +585,7 @@ int GbnfParser::parse(const char* src, std::string* err) {
|
||||
const char* pos = parse_space(src, true);
|
||||
while (*pos) pos = parse_rule(pos);
|
||||
|
||||
/* Every referenced rule must exist. Upstream reports the missing NAME rather than the
|
||||
* index, which is the difference between a diagnostic and a number. */
|
||||
/* Every referenced rule must exist; report the missing rule by name, as upstream does. */
|
||||
for (const auto& rule : rules_) {
|
||||
if (rule.empty()) throw std::runtime_error("undefined rule");
|
||||
for (const auto& e : rule) {
|
||||
@@ -601,8 +598,8 @@ int GbnfParser::parse(const char* src, std::string* err) {
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& ex) {
|
||||
/* The parser is recursive descent and throws, as upstream's does. Nothing escapes: a
|
||||
* parse failure is a status and a message, because errors are values here. */
|
||||
/* The parser throws internally, as upstream's does; a failure leaves as a status and
|
||||
* message. */
|
||||
if (err) *err = ex.what();
|
||||
rules_.clear();
|
||||
return RAD_E_FORMAT;
|
||||
@@ -614,8 +611,8 @@ int GbnfParser::parse(const char* src, std::string* err) {
|
||||
|
||||
namespace gbnf {
|
||||
|
||||
/* Every bound is an O(1) check on the path each stack already takes, and a grammar that reaches
|
||||
* one throws GbnfLimit (see "what a grammar may cost" in gbnf_internal.h). */
|
||||
/* Each bound is an O(1) check on the existing path; a grammar that reaches one throws GbnfLimit
|
||||
* ("what a grammar may cost", gbnf_internal.h). */
|
||||
void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks& out,
|
||||
SetBuild& build) {
|
||||
auto too_wide = [] {
|
||||
@@ -663,9 +660,8 @@ void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks&
|
||||
build.insert(out, std::move(curr));
|
||||
break;
|
||||
default:
|
||||
/* END, ALT, CHAR_ALT and CHAR_RNG_UPPER can never be the top of a stack. Reaching
|
||||
* one is a broken invariant in this file, not a runtime condition, so it aborts
|
||||
* rather than returning a status nobody could act on. */
|
||||
/* END, ALT, CHAR_ALT and CHAR_RNG_UPPER are never a stack top; reaching one is a
|
||||
* broken invariant, so abort. */
|
||||
fatal("gbnf: stack left on element type %d, which cannot be a stack top",
|
||||
(int)pos->type);
|
||||
}
|
||||
@@ -674,29 +670,24 @@ void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks&
|
||||
|
||||
} /* namespace gbnf */
|
||||
|
||||
/* LEFT RECURSION MAKES advance_stack GROW A STACK FOREVER, so it is found up front rather than
|
||||
* run into. Returns the index of a rule on such a cycle, or -1.
|
||||
/* Left recursion makes advance_stack grow a stack forever, so it is detected up front. Returns
|
||||
* the index of a rule on such a cycle, or -1.
|
||||
*
|
||||
* The epsilon closure expands the rule reference on top of a stack into the first element of
|
||||
* each alternative, and when that first element can match nothing it moves on to the second --
|
||||
* so a reference is in a rule's LEFT CORNER if everything before it in its alternative is
|
||||
* NULLABLE. Expanding a reference also pushes whatever follows it in the alternative, unless it
|
||||
* is the last element; so following a left-corner reference grows the stack by one exactly when
|
||||
* it is not in TAIL position. A cycle of left-corner references therefore grows the stack without
|
||||
* end iff one of its references is not in tail position. A cycle of tail references only revisits
|
||||
* stacks it has already seen, which the closure's `seen` set stops -- `S ::= ("a"?)*` is such a
|
||||
* cycle, and runs.
|
||||
* A reference is in a rule's left corner if everything before it in its alternative is nullable.
|
||||
* Expanding it also pushes what follows it, so it grows the stack exactly when it is not in tail
|
||||
* position. A cycle of left-corner references therefore diverges iff one of its references is not
|
||||
* in tail position; a cycle of tail references only revisits stacks the closure's `seen` set
|
||||
* already stops (`S ::= ("a"?)*` runs).
|
||||
*
|
||||
* NULLABILITY IS A FIXED POINT, not a property of one rule read on its own: `e ::= f` is nullable
|
||||
* because `f ::= "b" |` is, and a check that only recognises an empty alternative misses
|
||||
* `root ::= e root "c" | "a"` and hangs on it. It is computed with a worklist, and the cycle
|
||||
* search is an iterative strongly-connected-components pass, so both are linear in the grammar
|
||||
* and neither recurses: a 100,000-rule chain is a 100,000-frame recursion otherwise. */
|
||||
* Nullability is a fixed point (`e ::= f` is nullable because `f ::= "b" |` is; checking only for
|
||||
* an empty alternative misses `root ::= e root "c" | "a"`). It uses a worklist and the cycle search
|
||||
* an iterative SCC pass, so both are linear and non-recursive (a 100,000-rule chain would
|
||||
* otherwise recurse 100,000 frames deep). */
|
||||
static int64_t find_left_recursion(const GbnfRules& rules) {
|
||||
const size_t n = rules.size();
|
||||
|
||||
/* 1. Which rules can match the empty string. An alternative with a terminal in it never can;
|
||||
* one made only of rule references can once each of them can, so it waits on a count. */
|
||||
/* 1. Which rules can match the empty string. An alternative with a terminal never can; one of
|
||||
* only rule references can once all of them can, tracked by a pending count. */
|
||||
std::vector<char> nullable(n, 0);
|
||||
std::vector<uint32_t> alt_owner, alt_pending, work;
|
||||
std::vector<std::vector<uint32_t>> waiting(n); /* rule -> alternatives it holds up */
|
||||
@@ -735,8 +726,8 @@ static int64_t find_left_recursion(const GbnfRules& rules) {
|
||||
}
|
||||
waiting = {};
|
||||
|
||||
/* 2. The left-corner graph, one edge per reference that can come first, marked by whether it
|
||||
* is in tail position. */
|
||||
/* 2. The left-corner graph: one edge per reference that can come first, marked `grows` when
|
||||
* not in tail position. */
|
||||
struct Edge { uint32_t to; bool grows; };
|
||||
std::vector<size_t> edge_off(n + 1, 0);
|
||||
std::vector<Edge> edges;
|
||||
@@ -754,8 +745,8 @@ static int64_t find_left_recursion(const GbnfRules& rules) {
|
||||
edge_off[r + 1] = edges.size();
|
||||
}
|
||||
|
||||
/* 3. Strongly connected components (Tarjan's, with an explicit call stack). A growing edge
|
||||
* between two rules of one component -- a self-loop included -- is the cycle. */
|
||||
/* 3. Strongly connected components (Tarjan's, explicit call stack). A growing edge within one
|
||||
* component, self-loops included, is the cycle. */
|
||||
std::vector<int32_t> idx(n, -1), low(n, 0), comp(n, -1);
|
||||
std::vector<char> on_stack(n, 0);
|
||||
std::vector<uint32_t> scc;
|
||||
@@ -805,26 +796,17 @@ static int64_t find_left_recursion(const GbnfRules& rules) {
|
||||
|
||||
/* ================================================================== the compiled program */
|
||||
|
||||
/* THE COMPILED GRAMMAR IS NOT PER-REQUEST.
|
||||
/* The compiled program is shared, not per request. Its rules, initial stack set, mask plan and
|
||||
* the mask of each reachable state are a pure function of (text, root, vocabulary). A
|
||||
* GbnfGrammar per request holds only the position in it. Sharing means:
|
||||
* - repeated calls with the same grammar parse and plan it once;
|
||||
* - tensor-parallel ranks share one plan and mask cache, so every rank past the first hits;
|
||||
* - a state one request reached is never recomputed by a later one;
|
||||
* - the plan is built on the admitting thread, never the scheduler thread.
|
||||
*
|
||||
* Everything here is a pure function of (grammar text, root, vocabulary): the rules, the initial
|
||||
* stack set, the mask plan, and the token mask each reachable state admits. None of it depends on
|
||||
* which request is asking. A GbnfGrammar is created per request all the same, because the
|
||||
* POSITION in the program is per-request; what a grammar must NOT carry is a private copy of the
|
||||
* program, or an agent that calls the same tool twenty times parses the same grammar twenty times
|
||||
* and builds the same plan twenty times over.
|
||||
*
|
||||
* So the program is shared, and three things fall out of that beyond the obvious one: every
|
||||
* TENSOR-PARALLEL RANK shares one plan and one mask cache (the ranks hold separate grammars over
|
||||
* the same program and ask for the same full-vocabulary mask, so every rank past the first is a
|
||||
* hit); a state one request reached is a state no later request recomputes; and the plan -- the
|
||||
* expensive part, built once per grammar -- is built on the thread that ADMITS the first request
|
||||
* for it, which is never the scheduler thread.
|
||||
*
|
||||
* The stacks hold pointers into `rules`, so `rules` is immutable after publication and the
|
||||
* program is held by shared_ptr: a live grammar keeps its program alive even after the cache has
|
||||
* stopped pinning it, and those pointers are what makes a state comparable across requests at
|
||||
* all. */
|
||||
* Stacks point into `rules`, so `rules` is immutable after publication and the program is held by
|
||||
* shared_ptr: a live grammar keeps it alive after the cache unpins it. Those pointers are also
|
||||
* what makes a state comparable across requests. */
|
||||
struct GbnfState {
|
||||
GbnfStacks stacks; /* sorted, so the key does not depend on the order a walk produced */
|
||||
PartialUtf8 partial;
|
||||
@@ -838,10 +820,9 @@ struct GbnfState {
|
||||
}
|
||||
};
|
||||
|
||||
/* A STATE AS fill_mask HOLDS IT, NOT COPIED: the stacks through pointers, in the order the key
|
||||
* sorts them into. It hashes and compares as the GbnfState it would become, so the cache is
|
||||
* probed without building a key -- a copy of every stack, per mask -- and one is built only for a
|
||||
* mask that is stored. */
|
||||
/* A state as fill_mask holds it, uncopied: the stacks through pointers, in the key's sorted
|
||||
* order. It hashes and compares like the GbnfState it would become, so a probe copies no stacks;
|
||||
* a key is built only to store a mask. */
|
||||
struct GbnfStateView {
|
||||
const std::vector<const GbnfStack*>* stacks;
|
||||
PartialUtf8 partial;
|
||||
@@ -911,25 +892,21 @@ struct GbnfProgram {
|
||||
gbnf::MaskPlanPtr plan; /* see gbnf_mask.cpp */
|
||||
GbnfProgramInfo info;
|
||||
|
||||
/* Masks computed rather than served from the memo below, for the sampler's instrument.
|
||||
* Atomic because it is read and written off the lock; relaxed because it is a counter and
|
||||
* nothing is ordered against it. */
|
||||
/* Masks computed rather than served from the memo below (the sampler's instrument). Atomic
|
||||
* because it is used outside the lock; relaxed because nothing is ordered against it. */
|
||||
mutable std::atomic<uint64_t> computed{0};
|
||||
|
||||
/* THE MASK CACHE IS SHARED BETWEEN THREADS: every rank reaches it. A mask is a few kilobytes,
|
||||
* so entries are handed out by value under the lock and computed OUTSIDE it -- two threads
|
||||
* racing the same state both compute it and agree, which wastes a plan lookup and cannot
|
||||
* produce a wrong mask. It saves every rank past the first the plan work for a state, and a
|
||||
* speculative window revisiting a state the work again. */
|
||||
/* The mask cache is shared by every rank's thread. Masks are a few KiB, copied out under the
|
||||
* lock and computed outside it; two threads racing on one state both compute the same mask,
|
||||
* which only wastes work. */
|
||||
mutable std::mutex mu;
|
||||
struct Entry { std::vector<uint32_t> mask; uint64_t used = 0; };
|
||||
mutable std::unordered_map<GbnfState, Entry, GbnfStateHash, GbnfStateEq> masks;
|
||||
mutable uint64_t clock = 0;
|
||||
|
||||
/* A tool-calling schema's working set is on the order of a hundred states; 512 is room for a
|
||||
* schema several times larger, at a few megabytes of host memory for a large vocabulary. Past
|
||||
* it, evict the least recently used -- a linear scan, on a path that only runs behind a mask
|
||||
* that was computed. */
|
||||
/* A tool-calling schema's working set is about a hundred states; 512 leaves room for one
|
||||
* several times larger, at a few MB of host memory for a large vocabulary. Past it, the least
|
||||
* recently used entry is evicted by a linear scan, which runs only after a computed mask. */
|
||||
static constexpr size_t kMaxMasks = 512;
|
||||
|
||||
bool lookup(const GbnfStateView& k, uint32_t* dst, int64_t n_words) const {
|
||||
@@ -961,12 +938,12 @@ GbnfProgramInfo gbnf_program_info(const GbnfProgram& p) { return p.info; }
|
||||
|
||||
namespace {
|
||||
|
||||
/* Thirty-two schemas PINNED PER VOCABULARY. Capped because the key comes from client requests: a
|
||||
* caller sending a thousand distinct schemas must not be able to grow this without bound. */
|
||||
/* Programs pinned per vocabulary. Capped because keys come from clients, who must not be able to
|
||||
* grow the cache without bound. */
|
||||
constexpr size_t kMaxPrograms = 32;
|
||||
|
||||
/* Unpin the least recently used past either cap, and forget what nothing holds any more. The
|
||||
* caller holds C.mu. */
|
||||
/* Unpin least recently used programs past either cap, and forget those nothing holds. Caller
|
||||
* holds C.mu. */
|
||||
void cache_trim(VocabGbnf& C) {
|
||||
for (;;) {
|
||||
size_t pinned = 0, bytes = 0;
|
||||
@@ -986,8 +963,8 @@ void cache_trim(VocabGbnf& C) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The program for (text, root) if one is pinned or still alive, re-pinned as the most recently
|
||||
* used. The caller holds C.mu. */
|
||||
/* The program for (text, root) if pinned or still alive, re-pinned as most recently used. Caller
|
||||
* holds C.mu. */
|
||||
std::shared_ptr<const GbnfProgram> cache_find(VocabGbnf& C,
|
||||
const std::pair<std::string, std::string>& key) {
|
||||
auto it = C.programs.find(key);
|
||||
@@ -1010,11 +987,8 @@ std::shared_ptr<const GbnfProgram> cache_find(VocabGbnf& C,
|
||||
static int program_for_impl(const std::string& text, const std::string& root,
|
||||
const VocabView* vocab, std::shared_ptr<const GbnfProgram>* out,
|
||||
std::string* err) {
|
||||
/* KEYED ON (text, root) INSIDE THE VOCABULARY'S OWN CACHE, and not on (text, root, address)
|
||||
* in a table outside it. A compiled program embeds the vocabulary index and a plan over it,
|
||||
* so a table keyed on an address serves one vocabulary's whole compiled grammar to whichever
|
||||
* later view lands in the same storage -- and the mask that comes out is over a vocabulary
|
||||
* the request is not sampling from. */
|
||||
/* Keyed on (text, root) inside the vocabulary's own cache; see "the per-vocabulary cache"
|
||||
* for why not on the view's address. */
|
||||
VocabGbnf& C = gbnf_cache_for(vocab);
|
||||
const std::pair<std::string, std::string> key{ text, root };
|
||||
{
|
||||
@@ -1025,8 +999,8 @@ static int program_for_impl(const std::string& text, const std::string& root,
|
||||
}
|
||||
}
|
||||
|
||||
/* Compiled outside the lock: two callers racing the same new grammar would otherwise
|
||||
* serialise behind the plan build. The loser's copy is dropped on insert. */
|
||||
/* Compiled outside the lock so callers do not serialise behind a plan build. If two race on
|
||||
* the same grammar, the loser's copy is dropped on insert. */
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
GbnfParser parser(vocab);
|
||||
std::string perr;
|
||||
@@ -1062,8 +1036,8 @@ static int program_for_impl(const std::string& text, const std::string& root,
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* `rules` is final from here: the stacks hold pointers INTO it, so any later reallocation
|
||||
* would dangle every one of them. Upstream makes the same point with a move. */
|
||||
/* `rules` is final from here: stacks point into it, so a later reallocation would dangle
|
||||
* them. */
|
||||
auto p = std::make_shared<GbnfProgram>();
|
||||
for (const GbnfRule& r : parser.rules()) {
|
||||
p->rules.start.push_back((uint32_t)p->rules.elems.size());
|
||||
@@ -1116,10 +1090,9 @@ static int program_for_impl(const std::string& text, const std::string& root,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* NOTHING THROWN WHILE COMPILING LEAVES HERE. The parser catches its own errors, but the stack
|
||||
* machinery after it throws GbnfLimit on a grammar that outgrows its bounds, and any step can run
|
||||
* out of memory -- and this runs on the thread that admits the request, where an escaping
|
||||
* exception is std::terminate for every request on the server. */
|
||||
/* No exception escapes compiling. The stack machinery throws GbnfLimit and any step can throw
|
||||
* bad_alloc; this runs on the admitting thread, where an escaping exception would terminate the
|
||||
* server. */
|
||||
static int program_for(const std::string& text, const std::string& root, const VocabView* vocab,
|
||||
std::shared_ptr<const GbnfProgram>* out, std::string* err) {
|
||||
try {
|
||||
@@ -1150,10 +1123,15 @@ int GbnfGrammar::create(const std::string& text, const std::string& root, const
|
||||
const std::vector<int32_t>& trigger_tokens,
|
||||
std::unique_ptr<GbnfGrammar>* out, std::string* err) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
/* A lazy grammar constrains nothing until a trigger fires, so without one it never would. */
|
||||
if (lazy && trigger_words.empty() && trigger_tokens.empty()) {
|
||||
if (err) *err = "a lazy grammar needs at least one word or token trigger; without one it "
|
||||
"never constrains";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The parse, the left-recursion check and the initial stack set are all shared, and so is the
|
||||
* mask cache behind them: this is a lookup on the second request that asks for the same
|
||||
* schema. What stays per-request is the position in the program and the triggers. */
|
||||
/* The compiled program is shared, so a repeated grammar is a cache lookup. Only the position
|
||||
* in the program and the triggers are per request. */
|
||||
std::shared_ptr<const GbnfProgram> prog;
|
||||
const int st = program_for(text, root, vocab, &prog, err);
|
||||
if (st < 0) return st;
|
||||
@@ -1205,10 +1183,9 @@ static void accept_chr(const GbnfRuleSet& rules, const GbnfStack& stack, uint32_
|
||||
advance_stack(rules, next, out, build);
|
||||
}
|
||||
|
||||
/* A grammar that outgrew its bounds while accepting cannot be continued: the state it would be
|
||||
* in was never built. It is left with no live stack, so the next mask reports it and the request
|
||||
* is failed there, and the status says which of the two this was. A speculative walk rewinds
|
||||
* over it like any other refusal. */
|
||||
/* A grammar that outgrows its bounds while accepting cannot continue, since its next state was
|
||||
* never built. It is left with no live stack, so the next mask fails the request; the status says
|
||||
* which bound was hit. A speculative walk rewinds over it like any other refusal. */
|
||||
int GbnfGrammar::accept_token_piece(int32_t token, const std::string& piece) {
|
||||
try {
|
||||
return accept_token_piece_impl(token, piece);
|
||||
@@ -1234,23 +1211,18 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
|
||||
GbnfStacks new_stacks;
|
||||
SetBuild new_set(work);
|
||||
|
||||
/* THE STACKS THAT MATCH CODE POINTS ARE ADVANCED TOGETHER, one code point at a time, as
|
||||
* accept_str does. Advancing each through the whole piece on its own gives the same set --
|
||||
* the union of the parts is the part of the union -- but when many stacks converge on one
|
||||
* continuation, as every alternative of a wide rule does once it matches, each of them
|
||||
* re-expands that continuation, and the token costs the square of the width.
|
||||
/* Code-point stacks advance together, one code point at a time, as in accept_str. Advancing
|
||||
* each through the whole piece alone gives the same set, but stacks converging on one
|
||||
* continuation (e.g. the alternatives of a wide rule) would each re-expand it, quadratic in
|
||||
* the width.
|
||||
*
|
||||
* AND THEY ARE ADVANCED THROUGH THE MASK PLAN'S AUTOMATON (plan_step), which holds each stack
|
||||
* set as a state with its successors memoised per interval of code points. The set is the
|
||||
* one accept_chr builds; what changes is that a state seen before -- the same free-text
|
||||
* value, token after token -- is a lookup per code point rather than every closure rebuilt,
|
||||
* allocated and de-duplicated again. The set comes back sorted, which nothing reads: the
|
||||
* mask cache sorts its key, and a mask is a union over the stacks.
|
||||
* They step through the mask plan's automaton (plan_step), which memoises each state's
|
||||
* successors per code-point interval, so a seen state costs a lookup per code point instead
|
||||
* of rebuilding closures. The result equals what accept_chr builds; its sorted order is
|
||||
* incidental (the mask cache sorts its own key).
|
||||
*
|
||||
* The new set is written over the one the previous token left (`spare_`) and the two are
|
||||
* swapped, so a set of the same shape, token after token, allocates nothing; and when the
|
||||
* automaton says the token left the set the state it was -- the steady state of a free-text
|
||||
* value -- the set is not touched at all. */
|
||||
* The new set overwrites the previous token's (`spare_`) and the two are swapped, so a
|
||||
* steady-state set allocates nothing; when the state is unchanged the set is not touched. */
|
||||
current_.clear();
|
||||
for (const auto& stack : stacks_) {
|
||||
if (stack.empty()) continue;
|
||||
@@ -1267,7 +1239,7 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
|
||||
}
|
||||
GbnfStacks& out = spare_;
|
||||
if (n_cps > 0 && !current_.empty()) {
|
||||
/* `at_` names a state only when every stack steps over code points, so with it known no
|
||||
/* `at_` names a state only when every stack steps over code points, so when it is known no
|
||||
* stack matched a token terminal above and the set is the stepped stacks alone. */
|
||||
gbnf::PlanState at{ at_.gen, at_.id };
|
||||
const bool same = gbnf::plan_step(*prog_->plan, current_, &at, cps_.data(), n_cps, &out,
|
||||
@@ -1283,9 +1255,9 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
|
||||
current_[i]->end());
|
||||
at_ = At{};
|
||||
}
|
||||
/* What a token terminal matched goes first, then the rest without the ones it already holds;
|
||||
* with nothing matched by token, `out` is the set as it stands -- a state of the automaton,
|
||||
* or a subset of the set before, and either way without duplicates. */
|
||||
/* Stacks from token terminals go first, then the rest, de-duplicated against them. With no
|
||||
* token match, `out` is already duplicate-free (an automaton state, or a subset of the
|
||||
* previous set). */
|
||||
if (!new_stacks.empty()) {
|
||||
for (auto& s : out) new_set.insert(new_stacks, std::move(s));
|
||||
out.swap(new_stacks);
|
||||
@@ -1295,18 +1267,10 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
|
||||
partial_utf8_ = partial;
|
||||
|
||||
if (stacks_.empty()) {
|
||||
/* NOT AN ERROR HERE, WHICH IS WHY IT LOGS AT DEBUG. This is reached as a matter of course
|
||||
* by the SPECULATIVE WALK: Sampler::build_step advances the grammar over each PROPOSAL to
|
||||
* mask the position behind it, and a drafter is free to propose a token the grammar
|
||||
* forbids -- that is precisely what verification is for, and build_step handles it by
|
||||
* setting `dead` and masking no further. A speculative window on a constrained request
|
||||
* reaches this many times a second while behaving perfectly, producing correct, closed
|
||||
* JSON and stopping cleanly. At error level it reads as a defect and is not one.
|
||||
*
|
||||
* A token that is genuinely EMITTED against the mask IS a defect, and only the engine can
|
||||
* tell the two apart -- it alone knows the token was verified and is leaving. Engine::step
|
||||
* checks this status on the post-verification accept and reports it there, which is why
|
||||
* that status must not be dropped. */
|
||||
/* Debug level: the speculative walk (Sampler::build_step) reaches this routinely when a
|
||||
* drafter proposes a forbidden token, and handles it by setting `dead`. An emitted token
|
||||
* that is forbidden is a defect, but only Engine::step can tell, so it reports this
|
||||
* status on the post-verification accept; the status must not be dropped. */
|
||||
RAD_DEBUG("gbnf: token %d (\"%s\") left no live stack", token, piece.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
@@ -1329,8 +1293,8 @@ int GbnfGrammar::accept_token(int32_t token) {
|
||||
recent_.push_back(Recent{ token, scan_.off });
|
||||
const uint64_t start = scanner_->feed(scan_, piece.data(), piece.size());
|
||||
if (start == WordScanner::npos) {
|
||||
/* Keep only the tokens a word completing later could begin in: one that ends at or
|
||||
* before (fed - longest + 1) cannot hold the first byte of any word still to come. */
|
||||
/* Keep only tokens a later word could begin in: one ending at or before
|
||||
* (fed - longest + 1) cannot hold the first byte of a word still to come. */
|
||||
const uint64_t reach = scanner_->max_len() - 1;
|
||||
const uint64_t keep = scan_.off > reach ? scan_.off - reach : 0;
|
||||
size_t drop = 0;
|
||||
@@ -1343,8 +1307,8 @@ int GbnfGrammar::accept_token(int32_t token) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Replay from the first byte of the word, splitting the token it begins inside: the bytes
|
||||
* in front of it were free-form output and the grammar never claimed them. */
|
||||
/* Replay from the word's first byte, splitting the token it begins in; the bytes before it
|
||||
* are free-form output outside the grammar. */
|
||||
awaiting_trigger_ = false;
|
||||
std::vector<Recent> replay;
|
||||
replay.swap(recent_);
|
||||
@@ -1364,12 +1328,10 @@ int GbnfGrammar::accept_token(int32_t token) {
|
||||
|
||||
if (vocab_->is_eog(token)) {
|
||||
if (complete()) return RAD_OK;
|
||||
/* DEBUG FOR THE SAME REASON AS "left no live stack" in accept_token_piece. The mask admits
|
||||
* an end-of-generation token only once a stack has completed, so an emitted one does not
|
||||
* land here; what does is the speculative walk over a drafter's PROPOSAL, and a drafter
|
||||
* proposes the end of the turn whenever the text looks finished -- often, on a reply that
|
||||
* its token limit cuts off mid-structure. The emitted case is the defect, and
|
||||
* Engine::step reports it from this status. */
|
||||
/* Debug level, as for "left no live stack" in accept_token_piece. The mask admits EOG
|
||||
* only once a stack has completed, so this is normally a drafter's proposal in the
|
||||
* speculative walk; an emitted one is a defect that Engine::step reports from this
|
||||
* status. */
|
||||
RAD_DEBUG("gbnf: end-of-generation token %d offered while no stack had completed", token);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
@@ -1407,7 +1369,6 @@ int GbnfGrammar::accept_str(const std::string& piece) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
void GbnfGrammar::push_state() {
|
||||
saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_, at_ });
|
||||
}
|
||||
@@ -1432,17 +1393,15 @@ int GbnfGrammar::rollback() {
|
||||
int GbnfGrammar::mask_compute(uint32_t* bitmask, int64_t n_words) const {
|
||||
std::fill(bitmask, bitmask + n_words, 0u);
|
||||
|
||||
/* A DEAD STACK SET ADMITS NOTHING. It is reachable: accept_token_piece assigns the empty set
|
||||
* on the paths where it reports a failure, so anything that keeps asking for masks after that
|
||||
* arrives here, and the answer is the status the state deserves -- not a mask. */
|
||||
/* A dead (empty) stack set admits nothing. accept_token_piece leaves one after a failure, so
|
||||
* a later mask request gets a status here, not a mask. */
|
||||
if (stacks_.empty()) {
|
||||
RAD_ERR("gbnf: the grammar has no live parse left; the request cannot be continued");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* A mask that outgrows the bounds in "what a grammar may cost" throws from deep inside the
|
||||
* stack machinery, and this is on the scheduler thread: it becomes a status that fails the
|
||||
* request, never an exception that ends the process. */
|
||||
/* On the scheduler thread, so a mask past the bounds in "what a grammar may cost" becomes a
|
||||
* status that fails the request, never an escaping exception. */
|
||||
try {
|
||||
return gbnf::plan_fill(*prog_->plan, stacks_, partial_utf8_, complete(), bitmask, n_words);
|
||||
} catch (const GbnfLimit& e) {
|
||||
@@ -1459,21 +1418,17 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
|
||||
const int64_t n_tok = vocab_->n_tokens();
|
||||
if (n_words < bitmask_words(n_tok)) return RAD_E_SHAPE;
|
||||
|
||||
/* A lazy grammar that has not triggered constrains nothing, so every token is admissible and
|
||||
* the sampler skips the mask op entirely for this sequence. Saying "all ones" rather than
|
||||
* "no mask" keeps one code path in the driver. */
|
||||
/* An untriggered lazy grammar admits every token. The sampler skips the mask op for it anyway;
|
||||
* all ones keeps the driver to one code path. */
|
||||
if (awaiting_trigger_) {
|
||||
std::fill(bitmask, bitmask + n_words, 0xFFFFFFFFu);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE STATE CACHE, ahead of the plan. Keyed on everything fill_mask reads that can change --
|
||||
* the stack set, the carried partial and allow_eog -- and hashed but then compared EXACTLY,
|
||||
* because a collision accepted on the hash alone would hand back a mask for a state the
|
||||
* sequence is not in and admit the wrong token set. The key sorts the stacks: two requests
|
||||
* that reach the same state by the same path produce the same order anyway, but the sort is
|
||||
* what makes that a guarantee rather than an observation. The probe sorts pointers to the
|
||||
* stacks, in storage of the calling thread's own, and copies them only to store. */
|
||||
/* The state cache, ahead of the plan. Keyed on everything fill_mask reads that can change
|
||||
* (stack set, carried partial, allow_eog) and compared exactly after hashing, since a hash
|
||||
* collision would return the wrong mask. Stacks are sorted so equal sets give equal keys. The
|
||||
* probe sorts pointers in thread-local storage and copies stacks only to store. */
|
||||
thread_local std::vector<const GbnfStack*> sorted;
|
||||
sorted.clear();
|
||||
for (const GbnfStack& s : stacks_) sorted.push_back(&s);
|
||||
@@ -1486,7 +1441,7 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
|
||||
const int st = mask_compute(bitmask, n_words);
|
||||
if (st < 0) return st;
|
||||
|
||||
/* Store only a mask that stands: a dead state is not worth an entry and returns above. */
|
||||
/* A failed state returned above and is not cached. */
|
||||
prog_->store(state_of(key), bitmask, n_words);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+99
-126
@@ -1,69 +1,54 @@
|
||||
/* gbnf.h -- the GBNF grammar state machine.
|
||||
*
|
||||
* LIFTED from llama.cpp `src/llama-grammar.{h,cpp}` at upstream commit 06938ac12 (MIT). It lives
|
||||
* under core/sample/ rather than vendor/ because it is on the sampling path and the sampler owns
|
||||
* it; vendor/ belongs to the text frontend. It is vendor-SHAPED all the same: the algorithm is
|
||||
* upstream's, element for element, and the changes are listed here so a future re-lift knows what
|
||||
* to re-apply.
|
||||
*
|
||||
* What changed and why:
|
||||
* Lifted from llama.cpp `src/llama-grammar.{h,cpp}` at upstream commit 06938ac12 (MIT). It lives
|
||||
* in core/sample/ because the sampler owns it, but the algorithm is upstream's element for
|
||||
* element. Changes, for a future re-lift:
|
||||
* - `llama_vocab` became `VocabView` (vocab_view.h), so the sampler does not depend on the
|
||||
* tokeniser's concrete type and a grammar test can state its vocabulary in four lines.
|
||||
* - `GGML_ASSERT` / `GGML_ABORT` became this project's status returns and `fatal()`. Errors are
|
||||
* values (docs/IMPLEMENTATION.md); upstream's aborts inside the stack walk stay aborts,
|
||||
* because they are broken invariants rather than runtime conditions.
|
||||
* - The parser still throws internally -- it is a recursive-descent parser and that is what
|
||||
* upstream does -- but nothing escapes: `parse()` catches and returns a status with the
|
||||
* message in an out-parameter.
|
||||
* tokeniser's concrete type and a test can state its vocabulary in a few lines.
|
||||
* - `GGML_ASSERT` / `GGML_ABORT` became status returns and `fatal()` (errors are values,
|
||||
* docs/IMPLEMENTATION.md). Aborts inside the stack walk stay aborts: they are broken
|
||||
* invariants, not runtime conditions.
|
||||
* - The recursive-descent parser still throws internally; `parse()` catches and returns a
|
||||
* status with the message in an out-parameter.
|
||||
* - `llama_grammar_apply_impl`, which edited a candidate array in place, became `fill_mask`,
|
||||
* which writes a token bitmask. That is the whole reason the state machine stays on host: at
|
||||
* a 151K vocab the mask is 19 KiB, cheap enough to upload every step, where a candidate array
|
||||
* is not (spec §13).
|
||||
* - Everything a client's grammar can make the machine do is BOUNDED (gbnf_internal.h, "what a
|
||||
* grammar may cost"): what a repetition expands to, how deep parentheses nest, how large a
|
||||
* stack set grows, how much an epsilon closure explores, how much work one mask, one accepted
|
||||
* token or one compile does, and how large the automaton and the mask plan grow. A grammar
|
||||
* past a bound is refused at compile time or fails its request at run time; it never takes
|
||||
* the process with it.
|
||||
* - Left recursion is found with nullability computed as a fixed point and an iterative
|
||||
* strongly-connected-components pass. Upstream's recursive check missed recursion through an
|
||||
* indirectly nullable rule, and recursed once per rule of a chain.
|
||||
* - A closure's explored stacks are shared by every closure that builds the same set, the
|
||||
* stacks that match code points are advanced together rather than one at a time, and a
|
||||
* large set is de-duplicated through an index. Each gives the same set as upstream; without
|
||||
* them, stacks that converge on one continuation re-expand it once each.
|
||||
* - Accepting a token steps the stacks that match code points through the mask plan's
|
||||
* stack-set automaton (gbnf_mask.cpp, plan_step) rather than through a closure per stack per
|
||||
* code point, and the grammar remembers which automaton state its stacks are. The set is the
|
||||
* one upstream's accept builds; the test oracle keeps upstream's accept and every accepted
|
||||
* token is held to it.
|
||||
* - The token mask is not upstream's candidate walk. It is served from a plan precomputed when
|
||||
* the grammar is compiled (gbnf_mask.cpp): per stack suffix, the tokens it admits whatever lies
|
||||
* below it, and a small trie of what depends on what does. Upstream's walk survives only as
|
||||
* the test oracle (tests/gbnf_oracle.cpp), and every mask is held to it bit for bit.
|
||||
* which writes a token bitmask: 19 KiB at a 151K vocab, cheap enough to upload every step
|
||||
* where a candidate array is not (spec §13).
|
||||
* - Everything a client grammar can make the machine do is bounded (gbnf_internal.h, "what a
|
||||
* grammar may cost"): repetition expansion, nesting depth, stack-set size, closure
|
||||
* exploration, work per mask, per accepted token and per compile, and automaton and plan
|
||||
* size. A grammar past a bound is refused at compile time or fails its request at run time;
|
||||
* it never takes the process down.
|
||||
* - Left recursion is found with nullability as a fixed point and an iterative SCC pass.
|
||||
* Upstream's recursive check missed recursion through an indirectly nullable rule and
|
||||
* recursed once per rule of a chain.
|
||||
* - A closure's explored stacks are shared by every closure that builds the same set, stacks
|
||||
* that match code points advance together, and a large set is de-duplicated through an
|
||||
* index. Each gives upstream's set; without them, stacks that converge on one continuation
|
||||
* re-expand it once each.
|
||||
* - Accepting a token steps the code-point stacks through the mask plan's stack-set automaton
|
||||
* (gbnf_mask.cpp, plan_step) instead of a closure per stack per code point, and the grammar
|
||||
* remembers which automaton state its stacks are. The set is the one upstream's accept
|
||||
* builds; the test oracle keeps upstream's accept and checks every accepted token against it.
|
||||
* - The token mask is served from a plan precomputed at compile time (gbnf_mask.cpp): per stack
|
||||
* suffix, the tokens it admits whatever lies below it, and a small trie of the tokens that
|
||||
* depend on what does. Upstream's candidate walk survives only as the test oracle
|
||||
* (tests/gbnf_oracle.cpp), and every mask is checked against it bit for bit.
|
||||
*
|
||||
* THE COST OF THE MASK IS ON THE STEP. The mask is built on the scheduler thread with the rank
|
||||
* threads parked at the barrier, so whatever it takes is added to the step time of a constrained
|
||||
* request -- up to four times a step under speculation. A mask that walks the vocabulary costs
|
||||
* more than the decode step it sits inside, and a constrained tool call then runs at many times the
|
||||
* per-token cost of the same model writing prose.
|
||||
*
|
||||
* What it costs as written:
|
||||
*
|
||||
* - Compiling a grammar builds its mask plan, which walks the vocabulary once per place in the
|
||||
* grammar a mask can start. That is milliseconds to a few hundred of them, bounded, and done on
|
||||
* the thread that ADMITS the request (gbnf_compile), never on the scheduler thread.
|
||||
* Cost. The mask is built on the scheduler thread with the rank threads parked at the barrier,
|
||||
* so its cost adds to the step time of a constrained request, up to four times a step under
|
||||
* speculation. A mask that walks the vocabulary costs more than the decode step it sits in.
|
||||
* - Compiling builds the mask plan, walking the vocabulary once per place in the grammar a mask
|
||||
* can start: milliseconds to a few hundred of them, bounded, on the thread that admits the
|
||||
* request (gbnf_compile), never on the scheduler thread.
|
||||
* - A mask is then a key lookup per live stack, an OR of precomputed token sets, and a walk of
|
||||
* the few tokens whose admissibility depends on the stack below the key -- the same cost for
|
||||
* a state seen before and one never seen. A state seen before is also a memcpy from the
|
||||
* program's mask cache, shared by every request and rank that uses the grammar.
|
||||
* - The vocabulary index the plan is built over is computed once per vocabulary and shared.
|
||||
* Nothing is per request and nothing is on the device.
|
||||
* the few tokens whose admissibility depends on the stack below the key, at the same cost for
|
||||
* a new state as for a seen one. A seen state is also a memcpy from the program's mask cache,
|
||||
* shared by every request and rank that uses the grammar.
|
||||
* - The vocabulary index is computed once per vocabulary and shared. Nothing is per request and
|
||||
* nothing is on the device.
|
||||
*
|
||||
* So the state machine stays on host: the cost that would argue for a device-side grammar is a
|
||||
* mask computed by walking the vocabulary per step, and the answer to that is to precompute the
|
||||
* walk (XGrammar's adaptive token-mask cache, carried over to this machine's stacks), not a
|
||||
* different place to run it (spec §13).
|
||||
* So the state machine stays on host: the walk is precomputed (XGrammar's adaptive token-mask
|
||||
* cache, adapted to this machine's stacks) rather than moved to the device (spec §13).
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_internal.h"
|
||||
@@ -98,8 +83,8 @@ struct GbnfElement {
|
||||
uint32_t value; /* code point, rule id, or token id */
|
||||
};
|
||||
|
||||
/* A UTF-8 sequence split across token boundaries. Byte-level BPE emits partial sequences all the
|
||||
* time, so a grammar that could not carry one between tokens would reject perfectly good text. */
|
||||
/* A UTF-8 sequence split across token boundaries. Byte-level BPE emits these routinely, so the
|
||||
* grammar carries one from token to token. */
|
||||
struct PartialUtf8 {
|
||||
uint32_t value = 0; /* bits so far, unshifted */
|
||||
int n_remain = 0; /* bytes still needed; -1 marks an invalid sequence */
|
||||
@@ -110,16 +95,15 @@ using GbnfRules = std::vector<GbnfRule>;
|
||||
using GbnfStack = std::vector<const GbnfElement*>;
|
||||
using GbnfStacks = std::vector<GbnfStack>;
|
||||
|
||||
/* THE COMPILED GRAMMAR, SHARED BY EVERY REQUEST THAT ASKS FOR IT, with its mask plan and its mask
|
||||
* cache. Defined in gbnf.cpp, which says what it is worth; the short version is that nothing
|
||||
* inside it is per-request. `GbnfState` is the mask cache's key: the whole of what fill_mask
|
||||
* reads. */
|
||||
/* The compiled grammar with its mask plan and mask cache, shared by every request that uses it;
|
||||
* nothing in it is per-request (gbnf.cpp). `GbnfState` is the mask cache's key: everything
|
||||
* fill_mask reads. */
|
||||
struct GbnfProgram;
|
||||
struct GbnfState;
|
||||
|
||||
/* What compiling a grammar cost and what the compiled program holds. */
|
||||
struct GbnfProgramInfo {
|
||||
double compile_ms = 0.0; /* all of it: parse, checks and the mask plan */
|
||||
double compile_ms = 0.0; /* parse, checks and mask plan */
|
||||
double plan_ms = 0.0; /* of which, the mask plan */
|
||||
uint64_t plan_work = 0; /* units the plan charged against its bound */
|
||||
size_t rules = 0;
|
||||
@@ -150,15 +134,14 @@ public:
|
||||
const std::map<std::string, uint32_t>& symbol_ids() const { return symbol_ids_; }
|
||||
const GbnfRules& rules() const { return rules_; }
|
||||
|
||||
|
||||
private:
|
||||
const VocabView* vocab_ = nullptr;
|
||||
std::map<std::string, uint32_t> symbol_ids_;
|
||||
GbnfRules rules_;
|
||||
|
||||
/* What the parse has built beyond the text itself, and how deep the parentheses are right
|
||||
* now. Both are bounded (gbnf_internal.h, "what a grammar may cost"), because the text is
|
||||
* client data and the parser runs on shared threads. */
|
||||
/* Bytes built beyond the text itself, and the current parenthesis depth. Both are bounded
|
||||
* (gbnf_internal.h, "what a grammar may cost") because the text is client data parsed on
|
||||
* shared threads. */
|
||||
uint64_t budget_used_ = 0;
|
||||
uint32_t depth_ = 0;
|
||||
void charge(uint64_t bytes);
|
||||
@@ -178,61 +161,55 @@ private:
|
||||
|
||||
class GbnfGrammar {
|
||||
public:
|
||||
/* Build from grammar text. `root` names the start symbol. Returns RAD_OK, or RAD_E_FORMAT /
|
||||
* RAD_E_NOTFOUND / RAD_E_UNSUPPORTED with the reason in *err -- left recursion is
|
||||
* RAD_E_UNSUPPORTED, because it is a grammar this machine cannot run rather than one that is
|
||||
* malformed, and the distinction is what the user needs to fix it.
|
||||
/* Build from grammar text; `root` names the start symbol. Returns RAD_OK, or RAD_E_FORMAT /
|
||||
* RAD_E_NOTFOUND / RAD_E_UNSUPPORTED with the reason in *err. Left recursion is
|
||||
* RAD_E_UNSUPPORTED: the grammar is well-formed but this machine cannot run it.
|
||||
*
|
||||
* A LAZY grammar constrains nothing until a trigger fires, which is how a tool-calling
|
||||
* template stays free-form until the model starts writing a call. A trigger is a token id, or
|
||||
* a literal word found in the generated bytes; parsing resumes from where the word begins. */
|
||||
* A lazy grammar constrains nothing until a trigger fires, so a tool-calling template stays
|
||||
* free-form until the model starts writing a call. A trigger is a token id or a literal word
|
||||
* in the generated bytes; parsing resumes where the word begins. A lazy grammar with no
|
||||
* trigger is RAD_E_INVAL, since it would never constrain. */
|
||||
static int create(const std::string& text, const std::string& root, const VocabView* vocab,
|
||||
bool lazy,
|
||||
const std::vector<std::string>& trigger_words,
|
||||
const std::vector<int32_t>& trigger_tokens,
|
||||
std::unique_ptr<GbnfGrammar>* out, std::string* err);
|
||||
|
||||
/* Advance the state machine over one accepted token. Returns RAD_OK, or RAD_E_STATE if the
|
||||
* token left no stack alive -- which means the sampler emitted a token the grammar forbade,
|
||||
* a bug in the mask rather than in the request. RAD_E_FULL (or RAD_E_NOMEM) means the parse
|
||||
* outgrew the bounds in gbnf_internal.h: the grammar is left dead, and the request cannot go
|
||||
* on. */
|
||||
/* Advance over one accepted token. RAD_E_STATE means the token left no stack alive: the
|
||||
* sampler emitted a forbidden token, a mask bug rather than a bad request. RAD_E_FULL or
|
||||
* RAD_E_NOMEM means the parse outgrew the bounds in gbnf_internal.h; the grammar is left dead
|
||||
* and the request cannot continue. */
|
||||
int accept_token(int32_t token);
|
||||
|
||||
/* Advance over a raw string, for replaying a prompt prefix into the grammar. */
|
||||
int accept_str(const std::string& piece);
|
||||
|
||||
/* Fill a token bitmask: bit set means admissible. `n_words` must be at least
|
||||
* ceil(n_tokens/32). Returns RAD_OK, or RAD_E_STATE if the grammar admits no token at all,
|
||||
* which is a dead grammar and must fail the request rather than produce a random token, or
|
||||
* RAD_E_FULL / RAD_E_NOMEM if the mask outgrew its bounds, which must fail it the same way. */
|
||||
/* Fill a token bitmask, bit set = admissible; `n_words` >= ceil(n_tokens/32). RAD_E_STATE if
|
||||
* no token is admissible (a dead grammar), RAD_E_FULL / RAD_E_NOMEM if the mask outgrew its
|
||||
* bounds. Each must fail the request rather than let a random token through. */
|
||||
int fill_mask(uint32_t* bitmask, int64_t n_words) const;
|
||||
|
||||
/* Some stack has run to completion, so an end-of-generation token is admissible. */
|
||||
bool complete() const;
|
||||
|
||||
/* Masks this grammar's PROGRAM has had to compute rather than serve from its memo. Shared
|
||||
* with every other request on the same program, which is the point: see grammar.h. */
|
||||
/* Masks this grammar's program has computed rather than served from its memo. Shared with
|
||||
* every request on the same program; see grammar.h. */
|
||||
uint64_t masks_walked() const;
|
||||
|
||||
/* A lazy grammar that has not seen its trigger yet constrains nothing. */
|
||||
bool awaiting_trigger() const { return awaiting_trigger_; }
|
||||
|
||||
/* The state as it stands, read-only: what a mask is a function of. The test oracle computes
|
||||
* the same mask from these by upstream's candidate walk. */
|
||||
/* The current state, read-only: what a mask is a function of. The test oracle recomputes the
|
||||
* mask from these with upstream's candidate walk. */
|
||||
const GbnfStacks& stacks() const { return stacks_; }
|
||||
PartialUtf8 partial() const { return partial_utf8_; }
|
||||
const VocabView* vocab() const { return vocab_; }
|
||||
const GbnfProgram& program() const { return *prog_; }
|
||||
|
||||
/* PUSH AND POP THE WHOLE MUTABLE STATE, so a speculative window can be walked forward and
|
||||
* rewound (grammar.h says why). Everything create() fixes -- the rules, the vocabulary, the
|
||||
* decoded vocabulary, the trigger words -- is absent from the snapshot by construction;
|
||||
* what is here is exactly what accepting one token can change. The trigger fields are in it
|
||||
* because a draft token may fire the trigger mid-window, which is a state change like any
|
||||
* other and has to rewind with the rest.
|
||||
*
|
||||
* Nestable, though the sampler only ever needs one level. */
|
||||
/* Push and pop the whole mutable state, so a speculative window can be walked forward and
|
||||
* rewound (see grammar.h). What create() fixes (rules, vocabulary, trigger words) is not in the
|
||||
* snapshot; what accepting a token can change is. That includes the trigger fields, since a
|
||||
* draft token may fire the trigger mid-window. Nestable; the sampler uses one level. */
|
||||
void push_state();
|
||||
int rollback();
|
||||
|
||||
@@ -244,11 +221,10 @@ private:
|
||||
uint64_t start;
|
||||
};
|
||||
|
||||
/* The state of the mask plan's automaton `stacks_` is exactly, when it is one: which
|
||||
* automaton (`gen`) and which state in it, or an id of -1 when that is not known. It lets
|
||||
* accepting skip canonicalising the set, and skip rewriting it when a token leaves it where
|
||||
* it was. Everything that sets `stacks_` other than accepting through the automaton resets
|
||||
* it, or restores it with the stacks it describes. */
|
||||
/* The mask plan's automaton state that `stacks_` is, when known: the automaton (`gen`) and
|
||||
* the state in it, or id -1. Lets accepting skip canonicalising the set, and skip rewriting
|
||||
* it when a token leaves the state unchanged. Anything that sets `stacks_` other than an
|
||||
* automaton step resets it, or restores it together with the stacks it describes. */
|
||||
struct At {
|
||||
uint64_t gen = 0;
|
||||
int32_t id = -1;
|
||||
@@ -265,10 +241,10 @@ private:
|
||||
|
||||
const VocabView* vocab_ = nullptr;
|
||||
|
||||
/* THE RULES ARE SHARED AND THE POSITION IN THEM IS NOT. `stacks_` holds pointers INTO
|
||||
* prog_->rules, so the program has to outlive every grammar positioned in it and must never
|
||||
* be mutated once published -- which is what the shared_ptr and the const are here to say,
|
||||
* and also why the mask cache can be keyed on those pointers across requests at all. */
|
||||
/* The rules are shared; the position in them is not. `stacks_` points into prog_->rules, so
|
||||
* the program must outlive every grammar positioned in it and never change once published
|
||||
* (hence shared_ptr to const). That is also what lets the mask cache key on those pointers
|
||||
* across requests. */
|
||||
std::shared_ptr<const GbnfProgram> prog_;
|
||||
GbnfStacks stacks_;
|
||||
PartialUtf8 partial_utf8_{};
|
||||
@@ -276,15 +252,13 @@ private:
|
||||
|
||||
std::vector<Snapshot> saved_;
|
||||
|
||||
/* The mask itself, from the program's plan, with no memo. */
|
||||
/* The mask from the program's plan, bypassing the memo. */
|
||||
int mask_compute(uint32_t* bitmask, int64_t n_words) const;
|
||||
|
||||
/* THE TRIGGER, while the grammar is lazy and waiting. The words are scanned as the bytes
|
||||
* arrive and nothing already scanned is kept except the few tokens a word could still be
|
||||
* starting in -- at most the longest word's length of them -- which is also all a match
|
||||
* replays. So waiting costs the same on the ten-thousandth token of a reply as on the first,
|
||||
* and so does copying it into a snapshot. The scanner is fixed at create() and shared by
|
||||
* every copy of the state. */
|
||||
/* The trigger, while a lazy grammar waits. Words are scanned as bytes arrive; only the tokens
|
||||
* a word could still be starting in are kept (at most the longest word's length of them),
|
||||
* which is all a match replays. So waiting, and snapshotting it, cost the same on every token.
|
||||
* The scanner is fixed at create() and shared by every copy of the state. */
|
||||
bool awaiting_trigger_ = false;
|
||||
std::vector<int32_t> trigger_tokens_;
|
||||
std::shared_ptr<const WordScanner> scanner_;
|
||||
@@ -294,30 +268,29 @@ private:
|
||||
int accept_token_piece(int32_t token, const std::string& piece);
|
||||
int accept_token_piece_impl(int32_t token, const std::string& piece);
|
||||
|
||||
/* Scratch for accepting, kept so a token in the steady state of a value allocates nothing:
|
||||
* the piece's code points, the stacks that step over them, and the set before the last one
|
||||
* accepted, whose storage the next one is written into. None of it is state. */
|
||||
/* Scratch for accepting, so a steady-state token allocates nothing: the piece's code points,
|
||||
* the stacks that step over them, and the previous set, whose storage the next one reuses.
|
||||
* None of it is state. */
|
||||
std::vector<uint32_t> cps_;
|
||||
std::vector<const GbnfStack*> current_;
|
||||
GbnfStacks spare_;
|
||||
};
|
||||
|
||||
/* COMPILE A GRAMMAR, on the calling thread, into the program every GbnfGrammar::create for the
|
||||
* same (text, root, vocabulary) will be served from while `out` -- or any other holder -- keeps it
|
||||
* alive. This is the whole of the host work a grammar costs before its first mask: the parse, the
|
||||
* checks and the mask plan. The server calls it on the thread that admits the request, so the
|
||||
* scheduler thread never compiles. Returns what GbnfGrammar::create returns. */
|
||||
/* Compile a grammar on the calling thread into the program every GbnfGrammar::create for the
|
||||
* same (text, root, vocabulary) is served from while `out`, or any other holder, keeps it alive.
|
||||
* This is all the host work before a grammar's first mask: parse, checks and mask plan. The
|
||||
* server calls it on the admitting thread, so the scheduler thread never compiles. Returns what
|
||||
* GbnfGrammar::create returns. */
|
||||
int gbnf_compile(const std::string& text, const std::string& root, const VocabView* vocab,
|
||||
std::shared_ptr<const GbnfProgram>* out, std::string* err);
|
||||
|
||||
GbnfProgramInfo gbnf_program_info(const GbnfProgram& p);
|
||||
|
||||
/* Build the vocabulary index every grammar's plan is compiled against, if it is not built yet.
|
||||
* Worth calling once at startup: otherwise the first grammar to arrive pays for it. */
|
||||
/* Build the vocabulary index every grammar's plan is compiled against, if not built yet. Call
|
||||
* once at startup, or the first grammar to arrive pays for it. */
|
||||
int gbnf_prepare_vocab(const VocabView* vocab, GbnfVocabInfo* info);
|
||||
|
||||
/* Words a bitmask needs for this vocabulary. 19 KiB at 151K tokens, which is the number spec §13
|
||||
* quotes and the reason the state machine stays on host. */
|
||||
/* Words a bitmask needs for this vocabulary: 19 KiB at 151K tokens (spec §13). */
|
||||
inline int64_t bitmask_words(int64_t n_vocab) { return (n_vocab + 31) / 32; }
|
||||
|
||||
} /* namespace rad */
|
||||
+93
-116
@@ -1,17 +1,15 @@
|
||||
/* gbnf_internal.h -- what the GBNF state machine's three translation units share, and nothing
|
||||
* else includes.
|
||||
/* gbnf_internal.h -- shared by the GBNF state machine's three translation units only.
|
||||
*
|
||||
* gbnf.cpp the lifted machine: parser, stack machinery, accepting tokens, the compiled
|
||||
* program and its caches.
|
||||
* gbnf_mask.cpp the mask engine: the vocabulary index, the stack-set automaton and the
|
||||
* precomputed mask plan every fill_mask is served from.
|
||||
* tests/gbnf_oracle.cpp
|
||||
* upstream's candidate walk, kept as the oracle the mask engine is tested
|
||||
* against and nowhere on a serving path.
|
||||
* upstream's candidate walk, the test oracle for the mask engine; never on a
|
||||
* serving path.
|
||||
*
|
||||
* The stack machinery lives here rather than in one of them because all three must run the SAME
|
||||
* closure and the same character tests: the oracle is a second implementation of the mask, not of
|
||||
* the parse, and a difference between the two has to mean a defect in the mask engine.
|
||||
* The stack machinery is here so all three run the same closure and character tests: the oracle
|
||||
* reimplements the mask, not the parse, so any disagreement is a mask-engine defect.
|
||||
*/
|
||||
#pragma once
|
||||
#include "gbnf.h"
|
||||
@@ -30,80 +28,70 @@ namespace gbnf {
|
||||
|
||||
/* ============================================================ what a grammar may cost
|
||||
|
||||
* THE GRAMMAR TEXT IS CLIENT DATA, AND IT IS COMPILED AND WALKED ON SHARED THREADS: the HTTP
|
||||
* thread that admits the request, and the scheduler thread every other request's tokens come
|
||||
* from. So nothing a grammar says may make either one use unbounded memory, time or stack -- a
|
||||
* few hundred bytes of text that exhausts the machine is a request that ends every other
|
||||
* request with it. Every bound below is one of those, and each is set well above what real
|
||||
* grammars reach: a JSON schema of 500 tool calls compiles to about 1.3 MB of text, 22,000 rules
|
||||
* and a few megabytes of compiled grammar, nests parentheses two deep, and never holds more than
|
||||
* about 1,500 stacks at once; a schema nested 128 objects deep holds stacks about 130 frames
|
||||
* tall.
|
||||
* Grammar text is client data, compiled and walked on shared threads: the HTTP thread that
|
||||
* admits the request and the scheduler thread that serves every request. So no grammar may make
|
||||
* either use unbounded memory, time or stack. Each bound below is set well above real grammars:
|
||||
* a JSON schema of 500 tool calls compiles to about 1.3 MB of text, 22,000 rules and a few MB of
|
||||
* compiled grammar, nests parentheses two deep, and holds at most about 1,500 stacks at once; a
|
||||
* schema nested 128 objects deep holds stacks about 130 frames tall.
|
||||
*
|
||||
* WHAT A GRAMMAR MAY COMPILE TO, BEYOND ITS OWN TEXT. The parse itself is linear in the text
|
||||
* except where a construct amplifies it: a repetition copies its operand once per count, and a
|
||||
* generated rule's name repeats the name of the rule it came from. Those are charged here, so a
|
||||
* 100 KB literal under `{1999}` is refused before it allocates the 1.6 GB it asks for, and what
|
||||
* a program in the cache can hold is bounded by its text plus this. */
|
||||
* Bytes a grammar may compile to beyond its own text. The parse is linear in the text except
|
||||
* where a construct amplifies it: a repetition copies its operand once per count, and a
|
||||
* generated rule's name repeats its parent's name. Those are charged here, so a 100 KB literal
|
||||
* under `{1999}` is refused before it allocates 1.6 GB, and a cached program is bounded by its
|
||||
* text plus this. */
|
||||
inline constexpr uint64_t kMaxCompileBytes = 32ull << 20;
|
||||
|
||||
/* How deeply parentheses may nest. The parser is recursive descent, a pair of frames per level,
|
||||
* so an unbounded depth is a stack overflow that 40 KB of '(' reaches. */
|
||||
/* Maximum parenthesis nesting. The recursive-descent parser uses two frames per level, so
|
||||
* unbounded depth lets 40 KB of '(' overflow the stack. */
|
||||
inline constexpr uint32_t kMaxNesting = 256;
|
||||
|
||||
/* One SET OF STACKS, which is the whole state of the pushdown automaton at a position: how many
|
||||
* distinct stacks it may hold, and how many elements across all of them. A grammar can make the
|
||||
* set grow without end -- ambiguity that forks a stack per token, or a closure whose paths
|
||||
* multiply -- and every accept, every mask and every cached state copies it. */
|
||||
/* Limits on one stack set (the automaton's whole state at a position): distinct stacks, and
|
||||
* elements across all of them. Ambiguity or multiplying closure paths can grow the set without
|
||||
* end, and every accept, mask and cached state copies it. */
|
||||
inline constexpr size_t kMaxStacks = 1u << 14;
|
||||
inline constexpr size_t kMaxSetElems = 1u << 18;
|
||||
|
||||
/* Stack elements one epsilon closure may push while exploring, and one set may hold as explored,
|
||||
* which bounds the memory a closure holds. A grammar with no left recursion still has closures
|
||||
* whose PATHS multiply (each level of `r ::= s "x" | s "y"` doubles them), so the set bound above
|
||||
* is reached only after the exploring has been done; this is what stops it. */
|
||||
/* Stack elements one epsilon closure may push while exploring, and one set may hold as explored.
|
||||
* Without left recursion, closure paths can still multiply (each level of
|
||||
* `r ::= s "x" | s "y"` doubles them), and the set bound above is only checked after exploring;
|
||||
* this bound stops the exploring itself. */
|
||||
inline constexpr size_t kMaxClosureWork = 1u << 20;
|
||||
|
||||
/* THE WORK ONE OPERATION MAY DO: one accepted token, one mask. The bounds above cap sizes, and
|
||||
* sizes do not cap time: a closure pays for every stack it builds, and a walk pays for every trie
|
||||
* node it visits. So the machinery counts what it does against one budget per operation, in units
|
||||
* of roughly a nanosecond of the thread it runs on: a stack element copied or a char-range element
|
||||
* tested is one; creating a stack -- an allocation and an insertion into the explored set -- costs
|
||||
* kStackCost more. A grammar that needs more than this at one position fails the request rather
|
||||
* than holding the scheduler thread for more than about half a second. */
|
||||
/* Work one operation (one accepted token, one mask) may do. Size bounds do not cap time, so work
|
||||
* is counted per operation in units of roughly a nanosecond: one per stack element copied or
|
||||
* char-range element tested, plus kStackCost per stack created (an allocation and an insertion
|
||||
* into the explored set). Past the limit the request fails rather than hold the scheduler thread
|
||||
* for more than about half a second. */
|
||||
inline constexpr uint64_t kStackCost = 64;
|
||||
inline constexpr uint64_t kMaxOpWork = 1ull << 29;
|
||||
|
||||
/* THE WORK ONE COMPILE MAY DO, in the same units. Compiling precomputes the mask plan (see
|
||||
* gbnf_mask.cpp), which walks the vocabulary once for every place in the grammar where a mask can
|
||||
* start: on a quarter-million-piece vocabulary a tool-calling grammar needs a few tens of millions
|
||||
* of units, 200 tools about two hundred million, and a string bounded past the length of the
|
||||
* vocabulary's longest token -- the most a grammar can make the plan walk -- under two billion.
|
||||
* It runs on the thread that admits the request, never on the scheduler thread, and a grammar
|
||||
* that needs more than this is refused there, in a few seconds at most. */
|
||||
/* Work one compile may do, in the same units. The mask plan (gbnf_mask.cpp) walks the vocabulary
|
||||
* once per place a mask can start. On a quarter-million-piece vocabulary a tool-calling grammar
|
||||
* needs tens of millions of units, 200 tools about 200 million, and the worst case (a string
|
||||
* bounded past the longest token's length) under two billion. Compiling runs on the admitting
|
||||
* thread, never the scheduler thread; a grammar past this is refused within a few seconds. */
|
||||
inline constexpr uint64_t kMaxCompileWork = 1ull << 31;
|
||||
|
||||
/* WHAT ONE COMPILED PLAN MAY HOLD: its precomputed masks and remainder tries. A plan is shared by
|
||||
* every request that uses the grammar and is kept for later ones, so this is what one grammar may
|
||||
* cost the process while it is cached. A 200-tool grammar holds about 16 MiB on a
|
||||
* quarter-million-piece vocabulary, and a string bounded past the longest token about 40. */
|
||||
/* Bytes one compiled plan may hold (precomputed masks and remainder tries), i.e. what one cached
|
||||
* grammar may cost the process. On a quarter-million-piece vocabulary a 200-tool grammar holds
|
||||
* about 16 MiB, and a string bounded past the longest token about 40 MiB. */
|
||||
inline constexpr size_t kMaxPlanBytes = 64ull << 20;
|
||||
|
||||
/* What the programs a vocabulary's cache keeps PINNED may hold together, beside the count it pins.
|
||||
* A program some request still holds is kept whatever this says; one that nothing holds is what
|
||||
* this bounds. */
|
||||
/* Total bytes of the programs a vocabulary's cache pins, alongside its pin count. Bounds only
|
||||
* programs no request holds; a held program is always kept. */
|
||||
inline constexpr size_t kMaxPinnedBytes = 256ull << 20;
|
||||
|
||||
/* The stack-set automaton is a memo that grows as states are discovered, and a grammar whose
|
||||
* stacks deepen with every token discovers new states forever. Past the soft bound it is dropped
|
||||
* and rebuilt lazily at the next mask, which costs warm-up and nothing else; the hard bound is
|
||||
* what one operation may add before it is refused. */
|
||||
/* The stack-set automaton is a memo that grows as states are discovered, without end for a
|
||||
* grammar whose stacks deepen every token. Past the soft bound it is dropped and rebuilt lazily
|
||||
* at the next mask (costing only warm-up); the hard bound is what one operation may add before
|
||||
* it is refused. */
|
||||
inline constexpr size_t kMaxDfaElems = 1u << 22;
|
||||
inline constexpr size_t kMaxDfaWalkElems = 1u << 23;
|
||||
|
||||
/* A bound above was reached. Thrown from inside the stack machinery, which has no status path
|
||||
* (it is lifted code, recursive in places), and caught at every public entry point, where it
|
||||
* becomes a status and the request is refused or failed -- never the process. */
|
||||
/* A bound above was reached. Thrown from the stack machinery, which is lifted, partly recursive
|
||||
* code with no status path, and caught at every public entry point, where it becomes a status
|
||||
* that refuses or fails the request. */
|
||||
struct GbnfLimit : std::runtime_error {
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
@@ -133,16 +121,14 @@ struct StackLess {
|
||||
}
|
||||
};
|
||||
|
||||
/* ONE STACK SET WHILE IT IS BUILT, shared by every call that adds to that set: its running size,
|
||||
* which is what makes the set bounds exact rather than per call; the operation it is built for,
|
||||
* whose work every addition is charged to; and the stacks already explored for it.
|
||||
/* One stack set under construction, shared by every call that adds to it: its running size (so
|
||||
* the set bounds apply to the whole set, not per call), the operation whose work each addition is
|
||||
* charged to, and the stacks already explored.
|
||||
*
|
||||
* THE EXPLORED STACKS ARE THE SET'S, NOT ONE CLOSURE'S. Every stack a closure pops has had its
|
||||
* whole closure added to the set, so a later closure into the same set that reaches it has
|
||||
* nothing left to add there. Keeping `seen` per call instead re-derives it every time -- and when
|
||||
* many stacks converge on one continuation, as every alternative of a wide rule does once it
|
||||
* matches, that is one full re-expansion per stack, quadratic in a width the bounds allow. The
|
||||
* set that comes out, and the order it comes out in, are the same either way. */
|
||||
* `seen` belongs to the set, not to one closure: a stack a closure has popped already has its
|
||||
* whole closure in the set, so a later closure reaching it adds nothing. A per-call `seen` would
|
||||
* re-expand a shared continuation once per converging stack (e.g. every alternative of a wide
|
||||
* rule), quadratic in the width. The resulting set and its order are the same either way. */
|
||||
struct SetBuild {
|
||||
explicit SetBuild(OpWork& w) : work(w) {}
|
||||
|
||||
@@ -158,13 +144,10 @@ struct SetBuild {
|
||||
if (stacks > kMaxStacks || elems > kMaxSetElems) throw_set_limit();
|
||||
}
|
||||
|
||||
/* Append `s` to `out` -- the set this belongs to -- unless it is already there.
|
||||
*
|
||||
* A SET OF A FEW STACKS IS SEARCHED, A LARGE ONE IS INDEXED. The search is what the lifted
|
||||
* code does and is the fastest thing at the sizes real states have; but many stacks that
|
||||
* converge on one continuation each re-expand it into the same set, and a linear search per
|
||||
* insertion makes that quadratic in a set size the bounds allow. Past kIndexFrom the set is
|
||||
* indexed by hash, and the order stacks land in `out` is the same either way. */
|
||||
/* Append `s` to `out` (this build's set) unless already present. Small sets use the lifted
|
||||
* linear search, fastest at real state sizes; past kIndexFrom the set is indexed by hash,
|
||||
* since converging stacks would make linear search quadratic. Insertion order is the same
|
||||
* either way. */
|
||||
void insert(GbnfStacks& out, GbnfStack s);
|
||||
|
||||
private:
|
||||
@@ -221,8 +204,8 @@ inline std::pair<bool, const GbnfElement*> match_char(const GbnfElement* pos, ui
|
||||
return { found == is_positive, pos };
|
||||
}
|
||||
|
||||
/* True iff SOME completion of a partial UTF-8 sequence could satisfy the range at pos. This is
|
||||
* what lets a byte-level BPE token that ends mid-codepoint stay admissible. */
|
||||
/* True iff some completion of a partial UTF-8 sequence could satisfy the range at pos, so a
|
||||
* byte-level BPE token ending mid-codepoint stays admissible. */
|
||||
inline bool match_partial_char(const GbnfElement* pos, PartialUtf8 partial) {
|
||||
const bool is_positive = pos->type == GRE_CHAR || pos->type == GRE_CHAR_ANY;
|
||||
|
||||
@@ -252,8 +235,8 @@ inline bool match_partial_char(const GbnfElement* pos, PartialUtf8 partial) {
|
||||
return !is_positive;
|
||||
}
|
||||
|
||||
/* How many elements the char range at pos spans, which is what one match_char on it costs: it
|
||||
* walks the whole range whatever the code point. */
|
||||
/* Elements the char range at pos spans: the cost of one match_char, which walks the whole range
|
||||
* whatever the code point. */
|
||||
inline size_t char_range_len(const GbnfElement* pos) {
|
||||
return (size_t)(match_char(pos, 0).second - pos);
|
||||
}
|
||||
@@ -266,11 +249,9 @@ inline bool match_token(const GbnfElement* pos, int32_t token) {
|
||||
|
||||
/* ============================================================ the compiled rules
|
||||
|
||||
* EVERY RULE IN ONE ARENA, so an element's address is also its index. The stacks hold element
|
||||
* pointers, and the mask engine needs a fact about every element a stack names -- which class of
|
||||
* continuation it is (gbnf_mask.cpp) -- on every mask; with the rules held as separate vectors
|
||||
* that is a search per element, with one arena it is a subtraction. The arena is final once the
|
||||
* program is published: every stack points into it. */
|
||||
* Every rule in one arena, so an element's address gives its index by subtraction. The mask
|
||||
* engine looks up each stack element's continuation class (gbnf_mask.cpp) on every mask. The
|
||||
* arena is final once the program is published, since every stack points into it. */
|
||||
struct GbnfRuleSet {
|
||||
std::vector<GbnfElement> elems;
|
||||
std::vector<uint32_t> start; /* rule id -> index of its first element */
|
||||
@@ -280,9 +261,9 @@ struct GbnfRuleSet {
|
||||
size_t n_rules() const { return start.size(); }
|
||||
};
|
||||
|
||||
/* Expand a stack into the N stacks that each end at a terminal. This is the pushdown automaton's
|
||||
* epsilon closure and it is where rule references are resolved. `build` is `out` while it is
|
||||
* built; see SetBuild. Throws GbnfLimit past the bounds above. */
|
||||
/* Expand a stack into the stacks that each end at a terminal: the epsilon closure, where rule
|
||||
* references are resolved. `build` tracks `out` under construction (SetBuild). Throws GbnfLimit
|
||||
* past the bounds above. */
|
||||
void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks& out,
|
||||
SetBuild& build);
|
||||
|
||||
@@ -300,8 +281,7 @@ struct VocabIndex;
|
||||
std::shared_ptr<const VocabIndex> vocab_index_build(const VocabView& v);
|
||||
size_t vocab_index_bytes(const VocabIndex& x);
|
||||
|
||||
/* What compiling a grammar's mask plan cost and holds, for the log line and the acceptance
|
||||
* tool. */
|
||||
/* What building a mask plan cost and what it holds, for logging and the acceptance tool. */
|
||||
struct PlanStats {
|
||||
double ms = 0.0; /* wall time of the plan build */
|
||||
uint64_t work = 0; /* units charged against kMaxCompileWork */
|
||||
@@ -310,49 +290,46 @@ struct PlanStats {
|
||||
size_t max_depth = 0; /* the deepest of them, in stack entries */
|
||||
size_t dense = 0; /* of them, held as a full bitmask */
|
||||
size_t rem_nodes = 0; /* nodes across every remainder trie */
|
||||
size_t max_rem = 0; /* the largest one remainder trie */
|
||||
size_t max_rem = 0; /* the largest remainder trie */
|
||||
size_t bytes = 0; /* what the plan holds */
|
||||
};
|
||||
|
||||
/* A grammar's compiled mask plan. Its runtime half -- an automaton over stack sets and the scratch
|
||||
* a mask needs -- is a memo guarded by the plan's own lock, so a plan is shared by every request
|
||||
* and every rank that uses the grammar. */
|
||||
/* A grammar's compiled mask plan. Its runtime part (the stack-set automaton and mask scratch) is
|
||||
* a memo under the plan's own lock, so one plan serves every request and rank using the
|
||||
* grammar. */
|
||||
struct MaskPlan;
|
||||
struct MaskPlanDeleter { void operator()(MaskPlan* p) const; };
|
||||
using MaskPlanPtr = std::unique_ptr<MaskPlan, MaskPlanDeleter>;
|
||||
|
||||
/* Build the plan for a grammar whose rules are final. Returns RAD_OK or RAD_E_UNSUPPORTED with
|
||||
* the reason in *err, naming the rule from `rule_names` (by rule id) where it can: a grammar whose
|
||||
* masks cannot be precomputed within the bounds above is refused here rather than served slowly
|
||||
* later. Throws GbnfLimit or std::bad_alloc, which the caller turns into a status. */
|
||||
/* Build the plan for a grammar whose rules are final. Returns RAD_OK, or RAD_E_UNSUPPORTED with
|
||||
* the reason in *err (naming the rule from `rule_names`, by rule id, where possible) when the
|
||||
* masks cannot be precomputed within the bounds above. Throws GbnfLimit or std::bad_alloc, which
|
||||
* the caller turns into a status. */
|
||||
int plan_build(const GbnfRuleSet& rules, uint32_t root, const std::shared_ptr<const VocabIndex>& vx,
|
||||
const std::vector<std::string>* rule_names, MaskPlanPtr* out, PlanStats* stats,
|
||||
std::string* err);
|
||||
|
||||
/* The mask for a stack set: bit set means admissible. `n_words` covers the vocabulary. Returns
|
||||
* RAD_OK, or RAD_E_STATE if no token at all is admissible; throws GbnfLimit past the per-operation
|
||||
* bounds. Thread-safe: it takes the plan's lock. */
|
||||
/* The mask for a stack set, bit set = admissible; `n_words` covers the vocabulary. Returns
|
||||
* RAD_OK, or RAD_E_STATE if no token is admissible; throws GbnfLimit past the per-operation
|
||||
* bounds. Thread-safe (takes the plan's lock). */
|
||||
int plan_fill(const MaskPlan& plan, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog,
|
||||
uint32_t* bitmask, int64_t n_words);
|
||||
|
||||
/* STEP A STACK SET OVER CODE POINTS through the plan's automaton: `out` is the set accepting
|
||||
* cps[0..n) one at a time leaves -- what accept_chr over every stack, code point by code point,
|
||||
* builds -- sorted, without duplicates, written over what `out` held so its capacity is reused.
|
||||
* `stacks` need not be sorted and must not point into `out`.
|
||||
/* Step a stack set over code points through the plan's automaton. `out` receives the set left by
|
||||
* accepting cps[0..n) one at a time (what accept_chr over every stack builds), sorted and
|
||||
* de-duplicated, overwriting `out` so its capacity is reused. `stacks` need not be sorted and
|
||||
* must not point into `out`.
|
||||
*
|
||||
* `at` IS THE STATE THE CALLER'S SET IS, when it knows: on entry, a state an earlier step on this
|
||||
* plan returned, which spares canonicalising the set, or an id of -1; on return, the state
|
||||
* reached, or an id of -1 when that state holds an empty stack or a token terminal on top -- a
|
||||
* set the caller does not step whole, so not one it can name next time. Valid only while the
|
||||
* automaton that issued it lives; `gen` says which one that was. Returns true when the state
|
||||
* reached is the one `at` named on entry: the caller's set already is it, and `out` is left
|
||||
* alone. That is the steady state of a free-text value.
|
||||
* `at` is the caller's automaton state, if known. On entry: a state an earlier step on this plan
|
||||
* returned (skips canonicalising the set), or id -1. On return: the state reached, or id -1 when
|
||||
* it holds an empty stack or a token terminal on top (a set the caller does not step whole). Valid
|
||||
* only while the issuing automaton lives; `gen` identifies it. Returns true when the reached
|
||||
* state equals the entry `at`; `out` is then left untouched (the steady state of a free-text
|
||||
* value).
|
||||
*
|
||||
* The automaton memoises each state's successor per
|
||||
* interval of code points, so a state seen before costs a lookup per code point where the stack
|
||||
* machinery would rebuild every closure; inside a free-text value the state is the same one
|
||||
* token after token. Throws GbnfLimit past the per-operation bounds. Thread-safe: it takes the
|
||||
* plan's lock. */
|
||||
* The automaton memoises each state's successor per code-point interval, so a seen state costs a
|
||||
* lookup per code point instead of rebuilding closures. Throws GbnfLimit past the per-operation
|
||||
* bounds. Thread-safe (takes the plan's lock). */
|
||||
struct PlanState {
|
||||
uint64_t gen = 0;
|
||||
int32_t id = -1;
|
||||
|
||||
+210
-283
@@ -1,79 +1,56 @@
|
||||
/* gbnf_mask.cpp -- the token mask, precomputed per grammar so that no mask walks the vocabulary.
|
||||
*
|
||||
* THE COST OF A MASK IS ON THE STEP. fill_mask runs on the scheduler thread with the rank threads
|
||||
* parked at the barrier, so whatever it takes is added to the decode step of a constrained
|
||||
* request -- up to four times a step under speculation. A mask that descends the whole vocabulary
|
||||
* trie for a state it has not seen costs milliseconds on a quarter-million-piece vocabulary, and a
|
||||
* tool call reaches dozens of such states in its first steps. So nothing here descends the whole
|
||||
* vocabulary at run time: the grammar's compile does that, once per place a mask can start, and a
|
||||
* mask is assembled from the answers.
|
||||
* A mask's cost adds to the decode step (gbnf.h, "Cost"). Descending the whole vocabulary trie for
|
||||
* a new state costs milliseconds on a quarter-million-piece vocabulary, so only the compile does
|
||||
* that, once per place a mask can start; a mask is assembled from the answers.
|
||||
*
|
||||
* WHAT A MASK IS MADE OF. The state is a set of stacks, and a token is admissible iff SOME stack
|
||||
* admits it, so the mask is the union of one mask per stack. A stack's mask depends on its whole
|
||||
* contents in principle and on very little of them in practice: a token of a dozen characters
|
||||
* either stays inside the few frames nearest the top -- a string's content and its closing
|
||||
* quote, a free-text parameter and its end tag -- or leaves them through a delimiter. So a stack
|
||||
* S is split into a KEY, the frames nearest its top, and the CONTEXT below them:
|
||||
* Mask structure. A token is admissible iff some stack admits it, so the mask is the union of
|
||||
* per-stack masks. A short token either stays within the few frames nearest the top (a string's
|
||||
* content and closing quote, a free-text parameter and its end tag) or leaves them through a
|
||||
* delimiter. So a stack S is split into a key (the frames nearest the top) and the context below:
|
||||
*
|
||||
* S = context ++ key
|
||||
* mask(S) = accepted(key) U { t : t leaves the key after a prefix u, and the rest of
|
||||
* t is admitted by the context }
|
||||
*
|
||||
* accepted(key) does not depend on the context at all -- every path through the key's own frames
|
||||
* is a path through S -- so it is computed at compile time, by descending the vocabulary trie
|
||||
* with the key alone and an explicit bottom marker under it. What leaves the key is the
|
||||
* REMAINDER: for every token, the text after each point where it pops the key's last frame. Those
|
||||
* are kept as a small trie of their own, and at run time only that trie is walked, against the
|
||||
* real context. This is XGrammar's adaptive token mask cache (Dong et al., 2024) -- tokens split
|
||||
* into accepted, rejected and context-dependent per grammar position, with only the last checked
|
||||
* at run time -- carried over to a machine whose positions are stack SUFFIXES.
|
||||
* accepted(key) is independent of the context, so it is computed at compile time by descending
|
||||
* the vocabulary trie with the key over a bottom marker. The remainder (for every token, the text
|
||||
* after each point where it pops the key's last frame) is kept as a small trie, and only that is
|
||||
* walked at run time against the real context. This is XGrammar's adaptive token mask cache
|
||||
* (Dong et al., 2024), with stack suffixes as positions.
|
||||
*
|
||||
* WHY SUFFIXES AND NOT SINGLE ELEMENTS. The parser rewrites `x*` into a rule of its own and a
|
||||
* group into another, so the element on top of a stack is usually the one character class of a
|
||||
* one-element rule: `[^"\\]` inside a JSON string is the whole of its rule, and every token longer
|
||||
* than one character leaves it. Keyed on the top element alone, nearly the whole vocabulary would
|
||||
* be context-dependent at the positions that matter most. Keyed on the top three frames -- the
|
||||
* class, the repetition that loops over it and the closing quote below that -- the only tokens that
|
||||
* leave are the ones that close the string and keep going, a few hundred of them. The depth is
|
||||
* ADAPTIVE: a key is extended one frame down, into every frame that can sit below it, for as long
|
||||
* as its remainder is too large to walk on the step, and not otherwise.
|
||||
* Suffixes, not single elements. The parser gives `x*` and groups rules of their own, so a stack
|
||||
* top is often a one-element rule such as `[^"\\]` in a JSON string, which every multi-character
|
||||
* token leaves. Keyed on the top three frames (the class, its repetition, the closing quote) only
|
||||
* the few hundred tokens that close the string leave. Depth is adaptive: a key is extended one
|
||||
* frame down, into every frame that can sit below it, while its remainder is too large to walk.
|
||||
*
|
||||
* WHAT A KEY IS. Stack entries are element pointers, and two entries at different places in the
|
||||
* rules behave identically when what remains of their alternatives is the same sequence of
|
||||
* elements -- `"</parameter>\n"` closes every parameter of every tool, and its entries differ only
|
||||
* by address. Entries are therefore replaced by their CLASS, the hash-consed remainder of their
|
||||
* alternative, and keys are sequences of classes. Rules are hash-consed the same way first, so a
|
||||
* clause a template writes once per tool is one clause; and a repetition longer than the longest
|
||||
* token is one class whatever its count, because no token can tell the difference. A grammar of
|
||||
* fifty free-text parameters has one free-text key, not fifty, and `x{0,1000}` costs what
|
||||
* `x{0,128}` does on a vocabulary whose longest token is 128 characters.
|
||||
* Keys. Two stack entries behave identically when the rest of their alternatives is the same
|
||||
* element sequence (`"</parameter>\n"` closes every tool parameter). Entries are replaced by their
|
||||
* class, the hash-consed remainder of their alternative, and keys are class sequences. Rules are
|
||||
* hash-consed first, and a repetition longer than the longest token is one class whatever its
|
||||
* count. So fifty free-text parameters share one key, and `x{0,1000}` costs what `x{0,128}` does
|
||||
* when the longest token is 128 characters.
|
||||
*
|
||||
* WHAT A MASK THEN COSTS. For each stack: a lookup of its key, a few class comparisons deep; the
|
||||
* key's accepted set OR'ed in, which is a word-wise OR for a permissive key and a handful of bits
|
||||
* for a restrictive one; and, where the key has a remainder and the stack has a context, a walk of
|
||||
* the remainder trie from the context's state, which visits only the remainders the context keeps
|
||||
* alive. Nothing is proportional to the vocabulary except the OR, and nothing depends on whether
|
||||
* this state was seen before.
|
||||
* Mask cost. Per stack: a key lookup a few classes deep; an OR of the key's accepted set (word-wise
|
||||
* for a permissive key, a few bits for a restrictive one); and, if the key has a remainder and the
|
||||
* stack a context, a remainder-trie walk visiting only what the context keeps alive. Only the OR
|
||||
* scales with the vocabulary, and the cost is the same for new and seen states.
|
||||
*
|
||||
* A STATE CARRYING A SPLIT CHARACTER is the one exception to the plan, because what a token means
|
||||
* depends on the bytes carried in: only tokens that begin with the bytes that finish the
|
||||
* character are admissible at all. Those are a few hundred pieces in a byte-level vocabulary, kept
|
||||
* in a trie of their own per number of missing bytes, and walked with the full stack set.
|
||||
* Split characters. A state carrying a partial UTF-8 character admits only tokens that begin with
|
||||
* the missing bytes. Those few hundred pieces are kept in a trie per missing-byte count and walked
|
||||
* with the full stack set.
|
||||
*
|
||||
* THE AUTOMATON. Every walk here steps a set of stacks over code points. The successor of a set
|
||||
* depends only on WHICH of its stacks match the code point, and a set's character classes cut the
|
||||
* code points into a few intervals on which that answer is constant; so each state carries its
|
||||
* interval boundaries and the successor per interval, built on first use. A trie node's children
|
||||
* are sorted by code point, so the walk takes a whole run of children per interval -- an interval
|
||||
* no stack matches is skipped with one binary search, which is what makes a restrictive state
|
||||
* cost nothing at the vocabulary's widest node.
|
||||
* The automaton. A set's successor depends only on which of its stacks match the code point, and
|
||||
* its character classes cut the code points into intervals where that is constant; each state
|
||||
* stores its intervals and per-interval successor, built on first use. Trie children are sorted by
|
||||
* code point, so a walk takes a run of children per interval and skips a non-matching interval
|
||||
* with one binary search, making a restrictive state cheap even at the widest node.
|
||||
*
|
||||
* WHAT IS REFUSED. A grammar whose keys cannot be made small within kMaxKeyDepth frames -- one
|
||||
* where how much a token may take depends on how deep the parse is, without bound -- or whose
|
||||
* plan outgrows kMaxCompileWork, kMaxPlanBytes or the bound on one stack set, is refused when it
|
||||
* is compiled, naming the rule where it can: the alternative would be masks that are slow for as
|
||||
* long as the grammar is in use. What is refused is ambiguity and unbounded context, which the
|
||||
* grammars chat templates and the JSON-schema converter write do not have.
|
||||
* Refusal. A grammar whose keys cannot be made small within kMaxKeyDepth frames (token reach
|
||||
* depends on unbounded parse depth), or whose plan exceeds kMaxCompileWork, kMaxPlanBytes or the
|
||||
* stack-set bound, is refused at compile time, naming the rule where possible, rather than served
|
||||
* with slow masks. Grammars from chat templates and the JSON Schema converter are not affected.
|
||||
*/
|
||||
#include "gbnf_internal.h"
|
||||
|
||||
@@ -92,22 +69,20 @@ namespace {
|
||||
constexpr uint32_t kNone = 0xFFFFFFFFu;
|
||||
constexpr int32_t kUnbuilt = -2;
|
||||
|
||||
/* HOW LARGE A KEY'S REMAINDER MAY BE, which is what the run-time half of a mask may cost for one
|
||||
* key: a remainder trie is walked from the context's state, and in the worst case -- a context
|
||||
* that admits every remainder -- visits every node of it. Past either bound the key is extended
|
||||
* one frame down instead, where more of what leaves it is decided at compile time. */
|
||||
/* Maximum size of a key's remainder, which bounds a mask's run-time cost per key: the remainder
|
||||
* trie walk visits every node in the worst case. Past either bound the key is extended one frame
|
||||
* down, so more is decided at compile time. */
|
||||
constexpr size_t kMaxRemEntries = 1u << 13;
|
||||
constexpr size_t kMaxRemNodes = 1u << 13;
|
||||
|
||||
/* A walk whose remainder is already far past the bound is stopped where it is: the key will be
|
||||
* extended whatever the rest of the walk finds, and a key that leaves after its first character
|
||||
* would otherwise walk the whole vocabulary to learn that. Counted as tokens under the nodes where
|
||||
* the key has been left, so it is an overestimate and never stops a walk that could have fitted. */
|
||||
/* A walk whose remainder is already far past the bound stops early, since the key will be extended
|
||||
* anyway (otherwise a key left after one character walks the whole vocabulary). Counted as tokens
|
||||
* under nodes where the key was left, an overestimate, so it never stops a walk that would fit. */
|
||||
constexpr uint64_t kAbortRemTokens = 1u << 15;
|
||||
|
||||
/* How many frames a key may span. Real grammars settle within three or four: a string inside its
|
||||
* repetition inside its quotes, a whitespace run inside its optional. A key still too permissive
|
||||
* this deep is a grammar whose masks depend on unbounded stack context, which is refused. */
|
||||
/* Maximum frames per key. Real grammars settle within three or four (a string in its repetition in
|
||||
* its quotes; whitespace in its optional). A key still too permissive this deep means masks depend
|
||||
* on unbounded stack context, and the grammar is refused. */
|
||||
constexpr uint16_t kMaxKeyDepth = 12;
|
||||
|
||||
inline void set_bit(uint32_t* bits, int32_t id) {
|
||||
@@ -127,26 +102,22 @@ double ms_since(std::chrono::steady_clock::time_point t0) {
|
||||
|
||||
/* ============================================================ token tries
|
||||
|
||||
* A trie over code-point sequences, one terminal per token. The vocabulary is one; each key's
|
||||
* remainder is another; the pieces that resume a split character are three more.
|
||||
* A trie over code-point sequences, one terminal per token: one for the vocabulary, one per key
|
||||
* remainder, and three for pieces that resume a split character.
|
||||
*
|
||||
* Nodes are in BREADTH-FIRST order, which buys two things: a node's children occupy a CONTIGUOUS
|
||||
* id range, so an edge scan is a sequential read and no child pointers are stored; and a whole
|
||||
* level is contiguous, so a walk -- which is also breadth-first -- reads the node array front to
|
||||
* back. ONE STRUCT PER NODE AND NOT FOUR ARRAYS, because a visit reads all four fields; and the
|
||||
* terminals are held in NODE ORDER, so a level's terminals are read in increasing order too. The
|
||||
* walk is bound on how it touches memory rather than on work per node, and a pointer-linked
|
||||
* layout is slower than the rescanning walk a trie exists to replace.
|
||||
* Nodes are in breadth-first order, so a node's children are a contiguous id range (no child
|
||||
* pointers) and a breadth-first walk reads the node array front to back. Fields are one struct
|
||||
* per node since a visit reads all four, and terminals are in node order. The walk is
|
||||
* memory-bound; a pointer-linked layout is slower than the rescanning walk the trie replaces.
|
||||
*
|
||||
* Beside the breadth-first layout, every node knows its subtree's range in LEXICOGRAPHIC order,
|
||||
* `lo..hi` into `lex`. A walk never reads it; the compile does, to list what is under a node where
|
||||
* a key has been left, and so does the one construct that admits a whole subtree at once -- a
|
||||
* token element (`<[id]>`, `!<[id]>`), which matches a token's id wherever it is reached. */
|
||||
* Each node also records its subtree's range `lo..hi` in lexicographic order (`lex`). The walk
|
||||
* never reads it; the compile uses it to list what lies under a node where a key was left, as
|
||||
* do token elements (`<[id]>`, `!<[id]>`), which match a token's id wherever reached. */
|
||||
struct TrieNode {
|
||||
uint32_t cp; /* the code point on the edge INTO this node */
|
||||
uint32_t cp; /* the code point on the edge into this node */
|
||||
uint32_t first; /* its first child's node id */
|
||||
uint32_t n_child; /* how many children follow it */
|
||||
uint32_t tbeg; /* its first terminal slot; it ends at the NEXT node's tbeg */
|
||||
uint32_t tbeg; /* its first terminal slot; it ends at the next node's tbeg */
|
||||
};
|
||||
|
||||
struct TokenTrie {
|
||||
@@ -172,10 +143,9 @@ struct TrieEntry {
|
||||
int32_t id;
|
||||
};
|
||||
|
||||
/* LEXICOGRAPHIC ORDER IS WHAT MAKES A NODE A RANGE: two sequences share a d-code-point prefix iff
|
||||
* they are adjacent in this order and agree to depth d, so every node of the trie is a contiguous
|
||||
* slice of the sorted entries and the build never needs a per-node map. The sequences are
|
||||
* 0-terminated in the arena, which stops the comparison. */
|
||||
/* Sorted lexicographically, every trie node is a contiguous slice of the entries (sequences
|
||||
* sharing a prefix are adjacent), so the build needs no per-node map. Sequences are 0-terminated
|
||||
* in the arena, which stops the comparison. */
|
||||
static void trie_build(TokenTrie& t, const uint32_t* cps, std::vector<TrieEntry>& ents,
|
||||
int32_t unique_over) {
|
||||
const uint32_t n = (uint32_t)ents.size();
|
||||
@@ -198,10 +168,9 @@ static void trie_build(TokenTrie& t, const uint32_t* cps, std::vector<TrieEntry>
|
||||
t.hi.push_back(n);
|
||||
cur.push_back({ 0u, n });
|
||||
|
||||
/* Level d's nodes were appended in the order their ranges appear in `cur`, so node id
|
||||
* `level_lo + i` is the node whose range is cur[i]. Children are appended in the same sweep,
|
||||
* which keeps each node's children -- and the next whole level -- contiguous, and makes node
|
||||
* ids increase with the order nodes are PROCESSED, which the terminal slots depend on. */
|
||||
/* Node `level_lo + i` has range cur[i]. Children are appended in the same sweep, keeping each
|
||||
* node's children and the next level contiguous, and making node ids follow processing order,
|
||||
* which the terminal slots depend on. */
|
||||
uint32_t level_lo = 0;
|
||||
for (uint32_t d = 0; !cur.empty(); ++d) {
|
||||
nxt.clear();
|
||||
@@ -251,26 +220,24 @@ struct VocabIndex {
|
||||
std::vector<int32_t> eog; /* end-of-generation: admissible once a stack completes */
|
||||
|
||||
/* Every piece decoded from a clean start, 0-terminated, in one arena that opens with a pad
|
||||
* element. `off` is kNone for a token the walk never considers: end-of-generation, and a
|
||||
* control token with no text, which can satisfy no character. */
|
||||
* element. `off` is kNone for tokens the walk skips: end-of-generation, and control tokens
|
||||
* with no text. */
|
||||
std::vector<uint32_t> cps;
|
||||
std::vector<uint32_t> off;
|
||||
std::vector<PartialUtf8> tail;
|
||||
TokenTrie trie;
|
||||
|
||||
/* Pieces that decode to no characters and carry nothing out: an overlong sequence for U+0000
|
||||
* first, which ends a decoded sequence. Every live stack admits one -- a completed one too,
|
||||
* which admits nothing else -- so a state with a completed stack admits these whatever its
|
||||
* keys do. */
|
||||
/* Pieces that decode to no characters and carry nothing out (e.g. an overlong U+0000 first,
|
||||
* which ends a decoded sequence). Every live stack admits them, a completed one included, so
|
||||
* a state with a completed stack admits these regardless of its keys. */
|
||||
std::vector<int32_t> blank;
|
||||
|
||||
/* THE PIECES THAT RESUME A SPLIT CHARACTER, per number of bytes the carried character still
|
||||
* needs. With r bytes missing, a piece is admissible only if its first r bytes are
|
||||
* continuation bytes and the rest decodes on its own; its first code point is then the
|
||||
* carried bits followed by those r bytes' bits, and everything after it is fixed. So each
|
||||
* trie's root edges hold the r bytes' bits (plus one, since 0 ends a sequence) and the walk
|
||||
* ORs the carried bits in. A piece of fewer than r continuation bytes and nothing else leaves
|
||||
* the character still unfinished, and is admissible iff some stack could still take it. */
|
||||
/* Pieces that resume a split character, indexed by bytes still missing (r). A piece is
|
||||
* admissible only if its first r bytes are continuation bytes and the rest decodes alone; its
|
||||
* first code point is the carried bits followed by those r bytes' bits. So root edges hold
|
||||
* the r bytes' bits plus one (0 ends a sequence) and the walk ORs the carried bits in. A piece
|
||||
* of fewer than r continuation bytes only (`shorts`) leaves the character unfinished and is
|
||||
* admissible iff some stack could still take it. */
|
||||
struct Resume {
|
||||
std::vector<uint32_t> cps;
|
||||
TokenTrie trie;
|
||||
@@ -315,10 +282,8 @@ std::shared_ptr<const VocabIndex> vocab_index_build(const VocabView& v) {
|
||||
x->cps.insert(x->cps.end(), dec.first.begin(), dec.first.end());
|
||||
ents.push_back({ x->off[(size_t)id], dec.second, id });
|
||||
|
||||
/* Leading continuation bytes, and what they contribute to a character carried in. The
|
||||
* decode reads the piece as a C string, as decode_utf8 does, so a NUL ends the piece: it
|
||||
* stops the run like any other non-continuation byte, and a piece of continuation bytes
|
||||
* and then a NUL is as short as the bytes before it. */
|
||||
/* Leading continuation bytes and their bits. Like decode_utf8, the piece is read as a C
|
||||
* string, so a NUL ends it: continuation bytes followed by a NUL count as a short piece. */
|
||||
const size_t len = ::strnlen(piece.c_str(), piece.size());
|
||||
size_t k = 0;
|
||||
uint32_t bits = 0;
|
||||
@@ -331,8 +296,8 @@ std::shared_ptr<const VocabIndex> vocab_index_build(const VocabView& v) {
|
||||
for (int r = 1; r <= 3; ++r) {
|
||||
VocabIndex::Resume& R = x->resume[r - 1];
|
||||
if ((int)k == r && !more_cont) {
|
||||
/* Finishes the character with exactly its first r bytes; the rest decodes from a
|
||||
* clean start, and an invalid rest takes the whole piece with it. */
|
||||
/* Finishes the character with exactly r bytes; the rest decodes from a clean
|
||||
* start, and an invalid rest disqualifies the piece. */
|
||||
const auto rest = decode_utf8(piece.substr((size_t)r), PartialUtf8{});
|
||||
if (rest.second.n_remain < 0) continue;
|
||||
const uint32_t o = (uint32_t)R.cps.size();
|
||||
@@ -361,22 +326,20 @@ std::shared_ptr<const VocabIndex> vocab_index_build(const VocabView& v) {
|
||||
|
||||
/* ============================================================ the stack-set automaton
|
||||
|
||||
* A set of stacks is one state of the pushdown automaton's subset construction: walking the set
|
||||
* forward is the same answer as walking every stack and OR-ing, because admissibility is the
|
||||
* existence of a path, and the union of successors is exactly the set of stacks some path reaches.
|
||||
* States are interned by value, so a set reached twice is one state.
|
||||
* A stack set is one state of the subset construction: walking the set gives the same answer as
|
||||
* walking each stack and OR-ing, since admissibility is the existence of a path. States are
|
||||
* interned by value, so a set reached twice is one state.
|
||||
*
|
||||
* THE SUCCESSOR OF A STACK DOES NOT DEPEND ON THE CODE POINT. Stepping a char-range top pops the
|
||||
* range and pushes what follows it, which `match_char(top, 0).second` finds whatever the code
|
||||
* point; the code point decides only WHETHER the stack steps. So each stack's successor is a
|
||||
* closure computed once per state, and a state's transition depends only on which stacks fire.
|
||||
* The character classes of a state's tops cut the code points into intervals over which that
|
||||
* answer is constant, and the successor is kept per interval. A state holds:
|
||||
* A stack's successor does not depend on the code point: stepping a char-range top pops it and
|
||||
* pushes what follows (`match_char(top, 0).second`); the code point only decides whether the
|
||||
* stack steps. So each stack's successor closure is computed once per state, and a transition
|
||||
* depends only on which stacks fire, which is constant over the intervals the tops' character
|
||||
* classes cut. The successor is kept per interval. A state holds:
|
||||
*
|
||||
* ctop the char-range tops, which step over code points and test a carried partial;
|
||||
* ttop the token tops (`<[id]>`, `!<[id]>`), which match a token's id wherever reached;
|
||||
* has_empty whether the set holds the empty stack: a completed parse, or -- in a key's walk --
|
||||
* the bottom marker, meaning the key has been left.
|
||||
* has_empty whether the set holds the empty stack: a completed parse, or in a key's walk the
|
||||
* bottom marker, meaning the key has been left.
|
||||
*
|
||||
* States live in a deque, so a reference to one survives interning another. */
|
||||
class SetDfa {
|
||||
@@ -399,21 +362,19 @@ public:
|
||||
|
||||
explicit SetDfa(const GbnfRuleSet* rules) : rules_(rules) {}
|
||||
|
||||
/* The operation whose work every step is charged to, and the mark its growth is measured
|
||||
* from. */
|
||||
/* Set the operation every step is charged to, and the mark its growth is measured from. */
|
||||
void begin(OpWork* w) { work_ = w; walk_base_ = elems_; }
|
||||
|
||||
size_t elems() const { return elems_; }
|
||||
size_t n_states() const { return st_.size(); }
|
||||
const St& st(int32_t sid) const { return st_[(size_t)sid]; }
|
||||
|
||||
/* Canonicalise a stack set and return its state, or -1 for the empty set -- the dead state,
|
||||
* represented by absence so a caller can prune on the sign alone. */
|
||||
/* Canonicalise a stack set and return its state, or -1 for the empty (dead) set, so callers
|
||||
* can prune on the sign. */
|
||||
int32_t intern(GbnfStacks s) {
|
||||
if (s.empty()) return -1;
|
||||
/* WHAT A SORT COSTS, which is not its length: n log n comparisons of stacks, each as long
|
||||
* as the stacks' common prefix. Charged as every element once per level of the sort, so
|
||||
* a set too wide to sort within the bound is refused rather than sorted anyway. */
|
||||
/* A sort is n log n stack comparisons, each as long as the common prefix; charged as every
|
||||
* element once per sort level, so a set too wide to sort within the bound is refused. */
|
||||
size_t elems = 0;
|
||||
for (const GbnfStack& k : s) elems += k.size() + 1;
|
||||
work_->add(elems * (1 + (uint64_t)std::bit_width(s.size())));
|
||||
@@ -430,8 +391,8 @@ public:
|
||||
return intern_ptrs(ps, &s);
|
||||
}
|
||||
|
||||
/* The same, from pointers to the stacks. They are copied only if the set is a new state --
|
||||
* moved out of `owned` when the caller holds them in a vector of its own. */
|
||||
/* The same, from pointers to the stacks. They are copied only for a new state, or moved out
|
||||
* of `owned` when the caller passes its own vector. */
|
||||
int32_t intern_ptrs(const std::vector<const GbnfStack*>& ps, GbnfStacks* owned = nullptr) {
|
||||
if (ps.empty()) return -1;
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
@@ -486,9 +447,9 @@ public:
|
||||
return id;
|
||||
}
|
||||
|
||||
/* advance_stack(s) as a state. Memoised on the stack, because many stacks -- in one state or
|
||||
* in many -- close to the same place: every alternative of a wide rule that has just matched
|
||||
* returns to one continuation, and every token of a context is resolved from it. */
|
||||
/* advance_stack(s) as a state, memoised on the stack: many stacks, in one state or many,
|
||||
* close to the same place (every matched alternative of a wide rule returns to one
|
||||
* continuation). */
|
||||
int32_t closure(const GbnfStack& s) {
|
||||
auto it = closure_ids_.find(s);
|
||||
if (it != closure_ids_.end()) return it->second;
|
||||
@@ -501,14 +462,11 @@ public:
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The state whose stacks are the union of these states' stacks.
|
||||
*
|
||||
* The union is memoised on the states united -- a state's successors over two intervals, or
|
||||
* the closures of two contexts, are united again and again -- and built by MERGING POINTERS:
|
||||
* every state's stacks are already sorted, so a balanced tree of pairwise merges compares each
|
||||
* stack once per level where sorting the concatenation would compare them n log n times, and
|
||||
* no stack is copied until the union turns out to be a state not seen before. The bounds are
|
||||
* checked after every merge, so a union that will not fit is refused before it is built. */
|
||||
/* The state whose stacks are the union of these states' stacks. Memoised on the input
|
||||
* states, since the same unions recur. Each state's stacks are sorted, so the union is a
|
||||
* balanced tree of pairwise pointer merges (each stack compared once per level, not n log n)
|
||||
* and stacks are copied only for a new state. Bounds are checked after every merge, so an
|
||||
* oversized union is refused before it is built. */
|
||||
int32_t unite(std::vector<int32_t>& ids) {
|
||||
std::sort(ids.begin(), ids.end());
|
||||
ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
|
||||
@@ -552,9 +510,8 @@ public:
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The state's intervals, built on first use: every boundary of every char-range top. Over
|
||||
* each interval every top either matches every code point or none, because each of its items
|
||||
* starts or ends at a boundary. */
|
||||
/* The state's intervals, built on first use from every boundary of every char-range top, so
|
||||
* each top matches either all or none of the code points in an interval. */
|
||||
const St& parted(int32_t sid) {
|
||||
St& S = st_[(size_t)sid];
|
||||
if (S.parted) return S;
|
||||
@@ -586,9 +543,9 @@ public:
|
||||
return S;
|
||||
}
|
||||
|
||||
/* The successor over interval i of a parted state, computed on first use. The firing pattern
|
||||
* is memoised as well as the interval: many intervals fire the same stacks -- everything
|
||||
* that is not a quote or a backslash, in a JSON string -- and their union is built once. */
|
||||
/* The successor over interval i of a parted state, computed on first use. Also memoised by
|
||||
* firing pattern, since many intervals fire the same stacks (in a JSON string, everything but
|
||||
* a quote or backslash). */
|
||||
int32_t next(int32_t sid, size_t i) {
|
||||
St& S = st_[(size_t)sid];
|
||||
if (S.next[i] != kUnbuilt) return S.next[i];
|
||||
@@ -663,9 +620,8 @@ private:
|
||||
|
||||
/* ============================================================ the walk
|
||||
|
||||
* Descend a trie breadth-first carrying one automaton state per live node, setting a bit for every
|
||||
* token the state admits there. A node's tokens are admitted as follows, which is the candidate
|
||||
* walk's rule stated the other way up:
|
||||
* Descend a trie breadth-first with one automaton state per live node, setting a bit for every
|
||||
* token the state admits there (the candidate walk's rule, inverted):
|
||||
*
|
||||
* ending here admitted iff nothing is carried out, or some char-range top could take
|
||||
* some completion of what is;
|
||||
@@ -691,8 +647,7 @@ struct Walk {
|
||||
uint64_t frontier_limit = UINT64_MAX;
|
||||
bool aborted = false;
|
||||
|
||||
/* The admitted ids in the order they were first set, while there are few enough to be worth
|
||||
* listing; past `list_cap` only the bits are kept. */
|
||||
/* Admitted ids in first-set order, up to `list_cap`; past it only the bits are kept. */
|
||||
std::vector<int32_t>* list = nullptr;
|
||||
size_t list_cap = 0;
|
||||
bool list_full = false;
|
||||
@@ -712,10 +667,9 @@ static inline void admit(Walk& w, int32_t id) {
|
||||
}
|
||||
}
|
||||
|
||||
/* What a visit needs of the state it is made in. Read once per RUN of children -- every child in
|
||||
* one interval of the parent's state shares its successor -- rather than once per child: a
|
||||
* permissive walk visits every node of the vocabulary trie, and at that count the lookup of a
|
||||
* state is a measurable part of a visit. */
|
||||
/* What a visit needs of its state. Read once per run of children sharing an interval (and so a
|
||||
* successor), not per child: a permissive walk visits every vocabulary trie node, where the state
|
||||
* lookup is a measurable part of a visit. */
|
||||
struct VisitState {
|
||||
const SetDfa::St* S = nullptr;
|
||||
bool expand = false; /* it has char-range tops, so children can be stepped */
|
||||
@@ -732,8 +686,8 @@ static inline VisitState visit_state(const SetDfa& dfa, const Walk& w, int32_t s
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The tokens ending at a node whose state is live: admitted outright unless they carry out a
|
||||
* partial character, which some char-range top must be able to finish. */
|
||||
/* Tokens ending at a live node: admitted unless they carry out a partial character that no
|
||||
* char-range top can finish. */
|
||||
static void visit_terminals(Walk& w, OpWork& work, const VisitState& vs, uint32_t t0,
|
||||
uint32_t t1) {
|
||||
const TokenTrie& T = *w.trie;
|
||||
@@ -750,7 +704,7 @@ static void visit_terminals(Walk& w, OpWork& work, const VisitState& vs, uint32_
|
||||
}
|
||||
}
|
||||
|
||||
/* What a token top admits from below node n, `t1 - t0` of whose tokens end at n itself. */
|
||||
/* What a token top admits from below node n; `n_end` of n's subtree tokens end at n itself. */
|
||||
static __attribute__((noinline)) void visit_token_tops(Walk& w, OpWork& work,
|
||||
const VisitState& vs, uint32_t n,
|
||||
uint32_t n_end) {
|
||||
@@ -778,8 +732,8 @@ static __attribute__((noinline)) void visit_token_tops(Walk& w, OpWork& work,
|
||||
}
|
||||
}
|
||||
|
||||
/* Visit node n: admit what ends here and what a token top takes from below, record an exit.
|
||||
* Returns whether the node's children are worth stepping. */
|
||||
/* Visit node n: admit what ends here and what a token top takes from below, and record an exit.
|
||||
* Returns whether the node's children should be stepped. */
|
||||
static inline __attribute__((always_inline)) bool walk_visit(Walk& w, OpWork& work,
|
||||
const TrieNode* nd, uint32_t n,
|
||||
const VisitState& vs,
|
||||
@@ -825,10 +779,10 @@ static void walk(SetDfa& dfa, int32_t start, Walk& w, OpWork& work, WalkScratch&
|
||||
const uint32_t c1 = nd[n].first + nd[n].n_child;
|
||||
size_t i = 0;
|
||||
|
||||
/* One run of children per interval: the children are sorted, so the interval only
|
||||
* moves forward -- a step at a time among a few intervals, by binary search among
|
||||
* many -- a dead one is skipped by a binary search over the children, and a live one
|
||||
* hands every child in it the same state. */
|
||||
/* One run of children per interval. Children are sorted, so the interval only moves
|
||||
* forward (linear among few intervals, binary search among many). A dead interval is
|
||||
* skipped by binary search over the children; a live one gives all its children the
|
||||
* same state. */
|
||||
while (c < c1) {
|
||||
const uint64_t cp = cp_of(c);
|
||||
if (m <= 16) {
|
||||
@@ -863,11 +817,11 @@ static void walk(SetDfa& dfa, int32_t start, Walk& w, OpWork& work, WalkScratch&
|
||||
|
||||
/* ============================================================ the plan */
|
||||
|
||||
/* A KEY: a suffix of stack entries by class, bottom first. Held as a tree grown downward -- a
|
||||
* node is its bottom class plus the node for the entries above it -- which is also how a stack
|
||||
* is looked up: from its top, one entry down per level, until a node that is not extended.
|
||||
/* A key: a suffix of stack entries by class, bottom first. Held as a tree grown downward (a node
|
||||
* is its bottom class plus the node for the entries above it); a stack is looked up from its top,
|
||||
* one entry down per level, until a node that is not extended.
|
||||
*
|
||||
* `mask` is the accepted set: of a final node, used with any context; of an extended node that
|
||||
* `mask` is the accepted set: for a final node, used with any context; for an extended node that
|
||||
* can be a whole stack, used only when the stack ends there. `rem` is the remainder trie, walked
|
||||
* from the context's state when there is a context. */
|
||||
struct KeyNode {
|
||||
@@ -897,9 +851,9 @@ struct MaskPlan {
|
||||
std::vector<TokenTrie> rems;
|
||||
PlanStats stats;
|
||||
|
||||
/* THE RUN-TIME HALF IS A MEMO. The automaton here holds the states contexts close to and the
|
||||
* remainders step into; it grows as they are discovered and every state in it is a fact about
|
||||
* the grammar, so one lock covers it and every request and rank shares it. */
|
||||
/* Run-time memo: the automaton holding the states contexts close to and remainders step
|
||||
* into. It grows as states are discovered; each is a fact about the grammar, so one lock
|
||||
* covers it and every request and rank shares it. */
|
||||
mutable std::mutex mu;
|
||||
mutable std::unique_ptr<SetDfa> dfa;
|
||||
mutable WalkScratch ws;
|
||||
@@ -941,27 +895,23 @@ struct Grammar {
|
||||
}
|
||||
};
|
||||
|
||||
/* WHICH RULES ARE THE SAME RULE. A generated grammar repeats itself: every tool's
|
||||
* undeclared-parameter clause is `("<parameter=" ([^>] | ">" [^\n])* ">\n")`, and the parser gives
|
||||
* each copy -- the group, the repetition, the alternatives inside it -- rules of its own. Their
|
||||
* entries would be distinct classes, and each would get a key and a walk of the vocabulary of
|
||||
* its own, one per tool, for identical answers.
|
||||
/* Merge identical rules. Generated grammars repeat clauses (every tool's undeclared-parameter
|
||||
* clause `("<parameter=" ([^>] | ">" [^\n])* ">\n")`), and the parser gives each copy its own
|
||||
* rules, which would otherwise mean a key and a vocabulary walk per copy.
|
||||
*
|
||||
* So rules are hash-consed on their bodies with references replaced by the referenced rule's
|
||||
* canonical id, bottom-up over the reference graph's strongly connected components. A rule that
|
||||
* refers only to itself -- which is what a repetition is -- is hashed with its self-references
|
||||
* marked as such, so identical repetitions merge too. A larger cycle of rules is left distinct:
|
||||
* mutual recursion is rare in what generators emit and is correct unmerged. Returns the canonical
|
||||
* id of each rule; ids of merged rules are equal, and no id is a rule index. */
|
||||
* Rules are hash-consed on their bodies, with references replaced by the target's canonical id,
|
||||
* bottom-up over the reference graph's SCCs. A self-referencing rule (a repetition) is hashed
|
||||
* with its self-references marked, so identical repetitions merge. Larger cycles are left
|
||||
* distinct (rare in generated grammars, and correct unmerged). Returns each rule's canonical id;
|
||||
* merged rules share one, and no id is a rule index. */
|
||||
static std::vector<uint32_t> canonical_rules(const Grammar& G, const std::vector<char>& nullable,
|
||||
uint32_t max_cps, OpWork& work) {
|
||||
const GbnfRuleSet& R = G.R;
|
||||
const size_t NR = R.n_rules(), NE = R.elems.size();
|
||||
auto rule_end = [&](size_t r) { return r + 1 < NR ? R.start[r + 1] : (uint32_t)NE; };
|
||||
|
||||
/* Tarjan's strongly connected components over references, iteratively. Components come out
|
||||
* in reverse topological order: every rule a component refers to outside itself is already
|
||||
* canonical when it is reached. */
|
||||
/* Tarjan's SCCs over references, iteratively. Components come out in reverse topological
|
||||
* order, so every rule a component refers to outside itself is already canonical. */
|
||||
std::vector<int32_t> idx(NR, -1), low(NR, 0);
|
||||
std::vector<char> on(NR, 0);
|
||||
std::vector<uint32_t> stk;
|
||||
@@ -1019,14 +969,12 @@ static std::vector<uint32_t> canonical_rules(const Grammar& G, const std::vector
|
||||
out.append((const char*)&v, 4);
|
||||
};
|
||||
|
||||
/* A BOUNDED REPETITION IS A STAR, AS FAR AS ANY TOKEN CAN TELL. The parser writes x{0,n} as a
|
||||
* chain, `S(k) ::= x S(k-1) |` down to `S(1) ::= x |`, and every link is a rule of its own --
|
||||
* so `[^"]{0,1000}` would be a thousand keys, each walking the vocabulary. But a token holds
|
||||
* at most `max_cps` code points, and when x always consumes at least one, a token can take at
|
||||
* most that many repetitions: with more than that left, no token can tell the link from
|
||||
* `x*`. Such links are given the star's canonical id; the shorter ones stay what they are.
|
||||
* `depth` and `operand` hold, per link, how many repetitions it allows and the signature of
|
||||
* what it repeats; a star, which refers to itself, is not a link. */
|
||||
/* A bounded repetition looks like a star to any token. The parser writes x{0,n} as a chain
|
||||
* `S(k) ::= x S(k-1) |` down to `S(1) ::= x |`, one rule per link. A token holds at most
|
||||
* `max_cps` code points, so if x always consumes one, a link with more repetitions left than
|
||||
* that is indistinguishable from `x*` and gets the star's canonical id. `depth` and `operand`
|
||||
* hold, per link, its remaining repetitions and the signature of what it repeats; a star
|
||||
* (self-referencing) is not a link. */
|
||||
std::vector<uint32_t> depth(NR, 0);
|
||||
std::vector<std::string> operand(NR);
|
||||
auto consumes = [&](uint32_t a, uint32_t e) {
|
||||
@@ -1097,9 +1045,7 @@ static std::vector<uint32_t> canonical_rules(const Grammar& G, const std::vector
|
||||
return canon;
|
||||
}
|
||||
|
||||
/* Which rules can match the empty string: a fixed point, as in find_left_recursion. An
|
||||
* alternative with a terminal in it never can; one of rule references only can once all of them
|
||||
* can, so it waits on a count. */
|
||||
/* Which rules can match the empty string: a fixed point, as in find_left_recursion. */
|
||||
static std::vector<char> nullable_rules(const GbnfRuleSet& R, OpWork& work) {
|
||||
const size_t NR = R.n_rules(), NE = R.elems.size();
|
||||
std::vector<char> nullable(NR, 0);
|
||||
@@ -1142,16 +1088,13 @@ static std::vector<char> nullable_rules(const GbnfRuleSet& R, OpWork& work) {
|
||||
return nullable;
|
||||
}
|
||||
|
||||
/* THE CLASS OF AN ENTRY is what remains of its alternative from it on, element for element with
|
||||
* rule references by canonical rule, hash-consed from the end of each alternative backward. Two
|
||||
* entries of one class behave identically wherever they are: what a stack does next is fixed by
|
||||
* the elements its entries have left and the rules those reference. Class 0 is the end of an
|
||||
* alternative and is never an entry.
|
||||
/* An entry's class is the rest of its alternative from it on, with rule references by canonical
|
||||
* rule, hash-consed backward from the end of each alternative. Entries of one class behave
|
||||
* identically anywhere. Class 0 is the end of an alternative and is never an entry.
|
||||
*
|
||||
* A RUN OF ONE UNIT is capped the way a repetition chain is (canonical_rules): x{1000} is a
|
||||
* thousand x in a row, and an entry with more than `max_cps` of a unit that always consumes a
|
||||
* code point still ahead of it behaves, for every token, like one with one fewer. Such an entry
|
||||
* takes the class of the entry after it. */
|
||||
* A run of one unit is capped like a repetition chain (canonical_rules): x{1000} is a thousand x
|
||||
* in a row, and an entry with more than `max_cps` of a code-point-consuming unit ahead of it
|
||||
* behaves, for every token, like one with one fewer, so it takes the next entry's class. */
|
||||
static void compute_classes(Grammar& G, MaskPlan& P, const std::vector<char>& nullable,
|
||||
uint32_t max_cps, OpWork& work) {
|
||||
const GbnfRuleSet& R = G.R;
|
||||
@@ -1209,19 +1152,15 @@ static void compute_classes(Grammar& G, MaskPlan& P, const std::vector<char>& nu
|
||||
}
|
||||
}
|
||||
|
||||
/* A RULE THAT CAN NEVER MATCH ANYTHING, and cannot be left either: every way into it comes back
|
||||
* into it without reaching a character or its own end -- `r ::= r` is the shortest. A stack that
|
||||
* enters one closes to nothing at all, and upstream's candidate walk reads a stack set that is
|
||||
* empty as rejecting nothing, so the mask past such a point admits every token while accepting
|
||||
* any of them ends the parse. A mask built from stack suffixes cannot reproduce that reading --
|
||||
* it depends on whether the rest of one particular stack is empty -- and nothing a grammar means
|
||||
* depends on it, so a grammar that can reach such a rule is refused, by the rule's name.
|
||||
/* A blind rule can neither match anything nor be left (`r ::= r` is the shortest). A stack that
|
||||
* enters one closes to nothing, which upstream's candidate walk reads as admitting every token
|
||||
* while accepting any of them ends the parse. Suffix-based masks cannot reproduce that, and no
|
||||
* meaningful grammar depends on it, so a grammar that can reach such a rule is refused by name.
|
||||
*
|
||||
* A rule can POP past itself iff it is nullable, and its closure YIELDS a stack iff some element
|
||||
* it can reach before a first element that cannot pop is a terminal or a rule that yields. Both are
|
||||
* least fixed points computed with worklists, linear in the grammar -- a chain of a hundred
|
||||
* thousand rules is one pass, not one per link. A rule doing neither is blind. Returns a blind
|
||||
* rule reachable from the root, or kNone. */
|
||||
* A rule can pop past itself iff it is nullable; its closure yields a stack iff some element
|
||||
* reachable before the first non-nullable one is a terminal or a yielding rule. Both are least
|
||||
* fixed points computed with worklists in one linear pass. A rule doing neither is blind.
|
||||
* Returns a blind rule reachable from the root, or kNone. */
|
||||
static uint32_t blind_rule(const Grammar& G, const std::vector<char>& nullable, OpWork& work) {
|
||||
const GbnfRuleSet& R = G.R;
|
||||
const size_t NR = R.n_rules();
|
||||
@@ -1270,8 +1209,8 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
}
|
||||
work.add(NE);
|
||||
|
||||
/* Reachable rules. A reference inside an unreachable rule is not a place any stack can be,
|
||||
* and counting it would give frames predecessors they never have. */
|
||||
/* Reachable rules. References inside unreachable rules must not count, or frames would get
|
||||
* predecessors no stack has. */
|
||||
G.reach.assign(NR, 0);
|
||||
std::vector<uint32_t> todo{ G.root };
|
||||
G.reach[G.root] = 1;
|
||||
@@ -1288,7 +1227,7 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Tail references (a frame REPLACED rather than stacked on), and every reference by target. */
|
||||
/* Tail references (a frame replaced rather than stacked on), and every reference by target. */
|
||||
G.rev_tail.assign(NR, {});
|
||||
G.refs_to.assign(NR, {});
|
||||
std::vector<std::vector<uint32_t>> tail_to(NR);
|
||||
@@ -1311,8 +1250,8 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The frames a stack can have at its bottom: the root's, and whatever it hands over to by
|
||||
* tail reference. */
|
||||
/* Frames a stack can have at its bottom: the root's, and whatever it hands over to by tail
|
||||
* reference. */
|
||||
G.bottom_ok.assign(NR, 0);
|
||||
todo.assign(1, G.root);
|
||||
G.bottom_ok[G.root] = 1;
|
||||
@@ -1323,7 +1262,7 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
if (!G.bottom_ok[t]) { G.bottom_ok[t] = 1; todo.push_back(t); }
|
||||
}
|
||||
|
||||
/* The terminals, by class: every place a stack's top can be. */
|
||||
/* Terminals by class: every place a stack's top can be. */
|
||||
G.tops.assign(G.rep.size(), {});
|
||||
for (size_t r = 0; r < NR; ++r) {
|
||||
if (!G.reach[r]) continue;
|
||||
@@ -1345,16 +1284,14 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
G.stamp.assign(NR, 0);
|
||||
}
|
||||
|
||||
/* THE ENTRIES THAT CAN SIT DIRECTLY BELOW A FRAME OF RULE r: the element after every reference to
|
||||
* r, or to a rule that hands over to r by tail reference. Every entry below a stack's top is such
|
||||
* an element -- where the frame below resumes.
|
||||
/* Entries that can sit directly below a frame of rule r: the element after every reference to r,
|
||||
* or to a rule that hands over to r by tail reference (where the frame below resumes).
|
||||
*
|
||||
* KEPT BY ELEMENT, NOT BY CLASS, and a key's bottom entry carries the elements it can be. Classes
|
||||
* merge elements of different rules, and so merge what can sit below them: the `space` that ends
|
||||
* `integer` and the `space` after `integer` in the rule that uses it are one class, and below the
|
||||
* first is the second, so by class that class can sit below itself without end -- a chain no real
|
||||
* stack holds, and one a key would be extended along until it was refused. By element, adjacency
|
||||
* is exact, and a key grows only as deep as real stacks do. */
|
||||
* Kept by element, not class; a key's bottom entry carries the elements it can be. Classes merge
|
||||
* elements of different rules: the `space` ending `integer` and the `space` after `integer` in its
|
||||
* user are one class, so by class it could sit below itself without end, and a key would be
|
||||
* extended along that phantom chain until refused. By element, keys grow only as deep as real
|
||||
* stacks. */
|
||||
static const std::vector<uint32_t>& below_of(Grammar& G, uint32_t r, OpWork& work) {
|
||||
if (G.below_done[r]) return G.below[r];
|
||||
std::vector<uint32_t>& out = G.below[r];
|
||||
@@ -1380,13 +1317,11 @@ static const std::vector<uint32_t>& below_of(Grammar& G, uint32_t r, OpWork& wor
|
||||
|
||||
/* The entries that can sit directly below any of `pos`, as (class, element), sorted.
|
||||
*
|
||||
* ONE WALK FROM ALL OF `pos`'s RULES, not one below_of per rule. The links of a repetition chain
|
||||
* hand over to each other by tail reference, so the walk up from one link climbs every link above
|
||||
* it; and every link past the longest token is one class, so one key's positions are all n links
|
||||
* of `x{0,n}`. Walked a rule at a time that is n^2/2 steps -- `maxLength: 32000` took two seconds
|
||||
* to compile, and 48000 was refused for the work. Walked from every rule at once, each rule is
|
||||
* visited once. A rule whose own set is already known contributes it and is not climbed past. A
|
||||
* key of one rule, the common case, keeps the memo. */
|
||||
* One walk from all of `pos`'s rules, not below_of per rule. Repetition-chain links hand over by
|
||||
* tail reference, so climbing from one link visits every link above it, and one key's positions
|
||||
* can be all n links of `x{0,n}`; per rule that is n^2/2 steps. Walking from all rules at once
|
||||
* visits each rule once. A rule whose set is already known contributes it and is not climbed
|
||||
* past. A single-rule key (the common case) uses the below_of memo. */
|
||||
static void preds_of(Grammar& G, const MaskPlan& P, const std::vector<uint32_t>& pos,
|
||||
std::vector<std::pair<uint32_t, uint32_t>>* out, OpWork& work) {
|
||||
out->clear();
|
||||
@@ -1440,9 +1375,9 @@ static std::string rule_name_of(const std::vector<std::string>* names, uint32_t
|
||||
|
||||
/* ============================================================ building the keys */
|
||||
|
||||
/* What one key's walk decided. A final key keeps its accepted set, which holds whatever the
|
||||
* context, and its remainder trie. A key that is not final is extended; it keeps an accepted set
|
||||
* only if it can also be a whole stack, where there is no context and that set is the mask. */
|
||||
/* What one key's walk decided. A final key keeps its accepted set (valid for any context) and its
|
||||
* remainder trie. A non-final key is extended, and keeps an accepted set only if it can also be a
|
||||
* whole stack, where that set is the mask. */
|
||||
struct Outcome {
|
||||
bool final_ = false;
|
||||
int32_t mask = -1;
|
||||
@@ -1467,8 +1402,8 @@ public:
|
||||
} else if (!w.aborted) {
|
||||
o.mask = store(w);
|
||||
} else {
|
||||
/* The walk was cut short once the key was known to be extended; as a whole stack it
|
||||
* needs the rest. */
|
||||
/* The walk stopped early because the key will be extended; as a whole stack it needs
|
||||
* a full walk. */
|
||||
clear(w);
|
||||
Walk whole = start_walk(false);
|
||||
walk(dfa_, s0, whole, work_, ws_);
|
||||
@@ -1492,8 +1427,8 @@ private:
|
||||
return w;
|
||||
}
|
||||
|
||||
/* Keep an accepted set: listed when the walk listed it, as a bitmask otherwise. Clears the
|
||||
* scratch bits either way. */
|
||||
/* Keep an accepted set: as a list if the walk listed it, else as a bitmask. Clears the scratch
|
||||
* bits either way. */
|
||||
int32_t store(Walk& w) {
|
||||
KeyMask m;
|
||||
if (!w.list_full) {
|
||||
@@ -1527,10 +1462,9 @@ private:
|
||||
return true;
|
||||
}
|
||||
if (!w.aborted) {
|
||||
/* What leaves the key and is not already admitted without it: the tokens under each
|
||||
* node where the key was left, from that depth on. A token that ends exactly there
|
||||
* leaves an empty remainder, which only a carried-out partial character can make
|
||||
* worth keeping. */
|
||||
/* The remainder: tokens under each node where the key was left, from that depth on,
|
||||
* that are not already admitted. A token ending exactly there leaves an empty
|
||||
* remainder, kept only if it carries out a partial character. */
|
||||
rents_.clear();
|
||||
bool too_many = false;
|
||||
for (const auto& f : frontier_) {
|
||||
@@ -1601,7 +1535,7 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr<const
|
||||
work.limit = kMaxCompileWork;
|
||||
|
||||
Grammar G(R, root);
|
||||
/* The longest token in code points, which is as far as any mask can see into the grammar. */
|
||||
/* The longest token in code points: how far any mask can see into the grammar. */
|
||||
const uint32_t max_cps = X.trie.depth > 0 ? X.trie.depth - 1 : 0;
|
||||
const std::vector<char> nullable = nullable_rules(R, work);
|
||||
compute_classes(G, P, nullable, max_cps, work);
|
||||
@@ -1639,14 +1573,13 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr<const
|
||||
GbnfStack local;
|
||||
for (size_t qi = 0; qi < todo.size(); ++qi) {
|
||||
const int32_t ki = todo[qi];
|
||||
/* The compile automaton is a memo like the run-time one; it is dropped between keys once
|
||||
* it is large, never during a walk. Each key is one operation as far as its growth bound
|
||||
* goes, as each mask is at run time. */
|
||||
/* The compile automaton is a memo, dropped between keys (never during a walk) once large.
|
||||
* Each key counts as one operation for the growth bound, as each mask does at run time. */
|
||||
if (dfa.elems() > kMaxDfaElems) dfa = SetDfa(&R);
|
||||
dfa.begin(&work);
|
||||
|
||||
/* A node's class is its BOTTOM entry and `up` is the suffix above it, so following `up`
|
||||
* lists the key bottom-first, which is a stack's order. */
|
||||
/* A node's class is its bottom entry and `up` the suffix above it, so following `up`
|
||||
* lists the key bottom-first, in stack order. */
|
||||
local.clear();
|
||||
for (int32_t k = ki; k >= 0; k = P.keys[(size_t)k].up)
|
||||
local.push_back(&R.elems[G.rep[P.keys[(size_t)k].cls]]);
|
||||
@@ -1715,9 +1648,9 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr<const
|
||||
|
||||
/* ============================================================ a mask */
|
||||
|
||||
/* The key a stack is served by, and how many of its entries it spans: from the top down, one
|
||||
* entry per level, until a node that is not extended or the stack runs out. -1 is a stack no key
|
||||
* covers, which the analysis rules out; it is reported rather than served. */
|
||||
/* The key serving a stack, and how many entries it spans: from the top down, one entry per level,
|
||||
* until a non-extended node or the stack's bottom. -1 means no key covers the stack, which the
|
||||
* analysis rules out; the caller reports it. */
|
||||
static int32_t key_of(const MaskPlan& P, const GbnfStack& S, size_t* depth, OpWork& work) {
|
||||
const GbnfRuleSet& R = *P.rules;
|
||||
const uint32_t c0 = P.cls[R.index(S.back())];
|
||||
@@ -1802,13 +1735,11 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks
|
||||
const SetDfa::St& S = dfa.st(s0);
|
||||
const TrieNode* nd = RS.trie.node.data();
|
||||
|
||||
/* A CHARACTER FINISHED AS U+0000 ENDS THE PIECE. The carried bits are zero only after the
|
||||
* head of an overlong sequence, and with zero bits to finish it the character decodes to 0 --
|
||||
* which in a decoded sequence is its terminator, so the piece reads as having no characters at
|
||||
* all, whatever follows. Such a piece is admissible as one that ends before its first
|
||||
* character is: outright if it carries nothing out, and otherwise if some char-range top could
|
||||
* finish what it does. Those pieces are all under the root edge for zero bits, the first, and
|
||||
* are served here rather than stepped over as a character. */
|
||||
/* A character finished as U+0000 ends the piece. Carried bits are zero only after the head of
|
||||
* an overlong sequence; finishing it with zero bits decodes to 0, the sequence terminator, so
|
||||
* the piece has no characters whatever follows. Such a piece is admissible if it carries
|
||||
* nothing out, or if some char-range top could finish what it carries. These pieces are all
|
||||
* under the first root edge (zero bits) and are handled here, not stepped as a character. */
|
||||
const bool nul = partial.value == 0 && nd[0].n_child > 0 && nd[nd[0].first].cp == 1;
|
||||
if (nul) {
|
||||
std::vector<uint32_t> todo{ nd[0].first };
|
||||
@@ -1843,11 +1774,9 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks
|
||||
}
|
||||
}
|
||||
|
||||
/* The plan's automaton, for one operation charged to `work`. The caller holds P.mu.
|
||||
*
|
||||
* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: every
|
||||
* state in it can be rediscovered, and a grammar whose stacks deepen with every token would
|
||||
* otherwise hold a new state per token for as long as it is cached. */
|
||||
/* The plan's automaton, for one operation charged to `work`. Caller holds P.mu. Past its bound
|
||||
* the memo is dropped and rebuilt rather than refused, since every state can be rediscovered and
|
||||
* a grammar whose stacks deepen every token would otherwise add a state per token. */
|
||||
static SetDfa& plan_dfa(const MaskPlan& P, OpWork& work) {
|
||||
if (!P.dfa || P.dfa->elems() > kMaxDfaElems) {
|
||||
if (P.dfa)
|
||||
@@ -1865,9 +1794,8 @@ bool plan_step(const MaskPlan& P, const std::vector<const GbnfStack*>& stacks, P
|
||||
std::lock_guard<std::mutex> lk(P.mu);
|
||||
SetDfa& dfa = plan_dfa(P, work);
|
||||
|
||||
/* The set as a state: the one the caller names, or canonicalised through pointers -- sorted,
|
||||
* without duplicates, and copied only if the automaton has not seen it. Charged as intern()
|
||||
* charges a sort. */
|
||||
/* The set as a state: the one the caller names, or canonicalised through pointers (sorted,
|
||||
* de-duplicated, copied only if new). The sort is charged as in intern(). */
|
||||
const bool named = at->id >= 0 && at->gen == P.dfa_gen;
|
||||
int32_t s0;
|
||||
if (named) {
|
||||
@@ -1891,8 +1819,7 @@ bool plan_step(const MaskPlan& P, const std::vector<const GbnfStack*>& stacks, P
|
||||
}
|
||||
int32_t s = s0;
|
||||
|
||||
/* One successor per code point: the interval the code point falls in, then that interval's
|
||||
* successor, each built on first use and served from the memo after. */
|
||||
/* Per code point: find its interval, then that interval's successor (both memoised). */
|
||||
for (size_t k = 0; k < n && s >= 0; ++k) {
|
||||
const SetDfa::St& S = dfa.parted(s);
|
||||
const size_t i = (size_t)(std::upper_bound(S.lo.begin(), S.lo.end(), cps[k]) -
|
||||
|
||||
+21
-40
@@ -1,4 +1,4 @@
|
||||
/* grammar.cpp -- the GBNF backend that ships, and the schema seam onto it.
|
||||
/* grammar.cpp -- the GBNF grammar backend and the JSON Schema entry point onto it.
|
||||
*/
|
||||
#include "grammar.h"
|
||||
#include "gbnf.h"
|
||||
@@ -7,23 +7,20 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <exception>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace rad {
|
||||
|
||||
int64_t grammar_mask_words(int64_t n_vocab) { return bitmask_words(n_vocab); }
|
||||
|
||||
/* HOW DEEPLY A SCHEMA MAY NEST, in objects and arrays. The converter recurses once per level and
|
||||
* names each rule after its whole path, so its output grows with the square of the depth: a
|
||||
* 72 KB schema 3,000 levels deep compiles to 67 MB of grammar, and deeper ones exhaust the
|
||||
* memory or the stack of the thread that admits the request. A schema nested as deep as this one
|
||||
* allows converts in tens of milliseconds to a couple of megabytes, and a schema written to
|
||||
* describe data nests far less. */
|
||||
/* Maximum schema nesting, in objects and arrays. The converter recurses once per level and names
|
||||
* each rule after its full path, so output grows with the square of the depth (a 72 KB schema
|
||||
* 3,000 levels deep gives 67 MB of grammar) and deeper ones exhaust the admitting thread's memory
|
||||
* or stack. At this depth a schema converts in tens of milliseconds to a couple of megabytes. */
|
||||
static constexpr size_t kMaxSchemaDepth = 512;
|
||||
|
||||
/* Walked with an explicit stack, because the values it exists to catch are the ones too deep to
|
||||
* recurse over. */
|
||||
/* Iterative, because the values it must catch are too deep to recurse over. */
|
||||
static size_t json_depth(const nlohmann::ordered_json& root) {
|
||||
std::vector<std::pair<const nlohmann::ordered_json*, size_t>> todo{ { &root, 1 } };
|
||||
size_t deepest = 0;
|
||||
@@ -37,26 +34,16 @@ static size_t json_depth(const nlohmann::ordered_json& root) {
|
||||
return deepest;
|
||||
}
|
||||
|
||||
/* ONE JSON-SCHEMA COMPILER, AND IT IS THE VENDORED ONE.
|
||||
*
|
||||
* `response_format` on /v1/chat/completions goes to the chat template, which compiles it with the
|
||||
* vendored converter; on /v1/completions it is refused by the accept-list (kAcceptedCompletion)
|
||||
* before parse_output_format runs, and that is the only path to this seam. A second, separately
|
||||
* maintained copy of the same upstream compiler would therefore be the copy no request reaches,
|
||||
* while the vendored one serves every schema. The hardening that belongs on a schema compiler
|
||||
* fed client data -- vendor/patches 0003 and 0004, which close a hang and two out-of-bounds
|
||||
* reads and refuse three constructs upstream accepts and then gets wrong -- lives in the
|
||||
* vendored copy, which is the copy that runs.
|
||||
*
|
||||
* This function is the seam response_format would go through if /v1/completions accepted it.
|
||||
* No request reaches it.
|
||||
*
|
||||
* The vendored entry point throws; errors are values by the time a caller sees them. */
|
||||
/* Uses the vendored converter, the only JSON Schema compiler in the tree; its hardening for
|
||||
* client data is in vendor/patches 0003 and 0004. Client schemas reach it from /v1/completions
|
||||
* (`json_schema`, `response_format`) through the server's grammar bridge; on
|
||||
* /v1/chat/completions the chat template compiles them instead. The converter throws; errors
|
||||
* are returned as statuses. */
|
||||
int grammar_from_json_schema(const std::string& schema_json, const std::string& root,
|
||||
std::string* out_gbnf, std::string* err) {
|
||||
if (!out_gbnf) return RAD_E_INVAL;
|
||||
/* The converter names its top rule "root" and takes no say in it. Every caller in the tree
|
||||
* asks for "root"; anything else would silently get that instead, so it is refused. */
|
||||
/* The converter always names its top rule "root"; any other name is refused rather than
|
||||
* silently ignored. */
|
||||
if (!root.empty() && root != "root") {
|
||||
if (err) *err = "this converter always names the top rule 'root'";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -88,16 +75,14 @@ class GbnfBackend : public GrammarBackend {
|
||||
public:
|
||||
explicit GbnfBackend(std::unique_ptr<GbnfGrammar> g) : g_(std::move(g)) {}
|
||||
|
||||
const char* name() const override { return "gbnf"; }
|
||||
int accept_token(int32_t token) override { return g_->accept_token(token); }
|
||||
int fill_mask(uint32_t* m, int64_t n) const override { return g_->fill_mask(m, n); }
|
||||
bool complete() const override { return g_->complete(); }
|
||||
bool constrains() const override { return !g_->awaiting_trigger(); }
|
||||
uint64_t masks_walked() const override { return g_->masks_walked(); }
|
||||
|
||||
/* The GBNF machine's state is a stack set and a carried UTF-8 partial, both copyable, so a
|
||||
* rewind is a copy back -- there is nothing to reconstruct and no cost that scales with how
|
||||
* far the window went. */
|
||||
/* The state is a stack set and a carried UTF-8 partial, both copyable, so a rewind is a copy
|
||||
* whose cost does not depend on how far the window went. */
|
||||
bool can_speculate() const override { return true; }
|
||||
int push_state() override { g_->push_state(); return RAD_OK; }
|
||||
int rollback() override { return g_->rollback(); }
|
||||
@@ -110,9 +95,7 @@ int gbnf_ctor(const GrammarSpec& spec, const VocabView& vocab,
|
||||
std::unique_ptr<GrammarBackend>* out, std::string* err) {
|
||||
std::string text = spec.text;
|
||||
|
||||
/* A JSON Schema is compiled to GBNF here rather than being a second backend, because it is
|
||||
* not a different state machine -- it is the same one fed different text. Carrying it as a
|
||||
* backend would mean two places that can disagree about what a schema admits. */
|
||||
/* A JSON Schema is compiled to GBNF and run on the same machine, not a second backend. */
|
||||
if (spec.kind == GrammarKind::JsonSchema) {
|
||||
std::string gbnf;
|
||||
const int st = grammar_from_json_schema(spec.text, spec.root, &gbnf, err);
|
||||
@@ -129,9 +112,8 @@ int gbnf_ctor(const GrammarSpec& spec, const VocabView& vocab,
|
||||
if (!spec.prefix.empty()) {
|
||||
const int ps = g->accept_str(spec.prefix);
|
||||
if (ps < 0) {
|
||||
/* The grammar does not admit the prompt it was supposed to have been generating.
|
||||
* Constraining from here would mask against a state that does not describe this
|
||||
* request, so it is refused rather than run in the wrong place. */
|
||||
/* The grammar rejects the generation prompt; masking from here would use a state
|
||||
* that does not describe this request, so refuse. */
|
||||
if (err) *err = "the grammar does not admit this template's generation prompt, so it "
|
||||
"cannot be positioned at the start of the reply";
|
||||
return ps;
|
||||
@@ -152,9 +134,8 @@ int grammar_create(const GrammarSpec& spec, const VocabView& vocab,
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The compiler below turns its own failures into statuses; what is left is running out of
|
||||
* memory on the way, and this is called on the admission thread and the scheduler thread,
|
||||
* where an escaping exception ends every request on the server rather than this one. */
|
||||
/* The compiler returns its own failures as statuses; only bad_alloc can escape. This runs on
|
||||
* the admission and scheduler threads, where an escaping exception would end every request. */
|
||||
try {
|
||||
return gbnf_ctor(spec, vocab, out, err);
|
||||
} catch (const std::bad_alloc&) {
|
||||
|
||||
+36
-60
@@ -1,18 +1,13 @@
|
||||
/* grammar.h -- structured output: the grammar backend interface, and the bitmask that crosses to
|
||||
* the device.
|
||||
*
|
||||
* Structured output is GBNF, with JSON-schema compiled to a grammar. THE GRAMMAR STATE MACHINE
|
||||
* STAYS ON HOST, where it belongs -- it is a pushdown automaton over a rule set, it branches per
|
||||
* candidate, and none of that is work a GPU is good at. What crosses is a TOKEN BITMASK PER
|
||||
* SEQUENCE, which at a 151K vocab is 19 KiB, cheap enough to upload every step (spec §13). The
|
||||
* mask lands as the `sample_mask` op (docs/OPS.md), which is an ordinary declared op resolved
|
||||
* through the ordinary hierarchy.
|
||||
* Structured output is GBNF, with JSON Schema compiled to a grammar. The grammar state machine
|
||||
* stays on host: it is a pushdown automaton that branches per candidate, which suits a CPU. What
|
||||
* crosses is a token bitmask per sequence, 19 KiB at a 151K vocab, cheap enough to upload every
|
||||
* step (spec §13). The mask is applied by the ordinary `sample_mask` op (docs/OPS.md).
|
||||
*
|
||||
* The backend is a small interface so an alternative can be dropped in, and it is small on
|
||||
* purpose: three calls. GBNF is the shipped one and there is no reason to carry xgrammar for it.
|
||||
* If a device-side grammar ever earns its place, it implements this and nothing above it changes
|
||||
* -- at which point it gets a way to be selected, which is a thing to add then rather than a
|
||||
* registry to carry now for an entry that never arrived.
|
||||
* The backend interface is kept small so an alternative (e.g. a device-side grammar) can
|
||||
* implement it without changes above it. GBNF is the only backend, so there is no registry.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_internal.h"
|
||||
@@ -34,22 +29,18 @@ struct GrammarSpec {
|
||||
std::string text;
|
||||
std::string root = "root";
|
||||
|
||||
/* Lazy grammars constrain nothing until a trigger fires, which is how a tool-calling template
|
||||
* stays free-form until the model starts emitting a call. A trigger is a token id or a literal
|
||||
* word in the emitted bytes; see sampler.cpp for how a template's triggers become these. */
|
||||
/* A lazy grammar constrains nothing until a trigger fires, so a tool-calling template stays
|
||||
* free-form until the model starts a call. A trigger is a token id or a literal word in the
|
||||
* emitted bytes; sampler.cpp maps a template's triggers to these. */
|
||||
bool lazy = false;
|
||||
std::vector<std::string> trigger_words;
|
||||
std::vector<int32_t> trigger_tokens;
|
||||
|
||||
/* TEXT THE GRAMMAR HAS ALREADY SEEN, replayed into it before it constrains anything.
|
||||
*
|
||||
* A chat template's grammar describes the whole assistant turn, generation prompt included:
|
||||
* its root really does begin `"<|im_start|>assistant\n"`, because that is where the turn
|
||||
* begins. But those bytes are in the PROMPT, not in what the model is about to generate, so a
|
||||
* grammar started at its root demands them again -- and the model, obediently masked, emits
|
||||
* the literal text `<|im_start|>assistant` as its answer. Replaying the prefix is what puts
|
||||
* the automaton where the sampler actually is. Empty for a caller-supplied grammar, which
|
||||
* describes the reply and nothing before it. */
|
||||
/* Text replayed into the grammar before it constrains anything. A chat template's grammar
|
||||
* covers the whole assistant turn, so its root begins with the generation prompt (e.g.
|
||||
* `"<|im_start|>assistant\n"`), which is already in the prompt. Without the replay the mask
|
||||
* would force the model to emit it again. Empty for a caller-supplied grammar, which
|
||||
* describes only the reply. */
|
||||
std::string prefix;
|
||||
};
|
||||
|
||||
@@ -57,51 +48,38 @@ class GrammarBackend {
|
||||
public:
|
||||
virtual ~GrammarBackend() = default;
|
||||
|
||||
virtual const char* name() const = 0;
|
||||
|
||||
/* Advance over the token the sampler just emitted. Returns RAD_OK, or RAD_E_STATE if that
|
||||
* token was not admissible -- which means the mask and the pick disagreed, a bug on this side
|
||||
* rather than a bad request. RAD_E_FULL or RAD_E_NOMEM means the parse outgrew the backend's
|
||||
* bounds; the backend is then dead and its next fill_mask fails. */
|
||||
/* Advance over the token the sampler just emitted. RAD_E_STATE means the token was not
|
||||
* admissible: the mask and the pick disagreed, a bug here rather than a bad request.
|
||||
* RAD_E_FULL or RAD_E_NOMEM means the parse outgrew the backend's bounds; the backend is then
|
||||
* dead and its next fill_mask fails. */
|
||||
virtual int accept_token(int32_t token) = 0;
|
||||
|
||||
/* Fill `bitmask` ([n_words] words, bit set means admissible). RAD_E_STATE if nothing at all is
|
||||
* admissible, RAD_E_FULL or RAD_E_NOMEM if the state is past the backend's bounds; any of them
|
||||
* fails the request rather than emitting a token the grammar forbids. */
|
||||
/* Fill `bitmask` ([n_words] words, bit set = admissible). RAD_E_STATE if nothing is
|
||||
* admissible, RAD_E_FULL or RAD_E_NOMEM if the state is past the backend's bounds; each fails
|
||||
* the request rather than emit a forbidden token. */
|
||||
virtual int fill_mask(uint32_t* bitmask, int64_t n_words) const = 0;
|
||||
|
||||
/* Some parse has run to completion, so the sequence may stop here. */
|
||||
virtual bool complete() const = 0;
|
||||
|
||||
/* INSTRUMENT: how many masks this backend has had to COMPUTE rather than serve from a memo,
|
||||
* monotonic over the life of whatever the memo belongs to. Diff it around a fill_mask to learn
|
||||
* which of the two that call was.
|
||||
*
|
||||
* It is a counter and not a duration. Inferring computed-versus-hit from how long a fill_mask
|
||||
* took needs a cost threshold, and no threshold holds: a mask computed on a small grammar
|
||||
* finishes inside the time a memo hit on a large one takes, so the classification is wrong and
|
||||
* any per-mask cost derived from it is wrong by the same factor. A backend with no memo counts
|
||||
* every mask. */
|
||||
/* Instrument: masks computed rather than served from a memo, monotonic over the memo's
|
||||
* lifetime. Diff it around a fill_mask to classify that call. A counter, because timing cannot
|
||||
* classify: a computed mask on a small grammar can be faster than a memo hit on a large one.
|
||||
* A backend with no memo counts every mask. */
|
||||
virtual uint64_t masks_walked() const { return 0; }
|
||||
|
||||
/* False while a lazy grammar is still waiting for its trigger. The driver skips the mask op
|
||||
* for a sequence that is not being constrained, which is the only reason this is on the
|
||||
* interface rather than folded into fill_mask returning all-ones. */
|
||||
/* False while a lazy grammar waits for its trigger. Lets the driver skip the mask op for an
|
||||
* unconstrained sequence instead of applying an all-ones mask. */
|
||||
virtual bool constrains() const = 0;
|
||||
|
||||
/* ---------------------------------------------------------- speculation
|
||||
|
||||
* A CONSTRAINED SEQUENCE SPECULATES BY WALKING THE WINDOW AND REWINDING. The mask for draft
|
||||
* position i is the mask of the state reached by accepting drafts 0..i-1, so the sampler
|
||||
* pushes the state, advances over each proposal in turn to mask the position behind it, and
|
||||
* pops back to where the sequence really is. Without it a grammar-constrained request decodes
|
||||
* one token at a time, at several times the per-token cost of the same model generating
|
||||
* unconstrained prose.
|
||||
* A constrained sequence speculates by walking the window and rewinding. The mask for draft
|
||||
* position i comes from the state after accepting drafts 0..i-1, so the sampler pushes the
|
||||
* state, advances over each proposal to mask the next position, then pops back.
|
||||
*
|
||||
* A backend that cannot do this says so and is driven unspeculated -- the sampler decodes
|
||||
* such a request a token at a time rather than masking a draft position against a state the
|
||||
* sequence is not in, which would admit the wrong token set and read as a model that writes
|
||||
* malformed calls. */
|
||||
* A backend that cannot do this returns false and its requests decode one token at a time;
|
||||
* masking a draft position against the wrong state would admit the wrong token set. */
|
||||
virtual bool can_speculate() const { return false; }
|
||||
|
||||
/* Push the current state. Nestable; `rollback` pops the most recent. */
|
||||
@@ -112,15 +90,13 @@ public:
|
||||
/* Words a mask needs for a vocabulary of this size. */
|
||||
int64_t grammar_mask_words(int64_t n_vocab);
|
||||
|
||||
/* Compile a JSON Schema to GBNF text. Separated from create() so a caller that wants to SEE the
|
||||
* grammar -- `--debug-graph`, or a user asking why their schema behaves as it does -- can get it
|
||||
* without building a state machine. */
|
||||
/* Compile a JSON Schema to GBNF text, without building a state machine, so the grammar can be
|
||||
* inspected (e.g. `--debug-graph`). */
|
||||
int grammar_from_json_schema(const std::string& schema_json, const std::string& root,
|
||||
std::string* out_gbnf, std::string* err);
|
||||
|
||||
/* Build the grammar backend. Returns RAD_OK, or a negative status with a human-readable reason
|
||||
* in *err. There is ONE backend and it is GBNF: a name-keyed registry over a single entry with no
|
||||
* second registration site is a lookup that can only ever resolve to that entry. */
|
||||
/* Build the grammar backend (always GBNF). Returns RAD_OK, or a negative status with a
|
||||
* human-readable reason in *err. */
|
||||
int grammar_create(const GrammarSpec& spec, const VocabView& vocab,
|
||||
std::unique_ptr<GrammarBackend>* out, std::string* err);
|
||||
|
||||
|
||||
+101
-118
@@ -1,9 +1,8 @@
|
||||
/* host_ref.cpp -- llama.cpp's sampling chain, ported to plain C++ over a float array.
|
||||
*
|
||||
* Source: llama.cpp `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT). Ported rather
|
||||
* than linked: this is the oracle the device samplers are checked against, and an oracle that
|
||||
* drags a second inference engine in is a dependency rather than a reference. See host_ref.h for
|
||||
* the two places this deliberately differs from upstream -- the chain order and the RNG.
|
||||
* than linked, so the oracle carries no second engine as a dependency. host_ref.h lists the two
|
||||
* deliberate deviations: chain order and RNG.
|
||||
*/
|
||||
#include "host_ref.h"
|
||||
|
||||
@@ -29,10 +28,8 @@ void CandidateSet::from_logits(const float* logits, int64_t n_vocab) {
|
||||
selected = -1;
|
||||
}
|
||||
|
||||
/* Upstream sorts on the logit alone and leaves equal logits in whatever order the partial sort
|
||||
* happened to produce. That is fine for a single-threaded reference and useless for one that has
|
||||
* to agree with a device kernel, where the order equal elements land in is a property of the
|
||||
* block size. The id tie-break makes the sort a total order, so the two agree. */
|
||||
/* Upstream sorts on the logit alone, leaving ties in arbitrary order; on the device that order
|
||||
* depends on the block size. The id tie-break makes it a total order both sides share. */
|
||||
void CandidateSet::sort_desc() {
|
||||
if (sorted) return;
|
||||
std::stable_sort(c.begin(), c.end(), [](const Candidate& a, const Candidate& b) {
|
||||
@@ -44,29 +41,25 @@ void CandidateSet::sort_desc() {
|
||||
|
||||
/* ================================================================== reproducible randomness */
|
||||
|
||||
/* The stream's key, from abi/rad_sample.h. A stream this file does not know gets a key of its
|
||||
* own rather than the pick's, so it can never silently repeat the pick's draw. */
|
||||
/* The stream's key from abi/rad_sample.h. An unknown stream gets a key of its own, never the
|
||||
* pick's. */
|
||||
static uint64_t stream_key(uint32_t stream) {
|
||||
switch (stream) {
|
||||
case RAD_RNG_PICK: return RAD_SAMPLE_KEY_PICK;
|
||||
case RAD_RNG_XTC: return RAD_SAMPLE_KEY_XTC;
|
||||
case RAD_RNG_ACCEPT: return RAD_SAMPLE_KEY_ACCEPT;
|
||||
case RAD_RNG_RESID: return RAD_SAMPLE_KEY_RESID;
|
||||
default: return rad_sample_splitmix64((uint64_t)stream);
|
||||
}
|
||||
}
|
||||
|
||||
/* rad_sample_uniform01's bits, before the float conversion: one splitmix64 round over
|
||||
* ((seed ^ key) * golden ratio + pos). The same handful of integer ops a sampler kernel runs,
|
||||
* which is what makes it affordable there where a Mersenne twister's state is not. */
|
||||
/* rad_sample_uniform01's bits before the float conversion: one splitmix64 round over
|
||||
* ((seed ^ key) * golden ratio + pos), cheap and stateless enough for a kernel. */
|
||||
uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream) {
|
||||
return rad_sample_splitmix64((seed ^ stream_key(stream)) * 0x9E3779B97F4A7C15ull + pos);
|
||||
}
|
||||
|
||||
float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream) {
|
||||
/* 24 bits, which is every bit a float can hold. Drawing 32 and dividing by 2^32 would round
|
||||
* to 1.0f for the top values, and a uniform that can return 1.0 walks off the end of an
|
||||
* inverse CDF. Written as rad_sample_uniform01 itself, so the two cannot drift apart. */
|
||||
/* 24 bits: 32 bits divided by 2^32 can round to 1.0f, which walks off the end of an inverse
|
||||
* CDF. Calls rad_sample_uniform01 itself so host and device cannot drift apart. */
|
||||
return rad_sample_uniform01(seed ^ stream_key(stream), pos);
|
||||
}
|
||||
|
||||
@@ -86,22 +79,27 @@ void host_softmax(CandidateSet& s, bool do_sort) {
|
||||
e.p = p;
|
||||
cum += p;
|
||||
}
|
||||
if (cum <= 0.0) return; /* every candidate masked out; leave p at zero and let the pick say so */
|
||||
if (cum <= 0.0) return; /* everything masked; p stays zero and the pick reports it */
|
||||
for (auto& e : s.c) e.p = (float)(e.p / cum);
|
||||
}
|
||||
|
||||
/* Index of the highest logit, ties to the lowest id whatever the set's order, as the argmax
|
||||
* kernel breaks them. The set must not be empty. */
|
||||
static size_t best_index(const CandidateSet& s) {
|
||||
size_t best = 0;
|
||||
for (size_t i = 1; i < s.c.size(); ++i) {
|
||||
if (s.c[i].logit > s.c[best].logit) best = i;
|
||||
else if (s.c[i].logit == s.c[best].logit && s.c[i].id < s.c[best].id) best = i;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
void host_temp(CandidateSet& s, float temp) {
|
||||
if (s.c.empty()) return;
|
||||
|
||||
/* temp <= 0 is greedy and stays a real path rather than a caller's special case: the argmax
|
||||
* it produces must use the SAME tie-break the argmax kernel uses (lowest id wins), or a
|
||||
* temperature-0 request stops matching a greedy run. */
|
||||
/* temp <= 0 is greedy, so a temperature-0 request matches a greedy run. */
|
||||
if (temp <= 0.0f) {
|
||||
size_t max_i = 0;
|
||||
for (size_t i = 1; i < s.c.size(); ++i) {
|
||||
const Candidate& e = s.c[i];
|
||||
if (e.logit > s.c[max_i].logit) max_i = i;
|
||||
}
|
||||
const size_t max_i = best_index(s);
|
||||
for (size_t i = 0; i < s.c.size(); ++i)
|
||||
if (i != max_i) s.c[i].logit = -INFINITY;
|
||||
return;
|
||||
@@ -118,14 +116,14 @@ void host_top_k(CandidateSet& s, int32_t k) {
|
||||
}
|
||||
|
||||
void host_top_p(CandidateSet& s, float p, size_t min_keep) {
|
||||
if (p >= 1.0f || s.c.empty()) return;
|
||||
/* p <= 0 is off, as in sample_topp; upstream would keep min_keep candidates. */
|
||||
if (p >= 1.0f || !(p > 0.0f) || s.c.empty()) return;
|
||||
|
||||
s.sort_desc();
|
||||
host_softmax(s, false);
|
||||
|
||||
/* Upstream has an adaptive partial sort that grows k until the nucleus closes; it is a
|
||||
* performance path over a 151K vocab and produces the same set as a full sort, so the
|
||||
* reference takes the full sort and the device kernel takes the radix threshold. */
|
||||
/* Upstream's adaptive partial sort is a performance path that yields the same set; the
|
||||
* reference does a full sort and the device kernel a radix threshold. */
|
||||
float cum = 0.0f;
|
||||
size_t last_idx = s.c.size();
|
||||
for (size_t i = 0; i < s.c.size(); ++i) {
|
||||
@@ -138,10 +136,8 @@ void host_top_p(CandidateSet& s, float p, size_t min_keep) {
|
||||
void host_min_p(CandidateSet& s, float p, size_t min_keep) {
|
||||
if (p <= 0.0f || s.c.empty()) return;
|
||||
|
||||
/* Upstream has an unsorted fast path that filters in place and falls back to the sorted one
|
||||
* when too few survive. Both select the same SET and differ only in the order they leave it
|
||||
* in; the reference takes the sorted path because an order that depends on which path ran is
|
||||
* an order a device kernel cannot reproduce. */
|
||||
/* Upstream also has an unsorted fast path. It selects the same set but leaves a different
|
||||
* order, which a device kernel cannot reproduce, so the reference always sorts. */
|
||||
s.sort_desc();
|
||||
|
||||
const float min_logit = s.c[0].logit + std::log(p); /* p_i >= p * p_max */
|
||||
@@ -153,7 +149,7 @@ void host_min_p(CandidateSet& s, float p, size_t min_keep) {
|
||||
}
|
||||
|
||||
void host_typical(CandidateSet& s, float p, size_t min_keep) {
|
||||
if (p >= 1.0f || s.c.empty()) return;
|
||||
if (p >= 1.0f || !(p > 0.0f) || s.c.empty()) return;
|
||||
|
||||
host_softmax(s, true);
|
||||
|
||||
@@ -161,13 +157,12 @@ void host_typical(CandidateSet& s, float p, size_t min_keep) {
|
||||
for (const auto& e : s.c)
|
||||
if (e.p > 0.0f) entropy += -e.p * std::log(e.p);
|
||||
|
||||
/* The distance between a candidate's surprisal and the distribution's entropy. Sorting by it
|
||||
* is what makes typical sampling different from every other cut here: it keeps the tokens
|
||||
* that are AS surprising as expected, not the least surprising ones. */
|
||||
/* Distance between each candidate's surprisal and the entropy; typical sampling keeps the
|
||||
* tokens closest to the expected surprisal. A zero-probability candidate has none. */
|
||||
std::vector<float> shifted(s.c.size());
|
||||
for (size_t i = 0; i < s.c.size(); ++i) {
|
||||
const float pi = s.c[i].p;
|
||||
shifted[i] = std::fabs(-(pi > 0.0f ? std::log(pi) : -INFINITY) - entropy);
|
||||
shifted[i] = pi > 0.0f ? std::fabs(-std::log(pi) - entropy) : INFINITY;
|
||||
}
|
||||
|
||||
std::vector<size_t> idx(s.c.size());
|
||||
@@ -177,18 +172,26 @@ void host_typical(CandidateSet& s, float p, size_t min_keep) {
|
||||
return s.c[a].id < s.c[b].id; /* total order, same reason as sort_desc */
|
||||
});
|
||||
|
||||
/* The cut is a distance, not a count: the smallest distance whose candidates at or below it
|
||||
* carry at least p, with every candidate at that distance kept. sample_typical keeps the tied
|
||||
* set the same way, so the result does not depend on an order among equal distances. With no
|
||||
* such distance (rounding leaves the whole mass below p) nothing is cut. */
|
||||
float cum = 0.0f;
|
||||
size_t last_idx = idx.size();
|
||||
size_t keep = idx.size();
|
||||
for (size_t i = 0; i < idx.size(); ++i) {
|
||||
if (!(s.c[idx[i]].p > 0.0f)) break;
|
||||
cum += s.c[idx[i]].p;
|
||||
if (cum > p && (min_keep == 0 || i >= min_keep - 1)) { last_idx = i + 1; break; }
|
||||
const bool tie_next = i + 1 < idx.size() && shifted[idx[i + 1]] == shifted[idx[i]];
|
||||
if (cum >= p && !tie_next) { keep = i + 1; break; }
|
||||
}
|
||||
keep = std::max(keep, std::min(min_keep, idx.size()));
|
||||
|
||||
std::vector<Candidate> kept;
|
||||
kept.reserve(last_idx);
|
||||
for (size_t i = 0; i < last_idx; ++i) kept.push_back(s.c[idx[i]]);
|
||||
kept.reserve(keep);
|
||||
for (size_t i = 0; i < keep; ++i) kept.push_back(s.c[idx[i]]);
|
||||
s.c = std::move(kept);
|
||||
s.sorted = false; /* surprisal order is not logit order */
|
||||
s.sort_desc();
|
||||
}
|
||||
|
||||
void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
@@ -207,9 +210,8 @@ void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
if (it == count.end()) continue;
|
||||
const int n = it->second;
|
||||
|
||||
/* The paper divides. Dividing makes a token with a negative logit MORE likely, which is
|
||||
* obviously wrong, so everyone multiplies below zero instead. Upstream's comment says the
|
||||
* same thing and the reference has to reproduce the fix, not the paper. */
|
||||
/* The paper always divides, which makes a negative logit more likely; upstream
|
||||
* multiplies below zero instead, and the reference follows upstream. */
|
||||
if (e.logit <= 0.0f) e.logit *= rep;
|
||||
else e.logit /= rep;
|
||||
|
||||
@@ -248,8 +250,7 @@ bool DryBreakers::is_single(int32_t t) const {
|
||||
}
|
||||
|
||||
/* The longest prefix of `s` of at most `max` bytes that does not end inside a UTF-8 sequence.
|
||||
* Upstream truncates at the byte; cutting a character in half leaves a tail the tokeniser may
|
||||
* refuse, and a refused tail fails the whole request. */
|
||||
* Upstream cuts at the byte, which can leave a tail the tokeniser refuses, failing the request. */
|
||||
static std::string utf8_prefix(const std::string& s, size_t max) {
|
||||
if (s.size() <= max) return s;
|
||||
size_t n = max;
|
||||
@@ -270,17 +271,15 @@ int dry_prepare_breakers(const VocabView& vocab, const std::vector<std::string>&
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Upstream: get_overlapping_token_sequences. A full vocabulary scan per breaker string, which
|
||||
* is why this runs once per request on admission and never on the step path. */
|
||||
/* Upstream: get_overlapping_token_sequences. A full vocabulary scan per breaker, so this runs
|
||||
* once per request, never on the step path. */
|
||||
const int32_t n = vocab.n_tokens();
|
||||
for (const std::string& given : breakers) {
|
||||
const std::string str = utf8_prefix(given, kDryBreakerMaxBytes);
|
||||
if (str.empty()) continue;
|
||||
|
||||
/* THE TAIL DEPENDS ONLY ON WHERE THE BREAKER WAS SPLIT, not on which token covered its
|
||||
* head: every token whose suffix is the breaker's first i bytes is completed by the
|
||||
* tokenisation of the remaining bytes. So each split point is tokenised once rather than
|
||||
* once per matching token -- a breaker that starts with a common byte matches thousands
|
||||
/* The tail depends only on the split point i, not on which token covered the head, so
|
||||
* each split is tokenised once. A breaker starting with a common byte matches thousands
|
||||
* of tokens, and tokenising is the expensive half of the scan. */
|
||||
std::vector<std::vector<int32_t>> tail_at(str.size());
|
||||
std::vector<char> have(str.size(), 0);
|
||||
@@ -304,9 +303,7 @@ int dry_prepare_breakers(const VocabView& vocab, const std::vector<std::string>&
|
||||
std::vector<int32_t>& fresh = tail_at[i];
|
||||
const int st = vocab.tokenize(str.substr(i), &fresh);
|
||||
if (st < 0) {
|
||||
/* A breaker that cannot be tokenised is a breaker that silently stops
|
||||
* working, and a DRY request whose breakers vanished is a DRY request
|
||||
* that quietly changed behaviour. Say so. */
|
||||
/* Fail loudly rather than run DRY with a breaker missing. */
|
||||
RAD_WARN("dry: sequence breaker \"%s\" does not tokenise (%s)",
|
||||
str.c_str(), rad_strerror(st));
|
||||
out->seqs.clear();
|
||||
@@ -363,26 +360,24 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
if (!history || n_history <= 0) return;
|
||||
if (total_context <= 0) total_context = n_history;
|
||||
|
||||
const int64_t effective = (p.penalty_last_n == -1) ? total_context
|
||||
: std::max(p.penalty_last_n, 0);
|
||||
/* Any negative window is the whole context, as in sample_dry; upstream reads only -1 so. */
|
||||
const int64_t effective = p.penalty_last_n < 0 ? total_context : (int64_t)p.penalty_last_n;
|
||||
const int n_rep = (int)std::min(std::min(n_history, effective), total_context);
|
||||
if (n_rep <= p.allowed_length) return;
|
||||
|
||||
/* rat(i): the i-th token counting back from the end of the window. Upstream reads it off a
|
||||
* ring buffer; here the history is a flat array the scheduler already owns. */
|
||||
/* rat(i): the i-th token counting back from the end of the window. Upstream reads a ring
|
||||
* buffer; here the history is the scheduler's flat array. */
|
||||
auto rat = [&](int i) -> int32_t { return history[n_history - 1 - i]; };
|
||||
|
||||
std::vector<int> repeat_count((size_t)n_rep, 0);
|
||||
std::unordered_map<int32_t, int> max_token_repeat;
|
||||
|
||||
/* Step 1: a restart sequence bounds how long a repetition may be counted. Walking back from
|
||||
* the end, the first token that heads a complete breaker sequence caps it. */
|
||||
/* Step 1: the most recent complete breaker sequence caps the counted repeat length. */
|
||||
const int rep_limit = dry_rep_limit(breakers, history + (n_history - n_rep), n_rep);
|
||||
if (rep_limit < p.allowed_length) return;
|
||||
|
||||
/* Step 2: the Z-algorithm, run in reverse, giving for every position the length of the
|
||||
* suffix that also appears ending there. Linear despite the nested loops, because lt/rt bound
|
||||
* each token to one visit. */
|
||||
/* Step 2: the Z-algorithm in reverse, giving for every position the length of the suffix
|
||||
* that also ends there. Linear: lt/rt bound each token to one visit. */
|
||||
{
|
||||
const int last = n_rep - 1;
|
||||
int rt = 0, lt = 0;
|
||||
@@ -408,8 +403,8 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
}
|
||||
}
|
||||
|
||||
/* Step 3: for every position that ends a long-enough repeat, the NEXT token would extend it.
|
||||
* That token is the one to penalise, and by the length it would reach. */
|
||||
/* Step 3: the token after each long-enough repeat would extend it; record the longest
|
||||
* repeat per such token. */
|
||||
for (int i = 0; i < n_rep - 1; ++i) {
|
||||
const int len = repeat_count[(size_t)i];
|
||||
if (len < p.allowed_length) continue;
|
||||
@@ -418,18 +413,17 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
if (it == max_token_repeat.end() || it->second < len) max_token_repeat[tok] = len;
|
||||
}
|
||||
|
||||
/* Step 4: an exponential penalty in the excess length, clamped so pow() cannot overflow a
|
||||
* float -- log(FLT_MAX) is 88.72, and past that the penalty is infinite anyway. */
|
||||
const float FLOAT_MAX_LOG = 88.7228391f;
|
||||
/* Step 4: a penalty exponential in the excess length, with the exponent clamped so pow()
|
||||
* cannot overflow a float (log(FLT_MAX) = 88.72). */
|
||||
const float kFloatMaxLog = 88.7228391f;
|
||||
int max_exponent = 0;
|
||||
if (p.base > 1.000001f) max_exponent = (int)(FLOAT_MAX_LOG / std::log(p.base));
|
||||
if (p.base > 1.000001f) max_exponent = (int)(kFloatMaxLog / std::log(p.base));
|
||||
|
||||
for (auto& e : s.c) {
|
||||
auto it = max_token_repeat.find(e.id);
|
||||
if (it == max_token_repeat.end()) continue;
|
||||
|
||||
/* A token that is itself a single-token breaker is exempt: penalising it would penalise
|
||||
* the very thing that ends the repetition. */
|
||||
/* A single-token breaker is exempt: it is what ends the repetition. */
|
||||
if (breakers.is_single(e.id)) continue;
|
||||
|
||||
int exp_n = it->second - p.allowed_length;
|
||||
@@ -443,12 +437,13 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
|
||||
void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep,
|
||||
uint64_t seed, uint64_t pos) {
|
||||
if (probability <= 0.0f || threshold > 0.5f || s.c.size() < 2) return;
|
||||
/* threshold <= 0 is off, as in sample_xtc. Upstream fires and keeps only the least probable
|
||||
* candidate, since every candidate is at or above 0. */
|
||||
if (probability <= 0.0f || !(threshold > 0.0f) || threshold > 0.5f || s.c.size() < 2) return;
|
||||
|
||||
/* Its own RNG stream: XTC's coin and the pick must not be the same number, or a request
|
||||
* whose XTC fires becomes a request whose pick is correlated with that fact. It fires when
|
||||
* the uniform is BELOW the probability, the comparison `sample_xtc` makes, so the two agree
|
||||
* on the draw that lands exactly on it. */
|
||||
/* A separate RNG stream, so the pick is not correlated with XTC firing. Fires when the
|
||||
* uniform is below the probability, the comparison `sample_xtc` makes, so a draw exactly on
|
||||
* it agrees. */
|
||||
if (rng_uniform(seed, pos, RAD_RNG_XTC) >= probability) return;
|
||||
|
||||
host_softmax(s, true);
|
||||
@@ -459,8 +454,7 @@ void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_ke
|
||||
else break;
|
||||
}
|
||||
|
||||
/* Drop everything above the threshold EXCEPT the least probable of them. That is the whole
|
||||
* idea: remove the obvious continuation, not the unlikely ones. */
|
||||
/* Drop everything above the threshold except the least probable of them. */
|
||||
if (s.c.size() - pos_last >= min_keep && pos_last > 0)
|
||||
s.c.erase(s.c.begin(), s.c.begin() + (std::ptrdiff_t)pos_last);
|
||||
}
|
||||
@@ -485,17 +479,14 @@ int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos) {
|
||||
float max_l = -INFINITY;
|
||||
for (const auto& e : s.c) max_l = std::max(max_l, e.logit);
|
||||
if (!(max_l > -INFINITY)) {
|
||||
/* Every candidate is -inf. That is a fully-masked distribution, which is a grammar that
|
||||
* admits nothing -- a real failure, not a token. The caller fails the request. */
|
||||
/* Fully masked: the grammar admits nothing. The caller fails the request. */
|
||||
s.selected = -1;
|
||||
return -1;
|
||||
}
|
||||
if (s.c.size() == 1) { s.selected = 0; s.c[0].p = 1.0f; return s.c[0].id; }
|
||||
|
||||
/* DESCENDING LOGIT, ties to the lower id, not the set's current order. Any fixed order
|
||||
* samples correctly, but a total order makes the answer a property of the uniform rather than
|
||||
* of how the previous stage happened to permute the set -- and this is the order sample_pick
|
||||
* walks, since sample_topk leaves its candidates in it. */
|
||||
/* Walk in descending logit, ties to the lower id, independent of the set's current order.
|
||||
* This is the order sample_pick walks, since sample_topk leaves its candidates in it. */
|
||||
std::vector<size_t> order(s.c.size());
|
||||
std::iota(order.begin(), order.end(), (size_t)0);
|
||||
std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) {
|
||||
@@ -509,9 +500,8 @@ int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos) {
|
||||
|
||||
const double want = (double)rng_uniform(seed, pos, RAD_RNG_PICK) * total;
|
||||
|
||||
/* A candidate at -infinity is never chosen, and the fall-through is the last one above it: a
|
||||
* draw at the very top of the range can walk past every comparison in floating point, and
|
||||
* the candidates behind the last real one are the grammar-masked ones. */
|
||||
/* A -inf candidate is never chosen. A draw at the top of the range can pass every
|
||||
* comparison in floating point, so the fall-through is the last finite candidate. */
|
||||
double acc = 0.0;
|
||||
size_t chosen = order.front();
|
||||
for (size_t i : order) {
|
||||
@@ -538,59 +528,52 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) {
|
||||
|
||||
/* ================================================================== the chain */
|
||||
|
||||
static int32_t argmax_of(const CandidateSet& s) {
|
||||
if (s.c.empty()) return -1;
|
||||
size_t best = 0;
|
||||
for (size_t i = 1; i < s.c.size(); ++i) {
|
||||
if (s.c[i].logit > s.c[best].logit) best = i;
|
||||
else if (s.c[i].logit == s.c[best].logit && s.c[i].id < s.c[best].id) best = i;
|
||||
}
|
||||
if (!(s.c[best].logit > -INFINITY)) return -1; /* everything masked out */
|
||||
return s.c[best].id;
|
||||
}
|
||||
|
||||
int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
|
||||
ChainOrder order) {
|
||||
/* Penalties first in both orders, because they act on raw logits and every cut below acts on
|
||||
* probabilities derived from them. */
|
||||
/* Penalties first in both orders: they act on raw logits, the cuts on probabilities. */
|
||||
host_penalties(s, in.history, in.n_history, sp.penalty_last_n,
|
||||
sp.rep_penalty, sp.freq_penalty, sp.pres_penalty);
|
||||
|
||||
if (sp.dry_multiplier > 0.0f && in.dry_breakers) {
|
||||
/* DRY runs without breakers, as the device chain does; breakers only cap the repeat length.
|
||||
* An allowed length below 1 is 2, as sample_dry reads it (admission refuses one). */
|
||||
if (sp.dry_multiplier > 0.0f) {
|
||||
static const DryBreakers kNone;
|
||||
DryParams dp;
|
||||
dp.multiplier = sp.dry_multiplier;
|
||||
dp.base = sp.dry_base;
|
||||
dp.allowed_length = sp.dry_allowed_length;
|
||||
dp.allowed_length = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
|
||||
dp.penalty_last_n = sp.dry_penalty_last_n;
|
||||
host_dry(s, in.history, in.n_history, in.total_context, dp, *in.dry_breakers);
|
||||
host_dry(s, in.history, in.n_history, in.total_context, dp,
|
||||
in.dry_breakers ? *in.dry_breakers : kNone);
|
||||
}
|
||||
|
||||
/* THE GREEDY PATH SKIPS THE CHAIN, and it masks BEFORE it picks. Ordering matters here in a
|
||||
* way that is easy to get wrong: temperature 0 collapses every other logit to -inf, so a
|
||||
* mask applied afterwards can leave nothing at all. A greedy sequence is therefore
|
||||
* penalties -> mask -> argmax, not the chain with temp=0 threaded through it. */
|
||||
/* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other
|
||||
* logit to -inf, so a mask applied after it could leave nothing. */
|
||||
if (sp.greedy()) {
|
||||
host_mask(s, in.bitmask, in.n_words);
|
||||
const int32_t tok = argmax_of(s);
|
||||
for (size_t i = 0; i < s.c.size(); ++i) if (s.c[i].id == tok) { s.selected = (int)i; break; }
|
||||
return tok;
|
||||
if (s.c.empty()) return -1;
|
||||
const size_t best = best_index(s);
|
||||
if (!(s.c[best].logit > -INFINITY)) return -1; /* everything masked out */
|
||||
s.selected = (int)best;
|
||||
return s.c[best].id;
|
||||
}
|
||||
|
||||
if (order == ChainOrder::Radiance) {
|
||||
/* `temp_last` moves temperature behind the cuts, as the device chain moves it onto the
|
||||
* candidate plane (Sampler::issue); the cuts keep this order either way. */
|
||||
* candidate plane (Sampler::run). */
|
||||
if (!sp.temp_last) host_temp(s, sp.temp);
|
||||
host_mask(s, in.bitmask, in.n_words);
|
||||
host_top_k(s, sp.top_k);
|
||||
/* sample_topk narrows every row to the candidate width; top_k 0 is that width. */
|
||||
const int64_t width = in.max_candidates > 0 ? in.max_candidates : (int64_t)s.c.size();
|
||||
host_top_k(s, (int32_t)(sp.top_k > 0 ? std::min<int64_t>(sp.top_k, width) : width));
|
||||
host_top_p(s, sp.top_p, 1);
|
||||
host_min_p(s, sp.min_p, 1);
|
||||
host_typical(s, sp.typical_p, 1);
|
||||
host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos);
|
||||
if (sp.temp_last) host_temp(s, sp.temp);
|
||||
} else {
|
||||
/* llama.cpp's default order, for checking this port against llama.cpp itself. Note the
|
||||
* absence of top-n-sigma: it is not in SamplingParams and radiance does not ship it, so a
|
||||
* comparison that enables it upstream will disagree here and should. */
|
||||
/* llama.cpp's default order, for checking this port against llama.cpp. Top-n-sigma is
|
||||
* not in SamplingParams, so a comparison that enables it upstream will disagree. */
|
||||
host_mask(s, in.bitmask, in.n_words);
|
||||
host_top_k(s, sp.top_k);
|
||||
host_typical(s, sp.typical_p, 1);
|
||||
|
||||
+89
-105
@@ -1,39 +1,28 @@
|
||||
/* host_ref.h -- the host reference sampling chain.
|
||||
*
|
||||
* Sampling runs on device (spec §13): at a 151K vocab and batch 256 the logits are ~77 MiB a
|
||||
* step, and moving them across the link to run a host chain costs the bandwidth AND a
|
||||
* synchronisation, on the step path, at exactly the concurrency the engine exists to serve. So
|
||||
* every sampler is a kernel, not a lift.
|
||||
* Sampling runs on device (spec §13) through the declared sampler ops, whose oracle is libref
|
||||
* (spec §17). This is a second, independent formulation of the same chain: llama.cpp's samplers
|
||||
* ported to plain C++ over a float array, with no llama.cpp or ggml dependency, following
|
||||
* `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT). sample_test holds the sampler
|
||||
* driver's chain (Sampler over libref) to it row by row, and Sampler::logprobs_for uses host_dry to
|
||||
* undo DRY.
|
||||
*
|
||||
* This file is the other half of that sentence. A fallback you cannot test against is just an
|
||||
* untested slow path (spec §17), so the device samplers need an oracle, and the oracle is
|
||||
* llama.cpp's chain ported to plain C++ over a float array. Ported, not linked: there are no
|
||||
* llama.cpp headers here and no ggml, because a reference that drags a second engine in is a
|
||||
* dependency, and this is a reference. Each individual sampler below reproduces the semantics of
|
||||
* its counterpart in llama.cpp `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT),
|
||||
* including its edge cases, because reproducing the happy path only is how a comparison harness
|
||||
* agrees with the thing it is checking and both are wrong.
|
||||
* Where upstream and the op chain differ, this follows the chain, which is the contract:
|
||||
*
|
||||
* TWO THINGS DEVIATE FROM UPSTREAM, DELIBERATELY.
|
||||
* 1. Chain order. llama.cpp's default is penalties, DRY, top-n-sigma, top-k, typical, top-p,
|
||||
* min-p, XTC, temperature last. Radiance follows the spec and vLLM (see ChainOrder::Radiance).
|
||||
* Top-p, min-p and typical cut on probabilities, so running temperature first changes which
|
||||
* tokens survive. ChainOrder::LlamaCpp keeps upstream's order for checking this port against
|
||||
* llama.cpp itself.
|
||||
*
|
||||
* 1. THE CHAIN ORDER. llama.cpp's default chain is penalties, DRY, top-n-sigma, top-k, typical,
|
||||
* top-p, min-p, XTC, TEMPERATURE LAST. Radiance's order is the spec's and vLLM's: penalties,
|
||||
* temperature, grammar mask, top-k, then top-p / min-p / typical, then the pick. The
|
||||
* difference is not cosmetic -- top-p, min-p and typical all cut on probabilities, so whether
|
||||
* temperature ran first changes which tokens survive. Radiance's device kernels run the
|
||||
* radiance order (it is the order every OpenAI-compatible server is measured against), so
|
||||
* ChainOrder::Radiance is what rad-kbench compares against. ChainOrder::LlamaCpp exists so
|
||||
* this file can also be checked against llama.cpp itself, which is the only way to know the
|
||||
* port is faithful.
|
||||
* 2. RNG. Upstream keeps a stateful std::mt19937 per sampler, which a kernel cannot hold per
|
||||
* sequence and which makes results depend on batch composition. Here randomness is a pure
|
||||
* function of (seed, position, stream): abi/rad_sample.h's draw, bit for bit, with the same
|
||||
* per-stream keys, so the host sees exactly the uniforms the device stages see.
|
||||
*
|
||||
* 2. THE RNG. Upstream carries a stateful std::mt19937 per sampler. That cannot be a device
|
||||
* kernel: a kernel has no place to keep a Mersenne twister's 624 words of state per sequence,
|
||||
* and a stateful generator makes the answer depend on how many draws happened earlier, which
|
||||
* makes a comparison run irreproducible the moment the batch composition changes. Here the
|
||||
* randomness is a pure function of (seed, position, stream) -- counter-based, stateless, and
|
||||
* reproducible across a run with different batching. It is abi/rad_sample.h's draw, bit for
|
||||
* bit, with the same per-stream keys, so the pick and XTC's coin here see exactly the uniforms
|
||||
* the device stages see.
|
||||
* 3. Values. top_p, typical_p or xtc_threshold at or below 0 turns the stage off; typical keeps
|
||||
* every candidate tied at its cut; a negative DRY window is the whole context; and top_k 0 is
|
||||
* the candidate width (HostRefInput::max_candidates), not the whole vocabulary.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -49,16 +38,15 @@ namespace rad {
|
||||
/* ================================================================== the candidate set */
|
||||
|
||||
/* One candidate. `p` is meaningless until a softmax has run over the set; the samplers that need
|
||||
* it call one themselves, exactly as upstream's do. */
|
||||
* it call one themselves, as upstream's do. */
|
||||
struct Candidate {
|
||||
int32_t id = 0;
|
||||
float logit = 0.0f;
|
||||
float p = 0.0f;
|
||||
};
|
||||
|
||||
/* The set the chain narrows. `sorted` tracks descending-by-logit order, because half the
|
||||
* samplers upstream have a fast path that depends on it and a slow path that does not, and
|
||||
* dropping the flag silently changes which one runs. */
|
||||
/* The set the chain narrows. `sorted` tracks descending-by-logit order; many upstream samplers
|
||||
* take a different path when it is set, so it must stay accurate. */
|
||||
struct CandidateSet {
|
||||
std::vector<Candidate> c;
|
||||
bool sorted = false;
|
||||
@@ -71,26 +59,21 @@ struct CandidateSet {
|
||||
|
||||
/* ================================================================== reproducible randomness */
|
||||
|
||||
/* A counter-based generator: bits are a pure function of the three coordinates, so the same draw
|
||||
* comes out on the host reference and in the device kernel, in any batch order, at any batch
|
||||
* size. It IS rad_sample_uniform01 from abi/rad_sample.h -- splitmix64 over
|
||||
* ((seed ^ key) * golden ratio + pos) -- because a reference with its own generator agrees with
|
||||
* the device on no seeded draw at all.
|
||||
/* Counter-based generator: bits are a pure function of the three coordinates, so host and device
|
||||
* draw the same number in any batch order or size. It is rad_sample_uniform01 from
|
||||
* abi/rad_sample.h, splitmix64 over ((seed ^ key) * golden ratio + pos).
|
||||
*
|
||||
* `pos` is the sequence's output position -- token index within this request's generation -- so
|
||||
* a request's draws depend on where it is, not on when it was scheduled. `stream` separates
|
||||
* independent draws taken at the same position (the pick, XTC's coin, speculative acceptance's
|
||||
* uniforms) so they are not the same number; each maps to its RAD_SAMPLE_KEY_* key. */
|
||||
* `pos` is the output position (token index within this request's generation), so draws depend on
|
||||
* where a request is, not when it was scheduled. `stream` separates independent draws at the same
|
||||
* position; each maps to its RAD_SAMPLE_KEY_* key. */
|
||||
enum : uint32_t {
|
||||
RAD_RNG_PICK = 0, /* the final categorical draw */
|
||||
RAD_RNG_XTC = 1, /* XTC's "does this fire at all" coin */
|
||||
RAD_RNG_ACCEPT = 2, /* speculative acceptance, one per draft position (see accept.h) */
|
||||
RAD_RNG_RESID = 3 /* the residual draw after a speculative rejection */
|
||||
RAD_RNG_XTC = 1 /* XTC's "does this fire at all" coin */
|
||||
};
|
||||
|
||||
uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream);
|
||||
/* Uniform in [0,1). 24 bits of mantissa: a float cannot resolve more, and pretending otherwise
|
||||
* would make the host and the device disagree in the last place. */
|
||||
/* Uniform in [0,1) with 24 bits, the most a float resolves; more would let host and device
|
||||
* disagree in the last place. */
|
||||
float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream);
|
||||
|
||||
/* ================================================================== individual samplers */
|
||||
@@ -99,39 +82,42 @@ float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream);
|
||||
void host_softmax(CandidateSet& s, bool do_sort);
|
||||
|
||||
/* Upstream: llama_sampler_temp_impl. temp <= 0 collapses to the argmax by setting every other
|
||||
* logit to -inf, which is what keeps a temperature-0 request bit-identical to a greedy one. */
|
||||
* logit to -inf, keeping a temperature-0 request identical to a greedy one. */
|
||||
void host_temp(CandidateSet& s, float temp);
|
||||
|
||||
/* Upstream: llama_sampler_top_k_impl. k <= 0 is off. */
|
||||
/* Upstream: llama_sampler_top_k_impl. k <= 0 is off; host_sample passes the candidate width for
|
||||
* top_k 0 (see HostRefInput::max_candidates). */
|
||||
void host_top_k(CandidateSet& s, int32_t k);
|
||||
|
||||
/* Upstream: llama_sampler_top_p_apply. Ties AT the threshold are all kept, which can overshoot
|
||||
* p by the mass of the tie -- the alternative is inventing an order among equal probabilities. */
|
||||
/* Upstream: llama_sampler_top_p_apply. Keeps the shortest prefix in descending logit order, ties
|
||||
* to the lower id, whose mass reaches p, so a tie at the threshold is split by id as sample_topp
|
||||
* splits it. p <= 0 is off. */
|
||||
void host_top_p(CandidateSet& s, float p, size_t min_keep);
|
||||
|
||||
/* Upstream: llama_sampler_min_p_apply. A floor relative to the mode, not an absolute one. */
|
||||
void host_min_p(CandidateSet& s, float p, size_t min_keep);
|
||||
|
||||
/* Upstream: llama_sampler_typical_apply. Keeps the candidates whose surprisal is closest to the
|
||||
* distribution's entropy, which is not the same set as the most probable ones. */
|
||||
/* Upstream: llama_sampler_typical_apply, with sample_typical's cut. Keeps the candidates whose
|
||||
* surprisal is closest to the distribution's entropy, not the most probable ones: everything at or
|
||||
* below the smallest distance whose candidates carry at least p, ties at that distance included
|
||||
* (upstream cuts a prefix at mass > p). Zero-probability candidates go. p <= 0 is off. The result
|
||||
* is in descending logit order. */
|
||||
void host_typical(CandidateSet& s, float p, size_t min_keep);
|
||||
|
||||
/* Upstream: llama_sampler_penalties_apply, with the history passed in rather than accumulated in
|
||||
* a ring buffer. The scheduler already owns each request's token history, and a sampler that
|
||||
* kept its own copy would be a second place for it to be wrong.
|
||||
*
|
||||
* `history` is the sequence's tokens, oldest first; only the last `last_n` are counted. */
|
||||
/* Upstream: llama_sampler_penalties_apply, with the history passed in instead of kept in a ring
|
||||
* buffer; the scheduler owns each request's token history. `history` is oldest first; only the
|
||||
* last `last_n` tokens are counted. */
|
||||
void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
int32_t last_n, float rep, float freq, float pres);
|
||||
|
||||
/* DRY's sequence breakers, resolved to token sequences once per request rather than per step.
|
||||
* Upstream calls this `dry_processed_breakers` and builds it from the vocabulary; the cost is a
|
||||
* full vocabulary scan per breaker string, which is why it does not belong on the step path.
|
||||
/* DRY's sequence breakers, resolved to token sequences once per request (upstream's
|
||||
* `dry_processed_breakers`). Each breaker costs a full vocabulary scan, so this stays off the
|
||||
* step path.
|
||||
*
|
||||
* `seqs` maps a HEAD token to the tails that complete a breaker after it; an empty tail means the
|
||||
* head token contains a whole breaker by itself. The two bitsets over the vocabulary answer the
|
||||
* two questions the step path asks per token -- "does anything start here" and "is this token a
|
||||
* whole breaker" -- with one load, where the multimap is a hash lookup a token. */
|
||||
* `seqs` maps a head token to the tails that complete a breaker after it; an empty tail means the
|
||||
* head token holds a whole breaker. The bitsets answer the step path's two per-token questions
|
||||
* (does a breaker start here, is this token a whole breaker) with one load instead of a hash
|
||||
* lookup. */
|
||||
struct DryBreakers {
|
||||
std::unordered_multimap<int32_t, std::vector<int32_t>> seqs;
|
||||
std::vector<uint32_t> heads; /* bit t: token t heads at least one breaker sequence */
|
||||
@@ -140,7 +126,7 @@ struct DryBreakers {
|
||||
bool empty() const { return seqs.empty(); }
|
||||
|
||||
/* Build the two bitsets from `seqs`. dry_prepare_breakers calls it; a set filled by hand is
|
||||
* answered from the multimap until it is indexed, so the two ways of building one agree. */
|
||||
* answered from the multimap until indexed, so both answer the same. */
|
||||
void index(int32_t n_vocab);
|
||||
bool is_head(int32_t t) const;
|
||||
bool is_single(int32_t t) const;
|
||||
@@ -152,29 +138,25 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
/* THE BOUNDS ON WHAT A REQUEST MAY ASK THE BREAKER SCAN TO DO. Each breaker costs a pass over the
|
||||
* whole vocabulary on the scheduler thread, once per rank, so an unbounded list stalls every
|
||||
* sequence on the server for as long as the scan takes. Upstream truncates a breaker to 40 bytes
|
||||
* and its token tail to 20 tokens (llama_sampler_init_dry); the count bound is this engine's own,
|
||||
* well above the four breakers clients send by default, and a request over it is refused at
|
||||
* admission by name rather than silently shortened. */
|
||||
/* Bounds on the breaker scan. Each breaker is a full-vocabulary pass on the scheduler thread,
|
||||
* once per rank, stalling every sequence while it runs. Upstream truncates a breaker to 40 bytes
|
||||
* and its tail to 20 tokens (llama_sampler_init_dry). The count bound is this engine's own, well
|
||||
* above the four breakers clients send by default; a request over it is refused at admission. */
|
||||
constexpr size_t kDryMaxBreakers = 16;
|
||||
constexpr size_t kDryBreakerMaxBytes = 40;
|
||||
constexpr int kDryBreakerMaxTail = 20;
|
||||
|
||||
/* Upstream: get_overlapping_token_sequences, per breaker, with upstream's truncation of each
|
||||
* breaker to kDryBreakerMaxBytes (cut back to a UTF-8 boundary, so the tail still tokenises) and
|
||||
* of each tail to `max_tail_len` tokens. Refuses more than kDryMaxBreakers breakers with
|
||||
* RAD_E_INVAL. Returns RAD_E_UNSUPPORTED if the view has no tokeniser, because a DRY request
|
||||
* whose breakers silently became empty is a DRY request that quietly stopped working. */
|
||||
/* Upstream: get_overlapping_token_sequences, per breaker, truncating each breaker to
|
||||
* kDryBreakerMaxBytes (cut back to a UTF-8 boundary so the tail still tokenises) and each tail to
|
||||
* `max_tail_len` tokens. More than kDryMaxBreakers is RAD_E_INVAL. RAD_E_UNSUPPORTED if the view
|
||||
* has no tokeniser, rather than silently running DRY without breakers. */
|
||||
int dry_prepare_breakers(const VocabView& vocab, const std::vector<std::string>& breakers,
|
||||
DryBreakers* out, int max_tail_len = kDryBreakerMaxTail);
|
||||
|
||||
/* Upstream's step 1 of llama_sampler_dry_apply: walking back from the end of `window` (n tokens,
|
||||
* oldest first), the first token that heads a COMPLETE breaker sequence caps how long a repeat
|
||||
* may be counted. Returns that cap, or n when no breaker completes inside the window. Shared by
|
||||
* host_dry and the sampler's per-step staging, so the reference and the device stage are handed
|
||||
* the same limit. */
|
||||
/* Step 1 of upstream's llama_sampler_dry_apply: walking back from the end of `window` (n tokens,
|
||||
* oldest first), the first token that heads a complete breaker sequence caps the counted repeat
|
||||
* length. Returns that cap, or n when no breaker completes in the window. Shared by host_dry and
|
||||
* the sampler's per-step staging, so reference and device use the same limit. */
|
||||
int dry_rep_limit(const DryBreakers& breakers, const int32_t* window, int n);
|
||||
|
||||
struct DryParams {
|
||||
@@ -190,39 +172,39 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
int64_t total_context, const DryParams& p, const DryBreakers& breakers);
|
||||
|
||||
/* Upstream: llama_sample_xtc_apply. Fires with probability `probability`; when it fires it drops
|
||||
* every candidate above the threshold except the least probable of them, which is the point --
|
||||
* it removes the obvious continuation rather than the unlikely ones. */
|
||||
* every candidate above the threshold except the least probable of them, removing the obvious
|
||||
* continuations. threshold <= 0 is off, as in sample_xtc. */
|
||||
void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep,
|
||||
uint64_t seed, uint64_t pos);
|
||||
|
||||
/* The grammar mask. One bit per token, set means admissible; a cleared bit takes the logit to
|
||||
* -inf rather than removing the candidate, so the mask composes with everything downstream
|
||||
* without renumbering anything. `n_words` is ceil(n_vocab/32). */
|
||||
/* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf
|
||||
* instead of removing the candidate, so nothing downstream is renumbered. `n_words` is
|
||||
* ceil(n_vocab/32). */
|
||||
void host_mask(CandidateSet& s, const uint32_t* bitmask, int64_t n_words);
|
||||
|
||||
/* The pick. Inverse CDF over the surviving candidates in DESCENDING LOGIT ORDER, ties to the lower
|
||||
* id -- a total order, so the answer is a property of the uniform rather than of how the previous
|
||||
* stage happened to permute the set, and the order `sample_pick` walks the candidate set the
|
||||
* top-k leaves (and the order upstream's dist sampler walks a sorted set in). A candidate at
|
||||
* -infinity -- a grammar-masked logit -- is never returned, including by the fall-through a draw
|
||||
* at the very top of the range takes. Returns the token id, or -1 for an empty or fully masked
|
||||
* set. */
|
||||
/* The pick. Inverse CDF over the surviving candidates in descending logit order, ties to the
|
||||
* lower id. A total order makes the result depend only on the uniform, and it is the order
|
||||
* `sample_pick` walks top-k's output (and upstream's dist sampler walks a sorted set). A -inf
|
||||
* (grammar-masked) candidate is never returned, even by the fall-through at the top of the range.
|
||||
* Returns the token id, or -1 for an empty or fully masked set. */
|
||||
int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos);
|
||||
|
||||
/* Argmax over raw logits, lowest id winning a tie. The greedy path skips the chain entirely, so
|
||||
* this must agree with what host_temp(0) + host_pick would produce or a temperature-0 request
|
||||
* stops matching a greedy one. */
|
||||
/* Argmax over raw logits, lowest id winning a tie. The greedy path skips the chain, so this must
|
||||
* agree with host_temp(0) + host_pick. */
|
||||
int32_t host_argmax(const float* logits, int64_t n_vocab);
|
||||
|
||||
/* ================================================================== the chain */
|
||||
|
||||
/* The candidate width every stage after top-k works in, SamplerConfig::max_candidates' default. */
|
||||
constexpr int64_t kSampleCandidates = 1024;
|
||||
|
||||
enum class ChainOrder {
|
||||
Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
|
||||
LlamaCpp = 1 /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */
|
||||
};
|
||||
|
||||
/* Everything the chain needs that is not in SamplingParams. Kept separate because SamplingParams
|
||||
* is frozen in rad_core.h and these are per-step facts, not per-request settings. */
|
||||
/* Per-step inputs the chain needs beyond SamplingParams, which is frozen in rad_core.h and holds
|
||||
* per-request settings. */
|
||||
struct HostRefInput {
|
||||
const int32_t* history = nullptr; /* the sequence's tokens so far, oldest first */
|
||||
int64_t n_history = 0;
|
||||
@@ -230,16 +212,18 @@ struct HostRefInput {
|
||||
const uint32_t* bitmask = nullptr; /* grammar mask, or null */
|
||||
int64_t n_words = 0;
|
||||
uint64_t pos = 0; /* output position: the RNG's second coordinate */
|
||||
const DryBreakers* dry_breakers = nullptr;
|
||||
const DryBreakers* dry_breakers = nullptr; /* null runs DRY with no breakers */
|
||||
/* The chain's candidate width (SamplerConfig::max_candidates): top-k narrows every row to
|
||||
* at most this many, so top_k 0 samples from the most likely kSampleCandidates tokens. 0 is
|
||||
* the whole vocabulary. Read by ChainOrder::Radiance only. */
|
||||
int64_t max_candidates = kSampleCandidates;
|
||||
};
|
||||
|
||||
/* Run the whole chain over one row of logits and return the token. This is what rad-kbench
|
||||
* compares the device sampler against, per sequence, on the same logits. */
|
||||
/* Run the whole chain over one row of logits and return the token. */
|
||||
int32_t host_sample(const float* logits, int64_t n_vocab, const SamplingParams& sp,
|
||||
const HostRefInput& in, ChainOrder order = ChainOrder::Radiance);
|
||||
|
||||
/* The same, leaving the narrowed candidate set behind for a caller that wants to inspect it --
|
||||
* rad-kbench reports which stage diverged, and it cannot do that from a token id alone. */
|
||||
/* As host_sample, leaving the narrowed candidate set for inspection. */
|
||||
int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
|
||||
ChainOrder order = ChainOrder::Radiance);
|
||||
|
||||
|
||||
+221
-315
@@ -1,5 +1,5 @@
|
||||
/* sampler.cpp -- the sampler driver: declare the sampler ops, build the per-sequence parameter
|
||||
* array once per step, issue the chain. No sampler is implemented here; see sampler.h for why.
|
||||
* array once per step, issue the chain. No sampler is implemented here; see sampler.h.
|
||||
*/
|
||||
#include "sampler.h"
|
||||
#include "gbnf.h"
|
||||
@@ -13,22 +13,18 @@ namespace rad {
|
||||
|
||||
/* ================================================================== grammar triggers
|
||||
*
|
||||
* A chat template names its triggers the way a person would -- "the call starts at the word
|
||||
* <tool_call>" -- while GbnfGrammar wants them in the two forms it checks as tokens arrive: token
|
||||
* ids to compare against the id just emitted, and literal words to find in the emitted bytes.
|
||||
* The translation needs a vocabulary, so it happens here and not in the server.
|
||||
* Translates a chat template's triggers into the two forms GbnfGrammar checks as tokens arrive:
|
||||
* token ids compared against the emitted id, and literal words searched in the emitted bytes.
|
||||
* This needs the vocabulary, so it happens here rather than in the server.
|
||||
*
|
||||
* A WORD IS A TOKEN WHEN THE VOCABULARY SAYS SO. The word is tokenised with special tokens
|
||||
* recognised, since a template's markers are usually special tokens and a split of `<tool_call>`
|
||||
* into `<`, `tool`, `_call`, `>` is not what the model emits. One token makes an id trigger, which
|
||||
* costs a comparison; anything longer is scanned for as bytes, because the tokeniser may split it
|
||||
* differently depending on what came before it. Getting this wrong does not fail loudly -- it
|
||||
* yields a trigger that never fires, so the call comes out unconstrained, which reads as a model
|
||||
* that writes malformed calls.
|
||||
* A word is tokenised with special tokens recognised, since template markers such as
|
||||
* `<tool_call>` are usually special tokens. If it is one token it becomes an id trigger;
|
||||
* otherwise it is matched as bytes, because the tokeniser may split it differently depending on
|
||||
* context. A wrong translation fails silently: the trigger never fires and the call comes out
|
||||
* unconstrained.
|
||||
*
|
||||
* A REGULAR-EXPRESSION TRIGGER IS REFUSED. Its matcher would run over the reply once per token
|
||||
* on the scheduler thread; the templates in service all trigger on words. A request whose
|
||||
* template needs one is refused at admission, naming the pattern. */
|
||||
* Regular-expression triggers are refused at admission, naming the pattern; their matcher would
|
||||
* run over the reply once per token on the scheduler thread. */
|
||||
static int resolve_triggers(const VocabView& vocab,
|
||||
const std::vector<SamplingParams::GrammarTrigger>& triggers,
|
||||
std::vector<std::string>* words, std::vector<int32_t>* tokens,
|
||||
@@ -69,12 +65,16 @@ static int resolve_triggers(const VocabView& vocab,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A lazy grammar waits for a trigger before it constrains anything, so one without a trigger
|
||||
* would leave the whole reply unconstrained. */
|
||||
static const char* const kLazyNoTrigger =
|
||||
"a lazy grammar needs at least one word or token trigger; without one it never constrains";
|
||||
|
||||
/* ================================================================== small helpers */
|
||||
|
||||
/* Copy this rank's window out of a whole-vocabulary bitmask. `vocab_off` is word-aligned for
|
||||
* every shard this engine builds (the head is split on a multiple of 32), so the aligned arm is
|
||||
* the one that runs; the bit-shifting arm exists because a shard boundary is a placement decision
|
||||
* and not a promise, and a mask that is silently off by a few bits admits the wrong tokens. */
|
||||
/* Copy this rank's window out of a whole-vocabulary bitmask. The engine splits the head on a
|
||||
* multiple of 32, so `vocab_off` is normally word-aligned; the bitwise path covers any other
|
||||
* shard boundary, where a misaligned copy would admit the wrong tokens. */
|
||||
void Sampler::shard_mask(uint32_t* dst) const {
|
||||
const int64_t full = (int64_t)mask_full_.size();
|
||||
std::memset(dst, 0, (size_t)mask_words_ * 4);
|
||||
@@ -92,21 +92,14 @@ void Sampler::shard_mask(uint32_t* dst) const {
|
||||
}
|
||||
}
|
||||
|
||||
/* rad_runtime.h's RAD_B / RAD_W macros are C compound literals. They are legal C++ only as a
|
||||
* compiler extension, and this file is core code that has to build with -Wall -Wextra clean, so
|
||||
* the operands are built the ordinary way. */
|
||||
/* NARROWED TO THIS STEP'S ROWS, always. arch/common/rad_arch.h says why for the model's own
|
||||
* buffers and the reason is the sampler's too: a kernel cannot read the row count out of `M`,
|
||||
* because `M` is the band's upper bound, so every shim takes it off the operand. Handed over at
|
||||
* its DECLARED extent -- max_seqs * (max_spec + 1) rows -- an operand makes every stage compute a
|
||||
* full candidate set for rows that have no request behind them, over params the upload never
|
||||
* wrote. The extra rows are discarded, so nothing downstream is wrong and no bench can see it,
|
||||
* but each phantom row costs a vocabulary-wide reduction, and at one sequence every row but one
|
||||
* is a phantom.
|
||||
/* rad_runtime.h's RAD_B / RAD_W macros are C compound literals, legal C++ only as an extension,
|
||||
* and core code builds -Wall -Wextra clean, so operands are built the ordinary way. */
|
||||
/* Operands are always narrowed to this step's rows. `M` is only the band's upper bound, so
|
||||
* kernels take the row count from the operand (arch/common/rad_arch.h); at the declared extent,
|
||||
* max_seqs * (max_spec + 1), every stage would do a vocabulary-wide reduction for each empty row.
|
||||
*
|
||||
* `rows` is dim 0 for every buffer here -- logits, params, history, mask, candidates, pairs, the
|
||||
* gather and the token output all count sampled POSITIONS first -- and the strides below it are
|
||||
* products of the trailing dimensions, so shortening the outermost one leaves them correct. */
|
||||
* Every buffer here has sampled positions as dim 0, and its strides are products of the trailing
|
||||
* dimensions, so shortening dim 0 leaves them correct. */
|
||||
static RadOperand opd_rows(rad_buf h, int64_t rows) {
|
||||
RadOperand o{};
|
||||
o.kind = RAD_OPK_BUF;
|
||||
@@ -115,9 +108,8 @@ static RadOperand opd_rows(rad_buf h, int64_t rows) {
|
||||
return o;
|
||||
}
|
||||
|
||||
/* An optional operand this issue does not pass. The runtime holds every issue to its schema's
|
||||
* operand COUNT -- operands are positional -- so an absent trailing optional is spelled, not
|
||||
* dropped. */
|
||||
/* An absent optional operand. Operands are positional and the runtime checks an issue against
|
||||
* the schema's operand count, so a missing trailing optional must be passed as this. */
|
||||
static RadOperand opd_none() {
|
||||
RadOperand o{};
|
||||
o.kind = RAD_OPK_NONE;
|
||||
@@ -125,9 +117,8 @@ static RadOperand opd_none() {
|
||||
}
|
||||
|
||||
static int64_t rows_for(const SamplerConfig& c) {
|
||||
/* One row per SAMPLED POSITION, not per sequence: a speculative verify samples n_spec+1
|
||||
* positions for a sequence and each one has its own output position, hence its own RNG
|
||||
* coordinate. Sizing for the worst step is the same rule the arena follows (spec §3.1). */
|
||||
/* One row per sampled position: a verify samples n_spec+1 positions per sequence, each with
|
||||
* its own RNG coordinate. Sized for the worst step, as the arena is (spec §3.1). */
|
||||
return c.max_seqs * (int64_t)(c.max_spec + 1);
|
||||
}
|
||||
|
||||
@@ -144,15 +135,11 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
cfg_ = cfg;
|
||||
if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size;
|
||||
|
||||
/* THE STAGED MASK IS THIS RANK'S SHARD, AND THE GRAMMAR'S IS THE WHOLE VOCABULARY. Those are
|
||||
* different lengths the moment the head is sharded, and conflating them is silent: every
|
||||
* vocab-scoped sampler op is declared over `n_vocab_local` (op_vocab, below) and `sample_mask`
|
||||
* indexes its bitmask from bit zero, so a full-vocabulary mask handed to rank 1 masks its
|
||||
* logits with the admissibility of tokens 0..n_local -- ids that belong to rank 0. The result
|
||||
* is not a diagnosable error, it is a rank sampling from the wrong permission set.
|
||||
*
|
||||
* So the grammar fills `mask_full_` over the whole vocabulary, which is also where the "no
|
||||
* token is admissible anywhere" check belongs, and only this rank's window of it is staged. */
|
||||
/* The staged mask covers this rank's shard; the grammar's covers the whole vocabulary.
|
||||
* `sample_mask` indexes its bitmask from bit zero over `n_vocab_local`, so handing rank 1 the
|
||||
* full mask would apply rank 0's token admissibility to it. The grammar therefore fills
|
||||
* `mask_full_` (where the "nothing admissible anywhere" check belongs) and only this rank's
|
||||
* window is staged. */
|
||||
mask_words_ = grammar_mask_words(cfg_.n_vocab_local);
|
||||
mask_full_.assign((size_t)grammar_mask_words(cfg_.n_vocab), 0u);
|
||||
|
||||
@@ -161,10 +148,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
const int64_t ncand = cfg_.max_candidates;
|
||||
|
||||
/* ---------------------------------------------------------- buffers */
|
||||
/* PERSIST, not TRANSIENT: the parameter, history and mask planes are written by an upload
|
||||
* that happens BEFORE the run phase issues anything, so liveness over the declared op list
|
||||
* would conclude they are dead where they are in fact being filled. A transient whose first
|
||||
* definition is invisible to the planner is a transient the planner will happily overwrite. */
|
||||
/* The staging planes are PERSIST: they are filled by an upload before any op is issued, which
|
||||
* the planner's liveness over the op list cannot see, so as TRANSIENT they would be
|
||||
* overwritten. */
|
||||
auto decl = [&](const char* name, uint32_t dt, int64_t d0, int64_t d1, int kind) -> rad_buf {
|
||||
RadBufDecl d{};
|
||||
d.dtype = dt;
|
||||
@@ -181,44 +167,39 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
buf_params_late_ = decl("sampler.params_late", RAD_U32, rows,
|
||||
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
|
||||
buf_hist_ = decl("sampler.history", RAD_I32, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
/* One byte beside every history token: nonzero where that token is a whole DRY sequence
|
||||
* breaker, which DRY never penalises. Resolving a token against the breaker strings needs the
|
||||
* vocabulary, so it happens here on the host and the kernel reads the answer. */
|
||||
/* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never
|
||||
* penalised). Resolved on the host, which has the vocabulary. */
|
||||
buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
|
||||
buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT);
|
||||
buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT);
|
||||
if (vocab_parallel()) {
|
||||
/* THE PAIR PLANE AND THE GATHERED PLANE. sample_topk packs this rank's candidates into
|
||||
* `pairs` as (u32 global id, f32 logit); the all-gather places every rank's pairs for a
|
||||
* row SIDE BY SIDE, which is the one layout the merge can read at a single row stride. */
|
||||
/* sample_topk packs this rank's candidates into `pairs` as (u32 global id, f32 logit);
|
||||
* the all-gather lays every rank's pairs for a row side by side, so the merge reads one
|
||||
* row at a single stride. */
|
||||
buf_pairs_ = decl("sampler.cand_pairs", RAD_U32, rows, ncand * 2, RAD_BUF_TRANSIENT);
|
||||
buf_gather_ = decl("sampler.cand_gathered", RAD_U32, rows,
|
||||
ncand * cfg_.world_size * 2, RAD_BUF_TRANSIENT);
|
||||
}
|
||||
|
||||
/* THE LOGPROBS SUMMARY, PERSIST for the reason the staging planes are: nothing in the
|
||||
* declared op list reads it -- rank 0 copies it to the host behind the pick -- so liveness
|
||||
* over the op list would hand its bytes to the candidate planes the stages after it write. */
|
||||
/* The logprobs summary is PERSIST too: no declared op reads it (rank 0 copies it to the host
|
||||
* behind the pick), so liveness would let the candidate planes reuse its bytes. */
|
||||
buf_lp_ = decl("sampler.logprobs", RAD_F32, rows, lp_width(), RAD_BUF_PERSIST);
|
||||
if (vocab_parallel())
|
||||
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
|
||||
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
|
||||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_) {
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_ ||
|
||||
(vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) {
|
||||
RAD_ERR("sampler: a staging buffer failed to declare");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- ops */
|
||||
/* Every one of these is declared unconditionally and may fail to resolve. That is not an
|
||||
* error here: a deployment that never sends `typical_p` has no use for a typical kernel, and
|
||||
* failing declare over it would make an absent sampler an absent model. check_request turns
|
||||
* an unresolved sampler into a named refusal at admission instead. */
|
||||
/* `M` is the ranged parameter and it is the number of SAMPLED POSITIONS, not tokens: one row
|
||||
* at decode, n_spec+1 per sequence at a verify, and a kernel written for a single row is a
|
||||
* different kernel from one written for a batch of 256 (spec §2.2). */
|
||||
/* Every op is declared unconditionally and may fail to resolve; check_request refuses the
|
||||
* requests that need a missing one. `M` is ranged over sampled positions, so a kernel may
|
||||
* specialise for one row versus a batch of 256 (spec §2.2). */
|
||||
auto op_vocab = [&](const char* name) -> rad_op {
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -226,12 +207,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
};
|
||||
return rad_decl_op(b, name, p, 2, nullptr, 0);
|
||||
};
|
||||
/* THE VOCABULARY OFFSET, on the three stages that cross between a token id and a column of
|
||||
* this rank's logits row: top-k turns a column into a token id, and the penalties and DRY turn
|
||||
* the history's token ids into columns. Without it a rank past the first penalises the
|
||||
* columns of whatever ids happen to be small, which are other tokens entirely. Declared only
|
||||
* when the vocabulary is sharded, so a single-rank graph carries no parameter it has no use
|
||||
* for. */
|
||||
/* `vocab_off` for the three stages that map between token ids and this rank's columns:
|
||||
* top-k (column to id), penalties and DRY (history id to column). Declared only when the
|
||||
* vocabulary is sharded. */
|
||||
auto op_vocab_off = [&](const char* name) -> rad_op {
|
||||
if (!vocab_parallel())
|
||||
return op_vocab(name);
|
||||
@@ -242,8 +220,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
};
|
||||
return rad_decl_op(b, name, p, 3, nullptr, 0);
|
||||
};
|
||||
/* The stages after top-k read a candidate set, not the vocabulary, so their geometry is the
|
||||
* candidate width. That is what makes them cheap: 1024 entries rather than 151K. */
|
||||
/* Stages after top-k work on the candidate set, so their geometry is the candidate width. */
|
||||
auto op_cand = [&](const char* name) -> rad_op {
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -264,8 +241,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_typical_ = op_cand("sample_typical");
|
||||
op_xtc_ = op_cand("sample_xtc");
|
||||
op_pick_ = op_cand("sample_pick");
|
||||
/* THE SAME TEMPERATURE KERNEL OVER THE CANDIDATE PLANE: its `n_vocab` is the candidate width,
|
||||
* which is all the kernel reads it as -- a row length. */
|
||||
/* The temperature kernel again, over the candidate plane: `n_vocab` is only a row length to
|
||||
* it, so the candidate width works. */
|
||||
{
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -275,24 +252,21 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
}
|
||||
|
||||
if (vocab_parallel()) {
|
||||
/* lm_head is vocab-sharded, so each rank reduces ITS OWN shard and only the candidate
|
||||
* sets are combined -- k * world_size pairs, 2 KiB at k=64 and world_size=4, against the
|
||||
* ~77 MiB a full-logits gather would move (spec §9). */
|
||||
/* Each rank reduces its own shard and only the candidate sets are gathered: 2 KiB at
|
||||
* k=64 and world_size=4, versus ~148 MiB for full logits (spec §9). */
|
||||
RadParam ag[4] = {
|
||||
RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
|
||||
RadParam{ "numel", RAD_P_INT, (long long)(rows * ncand * 2), 0, nullptr },
|
||||
RadParam{ "dtype", RAD_P_STR, 0, 0, "f32" },
|
||||
/* ROW-INTERLEAVED. One sampled position's pairs from every rank have to land side by
|
||||
* side, because sample_merge_topk reads one row at one row stride. */
|
||||
/* Row-interleaved, so each position's pairs from every rank are adjacent. */
|
||||
RadParam{ "row", RAD_P_INT, (long long)(ncand * 2), 0, nullptr },
|
||||
};
|
||||
op_allgather_ = rad_decl_op(b, "all_gather", ag, 4, nullptr, 0);
|
||||
op_merge_ = op_cand("sample_merge_topk");
|
||||
}
|
||||
|
||||
/* THE RAW DISTRIBUTION'S SUMMARY, at the one width every request's top_logprobs fits in. A
|
||||
* deployment whose kernels lack it serves every request that does not ask for logprobs;
|
||||
* check_request refuses the ones that do, by name. */
|
||||
/* The raw-distribution summary, at a width that fits every request's top_logprobs. If it
|
||||
* does not resolve, check_request refuses only requests that ask for logprobs. */
|
||||
{
|
||||
RadParam p[4] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -303,8 +277,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_logprobs_ = rad_decl_op(b, "sample_logprobs", p, vocab_parallel() ? 4 : 3, nullptr, 0);
|
||||
}
|
||||
if (vocab_parallel()) {
|
||||
/* Each rank summarised its own shard; rank 0 merges them on the host, so every rank's
|
||||
* row lands beside the others' as the candidate pairs do. */
|
||||
/* Each rank summarises its own shard; rank 0 merges them on the host. Laid out side by
|
||||
* side, like the candidate pairs. */
|
||||
RadParam ag[4] = {
|
||||
RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
|
||||
RadParam{ "numel", RAD_P_INT, (long long)(rows * lp_width()), 0, nullptr },
|
||||
@@ -327,9 +301,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
int Sampler::stage_alloc() {
|
||||
const int64_t rows = rows_for(cfg_);
|
||||
|
||||
/* Pinned, because these are uploaded every step and a pageable source turns an async copy
|
||||
* into a staged one with a host bounce -- which is exactly the per-step cost the step batch
|
||||
* exists to remove (spec §8). */
|
||||
/* Pinned: uploaded every step, and a pageable source turns the async copy into a staged one
|
||||
* with a host bounce (spec §8). */
|
||||
params_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
@@ -341,8 +314,7 @@ int Sampler::stage_alloc() {
|
||||
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
|
||||
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
|
||||
|
||||
/* Rank 0's landing place for the logprobs copies, and only rank 0's: it is the rank that
|
||||
* reads them. */
|
||||
/* Logprobs readback; only rank 0 reads it. */
|
||||
if (cfg_.rank == 0) {
|
||||
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
|
||||
lp_host_ = (float*)rad_dev_alloc(rows * w * 4, RAD_MEM_HOST_PINNED);
|
||||
@@ -393,10 +365,9 @@ Sampler::~Sampler() { stage_free(); }
|
||||
|
||||
/* ================================================================== admission */
|
||||
|
||||
/* WHEN THE TWO HISTORY STAGES RUN, in one place, because admission, request setup and the step
|
||||
* staging each ask and must not disagree. llama.cpp's meaning throughout: a window of 0 turns the
|
||||
* stage off, and DRY also needs a base of at least 1. The multiplier is taken as positive because
|
||||
* a negative one rewards repetition, which is not a request anyone makes on purpose. */
|
||||
/* Whether the two history stages run, shared by admission, request setup and step staging so
|
||||
* they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY
|
||||
* also requires a positive multiplier; a negative one would reward repetition. */
|
||||
static bool penalties_on(const SamplingParams& sp) {
|
||||
return sp.penalty_last_n != 0 &&
|
||||
(sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f);
|
||||
@@ -412,24 +383,40 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
return st;
|
||||
};
|
||||
|
||||
/* Each range is tested as "inside", so a NaN fails it. top_p and typical_p are (0, 1], as
|
||||
* the server takes them: the chain reads 0 as off, where llama.cpp keeps one candidate, so
|
||||
* 0 has no single meaning to honour. */
|
||||
if (sp.top_k < 0) return refuse("top_k is negative", RAD_E_INVAL);
|
||||
if (sp.top_p < 0.0f || sp.top_p > 1.0f) return refuse("top_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.min_p < 0.0f || sp.min_p > 1.0f) return refuse("min_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.typical_p < 0.0f || sp.typical_p > 1.0f)
|
||||
return refuse("typical_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.temp < 0.0f) return refuse("temperature is negative", RAD_E_INVAL);
|
||||
if (sp.top_k > cfg_.max_candidates)
|
||||
return refuse("top_k exceeds the sampler's candidate width (--max-candidates)",
|
||||
RAD_E_INVAL);
|
||||
if (!(sp.top_p > 0.0f && sp.top_p <= 1.0f))
|
||||
return refuse("top_p is outside (0,1]", RAD_E_INVAL);
|
||||
if (!(sp.min_p >= 0.0f && sp.min_p <= 1.0f))
|
||||
return refuse("min_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (!(sp.typical_p > 0.0f && sp.typical_p <= 1.0f))
|
||||
return refuse("typical_p is outside (0,1]", RAD_E_INVAL);
|
||||
if (!(sp.temp >= 0.0f)) return refuse("temperature must be >= 0", RAD_E_INVAL);
|
||||
if (!(sp.xtc_probability >= 0.0f && sp.xtc_probability <= 1.0f))
|
||||
return refuse("xtc_probability is outside [0,1]", RAD_E_INVAL);
|
||||
if (!(sp.xtc_threshold >= 0.0f && sp.xtc_threshold <= 1.0f))
|
||||
return refuse("xtc_threshold is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.top_k > cfg_.max_candidates) {
|
||||
if (why)
|
||||
*why = "top_k " + std::to_string(sp.top_k) + " is wider than the sampler's candidate "
|
||||
"width of " + std::to_string(cfg_.max_candidates) + " tokens";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The penalty divides a positive logit by rep_penalty, so 0 would make it infinite. */
|
||||
if (penalties_on(sp) && !(sp.rep_penalty > 0.0f))
|
||||
return refuse("rep_penalty must be > 0", RAD_E_INVAL);
|
||||
/* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */
|
||||
if (dry_on(sp) && sp.dry_allowed_length < 1)
|
||||
return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL);
|
||||
if (sp.n_probs > RAD_MAX_LOGPROBS) {
|
||||
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
|
||||
" logprobs alternatives may be asked for";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Every breaker is a pass over the whole vocabulary on the scheduler thread, and every other
|
||||
* sequence on the server waits for it; see kDryMaxBreakers. Refused here, before any of that
|
||||
* work is queued, rather than truncated -- a request whose breakers quietly went missing is a
|
||||
* request whose output changed. */
|
||||
/* Each breaker is a full-vocabulary scan on the scheduler thread (see kDryMaxBreakers).
|
||||
* Refused rather than truncated, which would silently change the output. */
|
||||
if (dry_on(sp) && sp.dry_seq_breakers.size() > kDryMaxBreakers) {
|
||||
if (why)
|
||||
*why = "dry_sequence_breakers has " + std::to_string(sp.dry_seq_breakers.size()) +
|
||||
@@ -437,18 +424,14 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* An unresolved sampler is a named refusal, not a silent skip. A request whose min_p quietly
|
||||
* stopped being applied is a request whose output changed and nothing said so. */
|
||||
/* An unresolved sampler is a named refusal, never a silent skip. */
|
||||
auto need = [&](bool wanted, rad_op h, const char* n) -> const char* {
|
||||
return (wanted && !h) ? n : nullptr;
|
||||
};
|
||||
/* A SPLIT VOCABULARY MOVES GREEDY ONTO THE CHAIN, so what a greedy request needs moves with
|
||||
* it: not the argmax, but the temperature stage, the top-k, the merge and the pick that
|
||||
* build_step's top_k = 1 sends it through -- run() issues the temperature stage for every
|
||||
* batch with a chain row, even though its kernel leaves a greedy row (temperature 0) as it
|
||||
* is. Admission has to check what will actually be issued. */
|
||||
/* AND SO DOES ONE ASKING FOR LOGPROBS, which build_step stages as a top-1 chain row so its
|
||||
* token comes off a candidate plane (sampler.h). */
|
||||
/* Under a split vocabulary, or when it asks for logprobs, a greedy request is staged as a
|
||||
* top-1 chain row (see build_step), so it needs the chain ops (temperature, top-k, pick)
|
||||
* rather than the argmax. run() issues the temperature stage for any chain row, even though
|
||||
* it leaves a temperature-0 row unchanged. */
|
||||
const bool lp = sp.n_probs >= 0;
|
||||
const bool greedy_chain = sp.greedy() && (vocab_parallel() || lp);
|
||||
const char* missing = nullptr;
|
||||
@@ -456,9 +439,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_temp_, "sample_temp");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_pick_, "sample_pick");
|
||||
/* EVERY CHAIN ROW NEEDS THE TOP-K, whatever its own top_k says: it is the stage that writes
|
||||
* the candidate set every later stage reads. top_k = 0 asks for the whole candidate width,
|
||||
* not for no candidates. */
|
||||
/* Every chain row needs top-k, whatever its top_k: it writes the candidate set the later
|
||||
* stages read. top_k = 0 means the whole candidate width (max_candidates). */
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_topk_, "sample_topk");
|
||||
if (!missing) missing = need(sp.top_p < 1.0f, op_topp_, "sample_topp");
|
||||
if (!missing) missing = need(sp.min_p > 0.0f, op_minp_, "sample_minp");
|
||||
@@ -478,10 +460,9 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!sp.grammar.empty() && !vocab_)
|
||||
return refuse("a grammar was requested before the vocabulary was attached", RAD_E_STATE);
|
||||
|
||||
/* The triggers are resolved here as well as at begin_request, so a template whose triggers
|
||||
* this machine cannot run is a refusal at admission rather than a request cancelled on the
|
||||
* scheduler thread. */
|
||||
if (!sp.grammar.empty() && !sp.grammar_triggers.empty()) {
|
||||
/* Resolved here as well as in begin_request, so unsupported triggers are refused at
|
||||
* admission rather than cancelling the request on the scheduler thread. */
|
||||
if (!sp.grammar.empty() && (sp.grammar_lazy || !sp.grammar_triggers.empty())) {
|
||||
std::vector<std::string> words;
|
||||
std::vector<int32_t> tokens;
|
||||
std::string e;
|
||||
@@ -490,6 +471,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (why) *why = e;
|
||||
return st;
|
||||
}
|
||||
if (sp.grammar_lazy && words.empty() && tokens.empty())
|
||||
return refuse(kLazyNoTrigger, RAD_E_INVAL);
|
||||
}
|
||||
|
||||
return RAD_OK;
|
||||
@@ -508,32 +491,24 @@ int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::strin
|
||||
spec.text = sp.grammar;
|
||||
spec.root = "root";
|
||||
spec.lazy = sp.grammar_lazy;
|
||||
/* ONLY A NON-LAZY GRAMMAR IS POSITIONED AT THE START OF THE TURN. An eager grammar's root
|
||||
* describes the whole assistant turn and therefore opens with the generation prompt, which
|
||||
* is already in the prompt -- so it has to be replayed or the model is made to write it
|
||||
* out again. A LAZY one describes only the region after its trigger: its root begins at
|
||||
* `<tool_call>`, and feeding it a prefix it never claimed to match fails outright, taking
|
||||
* every tool-calling request with it. */
|
||||
/* Only an eager grammar replays the generation prompt prefix: its root describes the
|
||||
* whole assistant turn, which opens with text already in the prompt. A lazy grammar's
|
||||
* root starts at its trigger (e.g. `<tool_call>`) and would fail on that prefix. */
|
||||
spec.prefix = sp.grammar_lazy ? std::string() : sp.grammar_prefix;
|
||||
RAD_TRY(resolve_triggers(*vocab_, sp.grammar_triggers, &spec.trigger_words,
|
||||
&spec.trigger_tokens, err));
|
||||
RAD_TRY(grammar_create(spec, *vocab_, &st.grammar, err));
|
||||
}
|
||||
|
||||
/* BREAKERS ARE OPTIONAL. DRY runs whenever the request turns it on, as llama.cpp's does with an
|
||||
* empty breaker list; the breakers only limit how far back a repeat may be counted and exempt
|
||||
* the tokens that are breakers themselves. */
|
||||
/* Breakers are optional; DRY runs without them, as llama.cpp's does. They only cap how far
|
||||
* back a repeat is counted and exempt whole-breaker tokens. */
|
||||
if (dry_on(sp) && !sp.dry_seq_breakers.empty()) {
|
||||
if (!vocab_) {
|
||||
if (err) *err = "DRY needs a vocabulary to resolve its sequence breakers";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (sp.dry_seq_breakers.size() > kDryMaxBreakers) {
|
||||
if (err) *err = "too many DRY sequence breakers";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Once per request, never per step: a full vocabulary scan per breaker string is
|
||||
* milliseconds at a 151K vocab and has no business on the step path. */
|
||||
/* Once per request: a full vocabulary scan per breaker costs milliseconds at a 151K
|
||||
* vocab. */
|
||||
const int s = dry_prepare_breakers(*vocab_, sp.dry_seq_breakers, &st.dry,
|
||||
kDryBreakerMaxTail);
|
||||
if (s < 0) {
|
||||
@@ -560,8 +535,8 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
|
||||
auto it = seqs_.find(req_id);
|
||||
if (it == seqs_.end()) return RAD_OK; /* no grammar, nothing to advance */
|
||||
if (!it->second.grammar) return RAD_OK;
|
||||
/* TIMED for the same reason build_step is: this runs once per ACCEPTED token per rank, on the
|
||||
* step thread, so it is wall time on every constrained token. */
|
||||
/* Timed at Debug, like build_step: runs once per accepted token per rank on the step thread,
|
||||
* so it is wall time on every constrained token. */
|
||||
if ((int)log_level() < (int)Log::Debug) return it->second.grammar->accept_token(token);
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const int s = it->second.grammar->accept_token(token);
|
||||
@@ -574,11 +549,9 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
|
||||
return s;
|
||||
}
|
||||
|
||||
/* A CONSTRAINING GRAMMAR DOES NOT MEAN NO SPECULATION. build_step masks draft position i
|
||||
* against the state reached by accepting drafts 0..i-1 and then rewinds, so a backend that can
|
||||
* push and pop its state speculates like any other request -- which is worth several times the
|
||||
* per-token cost on a constrained request. What IS refused is a backend that cannot rewind:
|
||||
* masking its window would mean masking against a state the sequence is not in. */
|
||||
/* A constraining grammar does not rule out speculation: build_step masks draft position i
|
||||
* against the state after drafts 0..i-1 and then rewinds. Only a backend that cannot rewind is
|
||||
* refused. */
|
||||
bool Sampler::allows_speculation(uint64_t req_id) const {
|
||||
auto it = seqs_.find(req_id);
|
||||
if (it == seqs_.end() || !it->second.grammar) return true;
|
||||
@@ -603,17 +576,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
cur_stage_ = params_stage_;
|
||||
lp_rows_.clear();
|
||||
|
||||
/* DRY'S HOST HALF, for one row whose history `h[0, take)` is already staged. The breakers are
|
||||
* strings resolved against the vocabulary, so what they mean for this window is worked out
|
||||
* here and handed to the kernel as data: the repeat limit the most recent breaker imposes
|
||||
* (llama.cpp's step 1), and one byte per position marking the tokens that are whole breakers
|
||||
* and therefore never penalised. The window is the one the kernel will take -- the tail of
|
||||
* the staged row, `dry_penalty_last_n` long when that is positive.
|
||||
/* DRY's host half for one row whose history `h[0, take)` is staged. Over the window the
|
||||
* kernel uses (the tail of the row, `dry_penalty_last_n` long when positive) it computes the
|
||||
* repeat limit from the most recent breaker (llama.cpp's step 1) and marks whole-breaker
|
||||
* tokens, which are never penalised.
|
||||
*
|
||||
* Returns false when the breakers rule DRY out for the row altogether: a breaker closer to the
|
||||
* end than `allowed_length` leaves no repeat long enough to count. A row with no breakers
|
||||
* gets zero marks, because the plane is shared by the whole batch and another row may have
|
||||
* some. */
|
||||
* Returns false when a breaker closer to the end than `allowed_length` rules DRY out for the
|
||||
* row. A row without breakers still gets zero marks, because the plane is shared by the
|
||||
* batch. */
|
||||
auto stage_dry = [&](DeviceSampleParams& p, const int32_t* h, int64_t take,
|
||||
const DryBreakers* brk, int64_t row) -> bool {
|
||||
const int64_t last_n = p.dry_penalty_last_n;
|
||||
@@ -640,12 +610,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
const int n_pos = r->n_draft + 1;
|
||||
|
||||
if (n_pos > 1 && !allows_speculation(r->id)) {
|
||||
RAD_ERR("sampler: request %llu carries a constraining grammar its backend cannot "
|
||||
"snapshot, and %d draft tokens. The mask for draft position i is the mask of "
|
||||
"the state reached by accepting drafts 0..i-1, so masking the window needs "
|
||||
"push_state/rollback. The scheduler must consult allows_speculation() and "
|
||||
"decode this one a token at a time.",
|
||||
(unsigned long long)r->id, r->n_draft);
|
||||
RAD_ERR("sampler: request %llu has %d draft tokens and a constraining grammar that "
|
||||
"cannot snapshot its state; the scheduler must decode it a token at a time "
|
||||
"(allows_speculation)", (unsigned long long)r->id, r->n_draft);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -665,25 +632,19 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
SeqState* st = it == seqs_.end() ? nullptr : &it->second;
|
||||
const DryBreakers* brk = st && !st->dry.empty() ? &st->dry : nullptr;
|
||||
|
||||
/* THE WINDOW IS WALKED, THEN REWOUND. Position 0 is masked against the state the sequence
|
||||
* is really in; position k against the state reached by accepting drafts 0..k-1. The push
|
||||
* happens whatever the grammar's current mode, because a draft token can fire a lazy
|
||||
* grammar's trigger mid-window -- at which point the positions behind it DO need a mask,
|
||||
* and without the push they would be sampled unconstrained.
|
||||
/* The window is walked, then rewound: position k is masked against the state after
|
||||
* accepting drafts 0..k-1. The push happens even when the grammar is not yet
|
||||
* constraining, because a draft can fire a lazy grammar's trigger mid-window.
|
||||
*
|
||||
* `dead` is not a failure. A draft the grammar forbids simply cannot be accepted: the
|
||||
* target's own masked pick at that position will differ from it, so verification rejects
|
||||
* there and every position behind it is discarded. Masking stops and the rest of the
|
||||
* window is left unconstrained, which is what "discarded" needs it to be. */
|
||||
* `dead` is not a failure: a draft the grammar forbids will be rejected at verification
|
||||
* and every later position discarded, so masking stops for the rest of the window. */
|
||||
GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr;
|
||||
const bool walk = gr && n_pos > 1;
|
||||
if (walk) gr->push_state();
|
||||
bool dead = false;
|
||||
|
||||
/* THE REASONING BUDGET, walked over the window as the grammar is. Position k is inside the
|
||||
* block or not according to the committed reply and drafts 0..k-1, which is the only
|
||||
* history under which its token is ever emitted; a draft that ends the block early is
|
||||
* accepted or rejected like any other. */
|
||||
/* The reasoning budget is walked over the window like the grammar: position k is
|
||||
* judged by the committed reply plus drafts 0..k-1. */
|
||||
const bool budget = st && sp.thinking_budget >= 0 && sp.reasoning.known();
|
||||
ReasoningCount think;
|
||||
if (budget) {
|
||||
@@ -705,9 +666,8 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
std::memset(&p, 0, sizeof p);
|
||||
|
||||
p.seed = sp.seed;
|
||||
/* The output position, advanced across the speculative window: draft position k is
|
||||
* the (n_out + k)-th token this request will emit, so its randomness is the same
|
||||
* whether it arrived through speculation or one token at a time. */
|
||||
/* Output position: draft position k is token n_out + k, so its draw is the same with
|
||||
* or without speculation. */
|
||||
p.pos = (uint64_t)(n_out + k);
|
||||
|
||||
p.temp = sp.temp;
|
||||
@@ -727,21 +687,15 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.dry_penalty_last_n = sp.dry_penalty_last_n;
|
||||
p.mask_row = -1;
|
||||
|
||||
/* GREEDY OVER A SPLIT VOCABULARY IS A TOP-1 CHAIN, not an argmax. sample_argmax reads a
|
||||
* whole logits row and writes the winning COLUMN, which under vocab parallelism is
|
||||
* this rank's local index into its own shard -- a fluent answer built from the wrong
|
||||
* token ids. Staging top_k = 1 sends the row through top-k, the pair plane, the
|
||||
* gather and the merge instead, which is where a local index becomes a global one;
|
||||
* sample_pick over a single live candidate returns it deterministically, so the
|
||||
* result is the argmax it was always meant to be.
|
||||
/* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax
|
||||
* writes a column of this rank's shard, not a token id. Top-k plus the merge produce
|
||||
* global ids, and the pick over one candidate is deterministic. A greedy row asking
|
||||
* for logprobs is staged the same way, because logprobs_for reads the drawn value
|
||||
* from the candidate plane; the argmax and top-k share a tie rule, so the token is
|
||||
* unchanged.
|
||||
*
|
||||
* Such a row is a CHAIN row and does not carry RAD_SP_GREEDY: every candidate stage
|
||||
* skips a row that does, because in an unsplit batch that flag is what keeps the pick
|
||||
* from overwriting the argmax's answer with a draw. */
|
||||
/* A GREEDY ROW ASKING FOR LOGPROBS IS A TOP-1 CHAIN ROW TOO, for a reason of its own:
|
||||
* its token has to come off a candidate plane, which is where logprobs_for reads the
|
||||
* value it was drawn at. The argmax's tie rule is the top-k's, so the token is the
|
||||
* same. */
|
||||
* Such a row does not carry RAD_SP_GREEDY: candidate stages skip flagged rows, so the
|
||||
* pick does not overwrite the argmax's token. */
|
||||
const bool want_lp = sp.n_probs >= 0;
|
||||
if (sp.greedy()) {
|
||||
if (vocab_parallel() || want_lp) p.top_k = 1;
|
||||
@@ -749,9 +703,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
}
|
||||
if (want_lp) p.flags |= RAD_SP_LOGPROBS;
|
||||
if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC;
|
||||
/* TEMPERATURE LAST: the row's own temperature in the late stage's row, and 1 -- which
|
||||
* the temperature stage skips -- in whichever of the two it does not run in. Every row
|
||||
* gets a late row, because the late stage is issued over the whole batch. */
|
||||
/* Temperature last: the row's temperature goes in the late row and 1 (skipped) in the
|
||||
* early one; otherwise the reverse. Every row gets a late row, because the late stage
|
||||
* is issued over the whole batch. */
|
||||
const bool late = sp.temp_last && !sp.greedy() && sp.temp != 1.0f;
|
||||
DeviceSampleParams& lp = late_stage_[row];
|
||||
lp = p;
|
||||
@@ -761,17 +715,11 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
any_late_ = true;
|
||||
}
|
||||
|
||||
/* THE HISTORY THE PENALTIES AND DRY READ, staged only for a row that runs one of them
|
||||
* -- the copy is scheduler-thread work and the upload is step-path bytes, and neither
|
||||
* buys anything for a row that reads none of it. It is the prompt, everything
|
||||
* generated so far and, at draft position k, the k drafted tokens in front of it: the
|
||||
* token sampled there is emitted only if those drafts are, so they are part of the
|
||||
* output it is penalised against, exactly as they would be one token at a time. Oldest
|
||||
* first, truncated to the declared window -- a bound on the buffer, not a policy on
|
||||
* the sampler; penalty_last_n still decides how much of it counts. The row owns its
|
||||
* own row of the plane, so the window starts at offset 0 within it. */
|
||||
p.hist_off = 0;
|
||||
p.hist_len = 0;
|
||||
/* History for the penalties and DRY, staged only for rows that run one of them:
|
||||
* prompt, output so far and, at draft position k, the k drafts before it (they are
|
||||
* emitted only if accepted, as one token at a time). Oldest first, truncated to
|
||||
* max_hist; penalty_last_n still decides how much counts. Each row owns its row of the
|
||||
* plane, so hist_off stays 0. */
|
||||
if (pen || dry) {
|
||||
const int64_t len = n_total + k;
|
||||
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
|
||||
@@ -790,18 +738,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
if (gr && !dead && gr->constrains()) {
|
||||
uint32_t* dst = mask_stage_ + row * mask_words_;
|
||||
int s;
|
||||
/* WHAT THE MASK COSTS, MEASURED RATHER THAN ASSUMED. The mask is scheduler-thread
|
||||
* work with the rank threads waiting at the barrier, so it is wall time on every
|
||||
* constrained token and would decide the step if it were slow. Reported at Debug,
|
||||
* per 256 masks, mean and worst. */
|
||||
/* Mask cost, reported at Debug per 256 masks (mean and worst). It runs on the
|
||||
* scheduler thread while the rank threads wait at the barrier. */
|
||||
const bool inst = (int)log_level() >= (int)Log::Debug;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
/* ASK THE GRAMMAR WHETHER IT COMPUTED THE MASK, rather than inferring it from how
|
||||
* long the call took. No duration threshold separates the two: a mask computed
|
||||
* from the plan can finish inside the time a memo hit costs on a large
|
||||
* vocabulary, so a timing test counts computed masks as hits and any per-mask
|
||||
* cost derived from the split is wrong by that factor. The counter is exact and
|
||||
* costs a relaxed load. */
|
||||
/* Memo hits and computed masks are told apart by the grammar's walk counter, not
|
||||
* by duration: a computed mask can be as fast as a memo hit on a large
|
||||
* vocabulary. */
|
||||
const uint64_t w0 = inst ? st->grammar->masks_walked() : 0;
|
||||
if (!vocab_parallel()) {
|
||||
s = st->grammar->fill_mask(dst, mask_words_);
|
||||
@@ -812,15 +755,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
if (inst) {
|
||||
const double us = std::chrono::duration<double, std::micro>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
mask_us_ += us; mask_worst_us_ = mask_us_n_ && us < mask_worst_us_
|
||||
? mask_worst_us_ : us;
|
||||
mask_us_ += us;
|
||||
mask_worst_us_ = std::max(mask_worst_us_, us);
|
||||
if (st->grammar->masks_walked() != w0) { ++mask_slow_; mask_walk_us_ += us; }
|
||||
else ++mask_fast_;
|
||||
if (++mask_us_n_ == 256) {
|
||||
/* Mean per MASK and mean per COMPUTED mask are different questions and
|
||||
* the second is the one that says what a new state costs: a window's
|
||||
* masks are mostly memo hits, so the first tracks how many positions
|
||||
* asked. */
|
||||
/* Mean per computed mask is what a new state costs; the overall mean
|
||||
* is dominated by memo hits. */
|
||||
RAD_DEBUG("sampler: grammar mask %.2f ms mean, %.2f ms worst over 256; "
|
||||
"%lld memo hits, %lld computed at %.2f ms mean (%lld vocab, "
|
||||
"%lld words)",
|
||||
@@ -833,19 +774,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
}
|
||||
}
|
||||
if (s < 0 && k > 0) {
|
||||
/* A SPECULATIVE POSITION IS NOT A DEAD REQUEST. This is the state reached by
|
||||
* accepting drafts the sequence has not committed to, so "nothing is
|
||||
* admissible here" says the draft is wrong, not that the request is stuck.
|
||||
* Verification will reject at or before this position; stop masking and leave
|
||||
* the rest of the window unconstrained, since it is about to be discarded. */
|
||||
/* At a draft position this only means a draft is wrong; verification
|
||||
* rejects at or before here, so stop masking the rest of the window. */
|
||||
dead = true;
|
||||
} else if (s < 0) {
|
||||
/* A DEAD GRAMMAR FAILS ITS REQUEST, NOT THE STEP. Returning a status here
|
||||
* would reach the step loop as an engine fault and stop it stepping, so every
|
||||
* other client on the server would stop receiving tokens because one of them
|
||||
* sent a schema the model painted itself out of. The row is left unmasked for
|
||||
* this step -- it is about to be cancelled -- and the id goes to the engine
|
||||
* to close. */
|
||||
/* A dead grammar fails its request, not the step: an error status would stop
|
||||
* the step loop for every client. The row stays unmasked and the engine
|
||||
* cancels the request. */
|
||||
RAD_WARN("sampler: request %llu has no admissible token under its grammar; "
|
||||
"failing that request", (unsigned long long)r->id);
|
||||
failed_.push_back(r->id);
|
||||
@@ -853,10 +788,8 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.mask_row = (int32_t)row;
|
||||
p.flags |= RAD_SP_MASK;
|
||||
if ((int)log_level() >= (int)Log::Trace) {
|
||||
/* How many tokens the grammar allows THIS RANK to pick. Zero is legal
|
||||
* under sharding -- the admissible set can live entirely on another rank
|
||||
* -- and is the first thing to check when a grammar-constrained answer
|
||||
* comes out unconstrained. */
|
||||
/* Tokens the grammar allows on this rank. Zero is legal under sharding,
|
||||
* when the admissible set lives on another rank. */
|
||||
int64_t bits = 0;
|
||||
for (int64_t w = 0; w < mask_words_; ++w)
|
||||
bits += __builtin_popcount(dst[w]);
|
||||
@@ -872,8 +805,8 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
force_close(p, row, sp.reasoning.close);
|
||||
|
||||
if (want_lp) {
|
||||
/* The temperature the candidate value carries: the early stage's and the late
|
||||
* one's, each only where its kernel runs (temp > 0 and not 1). */
|
||||
/* Temperature the candidate value carries: early and late, each counted only
|
||||
* where its kernel applies it (temp > 0 and not 1). */
|
||||
auto t_of = [](float t) { return t > 0.0f && t != 1.0f ? t : 1.0f; };
|
||||
LpRow L;
|
||||
L.row = row;
|
||||
@@ -889,15 +822,11 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Back to where the sequence actually is. The tokens it really accepted are applied by
|
||||
* Sampler::accept_token after the step verifies, so anything the walk did must be gone
|
||||
* before then or the grammar would be ahead of the sequence by the whole window. */
|
||||
/* Rewind the walk; accepted tokens are applied by accept_token after verification. */
|
||||
if (walk) RAD_TRY(gr->rollback());
|
||||
}
|
||||
|
||||
/* THE WHOLE OF IT, not just the mask, because that is what the rank threads wait for. Without
|
||||
* this the mask's own number could fall to nothing and the step stay slow with no way to see
|
||||
* which side of the barrier the time was on. */
|
||||
/* Whole build time, which is what the rank threads wait for at the barrier. */
|
||||
if ((int)log_level() >= (int)Log::Debug) {
|
||||
build_us_ += std::chrono::duration<double, std::micro>(
|
||||
std::chrono::steady_clock::now() - t_build).count();
|
||||
@@ -915,8 +844,8 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
|
||||
const int64_t at = (int64_t)close - cfg_.vocab_off;
|
||||
const bool local = at >= 0 && at < cfg_.n_vocab_local;
|
||||
if (p.flags & RAD_SP_MASK) {
|
||||
/* The grammar's mask for this row. Under a split vocabulary the whole one is still in
|
||||
* mask_full_, and the close may be another rank's column. */
|
||||
/* Check the grammar's mask. Under a split vocabulary use mask_full_, since the close may
|
||||
* be another rank's column. */
|
||||
const bool admitted =
|
||||
vocab_parallel()
|
||||
? close < (int64_t)mask_full_.size() * 32 &&
|
||||
@@ -924,9 +853,8 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
|
||||
: local && (dst[at >> 5] >> (uint32_t)(at & 31)) & 1u;
|
||||
if (!admitted) return;
|
||||
}
|
||||
/* ONE ADMISSIBLE TOKEN, on whichever rank holds its column. The others mask the whole row
|
||||
* out, which the candidate merge reads as no candidate from them (the grammar's own masks do
|
||||
* the same when the admissible set lives on one shard). */
|
||||
/* One admissible token, on the rank that holds its column. Other ranks mask the whole row,
|
||||
* which the candidate merge reads as no candidates from them. */
|
||||
std::memset(dst, 0, (size_t)mask_words_ * 4);
|
||||
if (local) dst[at >> 5] |= 1u << (uint32_t)(at & 31);
|
||||
p.mask_row = (int32_t)row;
|
||||
@@ -944,18 +872,16 @@ int Sampler::build_greedy(int64_t n) {
|
||||
}
|
||||
n_seq_ = n;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
cur_stage_ = greedy_stage_;
|
||||
if (greedy_ready_) return RAD_OK;
|
||||
for (int64_t i = 0; i < cap; ++i) {
|
||||
DeviceSampleParams& p = greedy_stage_[i];
|
||||
std::memset(&p, 0, sizeof p);
|
||||
p.temp = 0.0f;
|
||||
p.top_k = 1;
|
||||
p.hist_off = 0;
|
||||
p.hist_len = 0;
|
||||
p.mask_row = -1;
|
||||
/* Over a split vocabulary a greedy row is a top-1 CHAIN row, for the reason build_step
|
||||
* gives, and so it does not carry the flag every candidate stage skips. */
|
||||
/* Over a split vocabulary a greedy row is an unflagged top-1 chain row (see
|
||||
* build_step). */
|
||||
p.flags = vocab_parallel() ? 0 : RAD_SP_GREEDY;
|
||||
}
|
||||
greedy_ready_ = true;
|
||||
@@ -987,24 +913,21 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A GREEDY ROW OVER A SPLIT VOCABULARY is staged as a top-1 chain row, never with the flag:
|
||||
* the argmax would return this rank's column for a token id. build_step and build_greedy both
|
||||
* hold that, so a flagged row here is a staging bug, and it is refused rather than served. */
|
||||
/* A greedy-flagged row under a split vocabulary is a staging bug (the argmax would return a
|
||||
* shard column), so it is refused. */
|
||||
if (any_greedy && vocab_parallel()) {
|
||||
RAD_ERR("sampler: a greedy-flagged row reached a split vocabulary, where the argmax "
|
||||
"returns a column of this rank's shard rather than a token id");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* Async copies on the compute stream and no host synchronisation, and only of what some row
|
||||
* will read: the history and the breaker marks for the penalties and DRY, the mask for a
|
||||
* grammar. The mask upload is 19 KiB a constrained sequence at a 151K vocab, which is the
|
||||
* number that makes a host-side grammar affordable at all (spec §13). */
|
||||
/* Async copies on the compute stream, only of what some row reads. The mask is 19 KiB per
|
||||
* constrained sequence at a 151K vocab, which keeps a host-side grammar affordable
|
||||
* (spec §13). */
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
/* The late temperature's rows only when this build staged one: a greedy build's rows come
|
||||
* from greedy_stage_, and late_stage_ then holds an older build's. */
|
||||
const bool late = any_late_ && cur_stage_ == params_stage_;
|
||||
/* Late rows only for a build_step build; build_greedy clears any_late_. */
|
||||
const bool late = any_late_;
|
||||
if (late)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
@@ -1033,9 +956,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
return rad_issue(c, op, v.data(), (int)v.size(), n_seq_);
|
||||
};
|
||||
|
||||
/* THE LOGPROBS SUMMARY, ON THE LOGITS AS THE MODEL WROTE THEM: every stage below writes them in
|
||||
* place. Only for a trunk build that staged a logprobs row -- a draft pass's greedy build
|
||||
* stages none, and must not overwrite the summary rank 0 is about to copy back. */
|
||||
/* The logprobs summary reads the raw logits, before any stage writes them in place. Only for
|
||||
* a build_step build with logprobs rows: a draft pass must not overwrite the summary rank 0
|
||||
* is about to copy back. */
|
||||
const bool lp = !lp_rows_.empty() && cur_stage_ == params_stage_ && op_logprobs_;
|
||||
const RadOperand o_lp = opd_rows(buf_lp_, n_seq_);
|
||||
if (lp) {
|
||||
@@ -1044,24 +967,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
RAD_TRY(issue(op_lp_gather_, { o_lp, opd_rows(buf_lp_g_, n_seq_) }));
|
||||
}
|
||||
|
||||
/* Penalties act on raw logits, before anything derives a probability from them. DRY takes the
|
||||
* breaker marks only when some row in the batch has breakers; its fourth operand is optional
|
||||
* and absent means no token is exempt. */
|
||||
/* Penalties act on raw logits. DRY gets the breaker marks only when some row has breakers;
|
||||
* absent means no token is exempt. */
|
||||
if (any_penalty) RAD_TRY(issue(op_penalties_, { o_logits, o_params, o_hist }));
|
||||
if (any_dry)
|
||||
RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() }));
|
||||
|
||||
/* The greedy rows take the argmax after penalties and the mask and never see temperature.
|
||||
* When the batch is mixed, BOTH the argmax and the chain are issued over the whole batch: the
|
||||
* argmax writes every row's token, and then every candidate stage skips the greedy rows
|
||||
* (RAD_SP_GREEDY) so the pick overwrites only the rows the chain owns. The cost is one extra
|
||||
* pass over the logits for the rows the other op owns -- ~77 MiB read at batch 256 -- against
|
||||
* one kernel launch per distinct parameter set, which at batch 256 is up to 256 launches. The
|
||||
* pass wins.
|
||||
*
|
||||
* Under vocab parallelism there is no greedy shortcut at all: build_step staged those rows at
|
||||
* top_k = 1, without the flag, so they take the chain, where the merge turns a local candidate
|
||||
* index into a global token id. */
|
||||
/* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax
|
||||
* and the chain run over the whole batch: the argmax writes every row, then the candidate
|
||||
* stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits
|
||||
* pass (~148 MiB at batch 256) beats up to 256 launches, one per parameter set. Under vocab
|
||||
* parallelism no row is flagged greedy (see build_step). */
|
||||
if (any_greedy) {
|
||||
if (any_mask) RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask }));
|
||||
RAD_TRY(issue(op_argmax_, { o_logits, o_params, o_tok }));
|
||||
@@ -1073,26 +989,20 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (any_mask && !any_greedy)
|
||||
RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask }));
|
||||
|
||||
/* top-k reduces the vocabulary to a candidate set, and everything after it works on that set.
|
||||
* Under tensor parallel this is the LOCAL top-k over this rank's shard; the candidate sets
|
||||
* are combined below and full logits are never gathered (spec §9).
|
||||
*
|
||||
* IT IS ISSUED WHENEVER THE CHAIN RUNS, not only when some row sets top_k. A row at
|
||||
* top_k = 0 asks for the whole candidate width, and the candidate planes are transient: a
|
||||
* step that skipped this would hand the pick whatever the planes last held -- the previous
|
||||
* step's candidates, or another op's bytes. */
|
||||
/* Top-k reduces the vocabulary to the candidate set the rest works on; under tensor parallel
|
||||
* it is per shard and the sets are merged below (spec §9). Always issued when the chain runs:
|
||||
* top_k = 0 means the full candidate width, and the transient candidate planes hold stale
|
||||
* bytes otherwise. */
|
||||
if (vocab_parallel()) {
|
||||
/* The fifth operand is the pair plane: this rank's candidates with GLOBAL ids, which is
|
||||
* what crosses the wire. cand_idx and cand_val still come back LOCAL and the merge
|
||||
* overwrites both, so nothing downstream ever sees a local id. */
|
||||
/* The fifth operand is the pair plane (global ids), which is what is gathered.
|
||||
* cand_idx/cand_val come back local and the merge overwrites both. */
|
||||
const RadOperand o_p = opd_rows(buf_pairs_, n_seq_);
|
||||
const RadOperand o_g = opd_rows(buf_gather_, n_seq_);
|
||||
RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, o_p }));
|
||||
RAD_TRY(issue(op_allgather_, { o_p, o_g }));
|
||||
RAD_TRY(issue(op_merge_, { o_g, o_params, o_ci, o_cv }));
|
||||
} else {
|
||||
/* No pair plane on a whole vocabulary, and it is passed as absent rather than left off:
|
||||
* the schema has five operands and an issue of four is refused. */
|
||||
/* No pair plane; passed as absent because the schema has five operands. */
|
||||
RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, opd_none() }));
|
||||
}
|
||||
|
||||
@@ -1105,10 +1015,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
|
||||
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
|
||||
|
||||
/* AND THE LOGPROBS ROWS ON THEIR WAY TO THE HOST, behind the pick on the same stream: the
|
||||
* summary, and the candidate planes the pick drew from (logprobs_for reads a token's value
|
||||
* there when the summary does not hold it). Only the rows between the first and the last
|
||||
* that asked, and only on rank 0, which is the rank collect_step asks. */
|
||||
/* Copy the logprobs rows to the host behind the pick, on rank 0 only (collect_step asks
|
||||
* it): the summary and the candidate planes, which logprobs_for reads when the summary lacks
|
||||
* the token. Only rows from the first to the last that asked. */
|
||||
if (lp && cfg_.rank == 0) {
|
||||
lp_lo_ = lp_rows_.front().row;
|
||||
lp_hi_ = lp_rows_.back().row + 1;
|
||||
@@ -1130,9 +1039,8 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
|
||||
const DeviceSampleParams& p = L.p;
|
||||
double y = (double)v * (double)L.temp;
|
||||
/* DRY subtracted a penalty that depends on the token and the window alone, so the host
|
||||
* reference computes it for this one token: a single candidate at 0 comes back at minus the
|
||||
* penalty. */
|
||||
/* DRY's penalty depends only on the token and the window, so the host reference recomputes
|
||||
* it on a single candidate at 0, which comes back as minus the penalty. */
|
||||
if (p.flags & RAD_SP_DRY) {
|
||||
static const DryBreakers kNone;
|
||||
CandidateSet s;
|
||||
@@ -1146,9 +1054,9 @@ float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
|
||||
L.dry ? *L.dry : kNone);
|
||||
y -= (double)s.c[0].logit;
|
||||
}
|
||||
/* The penalties, inverted: presence and frequency added back, then the repetition penalty
|
||||
* undone on the side of zero the logit is on -- it never changes sign. The window is the
|
||||
* stage's: the tail of the staged history, penalty_last_n long when that is positive. */
|
||||
/* Penalties inverted: presence and frequency added back, then repetition undone on the
|
||||
* logit's side of zero (it never changes sign). Window: the tail of the staged history,
|
||||
* penalty_last_n long when positive. */
|
||||
if (p.flags & RAD_SP_PENALTY) {
|
||||
int64_t n = (int64_t)L.hist.size(), o = 0;
|
||||
if (p.penalty_last_n > 0 && n > p.penalty_last_n) { o = n - p.penalty_last_n; n = p.penalty_last_n; }
|
||||
@@ -1177,8 +1085,8 @@ int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* id
|
||||
if (live(r)) sum += (double)st[r * w + 1] * std::exp((double)st[r * w] - mx);
|
||||
*log_z = sum > 0.0 ? mx + std::log(sum) : NAN;
|
||||
|
||||
/* On the stack for every split the engine runs (eight ranks of 21 pairs is 168); a call for
|
||||
* more takes the heap rather than a bound. Once per emitted token, on collect_step's path. */
|
||||
/* Stack buffer covers up to eight ranks of 21 pairs (168); more falls back to the heap.
|
||||
* Runs once per emitted token on collect_step's path. */
|
||||
struct Pair { float v; int32_t id; };
|
||||
Pair buf[256];
|
||||
std::vector<Pair> heap;
|
||||
@@ -1214,16 +1122,14 @@ int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const
|
||||
if (x.row == row) { L = &x; break; }
|
||||
if (!L) return RAD_E_STATE;
|
||||
|
||||
/* Every rank's summary of its shard, merged: the maxima and normalisers by the usual
|
||||
* rescale, the largest by value with the lower id first. */
|
||||
/* Merge every rank's shard summary. */
|
||||
const int W = vocab_parallel() ? cfg_.world_size : 1;
|
||||
double log_z = 0.0;
|
||||
int32_t ids[kLpK * 8];
|
||||
float vals[kLpK * 8];
|
||||
const int n = merge_logprob_rows(lp_host_ + row * W * lp_width(), W, kLpK, &log_z, ids, vals,
|
||||
(int)(sizeof ids / sizeof ids[0]));
|
||||
/* A ROW WITH NO FINITE LOGIT HAS NO DISTRIBUTION to report against -- NaN logits out of the
|
||||
* model, or every one at -inf -- and any number sent for it would be invented. */
|
||||
/* No finite logit (NaN from the model, or all -inf) means no distribution to report. */
|
||||
if (!std::isfinite(log_z)) {
|
||||
RAD_WARN("sampler: row %lld has no finite logit; its logprobs cannot be computed",
|
||||
(long long)row);
|
||||
@@ -1238,8 +1144,8 @@ int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const
|
||||
out->top_lp[j] = (float)((double)vals[j] - log_z);
|
||||
}
|
||||
|
||||
/* The token's own raw logit: exact when it is among the largest, and otherwise recovered
|
||||
* from the value the pick drew it at. */
|
||||
/* The token's raw logit: exact if among the largest, else recovered from the value the pick
|
||||
* drew it at. */
|
||||
double own = NAN;
|
||||
for (int j = 0; j < n && std::isnan(own); ++j)
|
||||
if (ids[j] == token) own = (double)vals[j];
|
||||
|
||||
+133
-174
@@ -1,14 +1,12 @@
|
||||
/* sampler.h -- the sampler driver.
|
||||
*
|
||||
* SAMPLING RUNS ON DEVICE (spec §13). At a 151K vocab and batch 256 the logits are ~77 MiB a
|
||||
* step; moving them across the link to run a host chain costs both the bandwidth and a
|
||||
* synchronisation, on the step path, at exactly the concurrency the engine exists to serve. So
|
||||
* every sampler is a kernel, not a lift -- and this file does not implement one. It ISSUES the
|
||||
* declared sampler ops in order, exactly as an architecture plugin issues a GEMM: declared
|
||||
* through the ordinary builder, resolved through the ordinary hierarchy, serviced by
|
||||
* `libref` on the host domain or by a device plugin on the fast one.
|
||||
* Sampling runs on device (spec §13): at a 151K vocab and batch 256 the f32 logits are ~148 MiB a
|
||||
* step, too much to move to the host and synchronise on the step path. This file implements no
|
||||
* sampler. It issues the declared sampler ops in order, as an architecture plugin issues a GEMM:
|
||||
* declared through the ordinary builder and resolved through the ordinary hierarchy to `libref`
|
||||
* on the host domain or to a device plugin.
|
||||
*
|
||||
* THE ORDER, and it is not a detail -- reordering changes which tokens survive:
|
||||
* Chain order (reordering changes which tokens survive):
|
||||
*
|
||||
* penalties (repetition / frequency / presence, then DRY)
|
||||
* temperature
|
||||
@@ -18,38 +16,33 @@
|
||||
* XTC
|
||||
* the pick
|
||||
*
|
||||
* TEMPERATURE MAY RUN AFTER THE CUTS INSTEAD, per sequence: llama.cpp's order, which a request
|
||||
* names with `samplers` (SamplingParams::temp_last). Such a row's temperature is staged at 1 for
|
||||
* the stage above, which skips it, and at its own value for a second `sample_temp` over the
|
||||
* candidate plane after XTC -- the same kernel at the candidate width, so no plugin needs a
|
||||
* second implementation of it. Every other row is 1 there.
|
||||
* Temperature last: a request may ask for llama.cpp's order with `samplers`
|
||||
* (SamplingParams::temp_last). Such a row is staged with temperature 1 for the stage above, which
|
||||
* then skips it, and with its own value for a second `sample_temp` over the candidate plane after
|
||||
* XTC (the same kernel at the candidate width). Every other row is 1 there.
|
||||
*
|
||||
* LOGPROBS ARE READ OFF THE RAW LOGITS, before the first stage: `sample_logprobs` summarises each
|
||||
* row that asks (RAD_SP_LOGPROBS) as its maximum, its normaliser and its kLpK largest (one more
|
||||
* than RAD_MAX_LOGPROBS, for the row's width below), and rank 0 copies that back behind the pick.
|
||||
* The emitted token's own logprob is its raw logit less the log normaliser. When it is not among the largest its raw logit is no longer on the card
|
||||
* -- every stage wrote the logits in place -- so it is recovered from the value the pick drew it
|
||||
* at, the candidate plane's, by undoing temperature, DRY and the penalties on the host
|
||||
* (logprobs_for). Such a row is never a greedy-flagged one: a greedy row asking for logprobs is
|
||||
* staged as a top-1 chain row, so that its token is drawn from a candidate plane too.
|
||||
* Logprobs: `sample_logprobs` summarises the raw logits, before the first stage, for each row
|
||||
* flagged RAD_SP_LOGPROBS: its maximum, its normaliser and its kLpK largest (one more than
|
||||
* RAD_MAX_LOGPROBS, see kLpK). Rank 0 copies the summary back behind the pick. The emitted
|
||||
* token's logprob is its raw logit minus the log normaliser. When the token is not among the
|
||||
* largest, its raw logit is gone (every stage writes the logits in place), so logprobs_for
|
||||
* recovers it from the candidate-plane value the pick drew it at, undoing temperature, DRY and
|
||||
* the penalties on the host. Such a row is therefore never greedy-flagged: a greedy row asking
|
||||
* for logprobs is staged as a top-1 chain row.
|
||||
*
|
||||
* A GREEDY SEQUENCE SKIPS ALL OF IT and takes `sample_argmax` -- after penalties and the mask,
|
||||
* because temperature 0 collapses every other logit to -inf and a mask applied afterwards would
|
||||
* leave nothing at all. host_ref.cpp makes the same choice for the same reason and the two must
|
||||
* agree, or a temperature-0 request stops matching a greedy run.
|
||||
* Greedy: a greedy sequence skips the chain and takes `sample_argmax`, after penalties and the
|
||||
* mask. Temperature 0 collapses every other logit to -inf, so a mask applied afterwards would
|
||||
* leave nothing. host_ref.cpp makes the same choice and the two must agree, or a temperature-0
|
||||
* request stops matching a greedy run.
|
||||
*
|
||||
* PARAMETERS ARE DATA, NOT BRANCHES. Sequences in one batch have different sampling parameters,
|
||||
* so the parameters are a device-side per-sequence array built once per step from a pinned
|
||||
* staging buffer -- the same discipline the step batch uses (spec §8). A kernel that branched on
|
||||
* a host-side parameter would need one launch per distinct parameter set, which at batch 256 is
|
||||
* up to 256 launches for what is one kernel's worth of work.
|
||||
* Parameters are data, not branches. They are a per-sequence device array built once per step
|
||||
* from pinned staging, as the step batch is (spec §8). Branching on host-side parameters would
|
||||
* need one launch per distinct parameter set, up to 256 at batch 256.
|
||||
*
|
||||
* THE SCHEMA THIS DRIVER ISSUES AGAINST (docs/OPS.md, "Sampling"). No per-sequence value is an
|
||||
* op PARAMETER, because parameters are geometry -- the thing the selector matches constraints
|
||||
* against and freezes at declare. A per-sequence value cannot live there: two requests in one
|
||||
* batch with different top_p would be two different geometries and therefore two different
|
||||
* Schema (docs/OPS.md, "Sampling"). Op parameters are geometry, matched and frozen at declare,
|
||||
* so no per-sequence value can be one: two requests with different top_p would be two
|
||||
* resolutions of the same op. The seed and output position `sample_pick` draws from are in the
|
||||
* parameter row too. So every sampler op takes the row array as an operand:
|
||||
* row too. Every sampler op therefore takes the row array as an operand:
|
||||
*
|
||||
* sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout)
|
||||
* sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers?
|
||||
@@ -67,15 +60,14 @@
|
||||
* sample_merge_topk M(range) n_cand gathered, params -> cand_idx, cand_val
|
||||
* sample_logprobs M(range) n_vocab k vocab_off? logits, params -> stats
|
||||
*
|
||||
* `M` is the number of SAMPLED POSITIONS, not tokens: one per sequence at decode, n_spec+1 per
|
||||
* sequence at a verify. `params` is [M] rows of DeviceSampleParams below; `history` is
|
||||
* [M, max_hist] int32 of GLOBAL token ids, row m addressed by row m's hist_off/hist_len;
|
||||
* `breakers` is [M, max_hist] uint8 beside it, nonzero where that position's token is a whole DRY
|
||||
* sequence breaker; `bitmask` is [M, mask_words] uint32 addressed by the row's mask_row.
|
||||
* `vocab_off` is this rank's first vocabulary row and is declared only when the vocabulary is
|
||||
* split: the three ops that turn a token id into a column of this rank's logits subtract it.
|
||||
* Every one of these has a libref implementation: a sampler with no ref implementation has no
|
||||
* fallback and no oracle (spec §17).
|
||||
* `M` counts sampled positions, not tokens: one per sequence at decode, n_spec+1 per sequence at
|
||||
* a verify. `params` is [M] DeviceSampleParams rows. `history` is [M, max_hist] int32 global
|
||||
* token ids, row m addressed by its hist_off/hist_len. `breakers` is [M, max_hist] uint8 beside
|
||||
* it, nonzero where that token is a whole DRY sequence breaker. `bitmask` is [M, mask_words]
|
||||
* uint32, addressed by the row's mask_row. `vocab_off` is this rank's first vocabulary row,
|
||||
* declared only when the vocabulary is split; the three ops that map between token ids and this
|
||||
* rank's logit columns use it. Every op has a libref implementation, which is both its fallback
|
||||
* and its oracle (spec §17).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_sample.h"
|
||||
@@ -94,32 +86,29 @@ namespace rad {
|
||||
|
||||
/* ================================================================== the per-sequence row */
|
||||
|
||||
/* THE ROW AND ITS FLAGS LIVE IN abi/rad_sample.h, because they are the wire format of
|
||||
* an OPERAND and therefore part of the ABI: libref reads these rows and a kernel plugin
|
||||
* cannot include a core header. The alias keeps this file's spelling. */
|
||||
/* The row and its flags live in abi/rad_sample.h: they are an operand's wire format, read by
|
||||
* libref and by kernel plugins, which cannot include a core header. */
|
||||
using DeviceSampleParams = RadSampleParams;
|
||||
|
||||
/* ================================================================== configuration */
|
||||
|
||||
struct SamplerConfig {
|
||||
int64_t n_vocab = 0; /* the WHOLE vocabulary */
|
||||
int64_t n_vocab_local = 0; /* THIS RANK's shard of it; == n_vocab when world_size == 1 */
|
||||
int64_t n_vocab = 0; /* the whole vocabulary */
|
||||
int64_t n_vocab_local = 0; /* this rank's shard of it; == n_vocab when world_size == 1 */
|
||||
int64_t max_seqs = 0; /* the largest number of sequences one step may carry */
|
||||
int64_t max_hist = 2048; /* the penalty window bound; a longer request is truncated */
|
||||
int max_spec = 0;
|
||||
int rank = 0;
|
||||
int world_size = 1;
|
||||
/* This rank's first vocabulary row, which sample_topk adds to every candidate id it packs
|
||||
* into the pair plane so the merge sees GLOBAL ids, and which sample_penalties and sample_dry
|
||||
* subtract from the GLOBAL ids in the history to find this rank's column. Zero unless lm_head
|
||||
* is row-sharded. */
|
||||
/* This rank's first vocabulary row. sample_topk adds it to the candidate ids it packs into
|
||||
* the pair plane, so the merge sees global ids; sample_penalties and sample_dry subtract it
|
||||
* from the history's global ids. Zero unless lm_head is row-sharded. */
|
||||
int64_t vocab_off = 0;
|
||||
|
||||
/* The candidate-set width the cuts work over. Every sampler after top-k operates on
|
||||
* candidates rather than the vocabulary, so this bounds the buffers they read and write. It
|
||||
* is a bound, not a policy: a request asking for a larger top-k than this is refused at
|
||||
* admission, by name, rather than silently narrowed. */
|
||||
int64_t max_candidates = 1024;
|
||||
/* Candidate-set width for every stage after top-k; sizes their buffers. top_k 0 samples
|
||||
* from this many of the most likely tokens, not the whole vocabulary. A request asking for a
|
||||
* larger top-k is refused at admission, not silently narrowed. */
|
||||
int64_t max_candidates = kSampleCandidates;
|
||||
};
|
||||
|
||||
/* ================================================================== the driver */
|
||||
@@ -131,139 +120,116 @@ public:
|
||||
|
||||
/* ---------------------------------------------------------- declare phase */
|
||||
|
||||
/* Declare every sampler op and every buffer the chain needs, and allocate the pinned staging.
|
||||
* Runs once, alongside the architecture plugin's declare, so the sampler's kernels resolve
|
||||
* through the same hierarchy at the same time as everything else and a missing one is in the
|
||||
* same missing-list (spec §3.1).
|
||||
*
|
||||
* A sampler op that does not resolve is NOT a declare failure: a deployment that never sends
|
||||
* `typical_p` does not need a typical kernel. It becomes a failure when a request asks for
|
||||
* it, which `check_request` reports by name. */
|
||||
/* Declare every sampler op and buffer the chain needs and allocate the pinned staging. Runs
|
||||
* alongside the architecture plugin's declare, so a missing kernel lands in the same
|
||||
* missing-list (spec §3.1). An unresolved op is not a declare failure; check_request refuses
|
||||
* the requests that need it, by name. */
|
||||
int declare(RadBuilder* b, const SamplerConfig& cfg);
|
||||
|
||||
/* The vocabulary view the grammar backends walk. Set after the tokeniser loads, before the
|
||||
* first request. */
|
||||
/* The vocabulary the grammar backends walk. Set after the tokeniser loads, before the first
|
||||
* request. */
|
||||
void attach_vocab(const VocabView* v) { vocab_ = v; }
|
||||
|
||||
/* ---------------------------------------------------------- admission */
|
||||
|
||||
/* Can this request's sampling parameters be served? Returns RAD_OK, or RAD_E_NOKERNEL naming
|
||||
* the sampler that did not resolve, or RAD_E_INVAL naming the parameter that is out of range.
|
||||
* Called on admission, so a request fails at the door rather than three steps in. */
|
||||
/* Admission check. RAD_OK, RAD_E_NOKERNEL naming the sampler that did not resolve, or
|
||||
* RAD_E_INVAL naming the out-of-range parameter. */
|
||||
int check_request(const SamplingParams& sp, std::string* why) const;
|
||||
|
||||
/* Build this request's grammar state, if it has a grammar. Runs on the scheduler thread, so
|
||||
* it must not compile: a request admitted through the server carries its grammar compiled
|
||||
* (SamplingParams::grammar_program), and this finds that program and positions a grammar in
|
||||
* it. A request that arrives without one is compiled here, which costs its mask plan. */
|
||||
/* Build the request's grammar state, if it has a grammar. Runs on the scheduler thread, so it
|
||||
* should not compile: a server request carries its grammar compiled
|
||||
* (SamplingParams::grammar_program) and this only positions a grammar in it. A request
|
||||
* without one is compiled here, at the cost of its mask plan. */
|
||||
int begin_request(uint64_t req_id, const SamplingParams& sp, std::string* err);
|
||||
void end_request(uint64_t req_id);
|
||||
/* Does this request already have state here? The step loop reaches a request on every step it
|
||||
* is scheduled in, and begin_request is not idempotent -- calling it twice would rebuild the
|
||||
* automaton and throw away everything it had accepted, which silently unconstrains a
|
||||
* generation from its second token onward. */
|
||||
/* begin_request is not idempotent: a second call rebuilds the automaton and discards what it
|
||||
* accepted, unconstraining the rest of the generation. The step loop checks this first. */
|
||||
bool has_request(uint64_t req_id) const;
|
||||
|
||||
/* Requests build_step could not serve: a grammar that reached a state admitting no token.
|
||||
* Returned and cleared; the caller cancels them. Empty on almost every step. */
|
||||
/* Requests whose grammar reached a state admitting no token. Returned and cleared; the
|
||||
* caller cancels them. */
|
||||
std::vector<uint64_t> take_failed();
|
||||
|
||||
/* Advance a request's grammar over the token it just emitted. */
|
||||
int accept_token(uint64_t req_id, int32_t token);
|
||||
|
||||
/* May the scheduler speculate on this request? Yes, unless it carries a constraining grammar
|
||||
* whose backend cannot snapshot its state. The mask for draft position i depends on which of
|
||||
* positions 0..i-1 were accepted, so masking a window means walking the grammar forward over
|
||||
* the proposals and rewinding afterwards; a backend without push_state/rollback cannot, and
|
||||
* such a request decodes one token at a time rather than silently emitting drafts the grammar
|
||||
* forbids. */
|
||||
/* False only for a constraining grammar whose backend cannot snapshot its state. Masking a
|
||||
* draft window walks the grammar over the drafts and rewinds, which needs
|
||||
* push_state/rollback; without it the request decodes one token at a time. */
|
||||
bool allows_speculation(uint64_t req_id) const;
|
||||
/* Is allows_speculation's answer fixed for this request? It changes only when a grammar whose
|
||||
* backend cannot rewind starts to constrain, which is a commit's doing; a request with no
|
||||
* grammar, or one whose backend rewinds, answers the same at every step. */
|
||||
/* Whether allows_speculation's answer can no longer change. It changes only when a grammar
|
||||
* whose backend cannot rewind starts to constrain (on a commit). */
|
||||
bool speculation_fixed(uint64_t req_id) const;
|
||||
|
||||
/* ---------------------------------------------------------- step path */
|
||||
|
||||
/* Build the per-sequence parameter array, the packed penalty history and the grammar
|
||||
* bitmasks for this step, into pinned staging. Scheduler-thread work: it touches request
|
||||
* state and host grammar automata, and it must be done before the rank threads are released
|
||||
* at the barrier.
|
||||
*
|
||||
* Allocates nothing -- every buffer was sized at declare against max_seqs (spec §3.1). */
|
||||
/* Stage this step's parameter rows, penalty history and grammar bitmasks into pinned memory.
|
||||
* Scheduler thread, before the rank threads are released at the barrier. Allocates nothing;
|
||||
* every buffer was sized at declare against max_seqs (spec §3.1). */
|
||||
int build_step(const std::vector<Request*>& reqs);
|
||||
|
||||
/* THE SAME STAGING, FILLED FOR A GREEDY DRAFTER. `n` rows of argmax: no penalties, no
|
||||
* grammar mask, no history, and the RNG untouched -- so the chain resolves to op_argmax and
|
||||
* nothing else runs.
|
||||
*
|
||||
* It exists because a DRAFT round is not a request's own sampling. Its output is a
|
||||
* proposal the target then verifies, and the verifier is greedy (core/sample/accept.h): a
|
||||
* drafter that sampled at the request's temperature would spend the request's RNG stream
|
||||
* on tokens that may never be emitted, and would lower acceptance for nothing. Every MTP
|
||||
* head that ships inside a target checkpoint is greedy for the same reason. */
|
||||
/* Stage `n` greedy rows for a drafter: no penalties, mask or history, and no RNG use, so
|
||||
* only the argmax runs. Draft output is a proposal checked by a greedy verifier
|
||||
* (core/sample/accept.h); sampling it at the request's temperature would spend the request's
|
||||
* RNG stream on tokens that may never be emitted and lower acceptance. */
|
||||
int build_greedy(int64_t n);
|
||||
|
||||
/* Upload the staging and issue the chain. Rank-thread work, on the compute stream, with no
|
||||
* host synchronisation in it.
|
||||
*
|
||||
* `logits` holds [n_seq, n_vocab_local] and `out_tokens` receives [n_seq] token ids. Under
|
||||
* tensor parallel the candidate merge (`sample_merge_topk`, or `row_topk_merge` fused with the
|
||||
* top-k) happens between the top-k and the cuts; full logits are never gathered. */
|
||||
/* Upload the staging and issue the chain. Rank thread, compute stream, no host sync.
|
||||
* `logits` is [n_seq, n_vocab_local]; `out_tokens` receives [n_seq] token ids. Under tensor
|
||||
* parallel the candidate merge (`sample_merge_topk`, or `row_topk_merge` fused with the
|
||||
* top-k) runs between the top-k and the cuts; full logits are never gathered. */
|
||||
int run(RadCtx* c, rad_buf logits, rad_buf out_tokens);
|
||||
|
||||
/* THE EMITTED TOKEN'S LOGPROBS, after the step the last build_step staged has completed on the
|
||||
* card: row `row` must have been staged for a request with SamplingParams::n_probs >= 0, and
|
||||
* `token` is what the step sampled there. Rank 0's sampler only -- it is the one that copies
|
||||
* the summary back. RAD_E_STATE for a row that was not staged for logprobs; RAD_E_INVAL, with
|
||||
* `out->token` -1, for one whose numbers are not finite -- a row with no finite logit, or a
|
||||
* token drawn where none was -- which is a number no client should be sent. */
|
||||
/* The emitted token's logprobs, once the step the last build_step staged has completed.
|
||||
* `row` must have been staged with SamplingParams::n_probs >= 0 and `token` is what was
|
||||
* sampled there. Rank 0 only, since it holds the copy. RAD_E_STATE for a row not staged for
|
||||
* logprobs; RAD_E_INVAL with `out->token` = -1 when the numbers are not finite (no finite
|
||||
* logit in the row, or none for the token). */
|
||||
int logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const;
|
||||
/* Did `sample_logprobs` resolve? What the server advertises as logprobs support. */
|
||||
/* Whether `sample_logprobs` resolved; what the server advertises as logprobs support. */
|
||||
bool has_logprobs() const { return op_logprobs_ != RAD_NULL_HANDLE; }
|
||||
const SamplerConfig& config() const { return cfg_; }
|
||||
|
||||
/* The parameter rows the last build_step or build_greedy staged, and how many. What `run`
|
||||
* uploads, readable so the staging can be checked without a device behind it. */
|
||||
/* The rows the last build_step or build_greedy staged, as `run` uploads them; lets the
|
||||
* staging be checked without a device. */
|
||||
const DeviceSampleParams* staged_params(int64_t* n) const {
|
||||
if (n) *n = n_seq_;
|
||||
return cur_stage_;
|
||||
}
|
||||
/* Staged row `row`'s bitmask as `run` uploads it: this rank's shard, `mask_words()` words,
|
||||
* meaningful only where the row carries RAD_SP_MASK. */
|
||||
const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; }
|
||||
int64_t mask_words() const { return mask_words_; }
|
||||
|
||||
private:
|
||||
/* IS THE VOCABULARY ACTUALLY SPLIT? Not the same question as "is there more than one rank".
|
||||
* A tensor-parallel deployment whose plugin declares `output.weight` replicated gives every
|
||||
* rank the whole vocabulary, and then the candidate merge is not just unnecessary but wrong:
|
||||
* every rank would contribute the SAME k candidates and the gather would count them once per
|
||||
* rank. The declared width of this rank's logits is the fact, so that is what this asks. */
|
||||
/* Whether the vocabulary is split, judged by this rank's logit width rather than the rank
|
||||
* count: with `output.weight` replicated every rank holds the whole vocabulary, and a merge
|
||||
* would count each candidate once per rank. */
|
||||
bool vocab_parallel() const {
|
||||
return cfg_.world_size > 1 && cfg_.n_vocab_local < cfg_.n_vocab;
|
||||
}
|
||||
|
||||
/* `dry` holds the request's resolved sequence breakers, empty when it sent none -- which is
|
||||
* not "DRY off": DRY runs whenever its multiplier is set, with or without breakers. */
|
||||
/* `dry` holds the resolved sequence breakers, empty when the request sent none. Empty does
|
||||
* not mean DRY is off; DRY runs whenever its multiplier is set. */
|
||||
struct SeqState {
|
||||
std::unique_ptr<GrammarBackend> grammar;
|
||||
DryBreakers dry;
|
||||
/* Where the reply stands against its reasoning block, over `output[0, think_seen)`.
|
||||
* Advanced by build_step over what each commit appended, so a step costs the tokens it
|
||||
* added and not the reply's length. Read only when the request carries a budget. */
|
||||
/* Reasoning-block state over `output[0, think_seen)`. build_step advances it over the
|
||||
* newly committed tokens only. Read only when the request carries a thinking budget. */
|
||||
ReasoningCount think;
|
||||
size_t think_seen = 0;
|
||||
};
|
||||
|
||||
/* Mask staged row `row` to the reasoning block's close token: the budget is spent and the
|
||||
* sampled position is still inside the block. A grammar already masking the row keeps the
|
||||
* last word -- the close is forced only where the grammar admits it, and a row whose grammar
|
||||
* forbids it is left to the grammar and forced at a later position. */
|
||||
/* Mask staged row `row` to the reasoning block's close token, once the budget is spent
|
||||
* inside the block. A grammar mask on the row wins: the close is forced only where the
|
||||
* grammar admits it, otherwise at a later position. */
|
||||
void force_close(DeviceSampleParams& p, int64_t row, int32_t close);
|
||||
|
||||
SamplerConfig cfg_{};
|
||||
const VocabView* vocab_ = nullptr;
|
||||
bool declared_ = false;
|
||||
|
||||
/* Declared op handles. RAD_NULL_HANDLE means the op did not resolve; the admission check
|
||||
* turns that into a named refusal rather than a silent skip. */
|
||||
/* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */
|
||||
rad_op op_penalties_ = RAD_NULL_HANDLE;
|
||||
rad_op op_dry_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_ = RAD_NULL_HANDLE;
|
||||
@@ -278,7 +244,7 @@ private:
|
||||
rad_op op_argmax_ = RAD_NULL_HANDLE;
|
||||
rad_op op_allgather_ = RAD_NULL_HANDLE;
|
||||
rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */
|
||||
rad_op op_logprobs_ = RAD_NULL_HANDLE; /* the raw distribution's summary */
|
||||
rad_op op_logprobs_ = RAD_NULL_HANDLE; /* summary of the raw distribution */
|
||||
rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */
|
||||
|
||||
/* Device-side buffers, from the ordinary buffer plan. */
|
||||
@@ -294,17 +260,16 @@ private:
|
||||
rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */
|
||||
rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */
|
||||
|
||||
/* Pinned staging. One allocation each, at declare, never on the step path. */
|
||||
/* Pinned staging, allocated once at declare. */
|
||||
DeviceSampleParams* params_stage_ = nullptr;
|
||||
/* The late temperature's rows: params_stage_'s, with each row's temperature at 1 unless it
|
||||
* runs last. Uploaded only by a step where some row does (any_late_). */
|
||||
/* Copies of params_stage_'s rows with temperature 1 unless the row runs temperature last.
|
||||
* Uploaded only when some row does (any_late_). */
|
||||
DeviceSampleParams* late_stage_ = nullptr;
|
||||
bool any_late_ = false;
|
||||
/* THE GREEDY ROWS HAVE STAGING OF THEIR OWN, written once. A draft pass is staged while the
|
||||
* step before it -- whose sampler uploads `params_stage_` when the card reaches it -- may not
|
||||
* have run yet; rows written into the same staging would reach that step's sampler instead.
|
||||
* Every greedy row is the same row, so this one is filled on first use and never again, and
|
||||
* no upload of it can ever see a later build. */
|
||||
/* Greedy rows have their own staging, filled once on first use. A draft pass is staged
|
||||
* while the previous step's upload of params_stage_ may still be pending, so writing there
|
||||
* would change that step's rows. Every greedy row is identical, so no upload of this buffer
|
||||
* can observe a later build. */
|
||||
DeviceSampleParams* greedy_stage_ = nullptr;
|
||||
bool greedy_ready_ = false;
|
||||
const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */
|
||||
@@ -312,46 +277,42 @@ private:
|
||||
uint8_t* brk_stage_ = nullptr;
|
||||
uint32_t* mask_stage_ = nullptr;
|
||||
|
||||
int64_t mask_words_ = 0; /* words for THIS RANK's shard; what the mask op indexes */
|
||||
int64_t mask_words_ = 0; /* words for this rank's shard; what the mask op indexes */
|
||||
int64_t n_seq_ = 0;
|
||||
/* Does any DRY row this step carry breakers? Only then is the breaker plane uploaded and
|
||||
* handed to sample_dry; a batch whose DRY requests sent none issues it without the operand. */
|
||||
/* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
|
||||
* passed to sample_dry. */
|
||||
bool any_brk_ = false;
|
||||
|
||||
/* The whole-vocabulary mask the grammar fills, from which the staged shard is cut. Only used
|
||||
* when the head is sharded; see the note in declare(). */
|
||||
/* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used
|
||||
* only when the head is sharded; see declare(). */
|
||||
std::vector<uint32_t> mask_full_;
|
||||
|
||||
/* The grammar mask's cost, accumulated for the Debug line in build_step. Not state the step
|
||||
path reads -- a diagnostic, and one worth carrying: the mask walk is scheduler-thread work
|
||||
large enough to decide the step time of a constrained request, so it has to be visible
|
||||
rather than assumed. */
|
||||
/* Debug-level timing of the grammar mask, build_step and accept_token. The mask walk is
|
||||
scheduler-thread work that can set the step time of a constrained request. */
|
||||
double mask_us_ = 0.0;
|
||||
double mask_worst_us_ = 0.0;
|
||||
int64_t mask_us_n_ = 0;
|
||||
int64_t mask_fast_ = 0; /* memo hits */
|
||||
int64_t mask_slow_ = 0; /* walks */
|
||||
double mask_walk_us_ = 0.0; /* and what only the walks cost */
|
||||
double mask_walk_us_ = 0.0; /* time spent in walks only */
|
||||
double build_us_ = 0.0;
|
||||
int64_t build_n_ = 0;
|
||||
double accept_us_ = 0.0;
|
||||
int64_t accept_n_ = 0;
|
||||
void shard_mask(uint32_t* dst) const;
|
||||
|
||||
/* Requests whose grammar died this step. Drained by the engine, which cancels them -- one bad
|
||||
* request must not stop the step loop for everyone else. */
|
||||
/* Requests whose grammar died this step. The engine drains and cancels them, so one bad
|
||||
* request does not stop the step loop. */
|
||||
std::vector<uint64_t> failed_;
|
||||
|
||||
/* ---------------------------------------------------------- logprobs */
|
||||
/* THE SUMMARY'S WIDTH: RAD_MAX_LOGPROBS + 1 pairs, not RAD_MAX_LOGPROBS, so that a row is 44
|
||||
* floats -- whole 16-byte words, which is what the all-gather of a split vocabulary moves (and
|
||||
* libr4d's refuses anything else). The extra pair is never reported. */
|
||||
/* RAD_MAX_LOGPROBS + 1 pairs, so a summary row is 44 floats: whole 16-byte words, which
|
||||
* libr4d's all-gather of a split vocabulary requires. The extra pair is never reported. */
|
||||
static constexpr int kLpK = RAD_MAX_LOGPROBS + 1;
|
||||
static int64_t lp_width() { return 2 + 2 * (int64_t)kLpK; }
|
||||
/* WHAT UNDOING A ROW'S CHAIN NEEDS, kept from build_step for each row staged with
|
||||
* RAD_SP_LOGPROBS: the staged row itself, the temperature the candidate value carries, the
|
||||
* history window both history stages read, and the request's DRY breakers. Copied rather
|
||||
* than pointed at, because the staging is rebuilt by the next step. */
|
||||
/* What raw_logit needs to undo a RAD_SP_LOGPROBS row's chain, saved by build_step: the
|
||||
* staged row, the temperature the candidate value carries, the history window and the DRY
|
||||
* breakers. Copied, because the next step rebuilds the staging. */
|
||||
struct LpRow {
|
||||
int64_t row = -1;
|
||||
int32_t n_top = 0;
|
||||
@@ -368,24 +329,22 @@ private:
|
||||
float* lp_cv_host_ = nullptr;
|
||||
int64_t lp_lo_ = 0, lp_hi_ = 0; /* the rows copied, [lo, hi) */
|
||||
/* A token's raw logit from the value the pick drew it at: temperature, DRY and the penalties
|
||||
* undone, in the reverse of the order the chain applied them. */
|
||||
* undone in reverse order. */
|
||||
float raw_logit(const LpRow& L, int32_t token, float v) const;
|
||||
|
||||
/* Per-request grammar and DRY state, keyed by request id. Held here rather than in Request
|
||||
* because Request is a frozen struct shared across components and a unique_ptr in it would
|
||||
* make the scheduler's copies a compile error. */
|
||||
/* Per-request grammar and DRY state. Not in Request, a frozen struct the scheduler copies,
|
||||
* which a unique_ptr member would make non-copyable. */
|
||||
std::unordered_map<uint64_t, SeqState> seqs_;
|
||||
|
||||
int stage_alloc();
|
||||
void stage_free();
|
||||
};
|
||||
|
||||
/* SPLIT-VOCABULARY SUMMARIES, MERGED: `W` ranks' `sample_logprobs` rows of `k` pairs each, side by
|
||||
* side in `st` (W * (2 + 2k) floats). Sets the shared log normaliser and fills up to `cap` of the
|
||||
* largest (id, logit) pairs over every rank, descending, ties to the lower id; returns how many. A
|
||||
* rank whose maximum or normaliser is not finite contributes nothing, nor does a pair whose logit
|
||||
* is not finite, and `*log_z` comes back NaN when no rank contributes. One rank is the same
|
||||
* arithmetic. What Sampler::logprobs_for reads a step's summaries with. */
|
||||
/* Merge `W` ranks' `sample_logprobs` rows of `k` pairs each, side by side in `st`
|
||||
* (W * (2 + 2k) floats). Sets the combined log normaliser and fills up to `cap` of the largest
|
||||
* (id, logit) pairs, descending, ties to the lower id; returns how many. Ranks with a non-finite
|
||||
* maximum or normaliser and pairs with a non-finite logit are skipped; `*log_z` is NaN when no
|
||||
* rank contributes. W = 1 is valid. Used by Sampler::logprobs_for. */
|
||||
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
|
||||
int cap);
|
||||
|
||||
|
||||
+20
-39
@@ -1,15 +1,11 @@
|
||||
/* vocab_view.h -- what the sampler needs to know about a vocabulary, and nothing else.
|
||||
/* vocab_view.h -- what the sampler needs to know about a vocabulary.
|
||||
*
|
||||
* The tokeniser lives in core/text/ and belongs to the text frontend. The sampler needs exactly
|
||||
* three facts about a token -- how many there are, its printable piece, and whether it ends
|
||||
* generation -- plus, for DRY's sequence breakers and GBNF's `<token>` syntax, the ability to
|
||||
* tokenise a short literal. Taking a dependency on the whole tokeniser for that would put a
|
||||
* component boundary on the step path and make every sampler test drag a real vocabulary behind
|
||||
* it. An abstract view costs one virtual call per token per grammar step, which is host work the
|
||||
* device is not waiting on.
|
||||
* The sampler needs the token count, each token's piece and whether it ends generation, plus
|
||||
* tokenising a short literal for DRY's sequence breakers and GBNF's `<token>` syntax. This view
|
||||
* keeps the tokeniser (core/text/) out of the sampler and its tests; a virtual call per token per
|
||||
* grammar step is host work the device does not wait on.
|
||||
*
|
||||
* core/text/ implements this over the real vocab; SimpleVocab below implements it over a table,
|
||||
* which is what the tests use.
|
||||
* text/token_view.h implements it over the real vocab; SimpleVocab over a table, for tests.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_internal.h"
|
||||
@@ -27,10 +23,8 @@ public:
|
||||
|
||||
virtual int32_t n_tokens() const = 0;
|
||||
|
||||
/* The token's bytes as they would be appended to the output stream. The grammar walks these,
|
||||
* so a view that returns a display form rather than the exact bytes will admit the wrong
|
||||
* token set -- and the failure mode is plausible text with wrong structure, which is the
|
||||
* hardest kind to notice. */
|
||||
/* The token's exact bytes as appended to the output stream. The grammar walks these; a
|
||||
* display form would make it admit the wrong token set. */
|
||||
virtual const std::string& token_piece(int32_t id) const = 0;
|
||||
|
||||
/* End-of-generation: EOS, EOT, and whatever else this model ends on. A grammar admits one
|
||||
@@ -38,15 +32,14 @@ public:
|
||||
virtual bool is_eog(int32_t id) const = 0;
|
||||
|
||||
/* Tokenise a short literal. Only DRY's sequence breakers and GBNF's `<token>` form need it,
|
||||
* and both are optional features, so a view that has no tokeniser returns
|
||||
* RAD_E_UNSUPPORTED rather than pretending. */
|
||||
* both optional, so a view without a tokeniser returns RAD_E_UNSUPPORTED. */
|
||||
virtual int tokenize(const std::string& text, std::vector<int32_t>* out) const {
|
||||
(void)text; (void)out;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The same with special tokens recognised in the text, so `<tool_call>` comes back as the
|
||||
* one control token a template means by it. Grammar triggers are resolved through this. */
|
||||
/* As tokenize, but recognising special tokens, so `<tool_call>` comes back as the one control
|
||||
* token. Grammar triggers resolve through this. */
|
||||
virtual int tokenize_special(const std::string& text, std::vector<int32_t>* out) const {
|
||||
(void)text; (void)out;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -54,25 +47,16 @@ public:
|
||||
|
||||
/* ---------------- what a grammar backend derives from this vocabulary ----------------
|
||||
*
|
||||
* A GBNF mask is built over a DECODED form of the whole vocabulary -- every piece as code
|
||||
* points, plus a trie over them -- which costs a full vocabulary scan and is therefore
|
||||
* computed once and kept. It is kept HERE, with the vocabulary's own lifetime, because the
|
||||
* only other place to keep it is a table outside, and the only key such a table has is this
|
||||
* object's ADDRESS. An address is not an identity: a view destroyed and another constructed
|
||||
* in the same storage answers to the same key, and the second one is then served what was
|
||||
* derived for the first -- the decoded vocabulary, the trie over it, and the grammars
|
||||
* compiled against both. The mask that comes out is a mask over another model's tokens: it
|
||||
* admits the wrong set, or nothing at all, and nothing downstream can tell. Tying the cache
|
||||
* to the object makes the question unaskable.
|
||||
*
|
||||
* Opaque and mutable: what is cached is the backend's business and this header is the
|
||||
* sampler's interface, and filling it does not change what the vocabulary says. A backend
|
||||
* that caches nothing pays one null pointer. */
|
||||
* A GBNF mask works over a decoded form of the whole vocabulary (pieces as code points plus a
|
||||
* trie), which costs a full scan and is computed once. It is cached here, with the view's own
|
||||
* lifetime, because an external table could only key on the view's address, and a new view
|
||||
* built in the same storage would then be served the old model's decoded vocabulary and
|
||||
* compiled grammars. Opaque and mutable: its contents are the backend's business and filling
|
||||
* it does not change what the vocabulary says. */
|
||||
mutable std::shared_ptr<void> gbnf_cache;
|
||||
};
|
||||
|
||||
/* A vocabulary held as a table. Not a toy: it is what the sampler tests are written against, and
|
||||
* being able to state a vocabulary in four lines is what makes a grammar test readable. */
|
||||
/* A vocabulary held as a table, for the sampler and grammar tests. */
|
||||
class SimpleVocab : public VocabView {
|
||||
public:
|
||||
SimpleVocab() = default;
|
||||
@@ -85,8 +69,6 @@ public:
|
||||
return id;
|
||||
}
|
||||
|
||||
void mark_eog(int32_t id) { eog_.push_back(id); }
|
||||
|
||||
int32_t n_tokens() const override { return (int32_t)pieces_.size(); }
|
||||
|
||||
const std::string& token_piece(int32_t id) const override {
|
||||
@@ -100,14 +82,13 @@ public:
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Longest-match over the table, which is not BPE and does not pretend to be. It exists so a
|
||||
* DRY sequence breaker or a `<token>` literal resolves in a test; a real vocabulary's merge
|
||||
* machinery lives in core/text/. */
|
||||
/* A table has no special tokens of its own: every piece is matched as written. */
|
||||
int tokenize_special(const std::string& text, std::vector<int32_t>* out) const override {
|
||||
return tokenize(text, out);
|
||||
}
|
||||
|
||||
/* Longest match over the table, not BPE. Enough for a DRY breaker or a `<token>` literal in a
|
||||
* test; real tokenisation lives in core/text/. */
|
||||
int tokenize(const std::string& text, std::vector<int32_t>* out) const override {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
size_t pos = 0;
|
||||
|
||||
@@ -26,8 +26,8 @@ int WordScanner::build(const std::vector<std::string>& words, std::string* err)
|
||||
cls_[c] = (uint8_t)ncls_++;
|
||||
}
|
||||
|
||||
/* The trie, with its edges held densely from the start: a missing edge is kUnset until the
|
||||
* breadth-first pass below resolves it through the failure link. */
|
||||
/* The trie with dense edges; a missing edge is kUnset until the breadth-first pass resolves
|
||||
* it through the failure link. */
|
||||
constexpr uint32_t kUnset = ~0u;
|
||||
next_.assign(ncls_, kUnset);
|
||||
out_len_.assign(1, 0u);
|
||||
@@ -47,9 +47,9 @@ int WordScanner::build(const std::vector<std::string>& words, std::string* err)
|
||||
max_len_ = std::max<uint32_t>(max_len_, (uint32_t)w.size());
|
||||
}
|
||||
|
||||
/* Failure links in breadth-first order, so a state's link is final before any deeper state
|
||||
* reads it. A state's longest match is its own word if it ends one, which is longer than any
|
||||
* proper suffix, and otherwise its failure state's. */
|
||||
/* Failure links in breadth-first order, so a state's link is final before a deeper state
|
||||
* reads it. A state's longest match is its own word if it ends one, else its failure
|
||||
* state's. */
|
||||
const uint32_t n_states = (uint32_t)out_len_.size();
|
||||
std::vector<uint32_t> fail(n_states, 0u);
|
||||
std::vector<uint32_t> queue;
|
||||
|
||||
+15
-18
@@ -1,23 +1,20 @@
|
||||
/* word_scan.h -- find the first of a set of literal words in a byte stream that arrives in pieces.
|
||||
*
|
||||
* A lazy grammar waits for its trigger word -- `<tool_call>\n` on the Qwen templates -- and until
|
||||
* the word appears every generated token passes through here. The stream is the whole reply, so
|
||||
* anything that looks back over what has already arrived turns a long reply into quadratic host
|
||||
* work on the step path. This looks back at nothing: the scan state is one integer, each byte is
|
||||
* one table load, and what a match needs to be replayed is bounded by the longest word.
|
||||
* A lazy grammar waits for its trigger word (`<tool_call>\n` on the Qwen templates), and every
|
||||
* generated token passes through here until it appears. Looking back over the stream would make a
|
||||
* long reply quadratic host work, so the scan keeps one integer of state and does one table load
|
||||
* per byte; replaying a match needs at most the longest word.
|
||||
*
|
||||
* THE AUTOMATON is Aho-Corasick compiled to a full DFA over byte classes. The trie of the words
|
||||
* gets failure links in breadth-first order, and every missing edge is resolved through them once,
|
||||
* at build time, so the scan never follows a failure chain. Bytes that occur in no word share one
|
||||
* class, which keeps the table at (states x distinct word bytes + 1) entries -- a few hundred for
|
||||
* any real trigger set, so it stays in L1 however long the reply runs.
|
||||
* Automaton: Aho-Corasick compiled to a full DFA over byte classes. Failure links are built
|
||||
* breadth-first and every missing edge is resolved through them at build time, so the scan never
|
||||
* follows a failure chain. Bytes in no word share one class, so the table has
|
||||
* states x (distinct word bytes + 1) entries: a few hundred for a real trigger set, so it stays
|
||||
* in L1.
|
||||
*
|
||||
* THE MATCH REPORTED is the leftmost START among the occurrences that complete inside one fed
|
||||
* piece. That is the answer a search of the whole stream so far gives after each piece: nothing
|
||||
* completed in an earlier piece (the caller would have stopped), so every complete occurrence ends
|
||||
* in this one, and of those the leftmost is the one that begins first. Each state carries the
|
||||
* length of the LONGEST word ending there, because the longest word ending at a byte is the one
|
||||
* that starts earliest.
|
||||
* Match reported: the leftmost start among occurrences that complete inside one fed piece. Since
|
||||
* the caller stops at the first match, nothing completed earlier, so this equals a search of the
|
||||
* whole stream so far. Each state carries the length of the longest word ending there, which is
|
||||
* the one that starts earliest.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_internal.h"
|
||||
@@ -33,8 +30,8 @@ class WordScanner {
|
||||
public:
|
||||
static constexpr uint64_t npos = ~(uint64_t)0;
|
||||
|
||||
/* Where a stream is: the automaton state and how many bytes have been fed. Plain data, so a
|
||||
* speculative window can copy it and put it back. */
|
||||
/* Automaton state and bytes fed so far. Plain data, so a speculative window can copy and
|
||||
* restore it. */
|
||||
struct State {
|
||||
uint32_t s = 0;
|
||||
uint64_t off = 0;
|
||||
|
||||
Reference in new issue
Block a user