Archived
IQR-V4 for Qwen3.8-27B: - 15 recipes, data/recipes/q38-27b-iq2r-v4 .. q38-27b-iq8r-v4 (2.5 to 8 bits a weight), docs/IQR.md "IQR-V4". On the quantisation board's private split every entry has 2-19% less KL than its V3 twin of the same size (10-19% from 2.5 to 5.4 bits); IQ4R-L-V4 is 24% below the official FP8 checkpoint at 55% of its size, and IQ2R-L-V4 (2.8 bpw) is below the MXFP4 checkpoint. Containers with the DFlash2 drafter and the vision tower: huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4, served by deploy/compose/qwen3.8-27b-iqr-v4.yaml (IQR_V4 names the size) - GPTQ runs in act order inside the column trellis (tcq_order=1); the head-fed projections (attn_output, ssm_out) take a bf16 scale a (row, 128) block from five bits up; widths from measured prices - A vocabulary-weighted lm_head: four width classes of the computed trellis (output.k<B>), the tokens carrying the probability on the widest, decoded in one launch by logits_gemm_vocab with 16-bit head activations; 0.62 ms at one token on a TP2 rank against the int8 head's 1.02 ms. tools/vhead.py and data/vhead/ build the class split from the bf16 checkpoint; libquant reads the head's input Hessian for every class - At IQ6R-L and up, the int8 lm_head is GPTQ'd against its input Hessian (same bytes, median KL -8..-12%) - embed_lookup_iqr takes u7/u8 tables under a zero point and the 4096-state trellis at 6 and 7 bits - The whitepaper: radiance.stilldeadco.de/whitepapers/iqr-v4.pdf Faster IQR kernels: - The one-token GEMV gives each 16-row weight tile a block whose waves split K (5120 x 6144 at one token 42.3 -> 30.0 us), with a biased-int fold, a v_perm activation broadcast and one code stream a column - A 16-token WMMA tile without block barriers serves 2 to 16 tokens (6- and 7-bit codes from one token): a 4-bit weight takes 0.52-0.66 of FP8's time from one token to sixteen, 1.15-1.74x V3's kernels from four tokens up - The activation quantisers after the IQR gate_up (gemm_iqr_gated), the delta net's decode conv fold (gdn_conv_recurrent_update_had) and the attention gate (gate_had_quant_i8g) are folded into their producers, byte for byte the same codes: 128 fewer launches a decode step - End to end on one R9700 (TP1, no speculation): IQ4R-S-V4 decodes one stream in 24.7 ms against the MXFP4 checkpoint's 25.8 at five times lower KL; IQ3R-S-V4 is faster than MXFP4 at 1 to 8 streams. Prefill stays 8-9% behind MXFP4's 4-bit tile Quantisation tooling: - rescale=1 refits each row's scale to its codes after GPTQ; gptqsim measures a tensor's W16A16 form (tcq_code=mad16); an int8 trunk's calibration Grams can be recorded from the codes its GEMMs read (--calib-dir, TP1) - Fixed: the GPU trellis packs tcq_code=mad16's values two int16 a register New models (merged): - Spark 2.5 (spark25: bf16 and rotated-int8 IQ8R checkpoints, tensor parallelism with exact collectives, reasoning and tagged tool calls) with its DSpark drafter (exact attention and Markov walk ops), docs/SPARK25-IQ8R.md (@gostar) - Ling-3.0-flash (bailing_hybrid: KDA, dense latent attention with mla_attn_paged, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as a serial drafter), its w4a8 recipes and compose files for four and two cards (@keptn42) - Gemma 4 12B (gemma4_unified, served by the gemma4 plugins): its picture and audio embedders, a picture's placeholders read both ways on the sliding layers as the model was trained (the scheduler ends no prefill chunk inside such a run; RadBatch::n_bidi), windowed attention at head_dim 512, the assistant head as MTP drafter at one, two and four ranks, suppress_tokens from generation_config, bf16 and i8g compose files (@keptn42) Merged: - The prefill KV split sized by the live KV length rather than the model's max_ctx, recorded passes keyed by their split geometry, and --gpu-memory-mib, the inverse of --gpu-headroom-mib (@gostar) - Possessive quantifiers in tokenizer patterns where the greedy reading provably matches the same (Ling-3.0's), and the Grafana dashboard's first screen of totals (@keptn42) - The dashboard's history line (decode, prefill and TTFT over finished requests, kept in the browser, JSON export), session extremes that age and reset on a restart, card-count changes, an Advanced tab for the poll intervals, each request's prefill time from admission in /stats (prefill_s), and the page's JavaScript run by tests/js (@Memoria) - From PR #390: the file tier reads a routed layer with its own router's counts and waits for its deposits; the stop-string hold-back keeps back only a tail that can still become a stop string (before, every delta waited up to the longest stop's length); the sampler's planes are sized by the step's token bound, the n-gram ban runs beside a drafter, and a top-1 row issues no candidate cut (@Code000) - The n-gram reader refills its reads as they land, and a decode gather waits on the other rank's read of a row instead of reading it again (#369, @pokesjw) - libr3d's GEMM structs value-initialised so the tape audit sees no padding (@RikshaDriver) Added: - --ngram-placement disk=DIR: the n-gram table read from its own file, DIR/ngram-<id>.bin, filled from the container at the first start, on a faster or separate drive (#130) Fixed: - input_reference's H.264 round trip runs on libopenh264, which the image carries, at a quantiser held at the crf (a side under 16 padded and cut back); a build with no H.264 encoder answers 501 (#163) - kvtier: at most 1024 session rows under one shared first block; with one shared prompt the list grew a row a request and prefill fell from 9k to 2.5k tok/s after 500K requests (#375) - Speculative steps on an architecture with no pass-key callback keep their recorded passes under the live-KV prefill split Plugin ABI 35: - RadArgs::kv_used_max_h and wgp_count, RadBatch::kv_used_max_h and positions_h, the optional rad_arch_pass_key export and RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT; RadEncoderDecl::bidirectional and RadBatch's n_bidi runs. The layout fingerprint table is regenerated; out-of-tree plugins rebuild against 35 Thanks to @gostar, @keptn42, @Memoria, @Code000, @pokesjw and @RikshaDriver.
430 lines
25 KiB
C++
430 lines
25 KiB
C++
/* sampler.h -- the sampler driver.
|
|
*
|
|
* Sampling runs on device (spec §13): at a 151K vocab and batch 256 the f32 logits are ~148 MiB a
|
|
* step, too much to move to the host and synchronise on the step path. This file implements no
|
|
* sampler. It issues the declared sampler ops in order, as an architecture plugin issues a GEMM:
|
|
* declared through the ordinary builder and resolved through the ordinary hierarchy to `libref`
|
|
* on the host domain or to a device plugin.
|
|
*
|
|
* Chain order (reordering changes which tokens survive):
|
|
*
|
|
* penalties (repetition / frequency / presence, then DRY)
|
|
* the windowed no-repeat-ngram ban
|
|
* temperature
|
|
* the grammar mask
|
|
* top-k
|
|
* top-p, min-p, typical
|
|
* XTC
|
|
* the pick
|
|
*
|
|
* Temperature last: a request may ask for llama.cpp's order with `samplers`
|
|
* (SamplingParams::temp_last). Such a row is staged with temperature 1 for the stage above, which
|
|
* then skips it, and with its own value for a second `sample_temp` over the candidate plane after
|
|
* XTC (the same kernel at the candidate width). Every other row is 1 there.
|
|
*
|
|
* Logprobs: `sample_logprobs` summarises the raw logits, before the first stage, for each row
|
|
* flagged RAD_SP_LOGPROBS: its maximum, its normaliser and its kLpK largest (one more than
|
|
* RAD_MAX_LOGPROBS, see kLpK). Rank 0 copies the summary back behind the pick. The emitted
|
|
* token's logprob is its raw logit minus the log normaliser. When the token is not among the
|
|
* largest, its raw logit is gone (every stage writes the logits in place), so logprobs_for
|
|
* recovers it from the candidate-plane value the pick drew it at, undoing temperature, DRY and
|
|
* the penalties on the host. Such a row is therefore never greedy-flagged: a greedy row asking
|
|
* for logprobs is staged as a top-1 chain row.
|
|
*
|
|
* Greedy: a greedy sequence skips the chain and takes `sample_argmax`, after penalties and the
|
|
* mask. Temperature 0 collapses every other logit to -inf, so a mask applied afterwards would
|
|
* leave nothing. host_ref.cpp makes the same choice and the two must agree, or a temperature-0
|
|
* request stops matching a greedy run.
|
|
*
|
|
* Parameters are data, not branches. They are a per-sequence device array built once per step
|
|
* from pinned staging, as the step batch is (spec §8). Branching on host-side parameters would
|
|
* need one launch per distinct parameter set, up to 256 at batch 256.
|
|
*
|
|
* Schema (docs/OPS.md, "Sampling"). Op parameters are geometry, matched and frozen at declare,
|
|
* so no per-sequence value can be one: two requests with different top_p would be two
|
|
* resolutions of the same op. The seed and output position `sample_pick` draws from are in the
|
|
* row too. Every sampler op therefore takes the row array as an operand:
|
|
*
|
|
* sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout)
|
|
* sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers?
|
|
* -> logits (inout)
|
|
* sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram,
|
|
* whitelist?
|
|
* -> 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
|
|
* sample_logprobs M(range) n_vocab k vocab_off? logits, params -> stats
|
|
*
|
|
* `M` counts sampled positions, not tokens: one per sequence at decode, n_spec+1 per sequence at
|
|
* a verify. `params` is [M] DeviceSampleParams rows. `history` is [M, max_hist] int32 global
|
|
* token ids, row m addressed by its hist_off/hist_len. `breakers` is [M, max_hist] uint8 beside
|
|
* it, nonzero where that token is a whole DRY sequence breaker. `bitmask` is [M, mask_words]
|
|
* uint32, addressed by the row's mask_row. The ban's `whitelist` is a [M, mask_words] uint32
|
|
* bitmask (a SET bit exempts that column from the ban) addressed by the row itself, absent when
|
|
* no staged row carries one. `vocab_off` is this rank's first vocabulary row,
|
|
* declared only when the vocabulary is split; the three ops that map between token ids and this
|
|
* rank's logit columns use it. Every op has a libref implementation, which is both its fallback
|
|
* and its oracle (spec §17).
|
|
*/
|
|
#pragma once
|
|
#include "rad_sample.h"
|
|
#include "rad_spechub.h"
|
|
|
|
#include "../rad_core.h"
|
|
#include "grammar.h"
|
|
#include "host_ref.h"
|
|
#include "vocab_view.h"
|
|
|
|
#include <memory>
|
|
#include <string>
|
|
#include <unordered_map>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace rad {
|
|
|
|
/* ================================================================== the per-sequence row */
|
|
|
|
/* The row and its flags live in abi/rad_sample.h: they are an operand's wire format, read by
|
|
* libref and by kernel plugins, which cannot include a core header. */
|
|
using DeviceSampleParams = RadSampleParams;
|
|
|
|
/* ================================================================== configuration */
|
|
|
|
struct SamplerConfig {
|
|
int64_t n_vocab = 0; /* the whole vocabulary */
|
|
int64_t n_vocab_local = 0; /* this rank's shard of it; == n_vocab when world_size == 1 */
|
|
int64_t 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;
|
|
/* The step's token bound (--max-num-batched-tokens), 0 for none. A step samples one row per
|
|
* token it verifies or completes, and the model's logits rows are capped here too
|
|
* (rad_arch.h, max_logit_rows), so rows past it could never be staged; the planes are sized
|
|
* for min(max_seqs * (max_spec + 1), max(max_tok, max_seqs)). Never below max_seqs: a drafter
|
|
* pass stages one greedy row per sequence it drafts for (build_greedy). */
|
|
int64_t max_tok = 0;
|
|
int rank = 0;
|
|
int world_size = 1;
|
|
/* This rank's first vocabulary row. sample_topk adds it to the candidate ids it packs into
|
|
* the pair plane, so the merge sees global ids; sample_penalties and sample_dry subtract it
|
|
* from the history's global ids. Zero unless lm_head is row-sharded. */
|
|
int64_t vocab_off = 0;
|
|
|
|
/* Candidate-set width for every stage after top-k; sizes their buffers. top_k 0 samples
|
|
* from this many of the most likely tokens, not the whole vocabulary. A request asking for a
|
|
* larger top-k is refused at admission, not silently narrowed. */
|
|
int64_t max_candidates = kSampleCandidates;
|
|
|
|
/* --draft-coupling: declare the coupled verify (`mtp_couple_verify`) behind the pick and the
|
|
* per-row state plane it reads. */
|
|
bool draft_coupling = false;
|
|
};
|
|
|
|
/* ================================================================== the driver */
|
|
|
|
class Sampler {
|
|
public:
|
|
Sampler() = default;
|
|
~Sampler();
|
|
|
|
/* ---------------------------------------------------------- declare phase */
|
|
|
|
/* Declare every sampler op and buffer the chain needs and allocate the pinned staging. Runs
|
|
* alongside the architecture plugin's declare, so a missing kernel lands in the same
|
|
* missing-list (spec §3.1). An unresolved op is not a declare failure; check_request refuses
|
|
* the requests that need it, by name. */
|
|
int declare(RadBuilder* b, const SamplerConfig& cfg);
|
|
|
|
/* The vocabulary the grammar backends walk. Set after the tokeniser loads, before the first
|
|
* request. */
|
|
void attach_vocab(const VocabView* v) { vocab_ = v; }
|
|
|
|
/* ---------------------------------------------------------- admission */
|
|
|
|
/* Admission check. RAD_OK, RAD_E_NOKERNEL naming the sampler that did not resolve, or
|
|
* RAD_E_INVAL naming the out-of-range parameter. */
|
|
int check_request(const SamplingParams& sp, std::string* why) const;
|
|
|
|
/* Build the request's grammar state, if it has a grammar. Runs on the scheduler thread, so it
|
|
* should not compile: a server request carries its grammar compiled
|
|
* (SamplingParams::grammar_program) and this only positions a grammar in it. A request
|
|
* without one is compiled here, at the cost of its mask plan. */
|
|
int begin_request(uint64_t req_id, const SamplingParams& sp, std::string* err);
|
|
void end_request(uint64_t req_id);
|
|
/* begin_request is not idempotent: a second call rebuilds the automaton and discards what it
|
|
* accepted, unconstraining the rest of the generation. The step loop checks this first. */
|
|
bool has_request(uint64_t req_id) const;
|
|
|
|
/* Requests whose grammar reached a state admitting no token. Returned and cleared; the
|
|
* caller cancels them. */
|
|
std::vector<uint64_t> take_failed();
|
|
|
|
/* Advance a request's grammar over the token it just emitted. */
|
|
int accept_token(uint64_t req_id, int32_t token);
|
|
|
|
/* False only for a constraining grammar whose backend cannot snapshot its state. Masking a
|
|
* draft window walks the grammar over the drafts and rewinds, which needs
|
|
* push_state/rollback (a tree's rows each walk their own ancestors); without it the request
|
|
* decodes one token at a time. */
|
|
bool allows_speculation(uint64_t req_id) const;
|
|
/* Whether allows_speculation's answer can no longer change. It changes only when a grammar
|
|
* whose backend cannot rewind starts to constrain (on a commit). */
|
|
bool speculation_fixed(uint64_t req_id) const;
|
|
/* --draft-coupling: bind the per-round states of the linear draft just published, `n` of
|
|
* them (0 clears). Each must name this request, the round it belongs to, and a `draw.mode` the
|
|
* row actually ran. RAD_E_NOTFOUND for a request already ended here. */
|
|
int set_mtp_couple(uint64_t req_id, const RadMtpCoupleState* states, int n);
|
|
|
|
/* ---------------------------------------------------------- step path */
|
|
|
|
/* Stage this step's parameter rows, penalty history and grammar bitmasks into pinned memory.
|
|
* Scheduler thread, before the rank threads are released at the barrier. Allocates nothing;
|
|
* every buffer was sized at declare against max_seqs (spec §3.1). `step` is the engine's step
|
|
* the build stages for, carried into the coupling snapshot. */
|
|
int build_step(const std::vector<Request*>& reqs, int64_t step = -1);
|
|
|
|
/* Stage `n` greedy rows for a drafter: no penalties, mask or history, and no RNG use, so
|
|
* only the argmax runs. Draft output is a proposal checked by a greedy verifier
|
|
* (core/sample/accept.h); sampling it at the request's temperature would spend the request's
|
|
* RNG stream on tokens that may never be emitted and lower acceptance. */
|
|
int build_greedy(int64_t n);
|
|
|
|
/* Upload the staging and issue the chain. Rank thread, compute stream, no host sync.
|
|
* `logits` is [n_seq, n_vocab_local]; `out_tokens` receives [n_seq] token ids. Under tensor
|
|
* parallel the candidate merge (`sample_merge_topk`, or `row_topk_merge` fused with the
|
|
* top-k) runs between the top-k and the cuts; full logits are never gathered. */
|
|
int run(RadCtx* c, rad_buf logits, rad_buf out_tokens);
|
|
|
|
/* The emitted token's logprobs, once the step the last build_step staged has completed.
|
|
* `row` must have been staged with SamplingParams::n_probs >= 0 and `token` is what was
|
|
* sampled there. Rank 0 only, since it holds the copy. RAD_E_STATE for a row not staged for
|
|
* logprobs; RAD_E_INVAL with `out->token` = -1 when the numbers are not finite (no finite
|
|
* logit in the row, or none for the token). */
|
|
int logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const;
|
|
/* Whether `sample_logprobs` resolved; what the server advertises as logprobs support. */
|
|
bool has_logprobs() const { return op_logprobs_ != RAD_NULL_HANDLE; }
|
|
const SamplerConfig& config() const { return cfg_; }
|
|
|
|
/* The rows the last build_step or build_greedy staged, as `run` uploads them; lets the
|
|
* staging be checked without a device. */
|
|
const DeviceSampleParams* staged_params(int64_t* n) const {
|
|
if (n) *n = n_seq_;
|
|
return cur_stage_;
|
|
}
|
|
/* Staged row `row`'s bitmask as `run` uploads it: this rank's shard, `mask_words()` words,
|
|
* meaningful only where the row carries RAD_SP_MASK. */
|
|
const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; }
|
|
int64_t mask_words() const { return mask_words_; }
|
|
/* Staged row `row`'s n-gram ban pair {n, window}, as the last build_step staged it: a greedy
|
|
* build leaves it, since that step's upload may not have read it yet. */
|
|
const int32_t* staged_ngram(int64_t row) const { return ngram_stage_ + 2 * row; }
|
|
/* Staged row `row`'s bound coupled state, as `run` uploads it: all-zero where the row carries
|
|
* none (bonus row, greedy row, uncoupled step). Lets a build be checked without a device. */
|
|
const RadMtpCoupleState& staged_couple(int64_t row) const { return couple_stage_[row]; }
|
|
/* Whether any row of the last build carries a bound state, i.e. whether `run` issues the
|
|
* verify op at all. Cleared by build_greedy: a gate for run(), not for evidence. */
|
|
bool staged_any_couple() const { return any_couple_; }
|
|
/* The verify op the last build resolved, for naming its kernel in a log line. */
|
|
rad_op staged_couple_op() const { return op_couple_; }
|
|
|
|
/* What build_step staged for the coupled verify. build_greedy, which runs between that build
|
|
* and the step's wait, clears any_couple_ but leaves this snapshot. */
|
|
struct CoupleBuild {
|
|
int64_t step = -1; /* the engine step this build staged */
|
|
int64_t rows = 0; /* bound rows */
|
|
/* The distinct sequences among them, with their bound rows. */
|
|
std::vector<std::pair<uint64_t, int64_t>> seqs;
|
|
};
|
|
const CoupleBuild& couple_build() const { return couple_build_; }
|
|
/* The engine step whose build run() last issued the verify op for, or -1. */
|
|
int64_t staged_couple_issued_step() const { return couple_issued_step_; }
|
|
|
|
private:
|
|
/* Whether the vocabulary is split, judged by this rank's logit width rather than the rank
|
|
* count: with `output.weight` replicated every rank holds the whole vocabulary, and a merge
|
|
* would count each candidate once per rank. */
|
|
bool vocab_parallel() const {
|
|
return cfg_.world_size > 1 && cfg_.n_vocab_local < cfg_.n_vocab;
|
|
}
|
|
|
|
/* `dry` holds the resolved sequence breakers, empty when the request sent none. Empty does
|
|
* not mean DRY is off; DRY runs whenever its multiplier is set. */
|
|
struct SeqState {
|
|
std::unique_ptr<GrammarBackend> grammar;
|
|
DryBreakers dry;
|
|
/* Reasoning-block state over `output[0, think_seen)`. build_step advances it over the
|
|
* newly committed tokens only. Read only when the request carries a thinking budget. */
|
|
ReasoningCount think;
|
|
size_t think_seen = 0;
|
|
/* --draft-coupling: the linear draft's per-round states for the window the scheduler
|
|
* published, bound by set_mtp_couple and consumed by build_step. `couple_n` is how many of
|
|
* `couple` are live; 0 for a request whose drafts carry no coupled proposal. */
|
|
RadMtpCoupleState couple[RAD_MTP_COUPLE_MAX_ROUNDS]{};
|
|
int couple_n = 0;
|
|
};
|
|
|
|
/* Mask staged row `row` to the reasoning block's close token, once the budget is spent
|
|
* inside the block. A grammar mask on the row wins: the close is forced only where the
|
|
* grammar admits it, otherwise at a later position. */
|
|
void force_close(DeviceSampleParams& p, int64_t row, int32_t close);
|
|
/* Take `ids` out of the row: from the grammar's mask where it has one, from a full row where
|
|
* not. */
|
|
void suppress(DeviceSampleParams& p, int64_t row, const std::vector<int32_t>& ids);
|
|
|
|
SamplerConfig cfg_{};
|
|
const VocabView* vocab_ = nullptr;
|
|
bool declared_ = false;
|
|
|
|
/* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */
|
|
rad_op op_penalties_ = RAD_NULL_HANDLE;
|
|
rad_op op_dry_ = RAD_NULL_HANDLE;
|
|
/* The windowed no-repeat-ngram ban (`sample_ngram_ban`), the stage Unlimited-OCR's
|
|
* generation_config asks for. It reads the same history plane as the two above. */
|
|
rad_op op_ngram_ban_ = RAD_NULL_HANDLE;
|
|
rad_op op_temp_ = RAD_NULL_HANDLE;
|
|
rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */
|
|
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 */
|
|
rad_op op_couple_ = RAD_NULL_HANDLE; /* --draft-coupling only */
|
|
rad_op op_logprobs_ = RAD_NULL_HANDLE; /* summary of the raw distribution */
|
|
rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */
|
|
|
|
/* Device-side buffers, from the ordinary buffer plan. */
|
|
rad_buf buf_params_ = RAD_NULL_HANDLE;
|
|
rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */
|
|
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_ngram_ = RAD_NULL_HANDLE; /* the n-gram ban's {n, window} pair a row */
|
|
/* The ban's whitelist bitmask, [rows, mask_words] like the grammar mask plane: a SET bit
|
|
* exempts that column from the ban. Uploaded with the ban, only when a staged row has one. */
|
|
rad_buf buf_ngram_wl_ = RAD_NULL_HANDLE;
|
|
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) */
|
|
rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */
|
|
rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */
|
|
rad_buf buf_couple_ = RAD_NULL_HANDLE; /* [rows, RAD_MTP_COUPLE_STATE_WORDS], flag only */
|
|
RadMtpCoupleState* couple_stage_ = nullptr; /* pinned, one row per sampled position */
|
|
bool couple_ = false; /* --draft-coupling */
|
|
bool any_couple_ = false; /* does any row this step carry a bound state? */
|
|
CoupleBuild couple_build_{}; /* what the last build_step staged, for the evidence line */
|
|
int64_t couple_issued_step_ = -1; /* step whose verify op run() last issued */
|
|
|
|
/* Pinned staging, allocated once at declare. */
|
|
DeviceSampleParams* params_stage_ = nullptr;
|
|
/* Copies of params_stage_'s rows with temperature 1 unless the row runs temperature last.
|
|
* Uploaded only when some row does (any_late_). */
|
|
DeviceSampleParams* late_stage_ = nullptr;
|
|
bool any_late_ = false;
|
|
/* Greedy rows have their own staging, filled once on first use. A draft pass is staged
|
|
* while the previous step's upload of params_stage_ may still be pending, so writing there
|
|
* would change that step's rows. Every greedy row is identical, so no upload of this buffer
|
|
* can observe a later build. */
|
|
DeviceSampleParams* greedy_stage_ = nullptr;
|
|
bool greedy_ready_ = false;
|
|
const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */
|
|
int32_t* hist_stage_ = nullptr;
|
|
uint8_t* brk_stage_ = nullptr;
|
|
int32_t* ngram_stage_ = nullptr; /* [rows][2]: n-gram length, window */
|
|
uint32_t* ngram_wl_stage_ = nullptr; /* [rows][mask_words] exemption bitmask */
|
|
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;
|
|
/* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
|
|
* passed to sample_dry. */
|
|
bool any_brk_ = false;
|
|
/* Whether any row this step runs the n-gram ban over a history at least its n-gram long; a
|
|
* shorter one bans nothing. Its history is the plane the penalties use, so this only decides
|
|
* whether that plane is uploaded and the op issued. Cleared by build_greedy. */
|
|
bool any_ngram_ = false;
|
|
/* Whether any banned row this step whitelists a column of this rank's shard; only then is
|
|
* the exemption plane uploaded and passed to sample_ngram_ban. */
|
|
bool any_ngram_wl_ = false;
|
|
|
|
/* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used
|
|
* only when the head is sharded; see declare(). */
|
|
std::vector<uint32_t> mask_full_;
|
|
|
|
/* Debug-level timing of the grammar mask, build_step and accept_token. The mask walk is
|
|
scheduler-thread work that can set the step time of a constrained request. */
|
|
double mask_us_ = 0.0;
|
|
double mask_worst_us_ = 0.0;
|
|
int64_t mask_us_n_ = 0;
|
|
int64_t mask_fast_ = 0; /* memo hits */
|
|
int64_t mask_slow_ = 0; /* walks */
|
|
double mask_walk_us_ = 0.0; /* time spent in walks only */
|
|
double build_us_ = 0.0;
|
|
int64_t build_n_ = 0;
|
|
double accept_us_ = 0.0;
|
|
int64_t accept_n_ = 0;
|
|
void shard_mask(uint32_t* dst) const;
|
|
|
|
/* Requests whose grammar died this step. The engine drains and cancels them, so one bad
|
|
* request does not stop the step loop. */
|
|
std::vector<uint64_t> failed_;
|
|
|
|
/* ---------------------------------------------------------- logprobs */
|
|
/* RAD_MAX_LOGPROBS + 1 pairs, so a summary row is 44 floats: whole 16-byte words, which
|
|
* libr4d's all-gather of a split vocabulary requires. The extra pair is never reported. */
|
|
static constexpr int kLpK = RAD_MAX_LOGPROBS + 1;
|
|
static int64_t lp_width() { return 2 + 2 * (int64_t)kLpK; }
|
|
/* What raw_logit needs to undo a RAD_SP_LOGPROBS row's chain, saved by build_step: the
|
|
* staged row, the temperature the candidate value carries, the history window and the DRY
|
|
* breakers. Copied, because the next step rebuilds the staging. */
|
|
struct LpRow {
|
|
int64_t row = -1;
|
|
int32_t n_top = 0;
|
|
float temp = 1.0f; /* the candidate value is l / temp */
|
|
DeviceSampleParams p{};
|
|
std::vector<int32_t> hist; /* the staged history row, [0, hist_len) */
|
|
const DryBreakers* dry = nullptr; /* lives in seqs_ for the request's lifetime */
|
|
};
|
|
std::vector<LpRow> lp_rows_;
|
|
/* Rank 0's copies, written behind the pick: the summaries ([rows, W * lp_width()], W ranks
|
|
* side by side) and the candidate planes the pick drew from. */
|
|
float* lp_host_ = nullptr;
|
|
int32_t* lp_ci_host_ = nullptr;
|
|
float* lp_cv_host_ = nullptr;
|
|
int64_t lp_lo_ = 0, lp_hi_ = 0; /* the rows copied, [lo, hi) */
|
|
/* A token's raw logit from the value the pick drew it at: temperature, DRY and the penalties
|
|
* undone in reverse order. */
|
|
float raw_logit(const LpRow& L, int32_t token, float v) const;
|
|
|
|
/* Per-request grammar and DRY state. Not in Request, a frozen struct the scheduler copies,
|
|
* which a unique_ptr member would make non-copyable. */
|
|
std::unordered_map<uint64_t, SeqState> seqs_;
|
|
|
|
int stage_alloc();
|
|
void stage_free();
|
|
};
|
|
|
|
/* Merge `W` ranks' `sample_logprobs` rows of `k` pairs each, side by side in `st`
|
|
* (W * (2 + 2k) floats). Sets the combined log normaliser and fills up to `cap` of the largest
|
|
* (id, logit) pairs, descending, ties to the lower id; returns how many. Ranks with a non-finite
|
|
* maximum or normaliser and pairs with a non-finite logit are skipped; `*log_z` is NaN when no
|
|
* rank contributes. W = 1 is valid. Used by Sampler::logprobs_for. */
|
|
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
|
|
int cap);
|
|
|
|
} /* namespace rad */
|