Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+221
-315
@@ -1,5 +1,5 @@
|
||||
/* sampler.cpp -- the sampler driver: declare the sampler ops, build the per-sequence parameter
|
||||
* array once per step, issue the chain. No sampler is implemented here; see sampler.h for why.
|
||||
* array once per step, issue the chain. No sampler is implemented here; see sampler.h.
|
||||
*/
|
||||
#include "sampler.h"
|
||||
#include "gbnf.h"
|
||||
@@ -13,22 +13,18 @@ namespace rad {
|
||||
|
||||
/* ================================================================== grammar triggers
|
||||
*
|
||||
* A chat template names its triggers the way a person would -- "the call starts at the word
|
||||
* <tool_call>" -- while GbnfGrammar wants them in the two forms it checks as tokens arrive: token
|
||||
* ids to compare against the id just emitted, and literal words to find in the emitted bytes.
|
||||
* The translation needs a vocabulary, so it happens here and not in the server.
|
||||
* Translates a chat template's triggers into the two forms GbnfGrammar checks as tokens arrive:
|
||||
* token ids compared against the emitted id, and literal words searched in the emitted bytes.
|
||||
* This needs the vocabulary, so it happens here rather than in the server.
|
||||
*
|
||||
* A WORD IS A TOKEN WHEN THE VOCABULARY SAYS SO. The word is tokenised with special tokens
|
||||
* recognised, since a template's markers are usually special tokens and a split of `<tool_call>`
|
||||
* into `<`, `tool`, `_call`, `>` is not what the model emits. One token makes an id trigger, which
|
||||
* costs a comparison; anything longer is scanned for as bytes, because the tokeniser may split it
|
||||
* differently depending on what came before it. Getting this wrong does not fail loudly -- it
|
||||
* yields a trigger that never fires, so the call comes out unconstrained, which reads as a model
|
||||
* that writes malformed calls.
|
||||
* A word is tokenised with special tokens recognised, since template markers such as
|
||||
* `<tool_call>` are usually special tokens. If it is one token it becomes an id trigger;
|
||||
* otherwise it is matched as bytes, because the tokeniser may split it differently depending on
|
||||
* context. A wrong translation fails silently: the trigger never fires and the call comes out
|
||||
* unconstrained.
|
||||
*
|
||||
* A REGULAR-EXPRESSION TRIGGER IS REFUSED. Its matcher would run over the reply once per token
|
||||
* on the scheduler thread; the templates in service all trigger on words. A request whose
|
||||
* template needs one is refused at admission, naming the pattern. */
|
||||
* Regular-expression triggers are refused at admission, naming the pattern; their matcher would
|
||||
* run over the reply once per token on the scheduler thread. */
|
||||
static int resolve_triggers(const VocabView& vocab,
|
||||
const std::vector<SamplingParams::GrammarTrigger>& triggers,
|
||||
std::vector<std::string>* words, std::vector<int32_t>* tokens,
|
||||
@@ -69,12 +65,16 @@ static int resolve_triggers(const VocabView& vocab,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A lazy grammar waits for a trigger before it constrains anything, so one without a trigger
|
||||
* would leave the whole reply unconstrained. */
|
||||
static const char* const kLazyNoTrigger =
|
||||
"a lazy grammar needs at least one word or token trigger; without one it never constrains";
|
||||
|
||||
/* ================================================================== small helpers */
|
||||
|
||||
/* Copy this rank's window out of a whole-vocabulary bitmask. `vocab_off` is word-aligned for
|
||||
* every shard this engine builds (the head is split on a multiple of 32), so the aligned arm is
|
||||
* the one that runs; the bit-shifting arm exists because a shard boundary is a placement decision
|
||||
* and not a promise, and a mask that is silently off by a few bits admits the wrong tokens. */
|
||||
/* Copy this rank's window out of a whole-vocabulary bitmask. The engine splits the head on a
|
||||
* multiple of 32, so `vocab_off` is normally word-aligned; the bitwise path covers any other
|
||||
* shard boundary, where a misaligned copy would admit the wrong tokens. */
|
||||
void Sampler::shard_mask(uint32_t* dst) const {
|
||||
const int64_t full = (int64_t)mask_full_.size();
|
||||
std::memset(dst, 0, (size_t)mask_words_ * 4);
|
||||
@@ -92,21 +92,14 @@ void Sampler::shard_mask(uint32_t* dst) const {
|
||||
}
|
||||
}
|
||||
|
||||
/* rad_runtime.h's RAD_B / RAD_W macros are C compound literals. They are legal C++ only as a
|
||||
* compiler extension, and this file is core code that has to build with -Wall -Wextra clean, so
|
||||
* the operands are built the ordinary way. */
|
||||
/* NARROWED TO THIS STEP'S ROWS, always. arch/common/rad_arch.h says why for the model's own
|
||||
* buffers and the reason is the sampler's too: a kernel cannot read the row count out of `M`,
|
||||
* because `M` is the band's upper bound, so every shim takes it off the operand. Handed over at
|
||||
* its DECLARED extent -- max_seqs * (max_spec + 1) rows -- an operand makes every stage compute a
|
||||
* full candidate set for rows that have no request behind them, over params the upload never
|
||||
* wrote. The extra rows are discarded, so nothing downstream is wrong and no bench can see it,
|
||||
* but each phantom row costs a vocabulary-wide reduction, and at one sequence every row but one
|
||||
* is a phantom.
|
||||
/* rad_runtime.h's RAD_B / RAD_W macros are C compound literals, legal C++ only as an extension,
|
||||
* and core code builds -Wall -Wextra clean, so operands are built the ordinary way. */
|
||||
/* Operands are always narrowed to this step's rows. `M` is only the band's upper bound, so
|
||||
* kernels take the row count from the operand (arch/common/rad_arch.h); at the declared extent,
|
||||
* max_seqs * (max_spec + 1), every stage would do a vocabulary-wide reduction for each empty row.
|
||||
*
|
||||
* `rows` is dim 0 for every buffer here -- logits, params, history, mask, candidates, pairs, the
|
||||
* gather and the token output all count sampled POSITIONS first -- and the strides below it are
|
||||
* products of the trailing dimensions, so shortening the outermost one leaves them correct. */
|
||||
* Every buffer here has sampled positions as dim 0, and its strides are products of the trailing
|
||||
* dimensions, so shortening dim 0 leaves them correct. */
|
||||
static RadOperand opd_rows(rad_buf h, int64_t rows) {
|
||||
RadOperand o{};
|
||||
o.kind = RAD_OPK_BUF;
|
||||
@@ -115,9 +108,8 @@ static RadOperand opd_rows(rad_buf h, int64_t rows) {
|
||||
return o;
|
||||
}
|
||||
|
||||
/* An optional operand this issue does not pass. The runtime holds every issue to its schema's
|
||||
* operand COUNT -- operands are positional -- so an absent trailing optional is spelled, not
|
||||
* dropped. */
|
||||
/* An absent optional operand. Operands are positional and the runtime checks an issue against
|
||||
* the schema's operand count, so a missing trailing optional must be passed as this. */
|
||||
static RadOperand opd_none() {
|
||||
RadOperand o{};
|
||||
o.kind = RAD_OPK_NONE;
|
||||
@@ -125,9 +117,8 @@ static RadOperand opd_none() {
|
||||
}
|
||||
|
||||
static int64_t rows_for(const SamplerConfig& c) {
|
||||
/* One row per SAMPLED POSITION, not per sequence: a speculative verify samples n_spec+1
|
||||
* positions for a sequence and each one has its own output position, hence its own RNG
|
||||
* coordinate. Sizing for the worst step is the same rule the arena follows (spec §3.1). */
|
||||
/* One row per sampled position: a verify samples n_spec+1 positions per sequence, each with
|
||||
* its own RNG coordinate. Sized for the worst step, as the arena is (spec §3.1). */
|
||||
return c.max_seqs * (int64_t)(c.max_spec + 1);
|
||||
}
|
||||
|
||||
@@ -144,15 +135,11 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
cfg_ = cfg;
|
||||
if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size;
|
||||
|
||||
/* THE STAGED MASK IS THIS RANK'S SHARD, AND THE GRAMMAR'S IS THE WHOLE VOCABULARY. Those are
|
||||
* different lengths the moment the head is sharded, and conflating them is silent: every
|
||||
* vocab-scoped sampler op is declared over `n_vocab_local` (op_vocab, below) and `sample_mask`
|
||||
* indexes its bitmask from bit zero, so a full-vocabulary mask handed to rank 1 masks its
|
||||
* logits with the admissibility of tokens 0..n_local -- ids that belong to rank 0. The result
|
||||
* is not a diagnosable error, it is a rank sampling from the wrong permission set.
|
||||
*
|
||||
* So the grammar fills `mask_full_` over the whole vocabulary, which is also where the "no
|
||||
* token is admissible anywhere" check belongs, and only this rank's window of it is staged. */
|
||||
/* The staged mask covers this rank's shard; the grammar's covers the whole vocabulary.
|
||||
* `sample_mask` indexes its bitmask from bit zero over `n_vocab_local`, so handing rank 1 the
|
||||
* full mask would apply rank 0's token admissibility to it. The grammar therefore fills
|
||||
* `mask_full_` (where the "nothing admissible anywhere" check belongs) and only this rank's
|
||||
* window is staged. */
|
||||
mask_words_ = grammar_mask_words(cfg_.n_vocab_local);
|
||||
mask_full_.assign((size_t)grammar_mask_words(cfg_.n_vocab), 0u);
|
||||
|
||||
@@ -161,10 +148,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
const int64_t ncand = cfg_.max_candidates;
|
||||
|
||||
/* ---------------------------------------------------------- buffers */
|
||||
/* PERSIST, not TRANSIENT: the parameter, history and mask planes are written by an upload
|
||||
* that happens BEFORE the run phase issues anything, so liveness over the declared op list
|
||||
* would conclude they are dead where they are in fact being filled. A transient whose first
|
||||
* definition is invisible to the planner is a transient the planner will happily overwrite. */
|
||||
/* The staging planes are PERSIST: they are filled by an upload before any op is issued, which
|
||||
* the planner's liveness over the op list cannot see, so as TRANSIENT they would be
|
||||
* overwritten. */
|
||||
auto decl = [&](const char* name, uint32_t dt, int64_t d0, int64_t d1, int kind) -> rad_buf {
|
||||
RadBufDecl d{};
|
||||
d.dtype = dt;
|
||||
@@ -181,44 +167,39 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
buf_params_late_ = decl("sampler.params_late", RAD_U32, rows,
|
||||
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
|
||||
buf_hist_ = decl("sampler.history", RAD_I32, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
/* One byte beside every history token: nonzero where that token is a whole DRY sequence
|
||||
* breaker, which DRY never penalises. Resolving a token against the breaker strings needs the
|
||||
* vocabulary, so it happens here on the host and the kernel reads the answer. */
|
||||
/* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never
|
||||
* penalised). Resolved on the host, which has the vocabulary. */
|
||||
buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
|
||||
buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT);
|
||||
buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT);
|
||||
if (vocab_parallel()) {
|
||||
/* THE PAIR PLANE AND THE GATHERED PLANE. sample_topk packs this rank's candidates into
|
||||
* `pairs` as (u32 global id, f32 logit); the all-gather places every rank's pairs for a
|
||||
* row SIDE BY SIDE, which is the one layout the merge can read at a single row stride. */
|
||||
/* sample_topk packs this rank's candidates into `pairs` as (u32 global id, f32 logit);
|
||||
* the all-gather lays every rank's pairs for a row side by side, so the merge reads one
|
||||
* row at a single stride. */
|
||||
buf_pairs_ = decl("sampler.cand_pairs", RAD_U32, rows, ncand * 2, RAD_BUF_TRANSIENT);
|
||||
buf_gather_ = decl("sampler.cand_gathered", RAD_U32, rows,
|
||||
ncand * cfg_.world_size * 2, RAD_BUF_TRANSIENT);
|
||||
}
|
||||
|
||||
/* THE LOGPROBS SUMMARY, PERSIST for the reason the staging planes are: nothing in the
|
||||
* declared op list reads it -- rank 0 copies it to the host behind the pick -- so liveness
|
||||
* over the op list would hand its bytes to the candidate planes the stages after it write. */
|
||||
/* The logprobs summary is PERSIST too: no declared op reads it (rank 0 copies it to the host
|
||||
* behind the pick), so liveness would let the candidate planes reuse its bytes. */
|
||||
buf_lp_ = decl("sampler.logprobs", RAD_F32, rows, lp_width(), RAD_BUF_PERSIST);
|
||||
if (vocab_parallel())
|
||||
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
|
||||
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
|
||||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_) {
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_ ||
|
||||
(vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) {
|
||||
RAD_ERR("sampler: a staging buffer failed to declare");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- ops */
|
||||
/* Every one of these is declared unconditionally and may fail to resolve. That is not an
|
||||
* error here: a deployment that never sends `typical_p` has no use for a typical kernel, and
|
||||
* failing declare over it would make an absent sampler an absent model. check_request turns
|
||||
* an unresolved sampler into a named refusal at admission instead. */
|
||||
/* `M` is the ranged parameter and it is the number of SAMPLED POSITIONS, not tokens: one row
|
||||
* at decode, n_spec+1 per sequence at a verify, and a kernel written for a single row is a
|
||||
* different kernel from one written for a batch of 256 (spec §2.2). */
|
||||
/* Every op is declared unconditionally and may fail to resolve; check_request refuses the
|
||||
* requests that need a missing one. `M` is ranged over sampled positions, so a kernel may
|
||||
* specialise for one row versus a batch of 256 (spec §2.2). */
|
||||
auto op_vocab = [&](const char* name) -> rad_op {
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -226,12 +207,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
};
|
||||
return rad_decl_op(b, name, p, 2, nullptr, 0);
|
||||
};
|
||||
/* THE VOCABULARY OFFSET, on the three stages that cross between a token id and a column of
|
||||
* this rank's logits row: top-k turns a column into a token id, and the penalties and DRY turn
|
||||
* the history's token ids into columns. Without it a rank past the first penalises the
|
||||
* columns of whatever ids happen to be small, which are other tokens entirely. Declared only
|
||||
* when the vocabulary is sharded, so a single-rank graph carries no parameter it has no use
|
||||
* for. */
|
||||
/* `vocab_off` for the three stages that map between token ids and this rank's columns:
|
||||
* top-k (column to id), penalties and DRY (history id to column). Declared only when the
|
||||
* vocabulary is sharded. */
|
||||
auto op_vocab_off = [&](const char* name) -> rad_op {
|
||||
if (!vocab_parallel())
|
||||
return op_vocab(name);
|
||||
@@ -242,8 +220,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
};
|
||||
return rad_decl_op(b, name, p, 3, nullptr, 0);
|
||||
};
|
||||
/* The stages after top-k read a candidate set, not the vocabulary, so their geometry is the
|
||||
* candidate width. That is what makes them cheap: 1024 entries rather than 151K. */
|
||||
/* Stages after top-k work on the candidate set, so their geometry is the candidate width. */
|
||||
auto op_cand = [&](const char* name) -> rad_op {
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -264,8 +241,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_typical_ = op_cand("sample_typical");
|
||||
op_xtc_ = op_cand("sample_xtc");
|
||||
op_pick_ = op_cand("sample_pick");
|
||||
/* THE SAME TEMPERATURE KERNEL OVER THE CANDIDATE PLANE: its `n_vocab` is the candidate width,
|
||||
* which is all the kernel reads it as -- a row length. */
|
||||
/* The temperature kernel again, over the candidate plane: `n_vocab` is only a row length to
|
||||
* it, so the candidate width works. */
|
||||
{
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -275,24 +252,21 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
}
|
||||
|
||||
if (vocab_parallel()) {
|
||||
/* lm_head is vocab-sharded, so each rank reduces ITS OWN shard and only the candidate
|
||||
* sets are combined -- k * world_size pairs, 2 KiB at k=64 and world_size=4, against the
|
||||
* ~77 MiB a full-logits gather would move (spec §9). */
|
||||
/* Each rank reduces its own shard and only the candidate sets are gathered: 2 KiB at
|
||||
* k=64 and world_size=4, versus ~148 MiB for full logits (spec §9). */
|
||||
RadParam ag[4] = {
|
||||
RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
|
||||
RadParam{ "numel", RAD_P_INT, (long long)(rows * ncand * 2), 0, nullptr },
|
||||
RadParam{ "dtype", RAD_P_STR, 0, 0, "f32" },
|
||||
/* ROW-INTERLEAVED. One sampled position's pairs from every rank have to land side by
|
||||
* side, because sample_merge_topk reads one row at one row stride. */
|
||||
/* Row-interleaved, so each position's pairs from every rank are adjacent. */
|
||||
RadParam{ "row", RAD_P_INT, (long long)(ncand * 2), 0, nullptr },
|
||||
};
|
||||
op_allgather_ = rad_decl_op(b, "all_gather", ag, 4, nullptr, 0);
|
||||
op_merge_ = op_cand("sample_merge_topk");
|
||||
}
|
||||
|
||||
/* THE RAW DISTRIBUTION'S SUMMARY, at the one width every request's top_logprobs fits in. A
|
||||
* deployment whose kernels lack it serves every request that does not ask for logprobs;
|
||||
* check_request refuses the ones that do, by name. */
|
||||
/* The raw-distribution summary, at a width that fits every request's top_logprobs. If it
|
||||
* does not resolve, check_request refuses only requests that ask for logprobs. */
|
||||
{
|
||||
RadParam p[4] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
@@ -303,8 +277,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_logprobs_ = rad_decl_op(b, "sample_logprobs", p, vocab_parallel() ? 4 : 3, nullptr, 0);
|
||||
}
|
||||
if (vocab_parallel()) {
|
||||
/* Each rank summarised its own shard; rank 0 merges them on the host, so every rank's
|
||||
* row lands beside the others' as the candidate pairs do. */
|
||||
/* Each rank summarises its own shard; rank 0 merges them on the host. Laid out side by
|
||||
* side, like the candidate pairs. */
|
||||
RadParam ag[4] = {
|
||||
RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
|
||||
RadParam{ "numel", RAD_P_INT, (long long)(rows * lp_width()), 0, nullptr },
|
||||
@@ -327,9 +301,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
int Sampler::stage_alloc() {
|
||||
const int64_t rows = rows_for(cfg_);
|
||||
|
||||
/* Pinned, because these are uploaded every step and a pageable source turns an async copy
|
||||
* into a staged one with a host bounce -- which is exactly the per-step cost the step batch
|
||||
* exists to remove (spec §8). */
|
||||
/* Pinned: uploaded every step, and a pageable source turns the async copy into a staged one
|
||||
* with a host bounce (spec §8). */
|
||||
params_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
@@ -341,8 +314,7 @@ int Sampler::stage_alloc() {
|
||||
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
|
||||
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
|
||||
|
||||
/* Rank 0's landing place for the logprobs copies, and only rank 0's: it is the rank that
|
||||
* reads them. */
|
||||
/* Logprobs readback; only rank 0 reads it. */
|
||||
if (cfg_.rank == 0) {
|
||||
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
|
||||
lp_host_ = (float*)rad_dev_alloc(rows * w * 4, RAD_MEM_HOST_PINNED);
|
||||
@@ -393,10 +365,9 @@ Sampler::~Sampler() { stage_free(); }
|
||||
|
||||
/* ================================================================== admission */
|
||||
|
||||
/* WHEN THE TWO HISTORY STAGES RUN, in one place, because admission, request setup and the step
|
||||
* staging each ask and must not disagree. llama.cpp's meaning throughout: a window of 0 turns the
|
||||
* stage off, and DRY also needs a base of at least 1. The multiplier is taken as positive because
|
||||
* a negative one rewards repetition, which is not a request anyone makes on purpose. */
|
||||
/* Whether the two history stages run, shared by admission, request setup and step staging so
|
||||
* they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY
|
||||
* also requires a positive multiplier; a negative one would reward repetition. */
|
||||
static bool penalties_on(const SamplingParams& sp) {
|
||||
return sp.penalty_last_n != 0 &&
|
||||
(sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f);
|
||||
@@ -412,24 +383,40 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
return st;
|
||||
};
|
||||
|
||||
/* Each range is tested as "inside", so a NaN fails it. top_p and typical_p are (0, 1], as
|
||||
* the server takes them: the chain reads 0 as off, where llama.cpp keeps one candidate, so
|
||||
* 0 has no single meaning to honour. */
|
||||
if (sp.top_k < 0) return refuse("top_k is negative", RAD_E_INVAL);
|
||||
if (sp.top_p < 0.0f || sp.top_p > 1.0f) return refuse("top_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.min_p < 0.0f || sp.min_p > 1.0f) return refuse("min_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.typical_p < 0.0f || sp.typical_p > 1.0f)
|
||||
return refuse("typical_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.temp < 0.0f) return refuse("temperature is negative", RAD_E_INVAL);
|
||||
if (sp.top_k > cfg_.max_candidates)
|
||||
return refuse("top_k exceeds the sampler's candidate width (--max-candidates)",
|
||||
RAD_E_INVAL);
|
||||
if (!(sp.top_p > 0.0f && sp.top_p <= 1.0f))
|
||||
return refuse("top_p is outside (0,1]", RAD_E_INVAL);
|
||||
if (!(sp.min_p >= 0.0f && sp.min_p <= 1.0f))
|
||||
return refuse("min_p is outside [0,1]", RAD_E_INVAL);
|
||||
if (!(sp.typical_p > 0.0f && sp.typical_p <= 1.0f))
|
||||
return refuse("typical_p is outside (0,1]", RAD_E_INVAL);
|
||||
if (!(sp.temp >= 0.0f)) return refuse("temperature must be >= 0", RAD_E_INVAL);
|
||||
if (!(sp.xtc_probability >= 0.0f && sp.xtc_probability <= 1.0f))
|
||||
return refuse("xtc_probability is outside [0,1]", RAD_E_INVAL);
|
||||
if (!(sp.xtc_threshold >= 0.0f && sp.xtc_threshold <= 1.0f))
|
||||
return refuse("xtc_threshold is outside [0,1]", RAD_E_INVAL);
|
||||
if (sp.top_k > cfg_.max_candidates) {
|
||||
if (why)
|
||||
*why = "top_k " + std::to_string(sp.top_k) + " is wider than the sampler's candidate "
|
||||
"width of " + std::to_string(cfg_.max_candidates) + " tokens";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The penalty divides a positive logit by rep_penalty, so 0 would make it infinite. */
|
||||
if (penalties_on(sp) && !(sp.rep_penalty > 0.0f))
|
||||
return refuse("rep_penalty must be > 0", RAD_E_INVAL);
|
||||
/* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */
|
||||
if (dry_on(sp) && sp.dry_allowed_length < 1)
|
||||
return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL);
|
||||
if (sp.n_probs > RAD_MAX_LOGPROBS) {
|
||||
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
|
||||
" logprobs alternatives may be asked for";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Every breaker is a pass over the whole vocabulary on the scheduler thread, and every other
|
||||
* sequence on the server waits for it; see kDryMaxBreakers. Refused here, before any of that
|
||||
* work is queued, rather than truncated -- a request whose breakers quietly went missing is a
|
||||
* request whose output changed. */
|
||||
/* Each breaker is a full-vocabulary scan on the scheduler thread (see kDryMaxBreakers).
|
||||
* Refused rather than truncated, which would silently change the output. */
|
||||
if (dry_on(sp) && sp.dry_seq_breakers.size() > kDryMaxBreakers) {
|
||||
if (why)
|
||||
*why = "dry_sequence_breakers has " + std::to_string(sp.dry_seq_breakers.size()) +
|
||||
@@ -437,18 +424,14 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* An unresolved sampler is a named refusal, not a silent skip. A request whose min_p quietly
|
||||
* stopped being applied is a request whose output changed and nothing said so. */
|
||||
/* An unresolved sampler is a named refusal, never a silent skip. */
|
||||
auto need = [&](bool wanted, rad_op h, const char* n) -> const char* {
|
||||
return (wanted && !h) ? n : nullptr;
|
||||
};
|
||||
/* A SPLIT VOCABULARY MOVES GREEDY ONTO THE CHAIN, so what a greedy request needs moves with
|
||||
* it: not the argmax, but the temperature stage, the top-k, the merge and the pick that
|
||||
* build_step's top_k = 1 sends it through -- run() issues the temperature stage for every
|
||||
* batch with a chain row, even though its kernel leaves a greedy row (temperature 0) as it
|
||||
* is. Admission has to check what will actually be issued. */
|
||||
/* AND SO DOES ONE ASKING FOR LOGPROBS, which build_step stages as a top-1 chain row so its
|
||||
* token comes off a candidate plane (sampler.h). */
|
||||
/* Under a split vocabulary, or when it asks for logprobs, a greedy request is staged as a
|
||||
* top-1 chain row (see build_step), so it needs the chain ops (temperature, top-k, pick)
|
||||
* rather than the argmax. run() issues the temperature stage for any chain row, even though
|
||||
* it leaves a temperature-0 row unchanged. */
|
||||
const bool lp = sp.n_probs >= 0;
|
||||
const bool greedy_chain = sp.greedy() && (vocab_parallel() || lp);
|
||||
const char* missing = nullptr;
|
||||
@@ -456,9 +439,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_temp_, "sample_temp");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_pick_, "sample_pick");
|
||||
/* EVERY CHAIN ROW NEEDS THE TOP-K, whatever its own top_k says: it is the stage that writes
|
||||
* the candidate set every later stage reads. top_k = 0 asks for the whole candidate width,
|
||||
* not for no candidates. */
|
||||
/* Every chain row needs top-k, whatever its top_k: it writes the candidate set the later
|
||||
* stages read. top_k = 0 means the whole candidate width (max_candidates). */
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_topk_, "sample_topk");
|
||||
if (!missing) missing = need(sp.top_p < 1.0f, op_topp_, "sample_topp");
|
||||
if (!missing) missing = need(sp.min_p > 0.0f, op_minp_, "sample_minp");
|
||||
@@ -478,10 +460,9 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!sp.grammar.empty() && !vocab_)
|
||||
return refuse("a grammar was requested before the vocabulary was attached", RAD_E_STATE);
|
||||
|
||||
/* The triggers are resolved here as well as at begin_request, so a template whose triggers
|
||||
* this machine cannot run is a refusal at admission rather than a request cancelled on the
|
||||
* scheduler thread. */
|
||||
if (!sp.grammar.empty() && !sp.grammar_triggers.empty()) {
|
||||
/* Resolved here as well as in begin_request, so unsupported triggers are refused at
|
||||
* admission rather than cancelling the request on the scheduler thread. */
|
||||
if (!sp.grammar.empty() && (sp.grammar_lazy || !sp.grammar_triggers.empty())) {
|
||||
std::vector<std::string> words;
|
||||
std::vector<int32_t> tokens;
|
||||
std::string e;
|
||||
@@ -490,6 +471,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (why) *why = e;
|
||||
return st;
|
||||
}
|
||||
if (sp.grammar_lazy && words.empty() && tokens.empty())
|
||||
return refuse(kLazyNoTrigger, RAD_E_INVAL);
|
||||
}
|
||||
|
||||
return RAD_OK;
|
||||
@@ -508,32 +491,24 @@ int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::strin
|
||||
spec.text = sp.grammar;
|
||||
spec.root = "root";
|
||||
spec.lazy = sp.grammar_lazy;
|
||||
/* ONLY A NON-LAZY GRAMMAR IS POSITIONED AT THE START OF THE TURN. An eager grammar's root
|
||||
* describes the whole assistant turn and therefore opens with the generation prompt, which
|
||||
* is already in the prompt -- so it has to be replayed or the model is made to write it
|
||||
* out again. A LAZY one describes only the region after its trigger: its root begins at
|
||||
* `<tool_call>`, and feeding it a prefix it never claimed to match fails outright, taking
|
||||
* every tool-calling request with it. */
|
||||
/* Only an eager grammar replays the generation prompt prefix: its root describes the
|
||||
* whole assistant turn, which opens with text already in the prompt. A lazy grammar's
|
||||
* root starts at its trigger (e.g. `<tool_call>`) and would fail on that prefix. */
|
||||
spec.prefix = sp.grammar_lazy ? std::string() : sp.grammar_prefix;
|
||||
RAD_TRY(resolve_triggers(*vocab_, sp.grammar_triggers, &spec.trigger_words,
|
||||
&spec.trigger_tokens, err));
|
||||
RAD_TRY(grammar_create(spec, *vocab_, &st.grammar, err));
|
||||
}
|
||||
|
||||
/* BREAKERS ARE OPTIONAL. DRY runs whenever the request turns it on, as llama.cpp's does with an
|
||||
* empty breaker list; the breakers only limit how far back a repeat may be counted and exempt
|
||||
* the tokens that are breakers themselves. */
|
||||
/* Breakers are optional; DRY runs without them, as llama.cpp's does. They only cap how far
|
||||
* back a repeat is counted and exempt whole-breaker tokens. */
|
||||
if (dry_on(sp) && !sp.dry_seq_breakers.empty()) {
|
||||
if (!vocab_) {
|
||||
if (err) *err = "DRY needs a vocabulary to resolve its sequence breakers";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (sp.dry_seq_breakers.size() > kDryMaxBreakers) {
|
||||
if (err) *err = "too many DRY sequence breakers";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Once per request, never per step: a full vocabulary scan per breaker string is
|
||||
* milliseconds at a 151K vocab and has no business on the step path. */
|
||||
/* Once per request: a full vocabulary scan per breaker costs milliseconds at a 151K
|
||||
* vocab. */
|
||||
const int s = dry_prepare_breakers(*vocab_, sp.dry_seq_breakers, &st.dry,
|
||||
kDryBreakerMaxTail);
|
||||
if (s < 0) {
|
||||
@@ -560,8 +535,8 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
|
||||
auto it = seqs_.find(req_id);
|
||||
if (it == seqs_.end()) return RAD_OK; /* no grammar, nothing to advance */
|
||||
if (!it->second.grammar) return RAD_OK;
|
||||
/* TIMED for the same reason build_step is: this runs once per ACCEPTED token per rank, on the
|
||||
* step thread, so it is wall time on every constrained token. */
|
||||
/* Timed at Debug, like build_step: runs once per accepted token per rank on the step thread,
|
||||
* so it is wall time on every constrained token. */
|
||||
if ((int)log_level() < (int)Log::Debug) return it->second.grammar->accept_token(token);
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const int s = it->second.grammar->accept_token(token);
|
||||
@@ -574,11 +549,9 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
|
||||
return s;
|
||||
}
|
||||
|
||||
/* A CONSTRAINING GRAMMAR DOES NOT MEAN NO SPECULATION. build_step masks draft position i
|
||||
* against the state reached by accepting drafts 0..i-1 and then rewinds, so a backend that can
|
||||
* push and pop its state speculates like any other request -- which is worth several times the
|
||||
* per-token cost on a constrained request. What IS refused is a backend that cannot rewind:
|
||||
* masking its window would mean masking against a state the sequence is not in. */
|
||||
/* A constraining grammar does not rule out speculation: build_step masks draft position i
|
||||
* against the state after drafts 0..i-1 and then rewinds. Only a backend that cannot rewind is
|
||||
* refused. */
|
||||
bool Sampler::allows_speculation(uint64_t req_id) const {
|
||||
auto it = seqs_.find(req_id);
|
||||
if (it == seqs_.end() || !it->second.grammar) return true;
|
||||
@@ -603,17 +576,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
cur_stage_ = params_stage_;
|
||||
lp_rows_.clear();
|
||||
|
||||
/* DRY'S HOST HALF, for one row whose history `h[0, take)` is already staged. The breakers are
|
||||
* strings resolved against the vocabulary, so what they mean for this window is worked out
|
||||
* here and handed to the kernel as data: the repeat limit the most recent breaker imposes
|
||||
* (llama.cpp's step 1), and one byte per position marking the tokens that are whole breakers
|
||||
* and therefore never penalised. The window is the one the kernel will take -- the tail of
|
||||
* the staged row, `dry_penalty_last_n` long when that is positive.
|
||||
/* DRY's host half for one row whose history `h[0, take)` is staged. Over the window the
|
||||
* kernel uses (the tail of the row, `dry_penalty_last_n` long when positive) it computes the
|
||||
* repeat limit from the most recent breaker (llama.cpp's step 1) and marks whole-breaker
|
||||
* tokens, which are never penalised.
|
||||
*
|
||||
* Returns false when the breakers rule DRY out for the row altogether: a breaker closer to the
|
||||
* end than `allowed_length` leaves no repeat long enough to count. A row with no breakers
|
||||
* gets zero marks, because the plane is shared by the whole batch and another row may have
|
||||
* some. */
|
||||
* Returns false when a breaker closer to the end than `allowed_length` rules DRY out for the
|
||||
* row. A row without breakers still gets zero marks, because the plane is shared by the
|
||||
* batch. */
|
||||
auto stage_dry = [&](DeviceSampleParams& p, const int32_t* h, int64_t take,
|
||||
const DryBreakers* brk, int64_t row) -> bool {
|
||||
const int64_t last_n = p.dry_penalty_last_n;
|
||||
@@ -640,12 +610,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
const int n_pos = r->n_draft + 1;
|
||||
|
||||
if (n_pos > 1 && !allows_speculation(r->id)) {
|
||||
RAD_ERR("sampler: request %llu carries a constraining grammar its backend cannot "
|
||||
"snapshot, and %d draft tokens. The mask for draft position i is the mask of "
|
||||
"the state reached by accepting drafts 0..i-1, so masking the window needs "
|
||||
"push_state/rollback. The scheduler must consult allows_speculation() and "
|
||||
"decode this one a token at a time.",
|
||||
(unsigned long long)r->id, r->n_draft);
|
||||
RAD_ERR("sampler: request %llu has %d draft tokens and a constraining grammar that "
|
||||
"cannot snapshot its state; the scheduler must decode it a token at a time "
|
||||
"(allows_speculation)", (unsigned long long)r->id, r->n_draft);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -665,25 +632,19 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
SeqState* st = it == seqs_.end() ? nullptr : &it->second;
|
||||
const DryBreakers* brk = st && !st->dry.empty() ? &st->dry : nullptr;
|
||||
|
||||
/* THE WINDOW IS WALKED, THEN REWOUND. Position 0 is masked against the state the sequence
|
||||
* is really in; position k against the state reached by accepting drafts 0..k-1. The push
|
||||
* happens whatever the grammar's current mode, because a draft token can fire a lazy
|
||||
* grammar's trigger mid-window -- at which point the positions behind it DO need a mask,
|
||||
* and without the push they would be sampled unconstrained.
|
||||
/* The window is walked, then rewound: position k is masked against the state after
|
||||
* accepting drafts 0..k-1. The push happens even when the grammar is not yet
|
||||
* constraining, because a draft can fire a lazy grammar's trigger mid-window.
|
||||
*
|
||||
* `dead` is not a failure. A draft the grammar forbids simply cannot be accepted: the
|
||||
* target's own masked pick at that position will differ from it, so verification rejects
|
||||
* there and every position behind it is discarded. Masking stops and the rest of the
|
||||
* window is left unconstrained, which is what "discarded" needs it to be. */
|
||||
* `dead` is not a failure: a draft the grammar forbids will be rejected at verification
|
||||
* and every later position discarded, so masking stops for the rest of the window. */
|
||||
GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr;
|
||||
const bool walk = gr && n_pos > 1;
|
||||
if (walk) gr->push_state();
|
||||
bool dead = false;
|
||||
|
||||
/* THE REASONING BUDGET, walked over the window as the grammar is. Position k is inside the
|
||||
* block or not according to the committed reply and drafts 0..k-1, which is the only
|
||||
* history under which its token is ever emitted; a draft that ends the block early is
|
||||
* accepted or rejected like any other. */
|
||||
/* The reasoning budget is walked over the window like the grammar: position k is
|
||||
* judged by the committed reply plus drafts 0..k-1. */
|
||||
const bool budget = st && sp.thinking_budget >= 0 && sp.reasoning.known();
|
||||
ReasoningCount think;
|
||||
if (budget) {
|
||||
@@ -705,9 +666,8 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
std::memset(&p, 0, sizeof p);
|
||||
|
||||
p.seed = sp.seed;
|
||||
/* The output position, advanced across the speculative window: draft position k is
|
||||
* the (n_out + k)-th token this request will emit, so its randomness is the same
|
||||
* whether it arrived through speculation or one token at a time. */
|
||||
/* Output position: draft position k is token n_out + k, so its draw is the same with
|
||||
* or without speculation. */
|
||||
p.pos = (uint64_t)(n_out + k);
|
||||
|
||||
p.temp = sp.temp;
|
||||
@@ -727,21 +687,15 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.dry_penalty_last_n = sp.dry_penalty_last_n;
|
||||
p.mask_row = -1;
|
||||
|
||||
/* GREEDY OVER A SPLIT VOCABULARY IS A TOP-1 CHAIN, not an argmax. sample_argmax reads a
|
||||
* whole logits row and writes the winning COLUMN, which under vocab parallelism is
|
||||
* this rank's local index into its own shard -- a fluent answer built from the wrong
|
||||
* token ids. Staging top_k = 1 sends the row through top-k, the pair plane, the
|
||||
* gather and the merge instead, which is where a local index becomes a global one;
|
||||
* sample_pick over a single live candidate returns it deterministically, so the
|
||||
* result is the argmax it was always meant to be.
|
||||
/* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax
|
||||
* writes a column of this rank's shard, not a token id. Top-k plus the merge produce
|
||||
* global ids, and the pick over one candidate is deterministic. A greedy row asking
|
||||
* for logprobs is staged the same way, because logprobs_for reads the drawn value
|
||||
* from the candidate plane; the argmax and top-k share a tie rule, so the token is
|
||||
* unchanged.
|
||||
*
|
||||
* Such a row is a CHAIN row and does not carry RAD_SP_GREEDY: every candidate stage
|
||||
* skips a row that does, because in an unsplit batch that flag is what keeps the pick
|
||||
* from overwriting the argmax's answer with a draw. */
|
||||
/* A GREEDY ROW ASKING FOR LOGPROBS IS A TOP-1 CHAIN ROW TOO, for a reason of its own:
|
||||
* its token has to come off a candidate plane, which is where logprobs_for reads the
|
||||
* value it was drawn at. The argmax's tie rule is the top-k's, so the token is the
|
||||
* same. */
|
||||
* Such a row does not carry RAD_SP_GREEDY: candidate stages skip flagged rows, so the
|
||||
* pick does not overwrite the argmax's token. */
|
||||
const bool want_lp = sp.n_probs >= 0;
|
||||
if (sp.greedy()) {
|
||||
if (vocab_parallel() || want_lp) p.top_k = 1;
|
||||
@@ -749,9 +703,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
}
|
||||
if (want_lp) p.flags |= RAD_SP_LOGPROBS;
|
||||
if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC;
|
||||
/* TEMPERATURE LAST: the row's own temperature in the late stage's row, and 1 -- which
|
||||
* the temperature stage skips -- in whichever of the two it does not run in. Every row
|
||||
* gets a late row, because the late stage is issued over the whole batch. */
|
||||
/* Temperature last: the row's temperature goes in the late row and 1 (skipped) in the
|
||||
* early one; otherwise the reverse. Every row gets a late row, because the late stage
|
||||
* is issued over the whole batch. */
|
||||
const bool late = sp.temp_last && !sp.greedy() && sp.temp != 1.0f;
|
||||
DeviceSampleParams& lp = late_stage_[row];
|
||||
lp = p;
|
||||
@@ -761,17 +715,11 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
any_late_ = true;
|
||||
}
|
||||
|
||||
/* THE HISTORY THE PENALTIES AND DRY READ, staged only for a row that runs one of them
|
||||
* -- the copy is scheduler-thread work and the upload is step-path bytes, and neither
|
||||
* buys anything for a row that reads none of it. It is the prompt, everything
|
||||
* generated so far and, at draft position k, the k drafted tokens in front of it: the
|
||||
* token sampled there is emitted only if those drafts are, so they are part of the
|
||||
* output it is penalised against, exactly as they would be one token at a time. Oldest
|
||||
* first, truncated to the declared window -- a bound on the buffer, not a policy on
|
||||
* the sampler; penalty_last_n still decides how much of it counts. The row owns its
|
||||
* own row of the plane, so the window starts at offset 0 within it. */
|
||||
p.hist_off = 0;
|
||||
p.hist_len = 0;
|
||||
/* History for the penalties and DRY, staged only for rows that run one of them:
|
||||
* prompt, output so far and, at draft position k, the k drafts before it (they are
|
||||
* emitted only if accepted, as one token at a time). Oldest first, truncated to
|
||||
* max_hist; penalty_last_n still decides how much counts. Each row owns its row of the
|
||||
* plane, so hist_off stays 0. */
|
||||
if (pen || dry) {
|
||||
const int64_t len = n_total + k;
|
||||
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
|
||||
@@ -790,18 +738,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
if (gr && !dead && gr->constrains()) {
|
||||
uint32_t* dst = mask_stage_ + row * mask_words_;
|
||||
int s;
|
||||
/* WHAT THE MASK COSTS, MEASURED RATHER THAN ASSUMED. The mask is scheduler-thread
|
||||
* work with the rank threads waiting at the barrier, so it is wall time on every
|
||||
* constrained token and would decide the step if it were slow. Reported at Debug,
|
||||
* per 256 masks, mean and worst. */
|
||||
/* Mask cost, reported at Debug per 256 masks (mean and worst). It runs on the
|
||||
* scheduler thread while the rank threads wait at the barrier. */
|
||||
const bool inst = (int)log_level() >= (int)Log::Debug;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
/* ASK THE GRAMMAR WHETHER IT COMPUTED THE MASK, rather than inferring it from how
|
||||
* long the call took. No duration threshold separates the two: a mask computed
|
||||
* from the plan can finish inside the time a memo hit costs on a large
|
||||
* vocabulary, so a timing test counts computed masks as hits and any per-mask
|
||||
* cost derived from the split is wrong by that factor. The counter is exact and
|
||||
* costs a relaxed load. */
|
||||
/* Memo hits and computed masks are told apart by the grammar's walk counter, not
|
||||
* by duration: a computed mask can be as fast as a memo hit on a large
|
||||
* vocabulary. */
|
||||
const uint64_t w0 = inst ? st->grammar->masks_walked() : 0;
|
||||
if (!vocab_parallel()) {
|
||||
s = st->grammar->fill_mask(dst, mask_words_);
|
||||
@@ -812,15 +755,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
if (inst) {
|
||||
const double us = std::chrono::duration<double, std::micro>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
mask_us_ += us; mask_worst_us_ = mask_us_n_ && us < mask_worst_us_
|
||||
? mask_worst_us_ : us;
|
||||
mask_us_ += us;
|
||||
mask_worst_us_ = std::max(mask_worst_us_, us);
|
||||
if (st->grammar->masks_walked() != w0) { ++mask_slow_; mask_walk_us_ += us; }
|
||||
else ++mask_fast_;
|
||||
if (++mask_us_n_ == 256) {
|
||||
/* Mean per MASK and mean per COMPUTED mask are different questions and
|
||||
* the second is the one that says what a new state costs: a window's
|
||||
* masks are mostly memo hits, so the first tracks how many positions
|
||||
* asked. */
|
||||
/* Mean per computed mask is what a new state costs; the overall mean
|
||||
* is dominated by memo hits. */
|
||||
RAD_DEBUG("sampler: grammar mask %.2f ms mean, %.2f ms worst over 256; "
|
||||
"%lld memo hits, %lld computed at %.2f ms mean (%lld vocab, "
|
||||
"%lld words)",
|
||||
@@ -833,19 +774,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
}
|
||||
}
|
||||
if (s < 0 && k > 0) {
|
||||
/* A SPECULATIVE POSITION IS NOT A DEAD REQUEST. This is the state reached by
|
||||
* accepting drafts the sequence has not committed to, so "nothing is
|
||||
* admissible here" says the draft is wrong, not that the request is stuck.
|
||||
* Verification will reject at or before this position; stop masking and leave
|
||||
* the rest of the window unconstrained, since it is about to be discarded. */
|
||||
/* At a draft position this only means a draft is wrong; verification
|
||||
* rejects at or before here, so stop masking the rest of the window. */
|
||||
dead = true;
|
||||
} else if (s < 0) {
|
||||
/* A DEAD GRAMMAR FAILS ITS REQUEST, NOT THE STEP. Returning a status here
|
||||
* would reach the step loop as an engine fault and stop it stepping, so every
|
||||
* other client on the server would stop receiving tokens because one of them
|
||||
* sent a schema the model painted itself out of. The row is left unmasked for
|
||||
* this step -- it is about to be cancelled -- and the id goes to the engine
|
||||
* to close. */
|
||||
/* A dead grammar fails its request, not the step: an error status would stop
|
||||
* the step loop for every client. The row stays unmasked and the engine
|
||||
* cancels the request. */
|
||||
RAD_WARN("sampler: request %llu has no admissible token under its grammar; "
|
||||
"failing that request", (unsigned long long)r->id);
|
||||
failed_.push_back(r->id);
|
||||
@@ -853,10 +788,8 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.mask_row = (int32_t)row;
|
||||
p.flags |= RAD_SP_MASK;
|
||||
if ((int)log_level() >= (int)Log::Trace) {
|
||||
/* How many tokens the grammar allows THIS RANK to pick. Zero is legal
|
||||
* under sharding -- the admissible set can live entirely on another rank
|
||||
* -- and is the first thing to check when a grammar-constrained answer
|
||||
* comes out unconstrained. */
|
||||
/* Tokens the grammar allows on this rank. Zero is legal under sharding,
|
||||
* when the admissible set lives on another rank. */
|
||||
int64_t bits = 0;
|
||||
for (int64_t w = 0; w < mask_words_; ++w)
|
||||
bits += __builtin_popcount(dst[w]);
|
||||
@@ -872,8 +805,8 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
force_close(p, row, sp.reasoning.close);
|
||||
|
||||
if (want_lp) {
|
||||
/* The temperature the candidate value carries: the early stage's and the late
|
||||
* one's, each only where its kernel runs (temp > 0 and not 1). */
|
||||
/* Temperature the candidate value carries: early and late, each counted only
|
||||
* where its kernel applies it (temp > 0 and not 1). */
|
||||
auto t_of = [](float t) { return t > 0.0f && t != 1.0f ? t : 1.0f; };
|
||||
LpRow L;
|
||||
L.row = row;
|
||||
@@ -889,15 +822,11 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Back to where the sequence actually is. The tokens it really accepted are applied by
|
||||
* Sampler::accept_token after the step verifies, so anything the walk did must be gone
|
||||
* before then or the grammar would be ahead of the sequence by the whole window. */
|
||||
/* Rewind the walk; accepted tokens are applied by accept_token after verification. */
|
||||
if (walk) RAD_TRY(gr->rollback());
|
||||
}
|
||||
|
||||
/* THE WHOLE OF IT, not just the mask, because that is what the rank threads wait for. Without
|
||||
* this the mask's own number could fall to nothing and the step stay slow with no way to see
|
||||
* which side of the barrier the time was on. */
|
||||
/* Whole build time, which is what the rank threads wait for at the barrier. */
|
||||
if ((int)log_level() >= (int)Log::Debug) {
|
||||
build_us_ += std::chrono::duration<double, std::micro>(
|
||||
std::chrono::steady_clock::now() - t_build).count();
|
||||
@@ -915,8 +844,8 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
|
||||
const int64_t at = (int64_t)close - cfg_.vocab_off;
|
||||
const bool local = at >= 0 && at < cfg_.n_vocab_local;
|
||||
if (p.flags & RAD_SP_MASK) {
|
||||
/* The grammar's mask for this row. Under a split vocabulary the whole one is still in
|
||||
* mask_full_, and the close may be another rank's column. */
|
||||
/* Check the grammar's mask. Under a split vocabulary use mask_full_, since the close may
|
||||
* be another rank's column. */
|
||||
const bool admitted =
|
||||
vocab_parallel()
|
||||
? close < (int64_t)mask_full_.size() * 32 &&
|
||||
@@ -924,9 +853,8 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
|
||||
: local && (dst[at >> 5] >> (uint32_t)(at & 31)) & 1u;
|
||||
if (!admitted) return;
|
||||
}
|
||||
/* ONE ADMISSIBLE TOKEN, on whichever rank holds its column. The others mask the whole row
|
||||
* out, which the candidate merge reads as no candidate from them (the grammar's own masks do
|
||||
* the same when the admissible set lives on one shard). */
|
||||
/* One admissible token, on the rank that holds its column. Other ranks mask the whole row,
|
||||
* which the candidate merge reads as no candidates from them. */
|
||||
std::memset(dst, 0, (size_t)mask_words_ * 4);
|
||||
if (local) dst[at >> 5] |= 1u << (uint32_t)(at & 31);
|
||||
p.mask_row = (int32_t)row;
|
||||
@@ -944,18 +872,16 @@ int Sampler::build_greedy(int64_t n) {
|
||||
}
|
||||
n_seq_ = n;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
cur_stage_ = greedy_stage_;
|
||||
if (greedy_ready_) return RAD_OK;
|
||||
for (int64_t i = 0; i < cap; ++i) {
|
||||
DeviceSampleParams& p = greedy_stage_[i];
|
||||
std::memset(&p, 0, sizeof p);
|
||||
p.temp = 0.0f;
|
||||
p.top_k = 1;
|
||||
p.hist_off = 0;
|
||||
p.hist_len = 0;
|
||||
p.mask_row = -1;
|
||||
/* Over a split vocabulary a greedy row is a top-1 CHAIN row, for the reason build_step
|
||||
* gives, and so it does not carry the flag every candidate stage skips. */
|
||||
/* Over a split vocabulary a greedy row is an unflagged top-1 chain row (see
|
||||
* build_step). */
|
||||
p.flags = vocab_parallel() ? 0 : RAD_SP_GREEDY;
|
||||
}
|
||||
greedy_ready_ = true;
|
||||
@@ -987,24 +913,21 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A GREEDY ROW OVER A SPLIT VOCABULARY is staged as a top-1 chain row, never with the flag:
|
||||
* the argmax would return this rank's column for a token id. build_step and build_greedy both
|
||||
* hold that, so a flagged row here is a staging bug, and it is refused rather than served. */
|
||||
/* A greedy-flagged row under a split vocabulary is a staging bug (the argmax would return a
|
||||
* shard column), so it is refused. */
|
||||
if (any_greedy && vocab_parallel()) {
|
||||
RAD_ERR("sampler: a greedy-flagged row reached a split vocabulary, where the argmax "
|
||||
"returns a column of this rank's shard rather than a token id");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* Async copies on the compute stream and no host synchronisation, and only of what some row
|
||||
* will read: the history and the breaker marks for the penalties and DRY, the mask for a
|
||||
* grammar. The mask upload is 19 KiB a constrained sequence at a 151K vocab, which is the
|
||||
* number that makes a host-side grammar affordable at all (spec §13). */
|
||||
/* Async copies on the compute stream, only of what some row reads. The mask is 19 KiB per
|
||||
* constrained sequence at a 151K vocab, which keeps a host-side grammar affordable
|
||||
* (spec §13). */
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
/* The late temperature's rows only when this build staged one: a greedy build's rows come
|
||||
* from greedy_stage_, and late_stage_ then holds an older build's. */
|
||||
const bool late = any_late_ && cur_stage_ == params_stage_;
|
||||
/* Late rows only for a build_step build; build_greedy clears any_late_. */
|
||||
const bool late = any_late_;
|
||||
if (late)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
@@ -1033,9 +956,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
return rad_issue(c, op, v.data(), (int)v.size(), n_seq_);
|
||||
};
|
||||
|
||||
/* THE LOGPROBS SUMMARY, ON THE LOGITS AS THE MODEL WROTE THEM: every stage below writes them in
|
||||
* place. Only for a trunk build that staged a logprobs row -- a draft pass's greedy build
|
||||
* stages none, and must not overwrite the summary rank 0 is about to copy back. */
|
||||
/* The logprobs summary reads the raw logits, before any stage writes them in place. Only for
|
||||
* a build_step build with logprobs rows: a draft pass must not overwrite the summary rank 0
|
||||
* is about to copy back. */
|
||||
const bool lp = !lp_rows_.empty() && cur_stage_ == params_stage_ && op_logprobs_;
|
||||
const RadOperand o_lp = opd_rows(buf_lp_, n_seq_);
|
||||
if (lp) {
|
||||
@@ -1044,24 +967,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
RAD_TRY(issue(op_lp_gather_, { o_lp, opd_rows(buf_lp_g_, n_seq_) }));
|
||||
}
|
||||
|
||||
/* Penalties act on raw logits, before anything derives a probability from them. DRY takes the
|
||||
* breaker marks only when some row in the batch has breakers; its fourth operand is optional
|
||||
* and absent means no token is exempt. */
|
||||
/* Penalties act on raw logits. DRY gets the breaker marks only when some row has breakers;
|
||||
* absent means no token is exempt. */
|
||||
if (any_penalty) RAD_TRY(issue(op_penalties_, { o_logits, o_params, o_hist }));
|
||||
if (any_dry)
|
||||
RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() }));
|
||||
|
||||
/* The greedy rows take the argmax after penalties and the mask and never see temperature.
|
||||
* When the batch is mixed, BOTH the argmax and the chain are issued over the whole batch: the
|
||||
* argmax writes every row's token, and then every candidate stage skips the greedy rows
|
||||
* (RAD_SP_GREEDY) so the pick overwrites only the rows the chain owns. The cost is one extra
|
||||
* pass over the logits for the rows the other op owns -- ~77 MiB read at batch 256 -- against
|
||||
* one kernel launch per distinct parameter set, which at batch 256 is up to 256 launches. The
|
||||
* pass wins.
|
||||
*
|
||||
* Under vocab parallelism there is no greedy shortcut at all: build_step staged those rows at
|
||||
* top_k = 1, without the flag, so they take the chain, where the merge turns a local candidate
|
||||
* index into a global token id. */
|
||||
/* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax
|
||||
* and the chain run over the whole batch: the argmax writes every row, then the candidate
|
||||
* stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits
|
||||
* pass (~148 MiB at batch 256) beats up to 256 launches, one per parameter set. Under vocab
|
||||
* parallelism no row is flagged greedy (see build_step). */
|
||||
if (any_greedy) {
|
||||
if (any_mask) RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask }));
|
||||
RAD_TRY(issue(op_argmax_, { o_logits, o_params, o_tok }));
|
||||
@@ -1073,26 +989,20 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (any_mask && !any_greedy)
|
||||
RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask }));
|
||||
|
||||
/* top-k reduces the vocabulary to a candidate set, and everything after it works on that set.
|
||||
* Under tensor parallel this is the LOCAL top-k over this rank's shard; the candidate sets
|
||||
* are combined below and full logits are never gathered (spec §9).
|
||||
*
|
||||
* IT IS ISSUED WHENEVER THE CHAIN RUNS, not only when some row sets top_k. A row at
|
||||
* top_k = 0 asks for the whole candidate width, and the candidate planes are transient: a
|
||||
* step that skipped this would hand the pick whatever the planes last held -- the previous
|
||||
* step's candidates, or another op's bytes. */
|
||||
/* Top-k reduces the vocabulary to the candidate set the rest works on; under tensor parallel
|
||||
* it is per shard and the sets are merged below (spec §9). Always issued when the chain runs:
|
||||
* top_k = 0 means the full candidate width, and the transient candidate planes hold stale
|
||||
* bytes otherwise. */
|
||||
if (vocab_parallel()) {
|
||||
/* The fifth operand is the pair plane: this rank's candidates with GLOBAL ids, which is
|
||||
* what crosses the wire. cand_idx and cand_val still come back LOCAL and the merge
|
||||
* overwrites both, so nothing downstream ever sees a local id. */
|
||||
/* The fifth operand is the pair plane (global ids), which is what is gathered.
|
||||
* cand_idx/cand_val come back local and the merge overwrites both. */
|
||||
const RadOperand o_p = opd_rows(buf_pairs_, n_seq_);
|
||||
const RadOperand o_g = opd_rows(buf_gather_, n_seq_);
|
||||
RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, o_p }));
|
||||
RAD_TRY(issue(op_allgather_, { o_p, o_g }));
|
||||
RAD_TRY(issue(op_merge_, { o_g, o_params, o_ci, o_cv }));
|
||||
} else {
|
||||
/* No pair plane on a whole vocabulary, and it is passed as absent rather than left off:
|
||||
* the schema has five operands and an issue of four is refused. */
|
||||
/* No pair plane; passed as absent because the schema has five operands. */
|
||||
RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, opd_none() }));
|
||||
}
|
||||
|
||||
@@ -1105,10 +1015,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
|
||||
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
|
||||
|
||||
/* AND THE LOGPROBS ROWS ON THEIR WAY TO THE HOST, behind the pick on the same stream: the
|
||||
* summary, and the candidate planes the pick drew from (logprobs_for reads a token's value
|
||||
* there when the summary does not hold it). Only the rows between the first and the last
|
||||
* that asked, and only on rank 0, which is the rank collect_step asks. */
|
||||
/* Copy the logprobs rows to the host behind the pick, on rank 0 only (collect_step asks
|
||||
* it): the summary and the candidate planes, which logprobs_for reads when the summary lacks
|
||||
* the token. Only rows from the first to the last that asked. */
|
||||
if (lp && cfg_.rank == 0) {
|
||||
lp_lo_ = lp_rows_.front().row;
|
||||
lp_hi_ = lp_rows_.back().row + 1;
|
||||
@@ -1130,9 +1039,8 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
|
||||
const DeviceSampleParams& p = L.p;
|
||||
double y = (double)v * (double)L.temp;
|
||||
/* DRY subtracted a penalty that depends on the token and the window alone, so the host
|
||||
* reference computes it for this one token: a single candidate at 0 comes back at minus the
|
||||
* penalty. */
|
||||
/* DRY's penalty depends only on the token and the window, so the host reference recomputes
|
||||
* it on a single candidate at 0, which comes back as minus the penalty. */
|
||||
if (p.flags & RAD_SP_DRY) {
|
||||
static const DryBreakers kNone;
|
||||
CandidateSet s;
|
||||
@@ -1146,9 +1054,9 @@ float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
|
||||
L.dry ? *L.dry : kNone);
|
||||
y -= (double)s.c[0].logit;
|
||||
}
|
||||
/* The penalties, inverted: presence and frequency added back, then the repetition penalty
|
||||
* undone on the side of zero the logit is on -- it never changes sign. The window is the
|
||||
* stage's: the tail of the staged history, penalty_last_n long when that is positive. */
|
||||
/* Penalties inverted: presence and frequency added back, then repetition undone on the
|
||||
* logit's side of zero (it never changes sign). Window: the tail of the staged history,
|
||||
* penalty_last_n long when positive. */
|
||||
if (p.flags & RAD_SP_PENALTY) {
|
||||
int64_t n = (int64_t)L.hist.size(), o = 0;
|
||||
if (p.penalty_last_n > 0 && n > p.penalty_last_n) { o = n - p.penalty_last_n; n = p.penalty_last_n; }
|
||||
@@ -1177,8 +1085,8 @@ int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* id
|
||||
if (live(r)) sum += (double)st[r * w + 1] * std::exp((double)st[r * w] - mx);
|
||||
*log_z = sum > 0.0 ? mx + std::log(sum) : NAN;
|
||||
|
||||
/* On the stack for every split the engine runs (eight ranks of 21 pairs is 168); a call for
|
||||
* more takes the heap rather than a bound. Once per emitted token, on collect_step's path. */
|
||||
/* Stack buffer covers up to eight ranks of 21 pairs (168); more falls back to the heap.
|
||||
* Runs once per emitted token on collect_step's path. */
|
||||
struct Pair { float v; int32_t id; };
|
||||
Pair buf[256];
|
||||
std::vector<Pair> heap;
|
||||
@@ -1214,16 +1122,14 @@ int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const
|
||||
if (x.row == row) { L = &x; break; }
|
||||
if (!L) return RAD_E_STATE;
|
||||
|
||||
/* Every rank's summary of its shard, merged: the maxima and normalisers by the usual
|
||||
* rescale, the largest by value with the lower id first. */
|
||||
/* Merge every rank's shard summary. */
|
||||
const int W = vocab_parallel() ? cfg_.world_size : 1;
|
||||
double log_z = 0.0;
|
||||
int32_t ids[kLpK * 8];
|
||||
float vals[kLpK * 8];
|
||||
const int n = merge_logprob_rows(lp_host_ + row * W * lp_width(), W, kLpK, &log_z, ids, vals,
|
||||
(int)(sizeof ids / sizeof ids[0]));
|
||||
/* A ROW WITH NO FINITE LOGIT HAS NO DISTRIBUTION to report against -- NaN logits out of the
|
||||
* model, or every one at -inf -- and any number sent for it would be invented. */
|
||||
/* No finite logit (NaN from the model, or all -inf) means no distribution to report. */
|
||||
if (!std::isfinite(log_z)) {
|
||||
RAD_WARN("sampler: row %lld has no finite logit; its logprobs cannot be computed",
|
||||
(long long)row);
|
||||
@@ -1238,8 +1144,8 @@ int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const
|
||||
out->top_lp[j] = (float)((double)vals[j] - log_z);
|
||||
}
|
||||
|
||||
/* The token's own raw logit: exact when it is among the largest, and otherwise recovered
|
||||
* from the value the pick drew it at. */
|
||||
/* The token's raw logit: exact if among the largest, else recovered from the value the pick
|
||||
* drew it at. */
|
||||
double own = NAN;
|
||||
for (int j = 0; j < n && std::isnan(own); ++j)
|
||||
if (ids[j] == token) own = (double)vals[j];
|
||||
|
||||
Reference in new issue
Block a user