radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
/* 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.
*/
#include "accept.h"
#include "host_ref.h"
#include <algorithm>
#include <cmath>
namespace rad {
int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
int32_t* out, int32_t* n_accepted) {
if (!target || !out || !n_accepted || n_draft < 0) return RAD_E_INVAL;
if (n_draft > 0 && !draft) return RAD_E_INVAL;
int i = 0;
for (; i < n_draft; ++i) {
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. */
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 */
+98
View File
@@ -0,0 +1,98 @@
/* 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.
*
* Three rules, and the cheapest one is exact everywhere.
*
* 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.
*
* 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
* (docs/OPS.md, spec §10).
*/
#pragma once
#include "../rad_internal.h"
#include <cstdint>
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.
*
* 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. */
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);
} /* namespace rad */
+1388
View File
File diff suppressed because it is too large. Load diff
+301
View File
@@ -0,0 +1,301 @@
/* 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:
* - `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.
* - `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.
* - 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.
*
* 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.
* - 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.
*
* 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).
*/
#pragma once
#include "../rad_internal.h"
#include "vocab_view.h"
#include "word_scan.h"
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace rad {
/* ================================================================== grammar elements */
enum GreType {
GRE_END = 0, /* end of rule definition */
GRE_ALT = 1, /* start of an alternate definition */
GRE_RULE_REF = 2, /* reference to a rule */
GRE_CHAR = 3, /* terminal: a code point */
GRE_CHAR_NOT = 4, /* inverse char set: [^a], [^a-b] */
GRE_CHAR_RNG_UPPER = 5, /* modifies the preceding CHAR into an inclusive range */
GRE_CHAR_ALT = 6, /* adds an alternate char to the preceding set */
GRE_CHAR_ANY = 7, /* '.' */
GRE_TOKEN = 8, /* terminal: a token id, `<[id]>` */
GRE_TOKEN_NOT = 9 /* inverse token, `!<[id]>` */
};
struct GbnfElement {
GreType type;
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. */
struct PartialUtf8 {
uint32_t value = 0; /* bits so far, unshifted */
int n_remain = 0; /* bytes still needed; -1 marks an invalid sequence */
};
using GbnfRule = std::vector<GbnfElement>;
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. */
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 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;
size_t elements = 0;
size_t keys = 0; /* stack suffixes with a precomputed token set */
size_t dense_masks = 0; /* of those, held as a whole-vocabulary bitmask */
size_t max_key_depth = 0; /* the deepest suffix, in stack entries */
size_t rem_nodes = 0; /* nodes across every remainder trie */
size_t max_rem_nodes = 0; /* the largest remainder trie */
size_t bytes = 0; /* rules and plan; the mask cache is extra */
};
/* What the vocabulary index cost and holds. */
struct GbnfVocabInfo {
double build_ms = 0.0;
size_t bytes = 0;
};
/* ================================================================== the parser */
class GbnfParser {
public:
explicit GbnfParser(const VocabView* vocab = nullptr) : vocab_(vocab) {}
/* Returns RAD_OK, or RAD_E_FORMAT with the parse error in *err. Never throws out. */
int parse(const char* src, std::string* err);
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. */
uint64_t budget_used_ = 0;
uint32_t depth_ = 0;
void charge(uint64_t bytes);
uint32_t get_symbol_id(const char* src, size_t len);
uint32_t generate_symbol_id(const std::string& base);
void add_rule(uint32_t id, const GbnfRule& rule);
const char* parse_alternates(const char* src, const std::string& rule_name,
uint32_t rule_id, bool is_nested);
const char* parse_sequence(const char* src, const std::string& rule_name,
GbnfRule& rule, bool is_nested);
const char* parse_rule(const char* src);
};
/* ================================================================== the state machine */
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.
*
* 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. */
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. */
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. */
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. */
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. */
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. */
void push_state();
int rollback();
private:
/* A token that may still hold the start of a trigger word: its id and the stream offset of its
* first byte. It ends where the next one starts, or at the scan's current offset. */
struct Recent {
int32_t token;
uint64_t start;
};
struct Snapshot {
GbnfStacks stacks;
PartialUtf8 partial;
bool awaiting_trigger = false;
WordScanner::State scan;
std::vector<Recent> recent;
};
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. */
std::shared_ptr<const GbnfProgram> prog_;
GbnfStacks stacks_;
PartialUtf8 partial_utf8_{};
std::vector<Snapshot> saved_;
GbnfState state_key(bool allow_eog, int64_t n_words) const;
/* The mask itself, from the program's plan, with no 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. */
bool awaiting_trigger_ = false;
std::vector<int32_t> trigger_tokens_;
std::shared_ptr<const WordScanner> scanner_;
WordScanner::State scan_;
std::vector<Recent> recent_;
int accept_token_piece(int32_t token, const std::string& piece);
int accept_token_piece_impl(int32_t token, const std::string& piece);
};
/* 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. */
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. */
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. */
inline int64_t bitmask_words(int64_t n_vocab) { return (n_vocab + 31) / 32; }
} /* namespace rad */
+335
View File
@@ -0,0 +1,335 @@
/* gbnf_internal.h -- what the GBNF state machine's three translation units share, and nothing
* else includes.
*
* 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.
*
* 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.
*/
#pragma once
#include "gbnf.h"
#include <algorithm>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
namespace rad {
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.
*
* 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. */
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. */
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. */
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. */
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. */
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. */
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. */
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. */
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. */
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. */
struct GbnfLimit : std::runtime_error {
using std::runtime_error::runtime_error;
};
[[noreturn]] void throw_set_limit();
/* The work counter for one operation, passed to everything the operation calls. */
struct OpWork {
uint64_t used = 0;
uint64_t limit = kMaxOpWork;
void add(uint64_t n) {
used += n;
if (used > limit) over();
}
private:
[[noreturn]] void over() const;
};
uint64_t stack_hash(const GbnfStack& s);
struct StackLess {
bool operator()(const GbnfStack& a, const GbnfStack& b) const {
return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(),
[](const GbnfElement* pa, const GbnfElement* pb) { return pa < pb; });
}
};
/* 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.
*
* 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. */
struct SetBuild {
explicit SetBuild(OpWork& w) : work(w) {}
OpWork& work;
size_t stacks = 0, elems = 0;
std::set<GbnfStack, StackLess> seen;
size_t seen_elems = 0;
void add(size_t stack_size) {
stacks += 1;
elems += stack_size + 1;
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. */
void insert(GbnfStacks& out, GbnfStack s);
private:
static constexpr size_t kIndexFrom = 16;
std::unordered_multimap<uint64_t, size_t> index;
};
/* ============================================================ UTF-8 */
/* One code point from NUL-terminated text. Assumes valid UTF-8 but checks for overrun. */
std::pair<uint32_t, const char*> decode_utf8(const char* src);
/* Decode a piece, carrying an incomplete sequence in from the previous token and out to the next.
* The returned code-point vector is 0-terminated. An invalid sequence leaves no code points and
* a carried state of {0, -1}. */
std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src,
PartialUtf8 partial_start);
/* ============================================================ elements */
inline bool is_end_of_sequence(const GbnfElement* pos) {
return pos->type == GRE_END || pos->type == GRE_ALT;
}
inline bool is_char_elem(const GbnfElement* pos) {
return pos->type == GRE_CHAR || pos->type == GRE_CHAR_NOT || pos->type == GRE_CHAR_ANY;
}
inline bool is_token_elem(const GbnfElement* pos) {
return pos->type == GRE_TOKEN || pos->type == GRE_TOKEN_NOT;
}
/* True iff chr satisfies the char range at pos (regular or inverse), and the element after the
* range. pos must point at a char range element. */
inline std::pair<bool, const GbnfElement*> match_char(const GbnfElement* pos, uint32_t chr) {
bool found = false;
const bool is_positive = pos->type == GRE_CHAR || pos->type == GRE_CHAR_ANY;
do {
if (pos[1].type == GRE_CHAR_RNG_UPPER) {
found = found || (pos->value <= chr && chr <= pos[1].value);
pos += 2;
} else if (pos->type == GRE_CHAR_ANY) {
found = true;
pos += 1;
} else {
found = found || pos->value == chr;
pos += 1;
}
} while (pos->type == GRE_CHAR_ALT);
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. */
inline bool match_partial_char(const GbnfElement* pos, PartialUtf8 partial) {
const bool is_positive = pos->type == GRE_CHAR || pos->type == GRE_CHAR_ANY;
const uint32_t partial_value = partial.value;
const int n_remain = partial.n_remain;
if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) return false;
uint32_t low = partial_value << (n_remain * 6);
const uint32_t high = low | (uint32_t)((1 << (n_remain * 6)) - 1);
if (low == 0) {
if (n_remain == 2) low = 1u << 11;
else if (n_remain == 3) low = 1u << 16;
}
do {
if (pos[1].type == GRE_CHAR_RNG_UPPER) {
if (pos->value <= high && low <= pos[1].value) return is_positive;
pos += 2;
} else if (pos->type == GRE_CHAR_ANY) {
return true;
} else {
if (low <= pos->value && pos->value <= high) return is_positive;
pos += 1;
}
} while (pos->type == GRE_CHAR_ALT);
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. */
inline size_t char_range_len(const GbnfElement* pos) {
return (size_t)(match_char(pos, 0).second - pos);
}
inline bool match_token(const GbnfElement* pos, int32_t token) {
if (pos->type == GRE_TOKEN) return pos->value == (uint32_t)token;
if (pos->type == GRE_TOKEN_NOT) return pos->value != (uint32_t)token;
return false;
}
/* ============================================================ 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. */
struct GbnfRuleSet {
std::vector<GbnfElement> elems;
std::vector<uint32_t> start; /* rule id -> index of its first element */
const GbnfElement* rule(size_t id) const { return elems.data() + start[id]; }
uint32_t index(const GbnfElement* e) const { return (uint32_t)(e - elems.data()); }
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. */
void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks& out,
SetBuild& build);
/* The rules a compiled program's stacks point into. */
const GbnfRuleSet& program_rules(const GbnfProgram& p);
/* ============================================================ the mask engine (gbnf_mask.cpp) */
/* Everything the mask engine derives from a vocabulary: each piece decoded to code points, a
* trie over them, and the index of pieces that resume a split character. Built once per
* vocabulary and shared by every grammar compiled against it. */
struct VocabIndex;
/* Throws std::bad_alloc; a vocabulary with no text in it builds an empty index. */
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. */
struct PlanStats {
double ms = 0.0; /* wall time of the plan build */
uint64_t work = 0; /* units charged against kMaxCompileWork */
size_t classes = 0; /* distinct stack-entry classes */
size_t keys = 0; /* stack suffixes with a precomputed mask */
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 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. */
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. */
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. */
int plan_fill(const MaskPlan& plan, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog,
uint32_t* bitmask, int64_t n_words);
} /* namespace gbnf */
} /* namespace rad */
File diff suppressed because it is too large. Load diff
+166
View File
@@ -0,0 +1,166 @@
/* grammar.cpp -- the GBNF backend that ships, and the schema seam onto it.
*/
#include "grammar.h"
#include "gbnf.h"
#include <json-schema-to-grammar.h>
#include <nlohmann/json.hpp>
#include <algorithm>
#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. */
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. */
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;
while (!todo.empty()) {
const auto [j, d] = todo.back();
todo.pop_back();
if (!j->is_structured()) continue;
deepest = std::max(deepest, d);
for (const auto& c : *j) todo.push_back({ &c, d + 1 });
}
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. */
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. */
if (!root.empty() && root != "root") {
if (err) *err = "this converter always names the top rule 'root'";
return RAD_E_UNSUPPORTED;
}
try {
const auto schema = nlohmann::ordered_json::parse(schema_json);
if (json_depth(schema) > kMaxSchemaDepth) {
if (err) *err = "the schema nests more than " + std::to_string(kMaxSchemaDepth) +
" levels deep";
return RAD_E_INVAL;
}
*out_gbnf = json_schema_to_grammar(schema);
} catch (const std::exception& e) {
if (err) *err = e.what();
return RAD_E_INVAL;
}
if (out_gbnf->empty()) {
if (err) *err = "the schema compiled to an empty grammar";
return RAD_E_INVAL;
}
return RAD_OK;
}
/* ================================================================== the GBNF backend */
namespace {
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. */
bool can_speculate() const override { return true; }
int push_state() override { g_->push_state(); return RAD_OK; }
int rollback() override { return g_->rollback(); }
private:
std::unique_ptr<GbnfGrammar> g_;
};
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. */
if (spec.kind == GrammarKind::JsonSchema) {
std::string gbnf;
const int st = grammar_from_json_schema(spec.text, spec.root, &gbnf, err);
if (st < 0) return st;
text = std::move(gbnf);
}
std::unique_ptr<GbnfGrammar> g;
const int st = GbnfGrammar::create(text, spec.root.empty() ? "root" : spec.root, &vocab,
spec.lazy, spec.trigger_words, spec.trigger_tokens,
&g, err);
if (st < 0) return st;
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. */
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;
}
}
*out = std::make_unique<GbnfBackend>(std::move(g));
return RAD_OK;
}
} /* namespace */
int grammar_create(const GrammarSpec& spec, const VocabView& vocab,
std::unique_ptr<GrammarBackend>* out, std::string* err) {
if (!out) return RAD_E_INVAL;
if (spec.text.empty()) {
if (err) *err = "empty grammar";
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. */
try {
return gbnf_ctor(spec, vocab, out, err);
} catch (const std::bad_alloc&) {
if (err) *err = "out of memory building the grammar";
return RAD_E_NOMEM;
}
}
} /* namespace rad */
+127
View File
@@ -0,0 +1,127 @@
/* 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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include "vocab_view.h"
#include <memory>
#include <string>
#include <vector>
namespace rad {
enum class GrammarKind {
Gbnf = 0, /* the text is GBNF */
JsonSchema = 1 /* the text is a JSON Schema, compiled to GBNF at create time */
};
struct GrammarSpec {
GrammarKind kind = GrammarKind::Gbnf;
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. */
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. */
std::string prefix;
};
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. */
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. */
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. */
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. */
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 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. */
virtual bool can_speculate() const { return false; }
/* Push the current state. Nestable; `rollback` pops the most recent. */
virtual int push_state() { return RAD_E_UNSUPPORTED; }
virtual int rollback() { return RAD_E_UNSUPPORTED; }
};
/* 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. */
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. */
int grammar_create(const GrammarSpec& spec, const VocabView& vocab,
std::unique_ptr<GrammarBackend>* out, std::string* err);
} /* namespace rad */
+611
View File
@@ -0,0 +1,611 @@
/* 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.
*/
#include "host_ref.h"
#include "rad_sample.h"
#include <algorithm>
#include <cfloat>
#include <cmath>
#include <numeric>
namespace rad {
/* ================================================================== the candidate set */
void CandidateSet::from_logits(const float* logits, int64_t n_vocab) {
c.resize((size_t)n_vocab);
for (int64_t i = 0; i < n_vocab; ++i) {
c[(size_t)i].id = (int32_t)i;
c[(size_t)i].logit = logits[i];
c[(size_t)i].p = 0.0f;
}
sorted = false;
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. */
void CandidateSet::sort_desc() {
if (sorted) return;
std::stable_sort(c.begin(), c.end(), [](const Candidate& a, const Candidate& b) {
if (a.logit != b.logit) return a.logit > b.logit;
return a.id < b.id;
});
sorted = true;
}
/* ================================================================== 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. */
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. */
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. */
return rad_sample_uniform01(seed ^ stream_key(stream), pos);
}
/* ================================================================== individual samplers */
void host_softmax(CandidateSet& s, bool do_sort) {
if (s.c.empty()) return;
if (do_sort) s.sort_desc();
float max_l = s.c[0].logit;
if (!s.sorted)
for (size_t i = 1; i < s.c.size(); ++i) max_l = std::max(max_l, s.c[i].logit);
double cum = 0.0;
for (auto& e : s.c) {
const float p = std::exp(e.logit - max_l);
e.p = p;
cum += p;
}
if (cum <= 0.0) return; /* every candidate masked out; leave p at zero and let the pick say so */
for (auto& e : s.c) e.p = (float)(e.p / cum);
}
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. */
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;
}
for (size_t i = 0; i < s.c.size(); ++i)
if (i != max_i) s.c[i].logit = -INFINITY;
return;
}
for (auto& e : s.c) e.logit /= temp;
}
void host_top_k(CandidateSet& s, int32_t k) {
if (k <= 0) return;
if ((size_t)k >= s.c.size()) { s.sort_desc(); return; }
s.sort_desc();
s.c.resize((size_t)k);
}
void host_top_p(CandidateSet& s, float p, size_t min_keep) {
if (p >= 1.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. */
float cum = 0.0f;
size_t last_idx = s.c.size();
for (size_t i = 0; i < s.c.size(); ++i) {
cum += s.c[i].p;
if (cum >= p && i + 1 >= min_keep) { last_idx = i + 1; break; }
}
s.c.resize(last_idx);
}
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. */
s.sort_desc();
const float min_logit = s.c[0].logit + std::log(p); /* p_i >= p * p_max */
size_t i = 1; /* the mode always survives */
for (; i < s.c.size(); ++i)
if (s.c[i].logit < min_logit && i >= min_keep) break;
s.c.resize(i);
}
void host_typical(CandidateSet& s, float p, size_t min_keep) {
if (p >= 1.0f || s.c.empty()) return;
host_softmax(s, true);
float entropy = 0.0f;
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. */
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);
}
std::vector<size_t> idx(s.c.size());
std::iota(idx.begin(), idx.end(), (size_t)0);
std::stable_sort(idx.begin(), idx.end(), [&](size_t a, size_t b) {
if (shifted[a] != shifted[b]) return shifted[a] < shifted[b];
return s.c[a].id < s.c[b].id; /* total order, same reason as sort_desc */
});
float cum = 0.0f;
size_t last_idx = idx.size();
for (size_t i = 0; i < idx.size(); ++i) {
cum += s.c[idx[i]].p;
if (cum > p && (min_keep == 0 || i >= min_keep - 1)) { last_idx = i + 1; break; }
}
std::vector<Candidate> kept;
kept.reserve(last_idx);
for (size_t i = 0; i < last_idx; ++i) kept.push_back(s.c[idx[i]]);
s.c = std::move(kept);
s.sorted = false; /* surprisal order is not logit order */
}
void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history,
int32_t last_n, float rep, float freq, float pres) {
if (last_n == 0) return;
if (rep == 1.0f && freq == 0.0f && pres == 0.0f) return;
if (!history || n_history <= 0) return;
const int64_t window = last_n < 0 ? n_history : std::min<int64_t>(last_n, n_history);
std::unordered_map<int32_t, int> count;
count.reserve((size_t)window * 2);
for (int64_t i = n_history - window; i < n_history; ++i) count[history[i]]++;
for (auto& e : s.c) {
auto it = count.find(e.id);
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. */
if (e.logit <= 0.0f) e.logit *= rep;
else e.logit /= rep;
e.logit -= (float)n * freq + (n > 0 ? 1.0f : 0.0f) * pres;
}
s.sorted = false;
}
/* ------------------------------------------------------------------ DRY */
void DryBreakers::index(int32_t n_vocab) {
const size_t words = n_vocab > 0 ? ((size_t)n_vocab + 31) / 32 : 0;
heads.assign(words, 0u);
singles.assign(words, 0u);
for (const auto& e : seqs) {
const int32_t t = e.first;
if (t < 0 || t >= n_vocab) continue;
heads[(size_t)(t >> 5)] |= 1u << ((uint32_t)t & 31u);
if (e.second.empty()) singles[(size_t)(t >> 5)] |= 1u << ((uint32_t)t & 31u);
}
}
bool DryBreakers::is_head(int32_t t) const {
if (heads.empty()) return seqs.count(t) > 0;
return bit(heads, t);
}
bool DryBreakers::is_single(int32_t t) const {
if (singles.empty()) {
auto range = seqs.equal_range(t);
for (auto it = range.first; it != range.second; ++it)
if (it->second.empty()) return true;
return false;
}
return bit(singles, t);
}
/* 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. */
static std::string utf8_prefix(const std::string& s, size_t max) {
if (s.size() <= max) return s;
size_t n = max;
while (n > 0 && ((unsigned char)s[n] & 0xC0u) == 0x80u) --n;
return s.substr(0, n);
}
int dry_prepare_breakers(const VocabView& vocab, const std::vector<std::string>& breakers,
DryBreakers* out, int max_tail_len) {
if (!out) return RAD_E_INVAL;
out->seqs.clear();
out->heads.clear();
out->singles.clear();
if (breakers.empty()) return RAD_OK;
if (breakers.size() > kDryMaxBreakers) {
RAD_WARN("dry: %zu sequence breakers, more than the %zu the breaker scan accepts",
breakers.size(), kDryMaxBreakers);
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. */
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
* 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);
for (int32_t id = 0; id < n; ++id) {
const std::string& word = vocab.token_piece(id);
if (word.find(str) != std::string::npos) {
out->seqs.emplace(id, std::vector<int32_t>());
continue;
}
size_t pos = std::string::npos;
while ((pos = word.find(str[0], pos + 1)) != std::string::npos) {
bool match = true;
size_t i = 1;
for (; i < str.size() && i + pos < word.size(); ++i) {
if (word[pos + i] != str[i]) { match = false; break; }
}
if (!match) continue;
if (!have[i]) {
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. */
RAD_WARN("dry: sequence breaker \"%s\" does not tokenise (%s)",
str.c_str(), rad_strerror(st));
out->seqs.clear();
return st;
}
if (max_tail_len >= 0 && (int)fresh.size() > max_tail_len)
fresh.resize((size_t)max_tail_len);
have[i] = 1;
}
const std::vector<int32_t>& tail = tail_at[i];
bool dup = false;
auto range = out->seqs.equal_range(id);
for (auto it = range.first; it != range.second; ++it)
if (it->second == tail) { dup = true; break; }
if (!dup) out->seqs.emplace(id, tail);
}
}
}
out->index(n);
return RAD_OK;
}
int dry_rep_limit(const DryBreakers& breakers, const int32_t* window, int n) {
if (!window || n <= 0) return n > 0 ? n : 0;
if (breakers.empty()) return n;
/* rat(i): the i-th token counting back from the end of the window. */
auto rat = [&](int i) -> int32_t { return window[n - 1 - i]; };
for (int i = 0; i < n; ++i) {
const int32_t tok = rat(i);
if (!breakers.is_head(tok)) continue;
int longest = -1;
auto its = breakers.seqs.equal_range(tok);
for (auto it = its.first; it != its.second; ++it) {
const int seq_len = (int)it->second.size();
if (seq_len <= longest || seq_len > i) continue;
bool match = true;
for (int off = 0; off < seq_len; ++off) {
if (it->second[(size_t)off] != rat(i - off - 1)) { match = false; break; }
}
if (match) longest = seq_len;
}
if (longest >= 0) return i - longest;
}
return n;
}
void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
int64_t total_context, const DryParams& p, const DryBreakers& breakers) {
if (p.multiplier == 0.0f || p.base < 1.0f || p.penalty_last_n == 0) return;
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);
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. */
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. */
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. */
{
const int last = n_rep - 1;
int rt = 0, lt = 0;
for (int k = 1; k < n_rep; ++k) {
if (k > rt) {
int n = 0;
while (n + k < n_rep && rat(n) == rat(n + k)) ++n;
repeat_count[(size_t)(last - k)] = std::min(n, rep_limit);
if (n > 0) { lt = k; rt = k + n - 1; }
} else {
const int pi = k - lt;
const int right_part_len = rt - k + 1;
if (repeat_count[(size_t)(last - pi)] < right_part_len) {
repeat_count[(size_t)(last - k)] =
std::min(repeat_count[(size_t)(last - pi)], rep_limit);
} else {
int i = rt + 1;
while (i < n_rep && rat(i) == rat(i - k)) ++i;
repeat_count[(size_t)(last - k)] = std::min(i - k, rep_limit);
lt = k; rt = i - 1;
}
}
}
}
/* 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. */
for (int i = 0; i < n_rep - 1; ++i) {
const int len = repeat_count[(size_t)i];
if (len < p.allowed_length) continue;
const int32_t tok = rat(n_rep - 2 - i);
auto it = max_token_repeat.find(tok);
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;
int max_exponent = 0;
if (p.base > 1.000001f) max_exponent = (int)(FLOAT_MAX_LOG / 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. */
if (breakers.is_single(e.id)) continue;
int exp_n = it->second - p.allowed_length;
if (max_exponent > 0 && exp_n > max_exponent) exp_n = max_exponent;
e.logit -= p.multiplier * std::pow(p.base, (float)exp_n);
}
s.sorted = false;
}
/* ------------------------------------------------------------------ XTC */
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;
/* 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. */
if (rng_uniform(seed, pos, RAD_RNG_XTC) >= probability) return;
host_softmax(s, true);
size_t pos_last = 0;
for (size_t i = 0; i < s.c.size(); ++i) {
if (s.c[i].p >= threshold) pos_last = i;
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. */
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);
}
/* ------------------------------------------------------------------ the grammar mask */
void host_mask(CandidateSet& s, const uint32_t* bitmask, int64_t n_words) {
if (!bitmask) return;
for (auto& e : s.c) {
const int64_t w = (int64_t)e.id >> 5;
if (w >= n_words) { e.logit = -INFINITY; continue; }
if (!(bitmask[w] & (1u << ((uint32_t)e.id & 31u)))) e.logit = -INFINITY;
}
s.sorted = false;
}
/* ------------------------------------------------------------------ the pick */
int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos) {
if (s.c.empty()) { s.selected = -1; return -1; }
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. */
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. */
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) {
if (s.c[a].logit != s.c[b].logit) return s.c[a].logit > s.c[b].logit;
return s.c[a].id < s.c[b].id;
});
double total = 0.0;
for (size_t i : order) total += std::exp((double)s.c[i].logit - (double)max_l);
if (!(total > 0.0)) { s.selected = -1; return -1; }
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. */
double acc = 0.0;
size_t chosen = order.front();
for (size_t i : order) {
if (!(s.c[i].logit > -INFINITY)) continue;
chosen = i;
acc += std::exp((double)s.c[i].logit - (double)max_l);
if (acc >= want) break;
}
for (size_t i = 0; i < s.c.size(); ++i)
s.c[i].p = (float)(std::exp((double)s.c[i].logit - (double)max_l) / total);
s.selected = (int)chosen;
return s.c[chosen].id;
}
int32_t host_argmax(const float* logits, int64_t n_vocab) {
if (!logits || n_vocab <= 0) return -1;
int64_t best = 0;
for (int64_t i = 1; i < n_vocab; ++i)
if (logits[i] > logits[best]) best = i; /* strict >, so a tie keeps the lowest id */
return (int32_t)best;
}
/* ================================================================== 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. */
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) {
DryParams dp;
dp.multiplier = sp.dry_multiplier;
dp.base = sp.dry_base;
dp.allowed_length = sp.dry_allowed_length;
dp.penalty_last_n = sp.dry_penalty_last_n;
host_dry(s, in.history, in.n_history, in.total_context, dp, *in.dry_breakers);
}
/* 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. */
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 (order == ChainOrder::Radiance) {
host_temp(s, sp.temp);
host_mask(s, in.bitmask, in.n_words);
host_top_k(s, sp.top_k);
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);
} 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. */
host_mask(s, in.bitmask, in.n_words);
host_top_k(s, sp.top_k);
host_typical(s, sp.typical_p, 1);
host_top_p(s, sp.top_p, 1);
host_min_p(s, sp.min_p, 1);
host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos);
host_temp(s, sp.temp);
}
return host_pick(s, sp.seed, in.pos);
}
int32_t host_sample(const float* logits, int64_t n_vocab, const SamplingParams& sp,
const HostRefInput& in, ChainOrder order) {
if (!logits || n_vocab <= 0) return -1;
CandidateSet s;
s.from_logits(logits, n_vocab);
return host_sample_into(s, sp, in, order);
}
} /* namespace rad */
+246
View File
@@ -0,0 +1,246 @@
/* 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.
*
* 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.
*
* TWO THINGS DEVIATE FROM UPSTREAM, DELIBERATELY.
*
* 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. 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.
*/
#pragma once
#include "../rad_core.h"
#include "vocab_view.h"
#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>
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. */
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. */
struct CandidateSet {
std::vector<Candidate> c;
bool sorted = false;
int selected = -1; /* index into c, set by the pick; -1 until then */
void from_logits(const float* logits, int64_t n_vocab);
void sort_desc(); /* descending logit, ties broken by ascending id */
size_t size() const { return c.size(); }
};
/* ================================================================== 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.
*
* `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. */
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 */
};
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. */
float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream);
/* ================================================================== individual samplers */
/* Upstream: llama_sampler_softmax_impl. Fills `p` and normalises. */
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. */
void host_temp(CandidateSet& s, float temp);
/* Upstream: llama_sampler_top_k_impl. k <= 0 is off. */
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. */
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. */
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. */
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.
*
* `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. */
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 */
std::vector<uint32_t> singles; /* bit t: token t is a whole breaker by itself */
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. */
void index(int32_t n_vocab);
bool is_head(int32_t t) const;
bool is_single(int32_t t) const;
private:
static bool bit(const std::vector<uint32_t>& v, int32_t t) {
if (t < 0 || (size_t)(t >> 5) >= v.size()) return false;
return (v[(size_t)(t >> 5)] >> ((uint32_t)t & 31u)) & 1u;
}
};
/* 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. */
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. */
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. */
int dry_rep_limit(const DryBreakers& breakers, const int32_t* window, int n);
struct DryParams {
float multiplier = 0.0f;
float base = 1.75f;
int32_t allowed_length = 2;
int32_t penalty_last_n = -1; /* -1 = the whole context */
};
/* Upstream: llama_sampler_dry_apply, Z-algorithm and all. Ported from Koboldcpp originally
* (LostRuins/koboldcpp#982, author pi6am) by way of llama.cpp. */
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. */
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). */
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. */
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. */
int32_t host_argmax(const float* logits, int64_t n_vocab);
/* ================================================================== the chain */
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. */
struct HostRefInput {
const int32_t* history = nullptr; /* the sequence's tokens so far, oldest first */
int64_t n_history = 0;
int64_t total_context = 0; /* DRY's clamp; 0 means use n_history */
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;
};
/* 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. */
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. */
int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
ChainOrder order = ChainOrder::Radiance);
} /* namespace rad */
+925
View File
@@ -0,0 +1,925 @@
/* 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.
*/
#include "sampler.h"
#include "gbnf.h"
#include <algorithm>
#include <chrono>
#include <cstring>
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.
*
* 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 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. */
static int resolve_triggers(const VocabView& vocab,
const std::vector<SamplingParams::GrammarTrigger>& triggers,
std::vector<std::string>* words, std::vector<int32_t>* tokens,
std::string* err) {
words->clear();
tokens->clear();
for (const auto& t : triggers) {
if (t.value.empty()) continue;
std::vector<int32_t> ids;
switch (t.type) {
case 0: /* token: the spelling of exactly one token */
case 1: { /* word */
const int st = vocab.tokenize_special(t.value, &ids);
if (st < 0) {
if (err) *err = "grammar trigger '" + t.value + "' could not be tokenised";
return st;
}
if (ids.size() == 1) { tokens->push_back(ids[0]); break; }
if (t.type == 0) {
if (err) *err = "grammar trigger token '" + t.value +
"' is not a single token in this vocabulary";
return RAD_E_INVAL;
}
words->push_back(t.value);
break;
}
case 2: /* pattern */
case 3: /* pattern_full */
if (err) *err = "this chat template triggers its tool-call grammar on the "
"regular expression '" + t.value + "'; only word and token "
"triggers are supported";
return RAD_E_UNSUPPORTED;
default:
if (err) *err = "unknown grammar trigger type " + std::to_string(t.type);
return RAD_E_INVAL;
}
}
return RAD_OK;
}
/* ================================================================== 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. */
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);
if ((cfg_.vocab_off & 31) == 0) {
const int64_t w0 = cfg_.vocab_off >> 5;
const int64_t n = std::min(mask_words_, full - w0);
if (n > 0) std::memcpy(dst, mask_full_.data() + w0, (size_t)n * 4);
return;
}
for (int64_t i = 0; i < cfg_.n_vocab_local; ++i) {
const int64_t g = cfg_.vocab_off + i;
if (g >= cfg_.n_vocab) break;
if (mask_full_[(size_t)(g >> 5)] & (1u << (uint32_t)(g & 31)))
dst[i >> 5] |= 1u << (uint32_t)(i & 31);
}
}
/* 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.
*
* `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. */
static RadOperand opd_rows(rad_buf h, int64_t rows) {
RadOperand o{};
o.kind = RAD_OPK_BUF;
o.handle = h;
o.rows = 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. */
static RadOperand opd_none() {
RadOperand o{};
o.kind = RAD_OPK_NONE;
return o;
}
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). */
return c.max_seqs * (int64_t)(c.max_spec + 1);
}
/* ================================================================== declare */
int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
if (!b) return RAD_E_INVAL;
if (cfg.n_vocab <= 0 || cfg.max_seqs <= 0) {
RAD_ERR("sampler: n_vocab=%lld max_seqs=%lld is not a configuration",
(long long)cfg.n_vocab, (long long)cfg.max_seqs);
return RAD_E_INVAL;
}
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. */
mask_words_ = grammar_mask_words(cfg_.n_vocab_local);
mask_full_.assign((size_t)grammar_mask_words(cfg_.n_vocab), 0u);
const int64_t rows = rows_for(cfg_);
const int64_t nv = cfg_.n_vocab_local;
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. */
auto decl = [&](const char* name, uint32_t dt, int64_t d0, int64_t d1, int kind) -> rad_buf {
RadBufDecl d{};
d.dtype = dt;
d.rank = 2;
d.shape[0] = d0;
d.shape[1] = d1;
d.kind = kind;
d.domain = RAD_DOMAIN_DEVICE;
return rad_decl_buffer(b, name, &d);
};
buf_params_ = decl("sampler.params", 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. */
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. */
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);
}
if (!buf_params_ || !buf_hist_ || !buf_brk_ || !buf_mask_ || !buf_cand_i_ || !buf_cand_v_) {
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). */
auto op_vocab = [&](const char* name) -> rad_op {
RadParam p[2] = {
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
RadParam{ "n_vocab", RAD_P_INT, (long long)nv, 0, nullptr },
};
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. */
auto op_vocab_off = [&](const char* name) -> rad_op {
if (!vocab_parallel())
return op_vocab(name);
RadParam p[3] = {
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
RadParam{ "n_vocab", RAD_P_INT, (long long)nv, 0, nullptr },
RadParam{ "vocab_off", RAD_P_INT, (long long)cfg_.vocab_off, 0, nullptr },
};
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. */
auto op_cand = [&](const char* name) -> rad_op {
RadParam p[2] = {
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
RadParam{ "n_cand", RAD_P_INT, (long long)ncand, 0, nullptr },
};
return rad_decl_op(b, name, p, 2, nullptr, 0);
};
op_penalties_ = op_vocab_off("sample_penalties");
op_dry_ = op_vocab_off("sample_dry");
op_temp_ = op_vocab("sample_temp");
op_mask_ = op_vocab("sample_mask");
op_topk_ = op_vocab_off("sample_topk");
op_argmax_ = op_vocab("sample_argmax");
op_topp_ = op_cand("sample_topp");
op_minp_ = op_cand("sample_minp");
op_typical_ = op_cand("sample_typical");
op_xtc_ = op_cand("sample_xtc");
op_pick_ = op_cand("sample_pick");
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). */
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. */
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");
}
RAD_TRY(stage_alloc());
declared_ = true;
RAD_INFO("sampler: %lld-token vocabulary (%lld this rank), %lld rows, %lld mask words "
"(%s per row)", (long long)cfg_.n_vocab, (long long)nv, (long long)rows,
(long long)mask_words_, humanb(mask_words_ * 4).c_str());
return RAD_OK;
}
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). */
params_stage_ = (DeviceSampleParams*)rad_dev_alloc(
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc(
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
greedy_ready_ = false;
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
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);
if (!params_stage_ || !greedy_stage_ || !hist_stage_ || !brk_stage_ || !mask_stage_) {
RAD_ERR("sampler: could not pin %s of staging",
humanb(rows * ((int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
mask_words_ * 4)).c_str());
stage_free();
return RAD_E_NOMEM;
}
return RAD_OK;
}
void Sampler::stage_free() {
if (params_stage_) rad_dev_free(params_stage_, RAD_MEM_HOST_PINNED);
if (greedy_stage_) rad_dev_free(greedy_stage_, RAD_MEM_HOST_PINNED);
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
params_stage_ = nullptr;
greedy_stage_ = nullptr;
cur_stage_ = nullptr;
hist_stage_ = nullptr;
brk_stage_ = nullptr;
mask_stage_ = nullptr;
}
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. */
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);
}
static bool dry_on(const SamplingParams& sp) {
return sp.dry_multiplier > 0.0f && sp.dry_base >= 1.0f && sp.dry_penalty_last_n != 0;
}
int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
auto refuse = [&](const char* what, int st) {
if (why) *why = what;
return st;
};
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);
/* 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. */
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()) +
" entries; at most " + std::to_string(kDryMaxBreakers) + " are accepted";
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. */
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 top-k, the merge and the pick that build_step's top_k = 1 sends
* it through. Admission has to check what will actually be issued. */
const bool greedy_chain = sp.greedy() && vocab_parallel();
const char* missing = nullptr;
if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax");
if (!missing) missing = need(!sp.greedy(), 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. */
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");
if (!missing) missing = need(sp.typical_p < 1.0f, op_typical_, "sample_typical");
if (!missing) missing = need(sp.xtc_probability > 0.0f, op_xtc_, "sample_xtc");
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
if (!missing) missing = need(!sp.grammar.empty(), op_mask_, "sample_mask");
if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties");
if (missing) {
if (why) *why = std::string("no kernel resolved for '") + missing + "'";
return RAD_E_NOKERNEL;
}
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()) {
std::vector<std::string> words;
std::vector<int32_t> tokens;
std::string e;
const int st = resolve_triggers(*vocab_, sp.grammar_triggers, &words, &tokens, &e);
if (st < 0) {
if (why) *why = e;
return st;
}
}
return RAD_OK;
}
int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::string* err) {
SeqState st;
if (!sp.grammar.empty()) {
if (!vocab_) {
if (err) *err = "no vocabulary attached";
return RAD_E_STATE;
}
GrammarSpec spec;
spec.kind = GrammarKind::Gbnf;
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. */
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. */
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. */
const int s = dry_prepare_breakers(*vocab_, sp.dry_seq_breakers, &st.dry,
kDryBreakerMaxTail);
if (s < 0) {
if (err) *err = "a DRY sequence breaker could not be resolved against the vocabulary";
return s;
}
}
seqs_[req_id] = std::move(st);
return RAD_OK;
}
void Sampler::end_request(uint64_t req_id) { seqs_.erase(req_id); }
bool Sampler::has_request(uint64_t req_id) const { return seqs_.find(req_id) != seqs_.end(); }
std::vector<uint64_t> Sampler::take_failed() {
std::vector<uint64_t> v;
v.swap(failed_);
return v;
}
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. */
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);
accept_us_ += std::chrono::duration<double, std::micro>(
std::chrono::steady_clock::now() - t0).count();
if (++accept_n_ == 256) {
RAD_DEBUG("sampler: grammar accept_token %.3f ms mean over 256", accept_us_ / 256000.0);
accept_us_ = 0; accept_n_ = 0;
}
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. */
bool Sampler::allows_speculation(uint64_t req_id) const {
auto it = seqs_.find(req_id);
if (it == seqs_.end() || !it->second.grammar) return true;
return !it->second.grammar->constrains() || it->second.grammar->can_speculate();
}
bool Sampler::speculation_fixed(uint64_t req_id) const {
auto it = seqs_.find(req_id);
return it != seqs_.end() && (!it->second.grammar || it->second.grammar->can_speculate());
}
/* ================================================================== the step path */
int Sampler::build_step(const std::vector<Request*>& reqs) {
if (!declared_) return RAD_E_STATE;
const auto t_build = std::chrono::steady_clock::now();
const int64_t cap = rows_for(cfg_);
n_seq_ = 0;
any_brk_ = false;
cur_stage_ = params_stage_;
/* 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.
*
* 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. */
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;
const int64_t win = last_n > 0 ? std::min<int64_t>(take, last_n) : take;
const int64_t w0 = take - win;
const int32_t allowed = p.dry_allowed_length > 0 ? p.dry_allowed_length : 2;
uint8_t* f = brk_stage_ + row * cfg_.max_hist + w0;
if (!brk) {
std::memset(f, 0, (size_t)win);
return true;
}
if (win <= allowed) return true; /* the kernel takes its own early out */
const int rep = dry_rep_limit(*brk, h + w0, (int)win);
if (rep < allowed) return false;
p.dry_rep_limit = rep < win ? rep : 0;
for (int64_t i = 0; i < win; ++i) f[i] = brk->is_single(h[w0 + i]) ? 1 : 0;
any_brk_ = true;
return true;
};
for (Request* r : reqs) {
if (!r) continue;
const SamplingParams& sp = r->sp;
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);
return RAD_E_UNSUPPORTED;
}
if (n_seq_ + n_pos > cap) {
RAD_ERR("sampler: %lld sampled positions exceeds the %lld the arena was sized for",
(long long)(n_seq_ + n_pos), (long long)cap);
return RAD_E_FULL;
}
const int64_t n_prompt = (int64_t)r->prompt.size();
const int64_t n_out = (int64_t)r->output.size();
const int64_t n_total = n_prompt + n_out;
const bool pen = penalties_on(sp);
const bool dry = dry_on(sp);
auto it = seqs_.find(r->id);
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.
*
* `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. */
GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr;
const bool walk = gr && n_pos > 1;
if (walk) gr->push_state();
bool dead = false;
for (int k = 0; k < n_pos; ++k) {
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
const int64_t row = n_seq_++;
DeviceSampleParams& p = params_stage_[row];
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. */
p.pos = (uint64_t)(n_out + k);
p.temp = sp.temp;
p.top_p = sp.top_p;
p.min_p = sp.min_p;
p.typical_p = sp.typical_p;
p.rep_penalty = sp.rep_penalty;
p.freq_penalty = sp.freq_penalty;
p.pres_penalty = sp.pres_penalty;
p.xtc_probability = sp.xtc_probability;
p.xtc_threshold = sp.xtc_threshold;
p.dry_multiplier = sp.dry_multiplier;
p.dry_base = sp.dry_base;
p.top_k = sp.top_k;
p.penalty_last_n = sp.penalty_last_n;
p.dry_allowed_length = sp.dry_allowed_length;
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.
*
* 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. */
if (sp.greedy()) {
if (vocab_parallel()) p.top_k = 1;
else p.flags |= RAD_SP_GREEDY;
}
if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC;
/* 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;
if (pen || dry) {
const int64_t len = n_total + k;
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
int32_t* h = hist_stage_ + row * cfg_.max_hist;
for (int64_t i = 0; i < take; ++i) {
const int64_t src = len - take + i;
h[i] = src < n_prompt ? r->prompt[(size_t)src]
: src < n_total ? r->output[(size_t)(src - n_prompt)]
: r->draft[src - n_total];
}
p.hist_len = (int32_t)take;
if (pen) p.flags |= RAD_SP_PENALTY;
if (dry && stage_dry(p, h, take, brk, row)) p.flags |= RAD_SP_DRY;
}
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. */
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. */
const uint64_t w0 = inst ? st->grammar->masks_walked() : 0;
if (!vocab_parallel()) {
s = st->grammar->fill_mask(dst, mask_words_);
} else {
s = st->grammar->fill_mask(mask_full_.data(), (int64_t)mask_full_.size());
if (s >= 0) shard_mask(dst);
}
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;
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. */
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)",
mask_us_ / 256000.0, mask_worst_us_ / 1000.0,
(long long)mask_fast_, (long long)mask_slow_,
mask_slow_ ? mask_walk_us_ / (1000.0 * (double)mask_slow_) : 0.0,
(long long)cfg_.n_vocab, (long long)mask_words_);
mask_us_ = 0; mask_us_n_ = 0; mask_worst_us_ = 0;
mask_fast_ = 0; mask_slow_ = 0; mask_walk_us_ = 0.0;
}
}
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. */
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. */
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);
} else {
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. */
int64_t bits = 0;
for (int64_t w = 0; w < mask_words_; ++w)
bits += __builtin_popcount(dst[w]);
RAD_TRACE("sampler: req %llu row %lld mask allows %lld of %lld local "
"tokens (vocab_off %lld)", (unsigned long long)r->id,
(long long)row, (long long)bits,
(long long)cfg_.n_vocab_local, (long long)cfg_.vocab_off);
}
}
}
}
/* 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. */
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. */
if ((int)log_level() >= (int)Log::Debug) {
build_us_ += std::chrono::duration<double, std::micro>(
std::chrono::steady_clock::now() - t_build).count();
if (++build_n_ == 256) {
RAD_DEBUG("sampler: build_step %.3f ms mean over 256 (%lld rows)",
build_us_ / 256000.0, (long long)n_seq_);
build_us_ = 0; build_n_ = 0;
}
}
return RAD_OK;
}
int Sampler::build_greedy(int64_t n) {
if (!declared_) return RAD_E_STATE;
if (n < 0) return RAD_E_INVAL;
const int64_t cap = rows_for(cfg_);
if (n > cap) {
RAD_ERR("sampler: %lld greedy rows exceeds the %lld the arena was sized for",
(long long)n, (long long)cap);
return RAD_E_FULL;
}
n_seq_ = n;
any_brk_ = 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. */
p.flags = vocab_parallel() ? 0 : RAD_SP_GREEDY;
}
greedy_ready_ = true;
return RAD_OK;
}
int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
if (!declared_) return RAD_E_STATE;
if (!c || !logits || !out_tokens) return RAD_E_INVAL;
if (n_seq_ == 0) return RAD_OK;
const RadStream s = rad_stream(c);
bool any_mask = false, any_greedy = false, any_chain = false;
bool any_penalty = false, any_dry = false, any_xtc = false;
bool any_topp = false, any_minp = false, any_typ = false;
for (int64_t i = 0; i < n_seq_; ++i) {
const DeviceSampleParams& p = cur_stage_[i];
any_mask |= (p.flags & RAD_SP_MASK) != 0;
any_penalty |= (p.flags & RAD_SP_PENALTY) != 0;
any_dry |= (p.flags & RAD_SP_DRY) != 0;
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
if (p.flags & RAD_SP_GREEDY) any_greedy = true;
else {
any_chain = true;
any_topp |= p.top_p < 1.0f;
any_minp |= p.min_p > 0.0f;
any_typ |= p.typical_p < 1.0f;
}
}
/* 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. */
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). */
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_,
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
if (any_penalty || any_dry)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_,
n_seq_ * cfg_.max_hist * 4, s));
const bool pass_brk = any_dry && any_brk_;
if (pass_brk)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_,
n_seq_ * cfg_.max_hist, s));
if (any_mask)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_,
n_seq_ * mask_words_ * 4, s));
const RadOperand o_logits = opd_rows(logits, n_seq_);
const RadOperand o_params = opd_rows(buf_params_, n_seq_);
const RadOperand o_hist = opd_rows(buf_hist_, n_seq_);
const RadOperand o_brk = opd_rows(buf_brk_, n_seq_);
const RadOperand o_mask = opd_rows(buf_mask_, n_seq_);
const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_);
const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_);
const RadOperand o_tok = opd_rows(out_tokens, n_seq_);
auto issue = [&](rad_op op, std::initializer_list<RadOperand> ops) -> int {
std::vector<RadOperand> v(ops);
return rad_issue(c, op, v.data(), (int)v.size(), 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. */
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. */
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 }));
}
if (!any_chain) return RAD_OK;
RAD_TRY(issue(op_temp_, { o_logits, o_params }));
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. */
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. */
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. */
RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, opd_none() }));
}
if (any_topp) RAD_TRY(issue(op_topp_, { o_ci, o_cv, o_params }));
if (any_minp) RAD_TRY(issue(op_minp_, { o_ci, o_cv, o_params }));
if (any_typ) RAD_TRY(issue(op_typical_, { o_ci, o_cv, o_params }));
if (any_xtc) RAD_TRY(issue(op_xtc_, { o_ci, o_cv, o_params }));
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
return RAD_OK;
}
} /* namespace rad */
+306
View File
@@ -0,0 +1,306 @@
/* 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.
*
* THE ORDER, and it is not a detail -- reordering changes which tokens survive:
*
* penalties (repetition / frequency / presence, then DRY)
* temperature
* the grammar mask
* top-k
* top-p, min-p, typical
* XTC
* the pick
*
* 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.
*
* 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.
*
* 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
* 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:
*
* 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?
* -> logits (inout)
* sample_temp M(range) n_vocab logits, params -> logits (inout)
* sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout)
* sample_topk M(range) n_vocab vocab_off? logits, params -> cand_idx, cand_val,
* pairs?
* sample_argmax M(range) n_vocab logits, params -> token
* sample_topp M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val
* sample_minp M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val
* sample_typical M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val
* sample_xtc M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val
* sample_pick M(range) n_cand cand_idx, cand_val, params -> token
* sample_merge_topk M(range) n_cand gathered, params -> cand_idx, cand_val
*
* `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).
*/
#pragma once
#include "rad_sample.h"
#include "../rad_core.h"
#include "grammar.h"
#include "host_ref.h"
#include "vocab_view.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
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. */
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 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. */
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;
};
/* ================================================================== the driver */
class Sampler {
public:
Sampler() = default;
~Sampler();
/* ---------------------------------------------------------- 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. */
int declare(RadBuilder* b, const SamplerConfig& cfg);
/* The vocabulary view 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. */
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. */
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. */
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. */
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. */
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. */
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). */
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. */
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. */
int run(RadCtx* c, rad_buf logits, rad_buf out_tokens);
/* 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. */
const DeviceSampleParams* staged_params(int64_t* n) const {
if (n) *n = n_seq_;
return cur_stage_;
}
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. */
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. */
struct SeqState {
std::unique_ptr<GrammarBackend> grammar;
DryBreakers dry;
};
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. */
rad_op op_penalties_ = RAD_NULL_HANDLE;
rad_op op_dry_ = RAD_NULL_HANDLE;
rad_op op_temp_ = RAD_NULL_HANDLE;
rad_op op_mask_ = RAD_NULL_HANDLE;
rad_op op_topk_ = RAD_NULL_HANDLE;
rad_op op_topp_ = RAD_NULL_HANDLE;
rad_op op_minp_ = RAD_NULL_HANDLE;
rad_op op_typical_ = RAD_NULL_HANDLE;
rad_op op_xtc_ = RAD_NULL_HANDLE;
rad_op op_pick_ = RAD_NULL_HANDLE;
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 */
/* Device-side buffers, from the ordinary buffer plan. */
rad_buf buf_params_ = RAD_NULL_HANDLE;
rad_buf buf_hist_ = RAD_NULL_HANDLE;
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
rad_buf buf_mask_ = RAD_NULL_HANDLE;
rad_buf buf_cand_i_ = RAD_NULL_HANDLE;
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
rad_buf buf_gather_ = RAD_NULL_HANDLE;
rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */
/* Pinned staging. One allocation each, at declare, never on the step path. */
DeviceSampleParams* params_stage_ = nullptr;
/* 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. */
DeviceSampleParams* greedy_stage_ = nullptr;
bool greedy_ready_ = false;
const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */
int32_t* hist_stage_ = nullptr;
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 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. */
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(). */
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. */
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 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. */
std::vector<uint64_t> failed_;
/* 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. */
std::unordered_map<uint64_t, SeqState> seqs_;
int stage_alloc();
void stage_free();
};
} /* namespace rad */
+134
View File
@@ -0,0 +1,134 @@
/* vocab_view.h -- what the sampler needs to know about a vocabulary, and nothing else.
*
* 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.
*
* core/text/ implements this over the real vocab; SimpleVocab below implements it over a table,
* which is what the tests use.
*/
#pragma once
#include "../rad_internal.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace rad {
class VocabView {
public:
virtual ~VocabView() = default;
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. */
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
* only when some stack has run to completion. */
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. */
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. */
virtual int tokenize_special(const std::string& text, std::vector<int32_t>* out) const {
(void)text; (void)out;
return RAD_E_UNSUPPORTED;
}
/* ---------------- 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. */
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. */
class SimpleVocab : public VocabView {
public:
SimpleVocab() = default;
explicit SimpleVocab(std::vector<std::string> pieces) : pieces_(std::move(pieces)) {}
int32_t add(std::string piece, bool eog = false) {
int32_t id = (int32_t)pieces_.size();
pieces_.push_back(std::move(piece));
if (eog) eog_.push_back(id);
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 {
static const std::string empty;
if (id < 0 || id >= (int32_t)pieces_.size()) return empty;
return pieces_[id];
}
bool is_eog(int32_t id) const override {
for (int32_t e : eog_) if (e == id) return true;
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);
}
int tokenize(const std::string& text, std::vector<int32_t>* out) const override {
if (!out) return RAD_E_INVAL;
size_t pos = 0;
while (pos < text.size()) {
int32_t best = -1;
size_t best_len = 0;
for (int32_t id = 0; id < (int32_t)pieces_.size(); ++id) {
const std::string& p = pieces_[id];
if (p.empty() || p.size() <= best_len) continue;
if (text.compare(pos, p.size(), p) == 0) { best = id; best_len = p.size(); }
}
if (best < 0) return RAD_E_NOTFOUND;
out->push_back(best);
pos += best_len;
}
return RAD_OK;
}
private:
std::vector<std::string> pieces_;
std::vector<int32_t> eog_;
};
} /* namespace rad */
+77
View File
@@ -0,0 +1,77 @@
/* word_scan.cpp -- the Aho-Corasick build behind word_scan.h. */
#include "word_scan.h"
#include <algorithm>
namespace rad {
int WordScanner::build(const std::vector<std::string>& words, std::string* err) {
for (size_t i = 0; i < words.size(); ++i) {
if (words[i].empty()) {
if (err) *err = "trigger word " + std::to_string(i) + " is empty";
return RAD_E_INVAL;
}
}
/* Byte classes: one per distinct byte the words use, and class 0 for every other byte. */
std::fill(cls_, cls_ + 256, (uint8_t)0);
ncls_ = 1;
for (const std::string& w : words)
for (unsigned char c : w)
if (cls_[c] == 0) {
if (ncls_ == 256) {
if (err) *err = "the trigger words use more distinct bytes than a class holds";
return RAD_E_INVAL;
}
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. */
constexpr uint32_t kUnset = ~0u;
next_.assign(ncls_, kUnset);
out_len_.assign(1, 0u);
max_len_ = 0;
for (const std::string& w : words) {
uint32_t s = 0;
for (unsigned char c : w) {
uint32_t& e = next_[(size_t)s * ncls_ + cls_[c]];
if (e == kUnset) {
e = (uint32_t)out_len_.size();
out_len_.push_back(0u);
next_.resize(next_.size() + ncls_, kUnset);
}
s = next_[(size_t)s * ncls_ + cls_[c]];
}
out_len_[s] = (uint32_t)w.size();
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. */
const uint32_t n_states = (uint32_t)out_len_.size();
std::vector<uint32_t> fail(n_states, 0u);
std::vector<uint32_t> queue;
queue.reserve(n_states);
for (uint32_t c = 0; c < ncls_; ++c) {
uint32_t& e = next_[c];
if (e == kUnset) { e = 0; continue; }
fail[e] = 0;
queue.push_back(e);
}
for (size_t qi = 0; qi < queue.size(); ++qi) {
const uint32_t s = queue[qi];
if (out_len_[s] == 0) out_len_[s] = out_len_[fail[s]];
for (uint32_t c = 0; c < ncls_; ++c) {
uint32_t& e = next_[(size_t)s * ncls_ + c];
const uint32_t via_fail = next_[(size_t)fail[s] * ncls_ + c];
if (e == kUnset) { e = via_fail; continue; }
fail[e] = via_fail;
queue.push_back(e);
}
}
return RAD_OK;
}
} /* namespace rad */
+75
View File
@@ -0,0 +1,75 @@
/* 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.
*
* 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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
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. */
struct State {
uint32_t s = 0;
uint64_t off = 0;
};
/* Compile `words`. Every word must be non-empty; RAD_E_INVAL names the first that is not.
* An empty set builds a scanner that never matches. */
int build(const std::vector<std::string>& words, std::string* err);
bool empty() const { return max_len_ == 0; }
uint32_t max_len() const { return max_len_; }
/* Advance over `n` bytes. Returns the stream offset at which the leftmost occurrence that
* completes within these bytes begins, or npos when none completes. */
uint64_t feed(State& st, const char* p, size_t n) const {
uint64_t best = npos;
uint32_t s = st.s;
uint64_t off = st.off;
for (size_t i = 0; i < n; ++i) {
s = next_[(size_t)s * ncls_ + cls_[(uint8_t)p[i]]];
++off;
const uint32_t len = out_len_[s];
if (len && off - len < best) best = off - len;
}
st.s = s;
st.off = off;
return best;
}
private:
uint8_t cls_[256] = {};
uint32_t ncls_ = 1;
uint32_t max_len_ = 0;
std::vector<uint32_t> next_{ 0u }; /* [state * ncls_ + class] -> state */
std::vector<uint32_t> out_len_{ 0u }; /* longest word ending in the state, 0 for none */
};
} /* namespace rad */