radiance 1.12.0

New models:
- Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference
  clips (the `references` field of /v1/audio/speech and the streaming session), two cards
- Gemma 4 E2B/E4B (KV-shared layers, per-layer embeddings, clipped vision linears), with
  NVIDIA-Nemotron-3.5-Bolt-E4B in bf16 with DFlash and vision on one card, and E4B recipes

Speed:
- MXFP4 GEMMs for one to 64 rows and a tiled prefill GEMM at TN=4 from 1024 rows: the 27B MXFP4
  with DFlash2 decodes about 1% faster at c1, 5% at c4 and 14% at c16
- The fp8 and int8 LM heads read their weight once for 65 to 128 rows
- A prefill step of one sequence runs in two pieces on a second lane at two ranks (qwen35_fp8,
  gemma3): a 45K-token prompt on the 27B fp8 in 15.1 s instead of 16.2 s
- Gemma 3's fused all-reduce junctions also under a lossy wire
- --draft-short-from N: a block drafter runs its shorter block from N decoding sequences on
  (off by default; with 8 on the 27B MXFP4: c8 +12%, c16 +18%, c64 +32%, c1 unchanged)
- --tp-attn-split rows: GLM-5.3-Flash's MLA attention split by rows over the ranks, 18 to 21%
  faster prefill; lossy, `heads` stays the default
- --draft-coupling on: Qwen3.8-Flash-Next's MTP drafter samples its proposals from its reranked
  top-8 and the target's draw is coupled to it; pays at high temperatures (c1 at T 1.0: 155 ->
  178 tok/s), costs at low ones; off by default

Features:
- Edited prompts on windowed models (Gemma 4) reuse their prefix: periodic window snapshots, and
  snapshot-backed prefix KV kept across recomputes (an edited tail on Gemma 4 31B: 96 s -> 2.6 s)
- DELETE /sessions/<label> and DELETE /sessions?id=<id> forget one stored conversation
- --state-cache-dtype f16: the delta-net state cache at half the memory (qwen35 plugins; lossy)

Fixes:
- A browser's CORS preflight allows DELETE

Changes: Plugin ABI 27: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are flags now (--tp-attn-split, --draft-coupling, --state-cache-dtype).
This commit is contained in:
137 files changed
+12959 -1126

No files matched your search

+1
View File
@@ -128,6 +128,7 @@ public:
int lora_root(const char* native, const char* spellings);
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
int64_t from_hi, int64_t to_lo);
int drafter_short_block(int64_t block);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
+99 -3
View File
@@ -1418,7 +1418,12 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
: prog_.generator.layout != 0 ? "an image generator" : "a video generator");
return RAD_E_STATE;
}
if (!d->tmpl || !std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}")) {
if (!d->tmpl && !d->tmpl_plain) {
err(RAD_E_INVAL, "declare_audio_generator '%s': no prompt template (tmpl or tmpl_plain)",
nm);
return RAD_E_INVAL;
}
if (d->tmpl && (!std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}"))) {
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm);
return RAD_E_INVAL;
}
@@ -1428,6 +1433,45 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
"instructions and needs {input} alone", nm);
return RAD_E_INVAL;
}
/* References: a template with both of its slots, an item with one transcript before its one
* clip, and the clips' geometry; read whole by one branch's prompt (an unconditional branch
* would need references of its own). */
if (d->tmpl_ref) {
auto once = [](const char* t, const char* k) {
const char* a = t ? std::strstr(t, k) : nullptr;
return a && !std::strstr(a + 1, k);
};
const char* au = d->ref_item ? std::strstr(d->ref_item, "{audio}") : nullptr;
const char* tx = d->ref_item ? std::strstr(d->ref_item, "{text}") : nullptr;
if (!once(d->tmpl_ref, "{references}") || !once(d->tmpl_ref, "{input}") ||
std::strstr(d->tmpl_ref, "{instructions}") || !once(d->ref_item, "{audio}") ||
!once(d->ref_item, "{text}") || !au || !tx || tx > au) {
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_ref needs {references} and "
"{input} once each, and ref_item {text} before its one {audio}", nm);
return RAD_E_INVAL;
}
if (d->branches != 1 || !d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 ||
d->ref_max <= 0 || d->ref_max_samples < d->ref_hop) {
err(RAD_E_INVAL, "declare_audio_generator '%s': references are read by a model of one "
"branch from whole prompts, clips at a rate (%lld Hz) in frames of "
"%lld samples, at most %d of them and %lld samples a request", nm,
(long long)d->ref_rate, (long long)d->ref_hop, (int)d->ref_max,
(long long)d->ref_max_samples);
return RAD_E_INVAL;
}
}
if (d->branches != 0 && d->branches != 1 && d->branches != 2) {
err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence "
"or 2 (0 means 2)", nm, (int)d->branches);
return RAD_E_INVAL;
}
/* One branch has no unconditional prompt to render and no guidance to apply. */
if (d->branches == 1 && (d->neg_tmpl || d->default_cfg != 1.0)) {
err(RAD_E_INVAL, "declare_audio_generator '%s': a model of one branch has no "
"unconditional template and no guidance (default_cfg %g)", nm,
d->default_cfg);
return RAD_E_INVAL;
}
if (d->neg_tmpl && !d->prompt_whole) {
err(RAD_E_INVAL, "declare_audio_generator '%s': an unconditional template makes branches "
"of different lengths, which step together only as whole prompts; set "
@@ -1505,15 +1549,24 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
!buf_ok(d->audio_out, RAD_F32, win_samples * d->channels, "audio_out"))
return RAD_E_INVAL;
prog_.agen_str.name = nm;
prog_.agen_str.tmpl = d->tmpl;
prog_.agen_str.tmpl = d->tmpl ? d->tmpl : "";
prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : "";
prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : "";
prog_.agen_str.tmpl_ref = d->tmpl_ref ? d->tmpl_ref : "";
prog_.agen_str.ref_item = d->tmpl_ref && d->ref_item ? d->ref_item : "";
prog_.audio_gen = *d;
/* As for the image generator: the Program is moved after declare; strings live in agen_str. */
prog_.audio_gen.name = nullptr;
prog_.audio_gen.tmpl = nullptr;
prog_.audio_gen.tmpl_plain = nullptr;
prog_.audio_gen.neg_tmpl = nullptr;
prog_.audio_gen.tmpl_ref = nullptr;
prog_.audio_gen.ref_item = nullptr;
/* Without references the clips' geometry is nothing: the driver stages none. */
if (!d->tmpl_ref) {
prog_.audio_gen.ref_rate = prog_.audio_gen.ref_hop = prog_.audio_gen.ref_max_samples = 0;
prog_.audio_gen.ref_max = 0;
}
return RAD_OK;
}
@@ -1800,6 +1853,13 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
(long long)d->proposal_pitch);
return RAD_E_INVAL;
}
if (d->kind == RAD_DRAFT_BLOCK && d->proposal_pitch > 0 && d->proposal_pitch < d->depth) {
err(RAD_E_INVAL, "declare_drafter '%s': proposal_pitch %lld under depth %d. A block pass "
"writes each sequence's %d proposals into one row of the proposal buffer, "
"so a row must hold them.", nm, (long long)d->proposal_pitch, d->depth,
d->depth);
return RAD_E_INVAL;
}
/* A block pass embeds the mask id at every unfilled position, so it needs one. */
if (d->kind == RAD_DRAFT_BLOCK && d->mask_token < 0) {
err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no mask_token. Every "
@@ -1843,7 +1903,11 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
prog_.drafter_name = nm;
prog_.drafter.name = nullptr;
prog_.drafter.block = block;
if (prog_.drafter.proposal_pitch == 0) prog_.drafter.proposal_pitch = 1;
/* A block drafter's proposal row holds its whole block's tokens, and the engine reads row s
* at s * pitch (a short block fills only its front), so its pitch defaults to depth; a serial
* one writes a token a pass, at pitch 1 by default. */
if (prog_.drafter.proposal_pitch == 0)
prog_.drafter.proposal_pitch = prog_.drafter.kind == RAD_DRAFT_BLOCK ? prog_.drafter.depth : 1;
return RAD_OK;
}
@@ -1935,6 +1999,33 @@ int Builder::lora_alias(const char* native, const char* from, const char* to, in
return RAD_OK;
}
/* A block drafter's shorter block (rad_builder.h). Validated at declare: the core stages the block
* from it, and a block the plugin did not declare its ops at would fail the step. */
int Builder::drafter_short_block(int64_t block) {
if (finished_) {
err(RAD_E_STATE, "drafter_short_block after declare finished");
return RAD_E_STATE;
}
if (prog_.drafter.kind != RAD_DRAFT_BLOCK) {
err(RAD_E_STATE, "drafter_short_block: %s. Only a BLOCK drafter proposes a block; declare "
"it with rad_declare_drafter first.",
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
: "the declared drafter is a SERIAL head");
return RAD_E_STATE;
}
const int64_t full = prog_.drafter.block > 0 ? prog_.drafter.block : prog_.drafter.depth + 1;
const int64_t lead = full - prog_.drafter.depth; /* rows ahead of the proposing ones */
if (block >= full || block - lead < 1) {
err(RAD_E_INVAL, "drafter_short_block '%s': %lld rows. The short block must be shorter "
"than the drafter's own (%lld) and still propose a token (more than %lld "
"rows).", prog_.drafter_name.c_str(), (long long)block, (long long)full,
(long long)lead);
return RAD_E_INVAL;
}
prog_.drafter_short_block = block;
return RAD_OK;
}
void Builder::note_v(const char* f, va_list ap) {
char msg[1024];
vsnprintf(msg, sizeof msg, f ? f : "", ap);
@@ -2462,6 +2553,11 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
int rad_drafter_short_block(RadBuilder* b, int64_t block) {
if (!b) return RAD_E_INVAL;
return B(b)->drafter_short_block(block);
}
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_encoder(d);
+6 -1
View File
@@ -270,7 +270,12 @@ int rad_tools_text_prepare(const LoadedPlugins& lp, int field, const std::string
std::string buf(in.size() * 2 + 64, '\0');
for (int tries = 0; tries < 2; ++tries) {
const int64_t n = ap->arch_text_prepare(field, in.c_str(), &buf[0], (int64_t)buf.size());
if (n < 0) return (int)n;
if (n < 0) {
/* The plugin's reason, when it left one in the (zeroed) buffer. */
buf.resize(std::strlen(buf.c_str()));
*out = std::move(buf);
return (int)n;
}
if (n < (int64_t)buf.size()) {
buf.resize((size_t)n);
*out = std::move(buf);
+1 -1
View File
@@ -93,7 +93,7 @@ const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const
* (rad_arch_text_prepare): RAD_OK with the result in `*out` (the text unchanged when the plugin
* states no rewrite), or the plugin's negative status. */
int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::string& in,
std::string* out);
std::string* out); /* on a refusal, `out` is its reason or "" */
/* The architecture plugin's video positions (rad_arch_video_positions), or null when it exports
* none. */
+43
View File
@@ -56,6 +56,10 @@ static const Flag g_flags[] = {
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 3\n"
"and 4, none at 8" },
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
{ "--tp-attn-split", "MODE", "heads (default) | rows -- how a prefill-sized step's\n"
"attention splits over the ranks: rows gives each rank all\n"
"heads of its rows, a faster prefill for the projections at\n"
"full width on every card; not bit-identical to heads" },
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
"asks the driver, on requires peer access and stops without\n"
"it, off exchanges through pinned host memory" },
@@ -75,6 +79,9 @@ static const Flag g_flags[] = {
{ "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n"
"context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n"
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
{ "--state-cache-dtype", "T", "f32 (default) | f16 -- the recurrent state cache (delta net):\n"
"f16 halves the state pool, its checkpoints and its traffic,\n"
"and is lossy; the qwen35 plugins serve it" },
{ "--attn-prefill-fp8", "MODE", "off (default) | qk | pv | both -- the prefill attention's\n"
"Q.K^T, P.V or both as e4m3 WMMA over an fp8, fp8_v4 or\n"
"k6_v4 cache: faster at long context, and lossy" },
@@ -158,6 +165,13 @@ static const Flag g_flags[] = {
" own operating point, which the plugin states. A container\n"
" with no draft head is unaffected -- auto resolves to 0." },
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
{ "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n"
"from N decoding sequences on (0 never, the default): the\n"
"long block pays at one sequence, the short one at many" },
{ "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter samples each proposal\n"
" from its own shortlist and the sampler couples the target's draw\n"
" to it: more accepted drafts on sampled requests, the same output\n"
" law, other tokens than off for a fixed seed" },
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
{ "--host", "ADDR", "listen address" },
@@ -441,6 +455,12 @@ int config_parse(int argc, char** argv, Config* c) {
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; }
}
else if (S("--tp-attn-split")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "heads")) c->tp_attn_rows = 0;
else if (!std::strcmp(v, "rows")) c->tp_attn_rows = 1;
else { RAD_ERR("--tp-attn-split takes heads or rows, not '%s'", v); return RAD_E_INVAL; }
}
else if (S("--p2p")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO;
@@ -492,6 +512,14 @@ int config_parse(int argc, char** argv, Config* c) {
}
c->kv_cache_dtype = v;
}
else if (S("--state-cache-dtype")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (std::strcmp(v, "f32") && std::strcmp(v, "f16")) {
RAD_ERR("--state-cache-dtype takes f32 or f16, not '%s'", v);
return RAD_E_INVAL;
}
c->state_cache_dtype = v;
}
else if (S("--attn-prefill-fp8")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "off")) c->attn_prefill_fp8 = 0;
@@ -652,6 +680,16 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
}
else if (S("--draft-short-from")) { if (!num(0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL; }
else if (S("--draft-coupling")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "off")) c->draft_coupling = false;
else if (!std::strcmp(v, "on")) c->draft_coupling = true;
else {
RAD_ERR("--draft-coupling takes off or on, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--draft-model")) {
/* Refused, not ignored: separate draft models are not supported (spec §10), and the
* drafter comes from the container (rad-convert --draft-model merges one in; an MTP
@@ -1034,6 +1072,7 @@ const ShowRow kShow[] = {
return or_none(s, "every library found"); } },
{ "--tp", [](const Config& c) { return num(c.tp); } },
{ "--tp-wire", [](const Config& c) { return std::string(c.tp_wire_exact ? "exact" : "wht6"); } },
{ "--tp-attn-split", [](const Config& c) { return std::string(c.tp_attn_rows ? "rows" : "heads"); } },
{ "--tp-wire-min-kb", [](const Config& c) { return num(c.tp_wire_min_kb); } },
{ "--p2p", [](const Config& c) {
return std::string(c.p2p == RAD_P2P_ON ? "on" : c.p2p == RAD_P2P_OFF ? "off" : "auto"); } },
@@ -1049,6 +1088,7 @@ const ShowRow kShow[] = {
{ "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } },
{ "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } },
{ "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } },
{ "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } },
{ "--attn-prefill-fp8", [](const Config& c) {
return std::string(attn_prefill_fp8_name(c.attn_prefill_fp8)); } },
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
@@ -1087,6 +1127,9 @@ const ShowRow kShow[] = {
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
{ "--draft-short-from", [](const Config& c) {
return c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
{ "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } },
{ "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
{ "--host", [](const Config& c) { return c.host; } },
{ "--port", [](const Config& c) { return num(c.port); } },
+38 -20
View File
@@ -156,6 +156,7 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
sc.max_spec = cfg_.n_spec;
sc.rank = rank;
sc.world_size = cfg_.tp;
sc.draft_coupling = cfg_.draft_coupling;
RAD_TRY(smp.declare(b, sc));
/* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the
@@ -354,7 +355,7 @@ int Engine::issue_ahead(const RadBatch** out) {
for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i)
sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_);
for (int i = 0; i < block_rows_; ++i)
sched_.expect_draft(block_row_[(size_t)i].seq, drafter_.depth);
sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_);
const RadBatch* nb = sched_.step_next();
if (!nb) return RAD_OK;
/* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance
@@ -452,22 +453,7 @@ int Engine::step_loop() {
idle = 0;
if (t_on) phase_mark(PH_PLAN);
/* Zero freshly assigned recurrent slots before the step that reads them. The manager
* records the grab but cannot write (StateClear in core/mem/kv.h); the list is empty except
* on a sequence's first step. Each rank clears by its own plan: the slot number is the
* scheduler's, but the state size depends on the heads this rank holds, which can differ
* per rank (rad_arch.h remainder_place). */
for (const StateClear& c : ranks_[0]->kv.state_clears()) {
for (auto& rk : ranks_) {
const KVGroupPlan* gp = rk->kv.plan(c.group);
if (!gp || !gp->stateful()) continue;
const int64_t bytes = gp->layer_bytes_per_state();
for (int64_t l = 0; l < gp->n_layers; ++l)
if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot))
rad_memset_async(p, 0, bytes, rk->ctx.stream());
}
}
ranks_[0]->kv.clear_state_clears();
clear_fresh_states();
/* Entries that want logits rows, in BatchBuilder's out_ids order: those with
* produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt
@@ -526,7 +512,7 @@ int Engine::step_loop() {
}
if (t_on) phase_mark(PH_BEGIN);
for (auto& rk : ranks_) {
const int s = rk->sampler.build_step(so.reqs);
const int s = rk->sampler.build_step(so.reqs, b->step);
if (s < 0) { RAD_ERR("sampler build_step: %s", rad_strerror(s)); return s; }
/* A request the sampler could not serve is cancelled; the step goes on. */
for (uint64_t id : rk->sampler.take_failed()) cancel.push_back(id);
@@ -714,6 +700,9 @@ int Engine::step_loop() {
st = embedding_ ? collect_pooled(b, so) : collect_step(b, so);
if (t_on) phase_mark(PH_COLLECT);
if (st < 0) return fail_loop(st);
/* The step's sampler chain, verify op included, has returned: one line at the first
* coupled verify that actually completed. */
couple_verify_evidence(b->step);
if (cfg_.kld()) {
st = score_rows(b, so);
if (st < 0) return fail_loop(st);
@@ -1364,6 +1353,25 @@ void Engine::drain_completed() {
for (uint64_t id : done_) for (auto& rk : ranks_) rk->sampler.end_request(id);
}
/* Zero freshly assigned recurrent slots before the step that reads them. The manager records the
* grab but cannot write (StateClear in core/mem/kv.h); the list is empty except on a sequence's
* first step. Each rank clears by its own plan: the slot number is the scheduler's, but the state
* size depends on the heads this rank holds, which can differ per rank (rad_arch.h
* remainder_place). */
void Engine::clear_fresh_states() {
for (const StateClear& c : ranks_[0]->kv.state_clears()) {
for (auto& rk : ranks_) {
const KVGroupPlan* gp = rk->kv.plan(c.group);
if (!gp || !gp->stateful()) continue;
const int64_t bytes = gp->layer_bytes_per_state();
for (int64_t l = 0; l < gp->n_layers; ++l)
if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot))
rad_memset_async(p, 0, bytes, rk->ctx.stream());
}
}
ranks_[0]->kv.clear_state_clears();
}
int Engine::serve(std::unique_ptr<StallWatch> watch) {
startup_watch_ = std::move(watch);
if (ranks_.empty() || !ranks_[0]->ctx.program()) {
@@ -1687,6 +1695,7 @@ std::string Engine::engine_info() const {
e["tp_wire"] = cfg_.tp > 1 ? (cfg_.tp_wire_exact ? "exact" : "wht6") : "n/a";
e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb;
e["attn_prefill_fp8"] = attn_prefill_fp8_name(cfg_.attn_prefill_fp8);
e["tp_attn_split"] = cfg_.tp_attn_rows ? "rows" : "heads";
e["max_num_batched_tokens"] = cfg_.max_tok;
e["placement"] = cfg_.placement;
/* Each lookup table's requested and resolved placement. */
@@ -2568,8 +2577,9 @@ int Engine::run_server() {
std::string* why) const override {
const int s = rad_tools_text_prepare(*plugins, field, in, out);
if (s < 0 && why)
*why = s == RAD_E_INVAL ? "the model cannot take this text"
: std::string(rad_strerror(s));
*why = !out->empty() ? *out
: s == RAD_E_INVAL ? "the model cannot take this text"
: std::string(rad_strerror(s));
return s;
}
int submit(std::unique_ptr<gen::AudioRequest> r, std::string* why) override {
@@ -2595,6 +2605,14 @@ int Engine::run_server() {
in.default_steps = ad.voc_chunk > 0 ? 0 : ad.default_steps;
in.default_cfg = ad.default_cfg;
in.max_lanes = ad.max_lanes;
in.branches = ad.branches == 1 ? 1 : 2;
in.input_special = ad.input_special != 0;
in.tmpl_ref = pg.agen_str.tmpl_ref;
in.ref_item = pg.agen_str.ref_item;
in.ref_rate = ad.ref_rate;
in.ref_hop = ad.ref_hop;
in.ref_max_samples = ad.ref_max_samples;
in.ref_max = ad.ref_max;
audio_bridge.drv = aud_gen_;
audio_bridge.plugins = &plugins_;
d.audio = &audio_bridge;
+33
View File
@@ -19,6 +19,7 @@
*/
#pragma once
#include "rad_core.h"
#include "rad_spechub.h" /* RadMtpCoupleDraw/State: the coupled MTP wire rows */
#include "cvec.h"
#include <map>
#include <set>
@@ -338,6 +339,10 @@ private:
* string because RadDrafterDecl::name points into the Program. */
RadDrafterDecl drafter_{};
std::string drafter_name_;
/* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or
* --draft-short-from is 0. */
int64_t drafter_short_ = 0;
bool short_on_ = false; /* the short block runs now (block_shape) */
/* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding
* the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */
@@ -373,6 +378,9 @@ private:
gen::AudioDriver* aud_gen_ = nullptr;
gen::VideoDriver* vid_gen_ = nullptr;
int gen_loop();
/* Zeroes the state slots the KV manager granted since the last step, on every rank's stream,
* before the step or pass that first reads them. */
void clear_fresh_states();
bool serial_drafting() const;
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
int issue_serial_drafter(int step, StepOut& so);
@@ -395,6 +403,25 @@ private:
void step_state_fini();
StepSlot* slots_host_ = nullptr;
/* --draft-coupling (engine_draft.cpp). The head declares `mtp_couple_draws` and
* `mtp_couple_state`; the engine stages one draw per drafting row before the serial passes and
* reads the states back once, then binds each to the verify row it will be coupled at. */
bool mtp_couple_ = false;
rad_buf couple_draws_buf_ = 0, couple_state_buf_ = 0;
int64_t couple_rows_ = 0; /* the state plane's rows per round */
RadMtpCoupleDraw* couple_draw_stage_ = nullptr; /* pinned [max_seqs] */
RadMtpCoupleState* couple_readback_ = nullptr; /* pinned [rounds, couple_rows_] */
std::vector<RadMtpCoupleDraw> couple_by_card_; /* the plan's draw per card slot */
RadMtpCoupleState couple_bound_[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
bool couple_evidence_ = false; /* the completed-verify line was written (once a process) */
bool couple_host_note_ = false; /* the host-domain counterpart was written (once) */
bool couple_malformed_note_ = false; /* a status -1 round was reported (once) */
int stage_couple_draws(int n);
/* One INFO line at the first coupled verify that completed: the step, the live requests whose
* rows carried a bound state, the kernel and its domain. Read from the sampler's build
* snapshot after collect_step's wait, so it reports a finished verify, not an enqueue. */
void couple_verify_evidence(int step);
/* Step-time attribution, Debug only (see the barrier in step_loop): time per scheduler phase.
* The nine phases sum to the whole step, including the readback, commit and drafter after the
* join. */
@@ -413,10 +440,16 @@ private:
int block_pass(const RadBatch* db, const char* what, int step);
int issue_block_drafter(int step, StepOut& so);
int finish_block_drafter(const StepOut& so);
/* The block and proposal count this step's query pass runs at: the drafter's own, or its short
* block once --draft-short-from sequences decode, back to its own only two below. */
void block_shape(int* block, int* steps);
/* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows,
* in the query pass's order, and how many there are (0 when no query pass ran). */
std::vector<Scheduler::BlockRow> block_row_;
int block_rows_ = 0;
/* The proposals a row of the query pass took (block_shape), for finish_block_drafter and
* issue_ahead's expect_draft. */
int block_steps_ = 0;
/* Encoder driver (spec §11, core/engine_mm.cpp): encodes every media item the scheduler waits
* on, in passes of whole segments, and reads it back into the item. Runs between steps, never
* inside one. */
+55
View File
@@ -905,6 +905,9 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
bc.kv_quant = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4
: cfg_.kv_cache_dtype == "k6_v4" ? RAD_KVQ_K6V4 : RAD_KVQ_NONE;
bc.attn_prefill_fp8 = cfg_.attn_prefill_fp8;
bc.tp_attn_rows = cfg_.tp_attn_rows;
bc.state_dtype = cfg_.state_cache_dtype == "f16" ? RAD_F16 : 0;
bc.draft_coupling = cfg_.draft_coupling ? 1 : 0;
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
bc.scope = "";
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
@@ -1029,6 +1032,40 @@ int Engine::declare() {
return RAD_E_UNSUPPORTED;
}
}
/* The row split is a graph only the plugin can declare, and it splits over ranks. A plugin
* that does not say it serves it (RadArchProbe::tp_attn_rows_ok), or a single rank, would
* serve the head split under a name that promised the other, so the flag is refused rather
* than ignored. */
if (cfg_.tp_attn_rows) {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
if (!pb.tp_attn_rows_ok) {
RAD_ERR("--tp-attn-split rows: the '%s' plugin does not split attention by rows for "
"this model (heads does)", plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
if (cfg_.tp < 2) {
RAD_ERR("--tp-attn-split rows splits a prefill's attention over tensor-parallel ranks, "
"and --tp %d has none to split over (heads does)", cfg_.tp);
return RAD_E_INVAL;
}
RAD_WARN("attention: a prefill-sized step splits by rows over the %d ranks "
"(--tp-attn-split rows): every card holds the attention's projections at full "
"width, and the result is not bit-identical to the head split", cfg_.tp);
}
/* Likewise an f16 recurrent state: a plugin that does not say it declares one would keep f32
* under a flag that promised half the state memory. */
if (cfg_.state_cache_dtype == "f16") {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
if (!pb.state_f16_ok) {
RAD_ERR("--state-cache-dtype f16: the '%s' plugin does not declare its recurrent state "
"at f16 for this model (f32 does)", plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
RAD_INFO("recurrent state cache: f16 (--state-cache-dtype), half the state memory; lossy, "
"the generated text differs from f32");
}
/* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is
* selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel
* bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of
@@ -1303,6 +1340,24 @@ int Engine::declare() {
drafter_name_ = p0.drafter_name;
drafter_.name = drafter_name_.c_str();
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && cfg_.draft_short_from > 0
? p0.drafter_short_block : 0;
if (cfg_.draft_short_from > 0 && drafter_.kind == RAD_DRAFT_NONE)
RAD_WARN("--draft-short-from %lld: this deployment runs no drafter, so there is no block "
"to shorten", (long long)cfg_.draft_short_from);
else if (cfg_.draft_short_from > 0 && !drafter_short_)
RAD_WARN("--draft-short-from %lld: '%s' %s", (long long)cfg_.draft_short_from,
drafter_name_.c_str(),
drafter_.kind == RAD_DRAFT_BLOCK ? "declares no shorter block, so it keeps its own"
: "is a serial head, which proposes no block");
if (drafter_short_)
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
"row(s), %lld token(s)", (long long)cfg_.draft_short_from,
drafter_name_.c_str(),
(long long)drafter_short_,
(long long)(drafter_short_ - ((drafter_.block > 0 ? drafter_.block
: drafter_.depth + 1) -
drafter_.depth)));
if (drafter_.kind != RAD_DRAFT_NONE) {
/* A zero proposal handle means the sampler's token buffer: the head's logits go through
* the ordinary sampler chain. */
+175 -5
View File
@@ -6,6 +6,9 @@
*/
#include "engine_priv.h"
#include "sample/mtp_couple_evidence.h"
#include "sched/mtp_couple_bind.h"
#include "sched/mtp_couple_plan.h"
#include "sched/scheduler.h"
#include "device/device.h"
@@ -13,6 +16,7 @@
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
@@ -48,6 +52,55 @@ int Engine::step_state_init() {
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0]->device));
slots_host_ = static_cast<StepSlot*>(rad_dev_alloc(slot_bytes, RAD_MEM_HOST_PINNED));
if (!slots_host_) return RAD_E_NOMEM;
/* --draft-coupling: the head's two planes, found by name in the declared program, and the
* pinned staging beside them. A program without them is refused rather than served
* uncoupled. */
mtp_couple_ = cfg_.draft_coupling;
if (mtp_couple_) {
/* Coupling is defined on a linear serial chain. A block drafter proposes a whole block
* from one pass, so it has no per-round draw to couple and no per-round state. */
if (drafter_.kind != RAD_DRAFT_SERIAL || drafter_.depth <= 0) {
RAD_ERR("--draft-coupling on requires the linear serial draft chain (RAD_DRAFT_SERIAL "
"with depth > 0); this model declares drafter '%s' kind %d depth %d, which has "
"no per-round draw to couple",
drafter_.name ? drafter_.name : "(none)", drafter_.kind, drafter_.depth);
return RAD_E_UNSUPPORTED;
}
const Program& prog = ranks_[0]->program;
for (size_t i = 0; i < prog.buffers.size(); ++i) {
const std::string& name = prog.buffers[i].name;
auto ends = [&](const char* suffix) {
const size_t n = std::strlen(suffix);
return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0;
};
if (ends("mtp_couple_draws")) couple_draws_buf_ = (rad_buf)i;
if (ends("mtp_couple_state")) couple_state_buf_ = (rad_buf)i;
}
if (!couple_draws_buf_ || !couple_state_buf_) {
RAD_ERR("--draft-coupling on, but the architecture declared no coupled MTP planes; "
"this model's drafter cannot couple");
return RAD_E_STATE;
}
const RadBufDecl& sd = prog.buffers[couple_state_buf_].decl;
if (sd.rank != 3 || sd.shape[2] != (int64_t)RAD_MTP_COUPLE_STATE_WORDS) {
RAD_ERR("--draft-coupling: 'mtp_couple_state' is not the [rounds, rows, %d]-word "
"plane the coupling reads", (int)RAD_MTP_COUPLE_STATE_WORDS);
return RAD_E_STATE;
}
couple_rows_ = sd.shape[1];
/* One entry per card slot, indexed by StepEntry::card as slots_host_ is. */
couple_by_card_.assign((size_t)n_slot, RadMtpCoupleDraw{});
couple_draw_stage_ = static_cast<RadMtpCoupleDraw*>(
rad_dev_alloc(n_slot * (int64_t)sizeof(RadMtpCoupleDraw), RAD_MEM_HOST_PINNED));
couple_readback_ = static_cast<RadMtpCoupleState*>(rad_dev_alloc(
(int64_t)drafter_.depth * couple_rows_ * (int64_t)sizeof(RadMtpCoupleState),
RAD_MEM_HOST_PINNED));
if (!couple_draw_stage_ || !couple_readback_) return RAD_E_NOMEM;
RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the final reranked top8, maximal "
"coupling at the verify; fixed-seed tokens are NOT preserved", drafter_.depth);
}
RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
return RAD_OK;
}
@@ -62,6 +115,10 @@ void Engine::step_state_fini() {
}
if (slots_host_) rad_dev_free(slots_host_, RAD_MEM_HOST_PINNED);
slots_host_ = nullptr;
if (couple_draw_stage_) rad_dev_free(couple_draw_stage_, RAD_MEM_HOST_PINNED);
if (couple_readback_) rad_dev_free(couple_readback_, RAD_MEM_HOST_PINNED);
couple_draw_stage_ = nullptr;
couple_readback_ = nullptr;
if (step_end_) rad_event_destroy(step_end_);
step_end_ = nullptr;
}
@@ -142,6 +199,8 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
if (rounds <= 0) return RAD_OK;
serial_rounds_ = rounds;
serial_rows_ = n;
/* Before any serial pass reads a draw; round 1 is the history pass below. */
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(n));
/* RADIANCE_DEBUG_STAGE: running means of a draft pass's host time: batch + advance, greedy
* sampler chain, barrier release and issue. They cost the step nothing until their sum exceeds
@@ -213,6 +272,15 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
* history (Scheduler::serial_batch). */
RAD_TRY(advance_all(ADV_TAKE, serial_done_, true, n));
Rank& r0 = *ranks_[0];
if (mtp_couple_) {
/* Rounds 1..done of the drafting rows, on the same stream as the slots below. */
const void* state = r0.ctx.buf_ptr(couple_state_buf_);
if (!state || serial_done_ > (int)drafter_.depth) return RAD_E_STATE;
const int64_t pitch = couple_rows_ * (int64_t)sizeof(RadMtpCoupleState);
RAD_TRY(rad_memcpy_2d_async(couple_readback_, pitch, state, pitch,
(int64_t)n * (int64_t)sizeof(RadMtpCoupleState), serial_done_,
r0.ctx.stream()));
}
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
return RAD_OK;
@@ -253,8 +321,91 @@ int Engine::finish_serial_drafter(const StepOut& so) {
/* No draft for a request the sampler will not speculate on (a constraining grammar that
* cannot snapshot its state); the sampler would refuse the next step otherwise. */
if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue;
sched_.set_draft(serial_row_[(size_t)i].seq,
&draft_out_[(size_t)i * (size_t)rounds], done);
const uint64_t seq = serial_row_[(size_t)i].seq;
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)rounds], done);
if (!mtp_couple_) continue;
/* Bound only for a request still running: one this commit finished, or whose draft the
* scheduler refused, binds nothing, and set_mtp_couple(..., 0) clears an earlier step's
* states (RAD_E_NOTFOUND for a request the sampler already dropped).
*
* The position is the committed output length after this commit, the n_out the next
* build_step reads. It comes from the scheduler's commit snapshot, not the plan's Request
* pointer, which reap() may already have freed (sched/mtp_couple_bind.h). */
MtpCoupleBindPoint bp;
bp.found = sched_.committed_seq(seq, &bp.n_out, &bp.live);
if (!bp.found)
RAD_WARN("MTP coupled: serial row for sequence %llu is not in the committed step; "
"clearing its coupling", (unsigned long long)seq);
int n_bound = 0, n_malformed = 0;
std::string why;
const int bs = mtp_couple_bind_rounds(
bp, couple_draw_stage_[(size_t)i], &couple_readback_[(size_t)i], (int)couple_rows_,
done, slots_host_[serial_row_[(size_t)i].card], meta_.n_vocab, couple_bound_,
&n_bound, &why, &n_malformed);
if (bs < 0) { RAD_ERR("%s", why.c_str()); return bs; }
if (n_malformed > 0 && !couple_malformed_note_) {
couple_malformed_note_ = true;
RAD_WARN("MTP coupled: sequence %llu: %d draft round(s) had a shortlist with no valid "
"Q (non-finite score, duplicate id or no live entry); those rounds keep the "
"greedy proposal and the ordinary verify (logged once)",
(unsigned long long)seq, n_malformed);
}
for (auto& rk : ranks_) {
const int st = rk->sampler.set_mtp_couple(seq, couple_bound_,
rc == RAD_OK ? n_bound : 0);
if (st < 0 && st != RAD_E_NOTFOUND) return st;
}
}
return RAD_OK;
}
/* One line, once, at the first coupled verify that completed. It reads the snapshot build_step
* froze for the step whose wait just returned (sample/mtp_couple_evidence.h), which the
* drafter's build_greedy does not clear, and checks that run() issued the verify for that build.
* Sequences are re-checked as Running after the wait. Request numbers, the row count and the
* kernel name only; a host-domain row is labelled as such. */
void Engine::couple_verify_evidence(int step) {
if (!mtp_couple_ || couple_evidence_) return;
Sampler& smp = ranks_[0]->sampler;
const rad_op op = smp.staged_couple_op();
const MtpCoupleEvidence ev = mtp_couple_evidence(
smp.couple_build(), step, ranks_[0]->ctx.op_domain(op),
[this](uint64_t seq) { return sched_.running(seq); });
if (ev.rows <= 0 || smp.staged_couple_issued_step() != step) return;
const char* kernel = ranks_[0]->ctx.ip_kernel_name(op);
if (ev.device) {
couple_evidence_ = true;
RAD_INFO("MTP coupled verify completed: step %d, %lld bound row(s) over request(s) [%s], "
"kernel %s, domain device", step, (long long)ev.rows, ev.seqs.c_str(), kernel);
} else if (!couple_host_note_) {
couple_host_note_ = true;
RAD_INFO("MTP coupled verify completed on the host domain: step %d, %lld bound row(s) over "
"request(s) [%s], kernel %s -- not device evidence", step, (long long)ev.rows,
ev.seqs.c_str(), kernel);
}
}
/* --draft-coupling: the draw for every drafting row, before any serial pass reads it.
*
* The coordinate is the pre-commit output size, which strictly grows between two steps that draft
* one request, so (base, round) never repeats a draft stream. The card is the slot the advance
* writes; the propose op keeps the greedy proposal for a row whose draw names another card. The
* rule is sched/mtp_couple_plan.h. */
int Engine::stage_couple_draws(int n) {
std::string why;
const int stg = mtp_couple_plan_stage(sched_.plan(),
(int)(cfg_.max_seqs > 0 ? cfg_.max_seqs : 1),
serial_row_.data(), n, &couple_by_card_,
couple_draw_stage_, &why);
if (stg < 0) {
RAD_ERR("MTP coupled: %s", why.c_str());
return stg;
}
for (auto& rk : ranks_) {
void* dst = rk->ctx.buf_ptr(couple_draws_buf_);
if (!dst) return RAD_E_STATE;
RAD_TRY(rad_memcpy_async(dst, couple_draw_stage_,
n * (int64_t)sizeof(RadMtpCoupleDraw), rk->ctx.stream()));
}
return RAD_OK;
}
@@ -313,6 +464,21 @@ bool Engine::block_drafting() const {
* and its proposals go into the slots behind the anchor (ADV_BTAKE): exactly the token row the
* next verify reads (ADV_TRUNK), so the step issued ahead verifies them with no host round trip.
* collect_step's wait covers both passes and the slots' readback. */
void Engine::block_shape(int* block, int* steps) {
*steps = drafter_.depth;
/* The row count is the drafter's (defaulted and checked by declare_drafter). */
*block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
/* Its short block under load (rad_drafter_short_block): the same anchor convention, so as many
* fewer proposals as rows. The load is the step just run's, which the next step, the one these
* proposals are for, mostly repeats (Scheduler::short_block_on). */
if (drafter_short_ <= 0) return;
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), cfg_.draft_short_from);
if (short_on_) {
*steps -= *block - (int)drafter_short_;
*block = (int)drafter_short_;
}
}
int Engine::issue_block_drafter(int step, StepOut& so) {
block_rows_ = 0;
if (!block_drafting()) return RAD_OK;
@@ -321,8 +487,12 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
/* The sampled ids before either pass, as the serial driver reads them. */
RAD_TRY(collect_issue(so));
const int steps = drafter_.depth;
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
/* The short block too (block_shape): its query pass is a shorter batch the card positions
* the same way, its proposals the front of each row at the drafter's pitch (ADV_BTAKE), and
* the step issued ahead verifies that many (issue_ahead). */
int block = 0, steps = 0;
block_shape(&block, &steps);
block_steps_ = steps;
block_row_.resize((size_t)cfg_.max_seqs);
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
@@ -368,7 +538,7 @@ int Engine::finish_block_drafter(const StepOut& so) {
if (block_rows_ <= 0) return RAD_OK;
Rank& r0 = *ranks_[0];
const int steps = drafter_.depth;
const int steps = block_steps_;
draft_out_.assign((size_t)block_rows_ * (size_t)steps, 0);
for (int i = 0; i < block_rows_; ++i) {
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
+2
View File
@@ -53,6 +53,8 @@ int Engine::gen_loop() {
continue;
}
idle = 0;
/* A hybrid model's recurrent state: the slots a newly admitted request was granted. */
clear_fresh_states();
if (const int ps = prepare_release(b); ps < 0) return stop(ps);
for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot());
issue_what_.store(kIssueModel, std::memory_order_release);
+53 -1
View File
@@ -855,7 +855,10 @@ int Checkpoint::open_safetensors(const std::string& path) {
RAD_TRY(meta_merge_generation_config(md, &meta_));
RAD_TRY(meta_merge_preprocessor_configs(md, &meta_));
if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_;
if (!is_file && !is_index) RAD_TRY(add_companions());
if (!is_file && !is_index) {
RAD_TRY(add_companions());
RAD_TRY(add_torch_files());
}
/* FP8's block, where the checkpoint states one. */
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
long long r = 0, c = 0;
@@ -898,6 +901,55 @@ int Checkpoint::add_companions() {
return RAD_OK;
}
/* PyTorch checkpoints beside the safetensors (torch_zip.h): a model whose part ships only as a
* torch.save file, such as Fish Audio drama-3's codec.pth, read as data, never unpickled. Each is
* read under `<stem>.`, in name order. A file the weights-only reader refuses (a pickled training
* state, an optimiser) is not an error of the checkpoint, only of a plugin that maps its tensors,
* which then finds them absent; the warning says why. A torch copy of the model's own weights
* (`pytorch_model*.pth`, `consolidated*.pth`) is passed over, as the safetensors are read. */
int Checkpoint::add_torch_files() {
std::vector<std::string> files;
std::error_code ec;
for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) {
if (!de.is_regular_file(ec)) continue;
const std::string f = de.path().filename().string();
if (f.size() <= 4 || f.compare(f.size() - 4, 4, ".pth") != 0) continue;
if (f.rfind("pytorch_model", 0) == 0 || f.rfind("consolidated", 0) == 0) continue;
files.push_back(f);
}
std::sort(files.begin(), files.end());
for (const std::string& f : files) {
auto tz = std::make_unique<TorchZipFile>();
std::string why;
const std::string path = dir_ + "/" + f;
if (tz->open(path, &why) < 0) {
RAD_WARN("%s: not read (%s); a plugin that maps its tensors will not find them",
path.c_str(), why.c_str());
continue;
}
const std::string prefix = f.substr(0, f.size() - 4) + ".";
for (const TorchTensor& t : tz->tensors()) {
if (index_.count(prefix + t.name)) {
RAD_ERR("%s: '%s%s' is already in the checkpoint", path.c_str(), prefix.c_str(),
t.name.c_str());
return RAD_E_FORMAT;
}
SrcTensor s;
s.name = prefix + t.name;
s.rad_dtype = t.dtype;
s.shape = t.shape;
s.data = t.data;
s.bytes = (int64_t)t.bytes;
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
RAD_INFO("%s: %zu tensors under '%s', read from the pickle as data", path.c_str(),
tz->tensors().size(), prefix.c_str());
torch_.push_back(std::move(tz));
}
return RAD_OK;
}
/* Which published quantisation this is, from quantization_config alone; import_piece checks the
* tensors weight by weight, refusing a file at the first weight that disagrees. */
void Checkpoint::detect_import() {
+3
View File
@@ -24,6 +24,7 @@
#include "../rad_internal.h"
#include "../rad_core.h"
#include "safetensors.h"
#include "torch_zip.h"
#include "../text/gguf.h"
#include <deque>
@@ -187,6 +188,7 @@ private:
int open_diffusers();
int open_sgm();
int add_companions();
int add_torch_files();
int open_gguf(const std::string& path);
void detect_import();
@@ -195,6 +197,7 @@ private:
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
std::vector<std::unique_ptr<TorchZipFile>> torch_;
std::vector<SrcTensor> tensors_;
std::unordered_map<std::string, size_t> index_;
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
+661
View File
@@ -0,0 +1,661 @@
/* torch_zip.cpp -- the zip directory and the weights-only pickle machine (torch_zip.h). */
#include "torch_zip.h"
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <unordered_map>
namespace rad {
namespace {
/* ================================================================== the zip directory */
struct Entry {
const uint8_t* data = nullptr;
uint64_t bytes = 0;
};
uint16_t u16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }
uint32_t u32(const uint8_t* p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
uint64_t u64(const uint8_t* p) { return (uint64_t)u32(p) | ((uint64_t)u32(p + 4) << 32); }
/* Every stored entry, by name. torch.save writes ZIP64 records past 4 GiB and pads each local
* header's extra field so a storage starts 64-byte aligned, which is why the data offset is read
* from the local header rather than assumed from the central one. */
int zip_entries(const uint8_t* b, uint64_t n, std::unordered_map<std::string, Entry>* out,
std::string* why) {
auto no = [&](const std::string& w) {
*why = w;
return RAD_E_FORMAT;
};
if (n < 22) return no("too short to be a zip archive");
/* The end-of-central-directory record: the last signature within a comment's reach. */
int64_t eocd = -1;
const uint64_t lo = n > 22 + 65535 ? n - 22 - 65535 : 0;
for (uint64_t at = n - 22 + 1; at-- > lo;)
if (u32(b + at) == 0x06054b50) {
eocd = (int64_t)at;
break;
}
if (eocd < 0) return no("no zip end-of-central-directory record");
if (u16(b + eocd + 4) != 0 || u16(b + eocd + 6) != 0) return no("a multi-disk zip archive");
uint64_t count = u16(b + eocd + 10), cd_size = u32(b + eocd + 12), cd_off = u32(b + eocd + 16);
if (count == 0xffff || cd_size == 0xffffffffu || cd_off == 0xffffffffu) {
if (eocd < 20 || u32(b + eocd - 20) != 0x07064b50)
return no("a ZIP64 archive without its end-record locator");
const uint64_t z = u64(b + eocd - 20 + 8);
if (n < 56 || z > n - 56 || u32(b + z) != 0x06064b50)
return no("a ZIP64 end record outside the file");
count = u64(b + z + 32);
cd_size = u64(b + z + 40);
cd_off = u64(b + z + 48);
}
if (cd_off > n || cd_size > n - cd_off) return no("the central directory lies outside the file");
if (count > ((uint64_t)1 << 20)) return no("more than a million zip entries");
uint64_t at = cd_off;
const uint64_t end = cd_off + cd_size;
for (uint64_t i = 0; i < count; ++i) {
if (end - at < 46 || at > end || u32(b + at) != 0x02014b50)
return no("a malformed central directory entry");
const uint16_t flags = u16(b + at + 8), method = u16(b + at + 10);
uint64_t csize = u32(b + at + 20), usize = u32(b + at + 24);
const uint64_t nl = u16(b + at + 28), el = u16(b + at + 30), cl = u16(b + at + 32);
uint64_t loff = u32(b + at + 42);
if (46 + nl + el + cl > end - at) return no("a central directory entry runs past its end");
const std::string name((const char*)b + at + 46, (size_t)nl);
/* The ZIP64 extra field: an 8-byte value for each 32-bit field at its maximum, in order. */
const uint8_t* ex = b + at + 46 + nl;
for (uint64_t e = 0; e + 4 <= el;) {
const uint64_t id = u16(ex + e), sz = u16(ex + e + 2);
if (e + 4 + sz > el) return no("a malformed extra field in '" + name + "'");
if (id == 1) {
uint64_t f = e + 4;
const uint64_t fe = e + 4 + sz;
auto take = [&](uint64_t* v) {
if (*v != 0xffffffffu) return true;
if (f + 8 > fe) return false;
*v = u64(ex + f);
f += 8;
return true;
};
if (!take(&usize) || !take(&csize) || !take(&loff))
return no("a short ZIP64 extra field in '" + name + "'");
}
e += 4 + sz;
}
if (flags & 1) return no("'" + name + "' is encrypted");
if (method != 0)
return no("'" + name + "' is compressed (method " + std::to_string(method) +
"); torch.save stores its entries, and a compressed storage cannot be mapped");
if (csize != usize) return no("'" + name + "' is stored with two different sizes");
if (n < 30 || loff > n - 30 || u32(b + loff) != 0x04034b50)
return no("'" + name + "' has no local header where the directory places it");
const uint64_t data = loff + 30 + u16(b + loff + 26) + u16(b + loff + 28);
if (data > n || usize > n - data) return no("'" + name + "' runs past the end of the file");
if (!out->emplace(name, Entry{ b + data, usize }).second)
return no("'" + name + "' is in the archive twice");
at += 46 + nl + el + cl;
}
return RAD_OK;
}
/* ================================================================== the pickle machine */
/* A value of the weights-only subset. Containers hold indices into the machine's pool, so a value
* reached twice through the memo is one value. */
struct V {
enum K : uint8_t { None, Bool, Int, Float, Str, Bytes, Tuple, List, Dict, Global, Storage,
Tensor } k = None;
int64_t i = 0; /* Int, Bool; Storage: numel */
double f = 0;
std::string s; /* Str, Bytes, Global's "module.name", Storage's key */
std::vector<size_t> a; /* Tuple, List; Dict: keys and values interleaved */
uint32_t dtype = 0; /* Storage */
std::string cls; /* Storage: its class */
size_t storage = 0; /* Tensor */
int64_t offset = 0; /* Tensor, in elements */
std::vector<int64_t> shape, stride; /* Tensor */
};
/* The storages torch writes a state dict's tensors into, and the dtype each holds. Doubles and
* complex storages have no RAD dtype and are refused by name where they appear. */
uint32_t storage_dtype(const std::string& g) {
static const struct { const char* name; uint32_t dt; } kS[] = {
{ "torch.FloatStorage", RAD_F32 }, { "torch.HalfStorage", RAD_F16 },
{ "torch.BFloat16Storage", RAD_BF16 }, { "torch.LongStorage", RAD_I64 },
{ "torch.IntStorage", RAD_I32 }, { "torch.ShortStorage", RAD_I16 },
{ "torch.CharStorage", RAD_I8 }, { "torch.ByteStorage", RAD_U8 },
{ "torch.BoolStorage", RAD_BOOL },
};
for (const auto& s : kS)
if (g == s.name) return s.dt;
return RAD_DT_INVALID;
}
/* torch's weights-only allow-list, the part a state dict uses. */
bool allowed_global(const std::string& g) {
return g == "collections.OrderedDict" || g == "torch._utils._rebuild_tensor_v2" ||
g == "torch._utils._rebuild_parameter" || storage_dtype(g) != RAD_DT_INVALID;
}
class Machine {
public:
Machine(const uint8_t* p, uint64_t n) : p_(p), n_(n) {}
/* The pickle's result, or a negative status with `why`. */
int run(size_t* result, std::string* why);
const V& at(size_t i) const { return pool_[i]; }
size_t size() const { return pool_.size(); }
private:
static constexpr size_t kMaxPool = (size_t)1 << 23;
static constexpr size_t kMaxStack = (size_t)1 << 20;
static constexpr uint64_t kMaxStr = (uint64_t)1 << 20;
int no(const std::string& w) {
why_ = w + " at byte " + std::to_string(at_) + " of the pickle";
return RAD_E_FORMAT;
}
bool need(uint64_t k) const { return n_ - at_ >= k; }
size_t add(V v) {
pool_.push_back(std::move(v));
return pool_.size() - 1;
}
bool pop(size_t* v) {
if (stack_.size() <= (marks_.empty() ? 0 : marks_.back())) return false;
*v = stack_.back();
stack_.pop_back();
return true;
}
/* The items above the last mark, and the mark gone. */
bool pop_mark(std::vector<size_t>* items) {
if (marks_.empty()) return false;
const size_t m = marks_.back();
marks_.pop_back();
items->assign(stack_.begin() + (std::ptrdiff_t)m, stack_.end());
stack_.resize(m);
return true;
}
int push(size_t v) {
if (stack_.size() >= kMaxStack || pool_.size() >= kMaxPool)
return no("the pickle builds more than its bounds allow");
stack_.push_back(v);
return RAD_OK;
}
int str(uint64_t len, V::K k) {
if (len > kMaxStr || !need(len)) return no("a string past its bound or the pickle's end");
V v;
v.k = k;
v.s.assign((const char*)p_ + at_, (size_t)len);
at_ += len;
return push(add(std::move(v)));
}
int integer(int64_t x) {
V v;
v.k = V::Int;
v.i = x;
return push(add(std::move(v)));
}
int global(const std::string& mod, const std::string& name) {
const std::string g = mod + "." + name;
if (!allowed_global(g))
return no("the global '" + g + "', which a weights-only checkpoint does not name; "
"nothing in the file is run, so it is refused");
V v;
v.k = V::Global;
v.s = g;
return push(add(std::move(v)));
}
int reduce();
int persistent_id();
const uint8_t* p_;
uint64_t n_;
uint64_t at_ = 0;
std::vector<V> pool_;
std::vector<size_t> stack_, marks_;
std::unordered_map<uint32_t, size_t> memo_;
std::string why_;
};
int Machine::persistent_id() {
size_t pid;
if (!pop(&pid)) return no("BINPERSID with nothing to read");
const V& t = pool_[pid];
/* ('storage', <storage class>, key, location, numel) */
if (t.k != V::Tuple || t.a.size() != 5 || pool_[t.a[0]].k != V::Str ||
pool_[t.a[0]].s != "storage" || pool_[t.a[1]].k != V::Global ||
pool_[t.a[2]].k != V::Str || pool_[t.a[4]].k != V::Int)
return no("a persistent id that is not a storage");
V s;
s.k = V::Storage;
s.cls = pool_[t.a[1]].s;
s.dtype = storage_dtype(s.cls);
s.s = pool_[t.a[2]].s;
s.i = pool_[t.a[4]].i;
if (s.dtype == RAD_DT_INVALID) return no("the storage class '" + s.cls + "'");
if (s.i < 0) return no("a storage of negative size");
return push(add(std::move(s)));
}
int Machine::reduce() {
size_t args, fn;
if (!pop(&args) || !pop(&fn)) return no("REDUCE without its callable and arguments");
if (pool_[fn].k != V::Global) return no("REDUCE of something that is not a global");
if (pool_[args].k != V::Tuple) return no("REDUCE with arguments that are not a tuple");
const std::string g = pool_[fn].s;
const std::vector<size_t> a = pool_[args].a;
if (g == "collections.OrderedDict") {
if (!a.empty()) return no("an OrderedDict built from arguments");
V d;
d.k = V::Dict;
return push(add(std::move(d)));
}
if (g == "torch._utils._rebuild_tensor_v2") {
/* (storage, storage_offset, size, stride, requires_grad, backward_hooks[, metadata]) */
if (a.size() < 4 || pool_[a[0]].k != V::Storage || pool_[a[1]].k != V::Int ||
pool_[a[2]].k != V::Tuple || pool_[a[3]].k != V::Tuple)
return no("_rebuild_tensor_v2 with arguments that are not a tensor's");
V t;
t.k = V::Tensor;
t.storage = a[0];
t.offset = pool_[a[1]].i;
for (size_t d : pool_[a[2]].a) {
if (pool_[d].k != V::Int || pool_[d].i < 0) return no("a tensor size that is not one");
t.shape.push_back(pool_[d].i);
}
for (size_t d : pool_[a[3]].a) {
if (pool_[d].k != V::Int) return no("a tensor stride that is not one");
t.stride.push_back(pool_[d].i);
}
if (t.shape.size() != t.stride.size() || t.shape.size() > RAD_MAX_RANK)
return no("a tensor whose size and stride disagree, or of rank past " +
std::to_string(RAD_MAX_RANK));
return push(add(std::move(t)));
}
if (g == "torch._utils._rebuild_parameter") {
/* (data, requires_grad, backward_hooks): the parameter is its tensor. */
if (a.empty() || pool_[a[0]].k != V::Tensor) return no("_rebuild_parameter of a non-tensor");
return push(a[0]);
}
return no("a call of '" + g + "'");
}
int Machine::run(size_t* result, std::string* why) {
auto fail = [&](int st) {
*why = why_;
return st;
};
auto line = [&](std::string* out) {
const uint8_t* e = (const uint8_t*)std::memchr(p_ + at_, '\n', (size_t)(n_ - at_));
if (!e || (uint64_t)(e - (p_ + at_)) > 4096) return false;
out->assign((const char*)p_ + at_, (size_t)(e - (p_ + at_)));
at_ = (uint64_t)(e - p_) + 1;
return true;
};
int st = RAD_OK;
while (at_ < n_) {
const uint8_t op = p_[at_++];
switch (op) {
case 0x80: /* PROTO */
if (!need(1) || p_[at_] < 2 || p_[at_] > 5) return fail(no("a pickle protocol other than 2..5"));
++at_;
break;
case 0x95: /* FRAME: a length hint */
if (!need(8)) return fail(no("a truncated FRAME"));
at_ += 8;
break;
case 'c': { /* GLOBAL "module\nname\n" */
std::string mod, name;
if (!line(&mod) || !line(&name)) return fail(no("a malformed GLOBAL"));
st = global(mod, name);
break;
}
case 0x93: { /* STACK_GLOBAL */
size_t nm, md;
if (!pop(&nm) || !pop(&md) || pool_[nm].k != V::Str || pool_[md].k != V::Str)
return fail(no("STACK_GLOBAL without a module and a name"));
st = global(pool_[md].s, pool_[nm].s);
break;
}
case 'q': case 'r': case 0x94: { /* BINPUT, LONG_BINPUT, MEMOIZE */
uint32_t k;
if (op == 'q') {
if (!need(1)) return fail(no("a truncated BINPUT"));
k = p_[at_++];
} else if (op == 'r') {
if (!need(4)) return fail(no("a truncated LONG_BINPUT"));
k = u32(p_ + at_);
at_ += 4;
} else {
k = (uint32_t)memo_.size();
}
if (stack_.empty()) return fail(no("a memo store with nothing to store"));
if (memo_.size() >= kMaxStack) return fail(no("a memo past its bound"));
memo_[k] = stack_.back();
break;
}
case 'h': case 'j': { /* BINGET, LONG_BINGET */
uint32_t k;
if (op == 'h') {
if (!need(1)) return fail(no("a truncated BINGET"));
k = p_[at_++];
} else {
if (!need(4)) return fail(no("a truncated LONG_BINGET"));
k = u32(p_ + at_);
at_ += 4;
}
auto it = memo_.find(k);
if (it == memo_.end()) return fail(no("a memo read of an empty slot"));
st = push(it->second);
break;
}
case '(': /* MARK */
if (marks_.size() >= kMaxStack) return fail(no("marks past their bound"));
marks_.push_back(stack_.size());
break;
case ')': { /* EMPTY_TUPLE */
V t;
t.k = V::Tuple;
st = push(add(std::move(t)));
break;
}
case 't': case 0x85: case 0x86: case 0x87: { /* TUPLE, TUPLE1..3 */
V t;
t.k = V::Tuple;
if (op == 't') {
if (!pop_mark(&t.a)) return fail(no("TUPLE without a mark"));
} else {
const int k = op - 0x84;
t.a.resize((size_t)k);
for (int j = k - 1; j >= 0; --j)
if (!pop(&t.a[(size_t)j])) return fail(no("a short tuple"));
}
st = push(add(std::move(t)));
break;
}
case ']': case '}': { /* EMPTY_LIST, EMPTY_DICT */
V c;
c.k = op == ']' ? V::List : V::Dict;
st = push(add(std::move(c)));
break;
}
case 'a': case 'e': { /* APPEND, APPENDS */
std::vector<size_t> items(1);
if (op == 'a') {
if (!pop(&items[0])) return fail(no("APPEND with nothing to append"));
} else if (!pop_mark(&items)) {
return fail(no("APPENDS without a mark"));
}
if (stack_.empty() || pool_[stack_.back()].k != V::List)
return fail(no("APPEND to something that is not a list"));
V& l = pool_[stack_.back()];
l.a.insert(l.a.end(), items.begin(), items.end());
break;
}
case 's': case 'u': { /* SETITEM, SETITEMS */
std::vector<size_t> kv(2);
if (op == 's') {
if (!pop(&kv[1]) || !pop(&kv[0])) return fail(no("SETITEM without a pair"));
} else if (!pop_mark(&kv) || kv.size() % 2) {
return fail(no("SETITEMS without whole pairs"));
}
if (stack_.empty() || pool_[stack_.back()].k != V::Dict)
return fail(no("a SETITEM on something that is not a dict"));
V& d = pool_[stack_.back()];
d.a.insert(d.a.end(), kv.begin(), kv.end());
break;
}
case 'b': { /* BUILD: an OrderedDict's state (a state dict's _metadata), ignored */
size_t state;
if (!pop(&state)) return fail(no("BUILD without a state"));
if (stack_.empty() || pool_[stack_.back()].k != V::Dict)
return fail(no("BUILD of something other than a dict"));
break;
}
case 'X': case 0x8c: case 0x8d: case 'B': case 'C': case 0x8e: {
/* BINUNICODE, SHORT_BINUNICODE, BINUNICODE8, BINBYTES, SHORT_BINBYTES, BINBYTES8 */
uint64_t len;
const int w = (op == 0x8c || op == 'C') ? 1 : (op == 0x8d || op == 0x8e) ? 8 : 4;
if (!need((uint64_t)w)) return fail(no("a truncated string length"));
len = w == 1 ? p_[at_] : w == 4 ? u32(p_ + at_) : u64(p_ + at_);
at_ += (uint64_t)w;
st = str(len, (op == 'B' || op == 'C' || op == 0x8e) ? V::Bytes : V::Str);
break;
}
case 'J': /* BININT */
if (!need(4)) return fail(no("a truncated BININT"));
st = integer((int32_t)u32(p_ + at_));
at_ += 4;
break;
case 'K': /* BININT1 */
if (!need(1)) return fail(no("a truncated BININT1"));
st = integer(p_[at_++]);
break;
case 'M': /* BININT2 */
if (!need(2)) return fail(no("a truncated BININT2"));
st = integer(u16(p_ + at_));
at_ += 2;
break;
case 0x8a: { /* LONG1: little-endian two's complement of up to 8 bytes here */
if (!need(1)) return fail(no("a truncated LONG1"));
const uint64_t k = p_[at_++];
if (k > 8 || !need(k)) return fail(no("a LONG1 wider than 64 bits"));
uint64_t v = 0;
for (uint64_t j = 0; j < k; ++j) v |= (uint64_t)p_[at_ + j] << (8 * j);
if (k > 0 && k < 8 && (p_[at_ + k - 1] & 0x80)) v |= ~(uint64_t)0 << (8 * k);
at_ += k;
st = integer((int64_t)v);
break;
}
case 'G': { /* BINFLOAT, big-endian */
if (!need(8)) return fail(no("a truncated BINFLOAT"));
uint64_t v = 0;
for (int j = 0; j < 8; ++j) v = (v << 8) | p_[at_ + j];
at_ += 8;
V f;
f.k = V::Float;
std::memcpy(&f.f, &v, 8);
st = push(add(std::move(f)));
break;
}
case 0x88: case 0x89: { /* NEWTRUE, NEWFALSE */
V v;
v.k = V::Bool;
v.i = op == 0x88;
st = push(add(std::move(v)));
break;
}
case 'N':
st = push(add(V{}));
break;
case 'Q':
st = persistent_id();
break;
case 'R':
st = reduce();
break;
case '.': { /* STOP */
size_t r;
if (!pop(&r)) return fail(no("STOP with nothing to return"));
*result = r;
return RAD_OK;
}
default: {
char hex[8];
std::snprintf(hex, sizeof hex, "0x%02x", op);
return fail(no(std::string("the opcode ") + hex +
", which a weights-only checkpoint does not use"));
}
}
if (st < 0) return fail(st);
}
return fail(no("no STOP before the pickle's end"));
}
/* A state dict's tensors, nested dicts flattened to dotted names. The memo lets a dict hold itself
* or be shared by several parents; a state dict's dicts form a tree, so a dict reached a second
* time is refused, which also bounds the walk by the pool. */
constexpr int kMaxDictDepth = 64;
bool walk(const Machine& m, size_t d, const std::string& prefix, int depth,
std::vector<char>* seen, std::vector<std::pair<std::string, size_t>>* out,
std::string* why) {
if (depth > kMaxDictDepth) {
*why = "dicts nested deeper than " + std::to_string(kMaxDictDepth) + " under '" + prefix +
"'";
return false;
}
if ((*seen)[d]) {
*why = "a dict reached twice (under '" + prefix + "'); a state dict's dicts form a tree";
return false;
}
(*seen)[d] = 1;
const V& v = m.at(d);
for (size_t j = 0; j + 1 < v.a.size(); j += 2) {
const V& k = m.at(v.a[j]);
if (k.k != V::Str) continue;
const V& x = m.at(v.a[j + 1]);
if (x.k == V::Tensor) out->emplace_back(prefix + k.s, v.a[j + 1]);
else if (x.k == V::Dict &&
!walk(m, v.a[j + 1], prefix + k.s + ".", depth + 1, seen, out, why))
return false;
}
return true;
}
} /* namespace */
/* ================================================================== the file */
TorchZipFile::~TorchZipFile() { close(); }
void TorchZipFile::close() {
if (map_) ::munmap(map_, (size_t)bytes_);
if (fd_ >= 0) ::close(fd_);
map_ = nullptr;
base_ = nullptr;
bytes_ = 0;
fd_ = -1;
tensors_.clear();
}
int TorchZipFile::open(const std::string& path, std::string* why) {
close();
path_ = path;
fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd_ < 0) {
*why = std::strerror(errno);
return RAD_E_IO;
}
struct stat st{};
if (::fstat(fd_, &st) != 0) {
*why = std::strerror(errno);
close();
return RAD_E_IO;
}
bytes_ = (uint64_t)st.st_size;
void* m = bytes_ ? ::mmap(nullptr, (size_t)bytes_, PROT_READ, MAP_PRIVATE, fd_, 0) : MAP_FAILED;
if (m == MAP_FAILED) {
*why = bytes_ ? std::string("mmap: ") + std::strerror(errno) : std::string("empty file");
close();
return bytes_ ? RAD_E_IO : RAD_E_FORMAT;
}
map_ = (uint8_t*)m;
base_ = map_;
const int s = parse(why);
if (s < 0) close();
return s;
}
int TorchZipFile::open_bytes(const uint8_t* data, uint64_t bytes, std::string* why) {
close();
path_ = "(memory)";
base_ = data;
bytes_ = bytes;
return parse(why);
}
int TorchZipFile::parse(std::string* why) {
std::unordered_map<std::string, Entry> ent;
RAD_TRY(zip_entries(base_, bytes_, &ent, why));
/* The archive's one directory: the one holding data.pkl. */
std::string dir;
int n_pkl = 0;
for (const auto& [name, e] : ent) {
const size_t sl = name.find('/');
if (sl != std::string::npos && name.compare(sl, std::string::npos, "/data.pkl") == 0) {
dir = name.substr(0, sl + 1);
++n_pkl;
}
}
if (n_pkl != 1) {
*why = n_pkl ? "more than one data.pkl" : "no <archive>/data.pkl: not a torch.save checkpoint";
return RAD_E_FORMAT;
}
if (auto it = ent.find(dir + "byteorder"); it != ent.end() &&
std::string((const char*)it->second.data, (size_t)it->second.bytes) != "little") {
*why = "a big-endian checkpoint";
return RAD_E_FORMAT;
}
const Entry& pk = ent[dir + "data.pkl"];
Machine m(pk.data, pk.bytes);
size_t root = 0;
RAD_TRY(m.run(&root, why));
if (m.at(root).k != V::Dict) {
*why = "the pickle's result is not a state dict";
return RAD_E_FORMAT;
}
std::vector<std::pair<std::string, size_t>> found;
std::vector<char> seen(m.size(), 0);
if (!walk(m, root, "", 0, &seen, &found, why)) return RAD_E_FORMAT;
for (const auto& [name, ti] : found) {
const V& t = m.at(ti);
const V& s = m.at(t.storage);
auto it = ent.find(dir + "data/" + s.s);
if (it == ent.end()) {
*why = "'" + name + "' reads storage '" + s.s + "', which the archive does not hold";
return RAD_E_FORMAT;
}
const int64_t esz = (int64_t)rad_dtype_bits(s.dtype) / 8;
/* The element count in checked arithmetic: a product that wraps would pass the fit
* check below with a shape that names far more bytes than the storage holds. */
int64_t numel = 1;
bool contig = true, wraps = false;
for (size_t d = t.shape.size(); d-- > 0;) {
if (t.shape[d] != 1 && t.stride[d] != numel) contig = false;
wraps |= __builtin_mul_overflow(numel, t.shape[d], &numel);
}
int64_t end_bytes = 0;
if (!wraps && t.offset >= 0)
wraps = __builtin_add_overflow(t.offset, numel, &end_bytes) ||
__builtin_mul_overflow(end_bytes, esz, &end_bytes);
if (wraps) {
*why = "'" + name + "' has a size or offset past 64 bits";
return RAD_E_FORMAT;
}
if (!contig) {
*why = "'" + name + "' is not contiguous in its storage";
return RAD_E_FORMAT;
}
if (t.offset < 0 || numel > s.i - t.offset || (uint64_t)end_bytes > it->second.bytes) {
*why = "'" + name + "' does not fit its storage '" + s.s + "'";
return RAD_E_FORMAT;
}
if (numel == 0) continue;
TorchTensor tt;
tt.name = name;
tt.dtype = s.dtype;
tt.storage = s.cls;
tt.shape = t.shape;
tt.data = it->second.data + t.offset * esz;
tt.bytes = (uint64_t)(numel * esz);
tensors_.push_back(std::move(tt));
}
return RAD_OK;
}
} /* namespace rad */
+64
View File
@@ -0,0 +1,64 @@
/* torch_zip.h -- a PyTorch checkpoint (torch.save's zip format) as tensors, read without running
* any of its pickle.
*
* A .pth from torch.save is a zip archive of stored entries: `<archive>/data.pkl`, a pickle of the
* state dict whose tensors name their bytes by a persistent id, `<archive>/data/<key>` holding
* each storage's raw little-endian bytes, and `<archive>/byteorder`. Fish Audio's codec ships this
* way (drama-3's codec.pth), with no safetensors copy.
*
* Unpickling would run whatever the file names. This reads the pickle as data instead: a small
* machine over the opcodes a weights-only file uses, whose only callables are the ones torch's own
* `weights_only` loader allows a state dict (collections.OrderedDict,
* torch._utils._rebuild_tensor_v2 and _rebuild_parameter) and whose only classes are the typed
* storages. Any other global, any other opcode, a compressed or encrypted entry, or a storage that
* does not hold its tensor is refused by name. Every read is bounds-checked and the machine's
* stack, memo and object counts are capped.
*
* Storages are mmapped, not copied; a tensor must be contiguous in its storage. Nested dicts
* flatten to dotted names, and values that are not tensors (an epoch count) are skipped.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <vector>
namespace rad {
struct TorchTensor {
std::string name;
uint32_t dtype = RAD_DT_INVALID;
std::string storage; /* the torch storage class, for diagnostics */
std::vector<int64_t> shape; /* row-major */
const uint8_t* data = nullptr;
uint64_t bytes = 0;
};
class TorchZipFile {
public:
TorchZipFile() = default;
~TorchZipFile();
TorchZipFile(const TorchZipFile&) = delete;
TorchZipFile& operator=(const TorchZipFile&) = delete;
/* RAD_OK, or a negative RAD_E_* with `why` saying what was refused. */
int open(const std::string& path, std::string* why);
/* The same over bytes the caller keeps alive (a test's archive in memory). */
int open_bytes(const uint8_t* data, uint64_t bytes, std::string* why);
void close();
const std::vector<TorchTensor>& tensors() const { return tensors_; }
const std::string& path() const { return path_; }
private:
int parse(std::string* why);
int fd_ = -1;
uint8_t* map_ = nullptr;
const uint8_t* base_ = nullptr;
uint64_t bytes_ = 0;
std::string path_;
std::vector<TorchTensor> tensors_;
};
} /* namespace rad */
+6
View File
@@ -65,6 +65,12 @@ struct AudioRequest {
* conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */
std::vector<int32_t> tokens;
std::vector<int32_t> neg_tokens;
/* References (RadAudioGenDecl::tmpl_ref): the clips' samples end to end, each padded to whole
* frames; their bounds in samples, [clips + 1]; and for each row of `tokens` the frame of the
* clips it is, -1 for a token. All empty without references. */
std::vector<float> ref_audio;
std::vector<int32_t> ref_cu;
std::vector<int32_t> ref_frame;
int64_t max_frames = 0; /* the most frames to make, >= 1 */
int32_t steps = 0; /* 0: the model's default */
float cfg = 0.0f; /* 0: the model's default */
+206 -42
View File
@@ -66,8 +66,23 @@ constexpr int64_t kAlign = 256;
struct Sizes {
int64_t T = 0, S = 0, L = 0, NB = 0;
int64_t NG = 0; /* stateful KV groups */
int64_t RS = 0, RN = 0; /* references: samples and clips a request */
};
/* The paged full-attention group, and how many stateful groups sit beside it. */
int32_t full_group(const Program& prog, int64_t* n_state) {
int32_t full = 0;
int64_t ns = 0;
for (size_t g = 1; g < prog.kv_groups.size(); ++g) {
const int kind = prog.kv_groups[g].decl.kind;
if (kind == RAD_KV_FULL && !full) full = (int32_t)g;
else if (kind == RAD_KV_LINEAR || kind == RAD_KV_CONV) ++ns;
}
if (n_state) *n_state = ns;
return full;
}
Sizes sizes_of(const Program& prog, int64_t block_size) {
const RadAudioGenDecl& d = prog.audio_gen;
Sizes z;
@@ -75,6 +90,9 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
z.S = prog.ctx.max_seqs;
z.L = d.max_lanes;
z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0;
full_group(prog, &z.NG);
z.RS = d.ref_max_samples;
z.RN = d.ref_max;
return z;
}
@@ -108,6 +126,16 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
z.S * I, /* R_ESLOT */
z.S * I, /* R_LROW */
z.S * I, /* R_PREFIX */
z.S * I, /* R_CTX */
z.S * I, /* R_ACC */
z.NG * z.S * I, /* R_SBT */
z.NG * z.S * AudioDriver::kMaxStateWidth * I, /* R_SIDX */
z.S * I, /* R_PSLOT */
z.S * I, /* R_PPOS */
z.S * I, /* R_PUSED */
z.RS * 4, /* R_RAUD */
z.RN > 0 ? (z.RN + 1) * I : 0, /* R_RCU */
z.RN > 0 ? z.T * I : 0, /* R_RFRM */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -121,8 +149,10 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
} /* namespace */
int64_t AudioDriver::device_bytes(const Program& prog) {
if (!prog.is_audio_generator() || prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
if (!prog.is_audio_generator()) return 0;
const int32_t fg = full_group(prog, nullptr);
if (!fg) return 0;
const Sizes z = sizes_of(prog, prog.kv_groups[(size_t)fg].block_size);
int64_t b[R_N][2];
return carve(z, b, R_N);
}
@@ -134,15 +164,39 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector<Ran
name_ = prog.agen_str.name;
kv_ = kv;
ranks_ = ranks;
/* The language model's KV, both branches of every lane: one paged full-attention group. */
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages exactly "
"one full-attention group, the language model's", prog.kv_groups.size() - 1);
/* The language model's KV, every branch of every lane: one paged full-attention group, and
* a hybrid model's linear-attention state and convolution groups beside it. */
state_groups_.clear();
int n_full = 0;
for (size_t g = 1; g < prog.kv_groups.size(); ++g) {
const int kind = prog.kv_groups[g].decl.kind;
if (kind == RAD_KV_FULL) {
++n_full;
} else if (kind == RAD_KV_LINEAR || kind == RAD_KV_CONV) {
StateGroup sg;
sg.g = (int32_t)g;
sg.width = std::max<int64_t>(1, kv->state_index_width((int32_t)g));
if (sg.width > kMaxStateWidth) {
RAD_ERR("audio generator: KV group %zu asks for %lld state slots a sequence; the "
"driver stages at most %lld", g, (long long)sg.width,
(long long)kMaxStateWidth);
return RAD_E_UNSUPPORTED;
}
state_groups_.push_back(sg);
} else {
n_full = -1;
break;
}
}
kv_group_ = full_group(prog, nullptr);
if (n_full != 1 || !kv_group_ || prog.kv_groups[(size_t)kv_group_].block_size <= 0) {
RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages one "
"paged full-attention group, the language model's, and the state and "
"convolution groups of a hybrid one beside it", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
}
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
block_size_ = prog.kv_groups[(size_t)kv_group_].block_size;
nb_ = decl_.branches == 1 ? 1 : 2;
const Sizes z = sizes_of(prog, block_size_);
max_tok_ = z.T;
max_seqs_ = z.S;
@@ -152,13 +206,13 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector<Ran
* chunk's vocode its frames and their context, and a whole prompt both its branches. */
const int64_t step_rows = chunked() ? decl_.voc_context + decl_.voc_chunk
: 2 * (decl_.win_lead + win_latents(decl_.win_frames));
const int64_t prompt_rows = decl_.prompt_whole ? 2 * decl_.max_prompt : 2;
if (max_seqs_ < 2 * decl_.max_lanes || max_tok_ < 2 * decl_.max_lanes ||
const int64_t prompt_rows = decl_.prompt_whole ? nb_ * decl_.max_prompt : nb_;
if (max_seqs_ < nb_ * decl_.max_lanes || max_tok_ < nb_ * decl_.max_lanes ||
max_tok_ < step_rows || max_tok_ < prompt_rows) {
RAD_ERR("audio generator: a pass carries %lld rows of %lld sequences; '%s' needs %lld "
"sequences for its %lld lanes, %lld rows for a %s and %lld for a whole prompt",
(long long)max_tok_, (long long)max_seqs_, name_.c_str(),
(long long)(2 * decl_.max_lanes), (long long)decl_.max_lanes,
(long long)(nb_ * decl_.max_lanes), (long long)decl_.max_lanes,
(long long)step_rows, chunked() ? "chunk's vocode" : "window's step",
(long long)prompt_rows);
return RAD_E_UNSUPPORTED;
@@ -191,7 +245,7 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector<Ran
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
out_.assign(ranks_.size(), RadBatch{});
aout_.assign(ranks_.size(), RadAudioGenBatch{});
kout_.assign(ranks_.size(), RadKVGroupBatch{});
kout_.assign(ranks_.size() * (1 + state_groups_.size()), RadKVGroupBatch{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
return RAD_OK;
@@ -222,7 +276,9 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
return RAD_E_INVAL;
};
const int64_t T = (int64_t)r->tokens.size(), Tn = (int64_t)r->neg_tokens.size();
if (!neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail)
if (nb_ == 1 && r->cfg != 0.0f && r->cfg != 1.0f)
return no("this model runs without guidance; guidance_scale must be 1");
if (nb_ == 2 && !neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail)
return no("the prompt is " + std::to_string(T) + " tokens, too short to hold its own "
"markers");
if (T < 1 || std::max(T, Tn) > d.max_prompt)
@@ -234,6 +290,25 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
" seconds)");
if (r->steps < 0 || r->steps > 1000) return no("num_inference_steps must be 1..1000");
if (r->cfg != 0.0f && !(r->cfg >= 1.0f)) return no("guidance_scale must be >= 1");
/* References: the clips the declaration allows, each a whole number of frames, and a frame
* for every row that names one. */
if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty()) {
const int64_t n_ref = (int64_t)r->ref_cu.size() - 1, hop = d.ref_hop;
bool ok = d.ref_max > 0 && n_ref >= 1 && n_ref <= d.ref_max && r->ref_cu[0] == 0 &&
r->ref_cu.back() == (int64_t)r->ref_audio.size() &&
(int64_t)r->ref_audio.size() <= d.ref_max_samples &&
(int64_t)r->ref_frame.size() == T;
for (int64_t i = 0; ok && i < n_ref; ++i)
ok = r->ref_cu[(size_t)i + 1] > r->ref_cu[(size_t)i] && r->ref_cu[(size_t)i + 1] % hop == 0;
const int64_t frames = ok ? r->ref_cu.back() / hop : 0;
for (int64_t t = 0; ok && t < T; ++t)
ok = r->ref_frame[(size_t)t] >= -1 && r->ref_frame[(size_t)t] < frames;
if (!ok)
return no(d.ref_max > 0 ? "the references do not fit this model: at most " +
std::to_string(d.ref_max) + " clips of whole frames, " +
std::to_string(d.ref_max_samples) + " samples together"
: std::string("this model takes no reference audio"));
}
if (!kv_->can_ever_fit(std::max(T, Tn) + r->max_frames + 1))
return no("a piece of " + std::to_string(r->max_frames) + " frames after a " +
std::to_string(T) + "-token prompt does not fit the KV cache even when it is "
@@ -307,16 +382,19 @@ int AudioDriver::admit_locked() {
const float cfg = r.cfg > 0.0f ? r.cfg : (float)decl_.default_cfg;
/* The unconditional prompt: the request's own (the conditional one at guidance 1, which
* makes the guided logits the conditional ones), or derived from the conditional one. */
std::vector<int32_t> neg = r.tokens;
if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) {
neg = r.neg_tokens;
} else if (!neg_own_) {
for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i)
neg[(size_t)i] = decl_.neg_token;
std::vector<int32_t> neg;
if (nb_ > 1) {
neg = r.tokens;
if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) {
neg = r.neg_tokens;
} else if (!neg_own_) {
for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i)
neg[(size_t)i] = decl_.neg_token;
}
}
/* Both branches for the whole piece, so nothing in flight ever waits for KV. */
/* Every branch for the whole piece, so nothing in flight ever waits for KV. */
bool ok = true;
for (int b = 0; b < 2 && ok; ++b) {
for (int b = 0; b < nb_ && ok; ++b) {
const int64_t rows = (b ? (int64_t)neg.size() : j.T) + r.max_frames + 1;
j.seq[b] = ((uint64_t)1 << 61) | next_seq_++;
if (kv_->add_sequence(j.seq[b]) < 0 || kv_->ensure(j.seq[b], rows) < 0) ok = false;
@@ -388,7 +466,7 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadAudioGenBatch& A = aout_[r];
RadKVGroupBatch& K = kout_[r];
RadKVGroupBatch& K = kout_[r * (1 + state_groups_.size())];
const int ri = (int)r;
B = RadBatch{};
B.step = step;
@@ -410,8 +488,23 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3
K.seqused = dptr<int32_t>(ri, R_USED);
K.block_size = block_size_;
K.max_blocks = max_blocks_;
B.n_kv_groups = 1;
/* A stateful group's block-table row is the sequence's slot, as the text scheduler
* stages it, so a kernel reading tables needs no second path. */
for (size_t gi = 0; gi < state_groups_.size(); ++gi) {
RadKVGroupBatch& Ks = (&K)[1 + gi];
Ks = RadKVGroupBatch{};
Ks.group = (rad_kvgroup)state_groups_[gi].g;
Ks.block_table = dptr<int32_t>(ri, R_SBT) + gi * max_seqs_;
Ks.block_table_pitch = 1;
Ks.seqused = dptr<int32_t>(ri, R_USED);
Ks.state_index = dptr<int32_t>(ri, R_SIDX) + gi * max_seqs_ * kMaxStateWidth;
Ks.state_index_pitch = state_groups_[gi].width;
Ks.max_blocks = 1;
}
B.n_kv_groups = (int)(1 + state_groups_.size());
B.kv = &K;
B.ctx_lens = dptr<int32_t>(ri, R_CTX);
B.num_accepted = dptr<int32_t>(ri, R_ACC);
}
A = RadAudioGenBatch{};
A.lane = dptr<int32_t>(ri, R_LANE);
@@ -432,10 +525,38 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3
A.slot = dptr<int32_t>(ri, R_ESLOT);
A.last_row = dptr<int32_t>(ri, R_LROW);
A.prefix = dptr<int32_t>(ri, R_PREFIX);
A.prev_slot = dptr<int32_t>(ri, R_PSLOT);
A.prev_pos = dptr<int32_t>(ri, R_PPOS);
A.prev_used = dptr<int32_t>(ri, R_PUSED);
B.agen_b = &A;
}
}
void AudioDriver::stage_state(const std::vector<uint64_t>& seqs, const std::vector<int32_t>& ctx) {
const int64_t n = (int64_t)seqs.size();
int32_t* cl = hptr<int32_t>(R_CTX);
int32_t* acc = hptr<int32_t>(R_ACC);
for (int64_t e = 0; e < n; ++e) {
cl[e] = ctx[(size_t)e];
/* One-based, as num_accepted always is: a pass commits every row it runs. */
acc[e] = 1;
}
reg_[R_CTX].used = reg_[R_ACC].used = n * 4;
for (size_t gi = 0; gi < state_groups_.size(); ++gi) {
const StateGroup& sg = state_groups_[gi];
int32_t* bt = hptr<int32_t>(R_SBT) + gi * max_seqs_;
int32_t* si = hptr<int32_t>(R_SIDX) + gi * max_seqs_ * kMaxStateWidth;
for (int64_t e = 0; e < n; ++e) {
bt[e] = kv_->state_slot(seqs[(size_t)e], sg.g);
kv_->state_index_row(seqs[(size_t)e], sg.g, si + e * sg.width, (int)sg.width);
}
}
if (!state_groups_.empty()) {
reg_[R_SBT].used = (int64_t)state_groups_.size() * max_seqs_ * 4;
reg_[R_SIDX].used = (int64_t)state_groups_.size() * max_seqs_ * kMaxStateWidth * 4;
}
}
/* The KV slot of position `p` in a sequence with this block table. */
static int32_t slot_of(const std::vector<int32_t>& bt, int64_t p, int64_t bs) {
const int64_t bi = p / bs;
@@ -515,12 +636,13 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
/* Each branch's rows: both whole, or the same chunk of both (their lengths are then equal). */
const int64_t p0 = j.prompt_done;
int64_t cb[2];
int64_t cb[2] = { 0, 0 };
if (decl_.prompt_whole) {
cb[0] = j.T;
cb[1] = j.Tn;
cb[1] = nb_ > 1 ? j.Tn : 0;
} else {
cb[0] = cb[1] = std::min<int64_t>(j.T - j.prompt_done, max_tok_ / 2);
cb[0] = std::min<int64_t>(j.T - j.prompt_done, max_tok_ / nb_);
cb[1] = nb_ > 1 ? cb[0] : 0;
}
const int64_t cmax = std::max(cb[0], cb[1]);
int32_t* tok = hptr<int32_t>(R_TOK);
@@ -528,12 +650,12 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
int32_t* slot = hptr<int32_t>(R_SLOT);
int32_t* cu = hptr<int32_t>(R_CU);
int64_t pitch = 1;
for (int b = 0; b < 2; ++b)
for (int b = 0; b < nb_; ++b)
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(j.seq[b], kv_group_).size());
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
cu[0] = 0;
for (int b = 0; b < 2; ++b) {
for (int b = 0; b < nb_; ++b) {
const std::vector<int32_t>& src = b ? j.neg : j.req->tokens;
const std::vector<int32_t>& bt = kv_->block_table(j.seq[b], kv_group_);
for (int64_t i = 0; i < cb[b]; ++i) {
@@ -547,26 +669,47 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
btab[b * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1;
used[b] = (int32_t)(p0 + cb[b]);
}
const int64_t rows = cu[2];
const int64_t rows = cu[nb_];
const bool last = p0 + cb[0] == j.T;
for (int b = 0; b < 2; ++b) {
hptr<int32_t>(R_ESLOT)[b] = 2 * j.lane + b;
std::vector<uint64_t> seqs;
std::vector<int32_t> ctx;
for (int b = 0; b < nb_; ++b) {
hptr<int32_t>(R_ESLOT)[b] = nb_ * j.lane + b;
hptr<int32_t>(R_LROW)[b] = cu[b + 1] - 1;
hptr<int32_t>(R_PREFIX)[b] = (int32_t)p0;
seqs.push_back(j.seq[b]);
ctx.push_back((int32_t)p0);
}
reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = 2 * 4;
stage_state(seqs, ctx);
reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = nb_ * 4;
hptr<int32_t>(R_LANE)[0] = j.lane;
hptr<int32_t>(R_LAST)[0] = last ? 1 : 0;
hptr<uint32_t>(R_SEED)[0] = (uint32_t)(j.req->seed & 0xffffffffu);
hptr<uint32_t>(R_SEED)[1] = (uint32_t)(j.req->seed >> 32);
reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = rows * 4;
reg_[R_CU].used = 3 * 4;
reg_[R_BT].used = 2 * pitch * 4;
reg_[R_USED].used = 2 * 4;
reg_[R_CU].used = (nb_ + 1) * 4;
reg_[R_BT].used = nb_ * pitch * 4;
reg_[R_USED].used = nb_ * 4;
reg_[R_LANE].used = reg_[R_LAST].used = 4;
reg_[R_SEED].used = 8;
/* The references: their clips, bounds and each row's frame (a whole prompt, so the rows are
* the prompt's own). */
const AudioRequest& q = *j.req;
const int64_t n_ref = q.ref_cu.empty() ? 0 : (int64_t)q.ref_cu.size() - 1;
h_rcu_.clear();
h_rfrm_.clear();
if (n_ref > 0) {
std::memcpy(hptr<float>(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4);
std::memcpy(hptr<int32_t>(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4);
std::memcpy(hptr<int32_t>(R_RFRM), q.ref_frame.data() + p0, (size_t)cb[0] * 4);
reg_[R_RAUD].used = (int64_t)q.ref_audio.size() * 4;
reg_[R_RCU].used = (int64_t)q.ref_cu.size() * 4;
reg_[R_RFRM].used = cb[0] * 4;
h_rcu_ = q.ref_cu;
h_rfrm_.assign(q.ref_frame.begin() + p0, q.ref_frame.begin() + p0 + cb[0]);
}
if (upload() < 0) return nullptr;
base_batches(rows, 2, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch);
base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch);
h_lane_.assign(1, j.lane);
h_last_.assign(1, last ? 1 : 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
@@ -575,6 +718,16 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
A.n_lane = 1;
A.lane_h = h_lane_.data();
A.last_h = h_last_.data();
if (n_ref > 0) {
const int ri = (int)r;
A.n_ref = n_ref;
A.ref_samples = (int64_t)q.ref_audio.size();
A.ref_audio = dptr<float>(ri, R_RAUD);
A.ref_cu = dptr<int32_t>(ri, R_RCU);
A.ref_cu_h = h_rcu_.data();
A.ref_frame = dptr<int32_t>(ri, R_RFRM);
A.ref_frame_h = h_rfrm_.data();
}
}
pass_.kind = RAD_GEN_PASS_PROMPT;
pass_.jobs.assign(1, j.id);
@@ -584,7 +737,7 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& js, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t L = (int64_t)js.size(), S = 2 * L;
const int64_t L = (int64_t)js.size(), S = nb_ * L;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* slot = hptr<int32_t>(R_SLOT);
@@ -597,17 +750,19 @@ const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& js, int step)
int64_t pitch = 1;
int32_t max_ctx = 0;
for (const Job* j : js)
for (int b = 0; b < 2; ++b)
for (int b = 0; b < nb_; ++b)
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(j->seq[b], kv_group_).size());
h_lane_.assign((size_t)L, 0);
h_frame_.assign((size_t)L, 0);
pass_.jobs.clear();
std::vector<uint64_t> seqs;
std::vector<int32_t> ctx;
for (int64_t i = 0; i < L; ++i) {
const Job& j = *js[(size_t)i];
for (int b = 0; b < 2; ++b) {
for (int b = 0; b < nb_; ++b) {
/* The frame's row follows the branch's prompt and its earlier frames. */
const int64_t p = (b ? j.Tn : j.T) + j.frame;
const int64_t e = 2 * i + b;
const int64_t e = nb_ * i + b;
const std::vector<int32_t>& bt = kv_->block_table(j.seq[b], kv_group_);
tok[e] = 0;
pos[e] = (int32_t)p;
@@ -616,9 +771,16 @@ const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& js, int step)
for (int64_t k = 0; k < pitch; ++k)
btab[e * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1;
used[e] = (int32_t)(p + 1);
hptr<int32_t>(R_ESLOT)[e] = 2 * j.lane + b;
/* The row before, whose hidden state the frame is sampled from: the prompt's last
* row for the first frame. */
hptr<int32_t>(R_PSLOT)[e] = slot_of(bt, p - 1, block_size_);
hptr<int32_t>(R_PPOS)[e] = (int32_t)(p - 1);
hptr<int32_t>(R_PUSED)[e] = (int32_t)p;
hptr<int32_t>(R_ESLOT)[e] = nb_ * j.lane + b;
hptr<int32_t>(R_LROW)[e] = (int32_t)e;
max_ctx = std::max<int32_t>(max_ctx, (int32_t)(p + 1));
seqs.push_back(j.seq[b]);
ctx.push_back((int32_t)p);
}
hptr<float>(R_CFG)[i] = j.cfg;
lane[i] = h_lane_[(size_t)i] = j.lane;
@@ -628,6 +790,7 @@ const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& js, int step)
pass_.jobs.push_back(j.id);
}
cu[S] = (int32_t)S;
stage_state(seqs, ctx);
reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = S * 4;
reg_[R_CU].used = (S + 1) * 4;
reg_[R_BT].used = S * pitch * 4;
@@ -635,6 +798,7 @@ const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& js, int step)
reg_[R_LANE].used = reg_[R_FRAME].used = reg_[R_CFG].used = L * 4;
reg_[R_SEED].used = 2 * L * 4;
reg_[R_ESLOT].used = reg_[R_LROW].used = S * 4;
reg_[R_PSLOT].used = reg_[R_PPOS].used = reg_[R_PUSED].used = S * 4;
if (upload() < 0) return nullptr;
base_batches(S, S, 1, max_ctx, step, true, pitch);
for (size_t r = 0; r < ranks_.size(); ++r) {
+24 -6
View File
@@ -5,9 +5,15 @@
* `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads
* through `submit()` and leave through their AudioTicket.
*
* A request holds a lane and two KV sequences, its conditional and unconditional branches, from
* admission to its last window; both are reserved for the whole piece at admission (prompt plus
* every frame the request may make), so a request in flight never waits for KV.
* A request holds a lane and two KV sequences, its conditional and unconditional branches (one,
* for a model of one branch: RadAudioGenDecl::branches), from admission to its last window; they
* are reserved for the whole piece at admission (prompt plus every frame the request may make), so
* a request in flight never waits for KV.
*
* The language model's KV is one paged full-attention group, beside which a hybrid model keeps
* the linear-attention state and convolution groups of its recurrent layers (RAD_KV_LINEAR,
* RAD_KV_CONV): one slot a sequence each, staged as their `state_index` rows, zeroed by the engine
* before the pass that first reads them.
*
* Pass priority, one pass at a time:
*
@@ -54,6 +60,9 @@ public:
/* The longest sequence a branch holds: the whole prompt and every frame. The KV group is
* sized from it. */
static int64_t max_seq_rows(const RadAudioGenDecl& d) { return d.max_prompt + d.max_frames + 1; }
/* State slots a state_index row holds at most: the state, and the scratch a kernel serving
* speculation asks for (RadKVGroupBatch::state_index_pitch), which a generator never runs. */
static constexpr int64_t kMaxStateWidth = 8;
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request, refused at once with `why` when it can never run. */
@@ -115,7 +124,11 @@ private:
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED,
R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC,
R_ESLOT, R_LROW, R_PREFIX, R_N };
R_ESLOT, R_LROW, R_PREFIX, R_CTX, R_ACC, R_SBT, R_SIDX, R_PSLOT, R_PPOS, R_PUSED,
R_RAUD, R_RCU, R_RFRM, R_N };
/* A hybrid model's stateful groups (linear-attention state, convolution history), each staged
* as one block-table word a sequence (its slot) and its state_index row. */
struct StateGroup { int32_t g = 0; int64_t width = 1; };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
@@ -124,6 +137,9 @@ private:
int upload();
void base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx, int step,
bool kv, int64_t bt_pitch);
/* The stateful groups' rows for the entries of a PROMPT or FRAME pass, entry e being `seq[e]`,
* with each entry's context before the pass (ctx_lens). */
void stage_state(const std::vector<uint64_t>& seqs, const std::vector<int32_t>& ctx);
int admit_locked();
void release_locked(Job& j);
@@ -152,6 +168,8 @@ private:
int64_t max_tok_ = 0, max_seqs_ = 0;
int64_t block_size_ = 0, max_blocks_ = 0;
int32_t kv_group_ = 0;
std::vector<StateGroup> state_groups_;
int nb_ = 2; /* sequences a request: RadAudioGenDecl::branches */
bool neg_own_ = false; /* the unconditional prompt is the request's own */
std::vector<RankIO> ranks_;
IKVManager* kv_ = nullptr;
@@ -167,12 +185,12 @@ private:
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadAudioGenBatch> aout_;
std::vector<RadKVGroupBatch> kout_;
std::vector<RadKVGroupBatch> kout_; /* [rank][1 + state groups] */
Pass pass_;
bool frame_turn_ = true; /* FRAME goes first when both are due */
/* Host arrays a pass's plugin reads on the host (the _h fields), for the life of the pass. */
std::vector<int32_t> h_lane_, h_last_, h_frame_, h_wlane_, h_flags_, h_widx_,
h_wf0_, h_wnf_, h_lcu_;
h_wf0_, h_wnf_, h_lcu_, h_rcu_, h_rfrm_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
+45
View File
@@ -606,6 +606,51 @@ void IdleTiers::drop_session(uint64_t id) {
sessions_.erase(it);
}
void IdleTiers::find_sessions(const std::string& label, uint64_t id,
std::vector<SessionChain>* out) const {
out->clear();
std::lock_guard lk(mu_);
for (const auto& kv : sessions_) {
const bool hit = id != 0 ? kv.first == id : (!label.empty() && kv.second.label == label);
if (!hit) continue;
SessionChain c;
c.id = kv.first;
c.label = kv.second.label;
c.chain = kv.second.chain;
out->push_back(std::move(c));
}
}
int64_t IdleTiers::shared_prefix_blocks(const std::vector<BlockHash>& chain,
const std::vector<uint64_t>& except) const {
if (chain.empty()) return 0;
std::lock_guard lk(mu_);
auto ro = roots_.find(chain[0]);
if (ro == roots_.end()) return 0;
int64_t most = 0;
for (uint64_t sid : ro->second) {
if (std::find(except.begin(), except.end(), sid) != except.end()) continue;
auto it = sessions_.find(sid);
if (it == sessions_.end()) continue;
const std::vector<BlockHash>& other = it->second.chain;
size_t n = 0;
while (n < chain.size() && n < other.size() && chain[n] == other[n]) ++n;
if ((int64_t)n > most) most = (int64_t)n;
}
return most;
}
void IdleTiers::cut_session(uint64_t id, int64_t keep_blocks, int64_t keep_tokens) {
std::lock_guard lk(mu_);
if (keep_blocks <= 0) { drop_session(id); return; }
auto it = sessions_.find(id);
if (it == sessions_.end()) return;
Session& s = it->second;
if ((int64_t)s.chain.size() <= keep_blocks) return;
s.chain.resize((size_t)keep_blocks);
s.n_tokens = keep_tokens;
}
std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
/* One slice's hold on the lock (YieldingMutex). */
struct Slice {
+25
View File
@@ -246,6 +246,31 @@ public:
* microseconds apart. */
std::vector<SessionInfo> sessions(Occupancy* occ = nullptr) const;
/* ---------------- a release names a session ----------------
*
* The cache keys by block and knows no conversation; the rows here are what a client can
* name. PrefixCache::release_session asks for the rows, walks their chains itself and
* reports back what is left of each. */
struct SessionChain {
uint64_t id = 0;
std::string label;
std::vector<BlockHash> chain;
};
/* Every row carrying `label`, or with `id` nonzero the one row of that id. A label is the
* client's and may stand on several leaves (a conversation branched and both ends were
* served); a release by label means all of them. */
void find_sessions(const std::string& label, uint64_t id,
std::vector<SessionChain>* out) const;
/* How many blocks at the start of `chain` another stored session walks too: the longest
* common prefix with any row at the same root whose id is not in `except`. Those blocks
* belong to the other conversation as much as to this one. */
int64_t shared_prefix_blocks(const std::vector<BlockHash>& chain,
const std::vector<uint64_t>& except) const;
/* The release is done: the row keeps its first `keep_blocks` (covering `keep_tokens`),
* which is the kept prefix or, beyond it, the deepest block a live request held back; it
* goes when that is zero. A kept stub is a leaf again until a later turn extends it. */
void cut_session(uint64_t id, int64_t keep_blocks, int64_t keep_tokens);
struct Stats {
/* `to_host` counts copies to host memory (link traffic); `dropped` counts VRAM copies
* then given up. An entry can be copied and never dropped. */
+88 -7
View File
@@ -368,14 +368,16 @@ int PrefixCache::insert(uint64_t session,
for (int64_t b = 0; b < n_full; ++b) {
const BlockHash& h = hs[(size_t)b];
auto it = map_.find(h);
/* A snapshot-backed prefix keeps its first bytes even in the host tier: a short
* recompute can round the KV differently, while older conversations' recurrent snapshots
* still depend on the original attention KV. Non-stateful caches may rebind below. */
if (it != map_.end() && (it->second.in_lru || has_linear_)) continue; /* touched below */
/* With snapshots (recurrent state or a sliding window) an existing entry keeps the bytes
* it was published with, wherever it is held: a snapshot deeper in the chain was computed
* from them, and a recompute in another step shape can round the KV differently. The
* recomputed blocks go with the request's sequence; a later hit restores the tier copy. */
if (it != map_.end() && (it->second.in_lru || has_linear_)) continue; /* touched below */
if (it != map_.end()) {
/* An off-device entry this request recomputed (a restore that did not fit, or a chain
* cut short). Its blocks become the entry's device copy and the tier copy goes
* (IdleTiers::rebound). An entry with a promotion in flight is left alone. */
/* Without snapshots, an off-device entry this request recomputed (a restore that did
* not fit, or a chain cut short): its blocks become the entry's device copy and the
* tier copy goes (IdleTiers::rebound). An entry with a promotion in flight is left
* alone. */
if (!tiers_ || !tiers_->resident_off_device(h)) continue;
std::vector<int32_t> mine(groups_.size(), -1);
size_t held = 0;
@@ -989,4 +991,83 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
stats_.ckpt_expired += (int64_t)gone.size();
return n;
}
/* ------------------------------------------------------------------ release on request */
int PrefixCache::release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out) {
if (!out) return RAD_E_INVAL;
*out = SessionRelease{};
if (!enabled_ || !tiers_ || block_size_ <= 0) return RAD_E_UNSUPPORTED;
if (label.empty() && id == 0) return RAD_E_INVAL;
if (keep_tokens < 0) return RAD_E_INVAL;
std::vector<IdleTiers::SessionChain> rows;
tiers_->find_sessions(label, id, &rows);
if (rows.empty()) return RAD_E_NOTFOUND;
std::vector<uint64_t> ids;
for (const IdleTiers::SessionChain& r : rows) ids.push_back(r.id);
/* A kept token keeps its whole block: the block holding it is what the next turn hits. */
const int64_t keep_blocks = (keep_tokens + block_size_ - 1) / block_size_;
int64_t entry_bytes = 0;
for (int32_t g : groups_) {
const KVGroupPlan* p = kv_->plan(g);
if (p) entry_bytes += p->bytes_per_block;
}
for (const IdleTiers::SessionChain& row : rows) {
const int64_t n = (int64_t)row.chain.size();
const int64_t shared = tiers_->shared_prefix_blocks(row.chain, ids);
const int64_t floor = std::max(keep_blocks, shared);
++out->sessions;
out->kept_tokens += std::min(keep_blocks, n) * block_size_;
out->kept_shared += std::max<int64_t>(0, std::min(shared, n) - keep_blocks);
/* Tip inwards, as expire() and the host tier's pressure do: what is left is still a
* prefix a lookup reaches. `live_upto` is one past the deepest block a request kept:
* the row is cut there, not at the kept prefix, so a later release reaches it. */
int64_t live_upto = 0;
for (int64_t b = n - 1; b >= floor; --b) {
const BlockHash& h = row.chain[(size_t)b];
auto it = map_.find(h);
if (it != map_.end()) {
Entry& e = it->second;
/* A sequence reads it, or a waiting request restored it and holds it against
* drop_clean: releasing would free nothing and lose the entry under them. Its
* snapshot stays with it; that request most likely resumes from it. */
if (e.in_lru && (shared_with_live(e) || held_.count(h) > 0)) {
++out->kept_live;
if (live_upto == 0) live_upto = b + 1;
continue;
}
if (e.in_lru) {
lru_.erase(e.lru);
e.in_lru = false;
release_blocks(e);
out->device_bytes += entry_bytes;
}
/* The host copy goes with the entry (forget), so count it before. */
if (tiers_->resident_off_device(h) || tiers_->droppable(h))
out->host_bytes += tiers_->entry_bytes();
tiers_->forget(h);
map_.erase(it);
++out->entries;
}
auto ck = ck_by_prefix_.find(h);
if (ck != ck_by_prefix_.end() && ck->second.valid && !handed(h) && !reserved(h)) {
const uint64_t session = ck->second.session;
retire_ckpt(ck);
unindex_ckpt(session, h);
++out->snapshots;
}
}
const int64_t cut = std::min(n, std::max(keep_blocks, live_upto));
tiers_->cut_session(row.id, cut, cut * block_size_);
}
out->tokens = out->entries * block_size_;
stats_.released += out->entries;
stats_.ckpt_released += out->snapshots;
return RAD_OK;
}
} /* namespace rad */
+34
View File
@@ -174,6 +174,23 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma
int64_t ctx, int64_t interval, int64_t slot_bytes,
int64_t share_bytes, int64_t room_bytes);
/* ------------------------------------------------------------------ a release */
/* What PrefixCache::release_session took out and what it left. Blocks are left for three
* reasons, counted apart so a caller can tell a half-shared conversation from a busy one: the
* caller asked for them (`keep_tokens`), another stored session's chain runs through them (a
* system prompt two conversations open with belongs to both), or a live sequence holds them. */
struct SessionRelease {
int64_t sessions = 0; /* rows the label or id named */
int64_t entries = 0; /* blocks forgotten, from VRAM or the host tier */
int64_t tokens = 0; /* entries x block size */
int64_t device_bytes = 0; /* pool bytes given back */
int64_t host_bytes = 0; /* host-tier slots given back */
int64_t snapshots = 0;
int64_t kept_tokens = 0; /* the chain's start, as asked, whole blocks */
int64_t kept_shared = 0; /* blocks beyond that on another stored session's chain */
int64_t kept_live = 0; /* blocks a running or waiting request holds */
};
/* ------------------------------------------------------------------ the cache */
class PrefixCache {
public:
@@ -314,6 +331,21 @@ public:
* than what follows it: conversations expire from the tip inwards and a shared system prompt
* outlives its readers. Returns how many entries went. */
int64_t expire(uint64_t now_ns, uint64_t ttl_ns);
/* ---------------- release on request ----------------
*
* Forget one stored conversation now instead of at the TTL: a client that deleted it, or
* replaced everything past a prefix (a compaction) and knows the rest is dead. `label` names
* every row carrying it, `id` (nonzero) one row by its engine id (IdleTiers::SessionInfo).
* The chain goes from the tip inwards like expire(): VRAM blocks to the pool, the host copy
* with them, the session's snapshots on the released blocks to the store. `keep_tokens`
* leaves the chain's first blocks standing (rounded up to whole blocks), so the prefix the
* client kept still hits. A block another stored session's chain shares stays, as does one a
* live sequence holds or a waiting request has restored; snapshots handed out or reserved
* this step stay too. RAD_E_NOTFOUND when nothing matches, RAD_E_UNSUPPORTED without the
* session table (no tiers attached). */
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out);
/* ---------------- linear checkpoints ---------------- */
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
* checkpoint lands on a boundary (spec §7.1, §7.3). */
@@ -356,6 +388,8 @@ public:
int64_t drops = 0;
/* Entries and snapshots removed by --prefix-cache-ttl, from any tier. */
int64_t expired = 0, ckpt_expired = 0;
/* Entries and snapshots a client released (release_session). */
int64_t released = 0, ckpt_released = 0;
};
const Stats& stats() const { return stats_; }
+4 -1
View File
@@ -442,6 +442,9 @@ int Registry::commit_(Staged& s, int order) {
const auto concurrent = dl_fn<RadKernelConcurrentFn>(s.handle, "rad_kernel_concurrent");
const auto collective = dl_fn<RadKernelCollectiveFn>(s.handle, "rad_kernel_collective");
const auto chainable = dl_fn<RadKernelChainFn>(s.handle, "rad_kernel_chain");
/* Per row when exported, else the library's own answer: a plugin that ships a device row and
* its host oracle in one library must not have the oracle's status leak onto the device row. */
const auto kern_ref = dl_fn<RadKernelReferenceFn>(s.handle, "rad_kernel_reference");
for (const auto& sr : staged_rows) {
KernelRow row;
row.info = sr.first;
@@ -452,7 +455,7 @@ int Registry::commit_(Staged& s, int order) {
const int coll = collective ? collective(sr.second) : 0;
row.collective = coll != 0;
row.releases_link = coll == 2;
row.reference = p.reference;
row.reference = kern_ref ? kern_ref(sr.second) != 0 : p.reference;
row.chain = chainable && chainable(sr.second) != 0;
rows_.push_back(row);
}
+16 -1
View File
@@ -392,6 +392,8 @@ public:
* for drafters that did not ask. */
bool drafter_shared_kv = false;
int32_t drafter_pos_offset = 0;
/* A block drafter's shorter block (rad_drafter_short_block), 0 when it serves only its own. */
int64_t drafter_short_block = 0;
/* The declared media encoder (rad_declare_encoder). `modalities == 0` when none: every
* text-only program, and every deployment with RadBuildCtx::max_enc_patches 0.
@@ -416,7 +418,8 @@ public:
* strings point at `agen_str`, as the image generator's do at `gen_str`. */
RadAudioGenDecl audio_gen{};
struct AudioGenStrings {
std::string name, tmpl, tmpl_plain, neg_tmpl; /* "" for an absent template */
/* "" for an absent template; tmpl_ref and ref_item RadAudioGenDecl's references */
std::string name, tmpl, tmpl_plain, neg_tmpl, tmpl_ref, ref_item;
} agen_str;
bool is_audio_generator() const { return audio_gen.max_lanes != 0; }
/* The declared video generator (rad_declare_video_generator); `max_lanes` 0 when none. */
@@ -762,6 +765,9 @@ struct Config {
* element plus a bf16 scale per 64) instead of 16 bits per element, 2.4x fewer bytes over
* PCIe. The received sum then differs undetectably, hence a named flag, not a heuristic. */
int tp_wire_exact = 1; /* --tp-wire exact|wht6 */
/* --tp-attn-split heads|rows: 1 runs a prefill-sized step's attention by rows over the ranks
* (RadBuildCtx::tp_attn_rows). Not bit-identical to the head split, so heads is the default. */
int tp_attn_rows = 0;
/* Smallest all-reduce message, in KiB, that the lossy wire compresses; smaller ones are sent
* exact. Compression pays only when the transfer is bandwidth-bound: a decode step's handful
* of residual rows costs more to rotate than it saves, while a prefill chunk is far larger.
@@ -808,6 +814,7 @@ struct Config {
* explicit and bf16 is the default. No "auto": it would always resolve to bf16 and only add
* another name. */
std::string kv_cache_dtype = "bf16";
std::string state_cache_dtype = "f32"; /* --state-cache-dtype: f32 | f16 */
/* --attn-prefill-fp8 off|qk|pv|both: RAD_ATTN_FP8_* bits, the prefill attention's products
* accepted in e4m3 (RadBuildCtx::attn_prefill_fp8). Lossy, so off is the default.
* attn_prefill_fp8_name() spells it as the flag does. */
@@ -906,6 +913,14 @@ struct Config {
* VRAM and still decode one token a step. */
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
/* A block drafter's short block (rad_drafter_short_block) from this many decoding sequences in
* the step just run; 0 never. Ignored without a drafter that declares one. */
int64_t draft_short_from = 0; /* --draft-short-from */
/* --draft-coupling off|on: a linear serial drafter samples its proposals and the sampler
* applies the maximal coupling at the verify (RadBuildCtx::draft_coupling, abi/rad_spechub.h).
* Off by default; on changes which tokens a fixed seed yields, not their law. */
bool draft_coupling = false;
/* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
*
+7 -2
View File
@@ -291,6 +291,8 @@ public:
void dump_profile() const; /* spec §16, opt-in, with its caveat printed */
const char* step_error() const { return step_fail_.c_str(); }
int64_t stream_waits() const { return n_stream_waits_; }
/* Lane 1 has work lane 0 has not joined (lane1_pending_). */
bool lane1_pending() const { return lane1_pending_; }
/* Host synchronisations on the step path. Always zero unless per-op timing is on (spec §16);
* tests read it. Teardown's drain is not counted. */
int64_t host_syncs() const { return n_host_syncs_; }
@@ -549,6 +551,9 @@ public:
/* Backs rad_step_fail(): stops the step like an operand rejection, with the caller's
* message. */
int step_fail(const char* what);
/* The device kernel `h` resolved to on this rank ("?" if it resolved none). For log
* attribution only. */
const char* ip_kernel_name(rad_op h) const;
private:
[[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const;
@@ -575,7 +580,6 @@ private:
* byte-compares the two results, finding kernels that are not a function of their inputs,
* which a host-vs-device comparison cannot detect. */
void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd);
const char* ip_kernel_name(rad_op h) const;
/* The reference library's host plan for (op, band): the band's own host plan when a reference
* library won it, else one resolved from `registry_` on first use. Null when none exists. */
const IssuePlan* oracle_reference(rad_op h, int band);
@@ -645,7 +649,8 @@ private:
bool own_lane1_ = false;
int lane_ = 0;
RadEvent lane_ev_[2] = { nullptr, nullptr };
/* An op was issued on lane 1 since lane 1 was last joined into lane 0 (the window's join). */
/* An op was issued on lane 1 since lane 1 was last joined into lane 0; lane 0 joins it before
* an op outside the second lane's window (Ctx::issue_body). */
bool lane1_pending_ = false;
/* The last device op on each lane that touched host-domain memory. A host op runs at issue on
* this thread and must be ordered behind every earlier device op that touched the host arena;
+6 -4
View File
@@ -593,18 +593,20 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
"it on the host anyway"
: "has no device kernel for this band");
/* The second lane's window (rad_lane1_window_begin): its concurrent buffers are live only across
* it, so lane 1 runs nothing outside it, and lane 1 is joined before lane 0 runs past it. */
* it, so lane 1 runs nothing outside it, and lane 0 joins lane 1 before it runs an op outside
* it, on either side: a transient of such an op may share bytes with a concurrent buffer. */
if (program_ && program_->lane1_w1 >= 0) {
if (lane_ == 1 && (p.order < program_->lane1_w0 || p.order > program_->lane1_w1))
const bool outside = p.order < program_->lane1_w0 || p.order > program_->lane1_w1;
if (lane_ == 1 && outside)
return abort_step_msg(h, RAD_E_STATE,
fmt("issued on the second lane outside its declared window (ops "
"%d..%d, this one %d): the buffers it may touch there are "
"live only across the window",
(int)program_->lane1_w0, (int)program_->lane1_w1, (int)p.order));
if (lane_ == 0 && lane1_pending_ && p.order > program_->lane1_w1) {
if (lane_ == 0 && lane1_pending_ && outside) {
const int js = lane_join(1, 0);
if (js < 0)
return abort_step_msg(h, js, "joining the second lane at its window's end failed");
return abort_step_msg(h, js, "joining the second lane outside its window failed");
}
}
if (lane_ == 1) lane1_pending_ = true;
+44
View File
@@ -0,0 +1,44 @@
/* mtp_couple_evidence.h -- what the completed-verify log line may claim.
*
* The line reports a coupled verify only when the build that staged bound rows belongs to the step
* whose wait just returned, and counts only sequences still live after that wait. It reads
* Sampler::couple_build(), the snapshot build_step froze, because the drafter's build_greedy
* clears staged_any_couple() before the wait. The op's domain is printed so a host reference row
* is not read as a device verify.
*
* A pure function of the snapshot, a liveness predicate and the domain, so it is tested without
* an Engine (tests/sample_test.cpp).
*/
#pragma once
#include "sampler.h"
#include <string>
namespace rad {
struct MtpCoupleEvidence {
int64_t rows = 0; /* bound rows of sequences still live after the wait */
bool device = false; /* the op that ran is a device op */
std::string seqs; /* those sequences, comma separated, in build order */
};
/* `live(seq)` answers whether the sequence is still Running; the engine passes a predicate over
* Scheduler::running(), the tests a set. Empty (rows == 0) when the snapshot is not this step's,
* or nothing it staged is still live. */
template <class Live>
MtpCoupleEvidence mtp_couple_evidence(const Sampler::CoupleBuild& b, int64_t step, int domain,
Live&& live) {
MtpCoupleEvidence e;
if (b.step != step) return e;
e.device = domain == RAD_DOMAIN_DEVICE;
for (const auto& s : b.seqs)
if (live(s.first)) {
e.rows += s.second;
if (!e.seqs.empty()) e.seqs += ",";
e.seqs += std::to_string(s.first);
}
return e;
}
} // namespace rad
+86 -2
View File
@@ -133,6 +133,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
}
cfg_ = cfg;
couple_ = cfg.draft_coupling;
if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size;
/* The staged mask covers this rank's shard; the grammar's covers the whole vocabulary.
@@ -185,6 +186,14 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
* exempts that column. The ban op indexes it by the sampled row, not by mask_row. */
buf_ngram_wl_ = decl("sampler.ngram_wl", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
/* The coupled state plane, one row per sampled position, PERSIST because an upload fills it
* before the run phase issues anything. A round's state belongs to the verify row that
* follows it, so it rides the sampler's row array. */
if (couple_) {
buf_couple_ = decl("sampler.mtp_couple", RAD_U32, rows, RAD_MTP_COUPLE_STATE_WORDS,
RAD_BUF_PERSIST);
if (!buf_couple_) return RAD_E_NOMEM;
}
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()) {
@@ -257,6 +266,19 @@ 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 coupled verify, over the candidate plane the pick read. A row with no bound state keeps
* the pick's token; a step with no bound row does not issue it. */
if (couple_) {
RadParam pc[3] = {
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
RadParam{ "n_cand", RAD_P_INT, (long long)ncand, 0, nullptr },
RadParam{ "n_vocab", RAD_P_INT, (long long)cfg_.n_vocab, 0, nullptr },
};
op_couple_ = rad_decl_op(b, "mtp_couple_verify", pc, 3, nullptr, 0);
if (!op_couple_) return RAD_E_NOKERNEL;
/* No rad_op_reads: the other sampler ops declare no lists, and a list on this op alone
* would narrow the candidate planes' lifetime to it and refuse the first sample_topk. */
}
/* The temperature kernel again, over the candidate plane: `n_vocab` is only a row length to
* it, so the candidate width works. */
{
@@ -316,6 +338,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
int Sampler::stage_alloc() {
const int64_t rows = rows_for(cfg_);
/* At most one entry per request; reserved here so a coupled step never allocates. */
couple_build_.seqs.reserve((size_t)cfg_.max_seqs);
/* Pinned: uploaded every step, and a pageable source turns the async copy into a staged one
* with a host bounce (spec §8). */
@@ -331,6 +355,11 @@ int Sampler::stage_alloc() {
ngram_stage_ = (int32_t*)rad_dev_alloc(rows * 2 * 4, RAD_MEM_HOST_PINNED);
ngram_wl_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
/* The coupled rows, pinned: uploaded every coupled step, and a pageable source would turn the
* async copy into a staged one with a host bounce (spec §8). */
if (couple_)
couple_stage_ = (RadMtpCoupleState*)rad_dev_alloc(
rows * (int64_t)sizeof(RadMtpCoupleState), RAD_MEM_HOST_PINNED);
/* Logprobs readback; only rank 0 reads it. */
if (cfg_.rank == 0) {
@@ -347,7 +376,7 @@ int Sampler::stage_alloc() {
}
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
!ngram_stage_ || !ngram_wl_stage_ || !mask_stage_) {
!ngram_stage_ || !ngram_wl_stage_ || !mask_stage_ || (couple_ && !couple_stage_)) {
RAD_ERR("sampler: could not pin %s of staging",
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
mask_words_ * 8 + 8)).c_str());
@@ -366,6 +395,8 @@ void Sampler::stage_free() {
if (ngram_stage_) rad_dev_free(ngram_stage_, RAD_MEM_HOST_PINNED);
if (ngram_wl_stage_) rad_dev_free(ngram_wl_stage_, RAD_MEM_HOST_PINNED);
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
if (couple_stage_) rad_dev_free(couple_stage_, RAD_MEM_HOST_PINNED);
couple_stage_ = nullptr;
if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED);
if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED);
if (lp_cv_host_) rad_dev_free(lp_cv_host_, RAD_MEM_HOST_PINNED);
@@ -602,7 +633,21 @@ bool Sampler::speculation_fixed(uint64_t req_id) const {
/* ================================================================== the step path */
int Sampler::build_step(const std::vector<Request*>& reqs) {
/* Every state must name this request and its own round: one from another request or round would
* couple against a Q this step never drew. */
int Sampler::set_mtp_couple(uint64_t req_id, const RadMtpCoupleState* states, int n) {
if (!couple_ || n < 0 || n > RAD_MTP_COUPLE_MAX_ROUNDS || (n && !states)) return RAD_E_STATE;
const auto it = seqs_.find(req_id);
if (it == seqs_.end()) return RAD_E_NOTFOUND;
for (int i = 0; i < n; ++i)
if (states[i].draw.seq != req_id || states[i].round != i + 1) return RAD_E_STATE;
SeqState& s = it->second;
for (int i = 0; i < n; ++i) s.couple[i] = states[i];
s.couple_n = n;
return RAD_OK;
}
int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
if (!declared_) return RAD_E_STATE;
const auto t_build = std::chrono::steady_clock::now();
@@ -612,8 +657,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
any_late_ = false;
any_ngram_ = false;
any_ngram_wl_ = false;
any_couple_ = false;
cur_stage_ = params_stage_;
lp_rows_.clear();
/* The evidence snapshot this build owns; build_greedy never touches it. */
couple_build_.step = step;
couple_build_.rows = 0;
couple_build_.seqs.clear();
/* 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
@@ -701,6 +751,30 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]);
const int64_t row = n_seq_++;
/* Row k verifies draft k against the state its round left. A row with no bound state
* (the bonus row, a greedy row, an uncoupled step) gets a zeroed one, and the verify
* leaves the pick's token alone. */
if (couple_) {
couple_stage_[row] = RadMtpCoupleState{};
const auto sit = seqs_.find(r->id);
if (sit != seqs_.end() && !sp.greedy() && r->draft && k + 1 < n_pos &&
k < sit->second.couple_n) {
const RadMtpCoupleState& c = sit->second.couple[k];
/* Same request and seed, this row's round, position and proposed token
* (rad_mtp_couple_binds); anything else is a stale state from another step. */
if (rad_mtp_couple_binds(c, r->id, sp.seed, (uint64_t)n_out, k, r->draft[k],
cfg_.n_vocab)) {
couple_stage_[row] = c;
any_couple_ = true;
++couple_build_.rows;
auto& q = couple_build_.seqs;
size_t j = 0;
while (j < q.size() && q[j].first != r->id) ++j;
if (j == q.size()) q.emplace_back(r->id, 1);
else ++q[j].second;
}
}
}
DeviceSampleParams& p = params_stage_[row];
std::memset(&p, 0, sizeof p);
@@ -940,6 +1014,7 @@ int Sampler::build_greedy(int64_t n) {
any_late_ = false;
any_ngram_ = false;
any_ngram_wl_ = false;
any_couple_ = false;
cur_stage_ = greedy_stage_;
/* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from
* the staging, and a stale pair from an earlier request's build must not issue the ban over
@@ -1030,6 +1105,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
if (any_mask)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_,
n_seq_ * mask_words_ * 4, s));
if (any_couple_)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_couple_), couple_stage_,
n_seq_ * (int64_t)sizeof(RadMtpCoupleState), s));
const RadOperand o_logits = opd_rows(logits, n_seq_);
const RadOperand o_params = opd_rows(buf_params_, n_seq_);
@@ -1119,6 +1197,12 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
RAD_TRY(issue(op_temp_late_, { o_cv, opd_rows(buf_params_late_, n_seq_) }));
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
/* After the pick, over the same plane: a coupled row replaces the pick's token and an unbound
* row keeps it. The issued step is recorded for the evidence line. */
if (any_couple_) {
RAD_TRY(issue(op_couple_, { o_ci, o_cv, o_params, opd_rows(buf_couple_, n_seq_), o_tok }));
couple_issued_step_ = couple_build_.step;
}
/* 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
+45 -2
View File
@@ -77,6 +77,7 @@
*/
#pragma once
#include "rad_sample.h"
#include "rad_spechub.h"
#include "../rad_core.h"
#include "grammar.h"
@@ -86,6 +87,7 @@
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
namespace rad {
@@ -115,6 +117,10 @@ struct SamplerConfig {
* 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 */
@@ -166,13 +172,18 @@ public:
/* 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). */
int build_step(const std::vector<Request*>& reqs);
* 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
@@ -206,6 +217,26 @@ public:
* 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 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
@@ -224,6 +255,11 @@ private:
* 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
@@ -253,6 +289,7 @@ private:
rad_op op_argmax_ = RAD_NULL_HANDLE;
rad_op op_allgather_ = RAD_NULL_HANDLE;
rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */
rad_op op_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 */
@@ -272,6 +309,12 @@ private:
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;
+2 -1
View File
@@ -133,6 +133,7 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
else
g.checkpoint_interval = 0;
g.window_ckpt = !has_linear && g.checkpoint_interval > 0;
g.window_periodic = g.window_ckpt && cfg.checkpoint_policy != "tip-only";
/* Window checkpoints do not support skipping snapshots inside a prefill span. */
g.span = (g.checkpoint_interval > 0 && !g.window_ckpt && cfg.prefill_span > 1)
? cfg.prefill_span : 1;
@@ -156,7 +157,7 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
* chunk; the log line makes that visible. tip-only window snapshots do not
* split at the interval, so their chunk is bounded by the token budget. */
const int64_t span_tok = g.checkpoint_interval * g.span;
const bool periodic = !g.window_ckpt || cfg.checkpoint_policy != "tip-only";
const bool periodic = !g.window_ckpt || g.window_periodic;
const int64_t eff = (g.checkpoint_interval > 0 && periodic && span_tok < cfg.max_tok)
? span_tok : cfg.max_tok;
RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint "
+3
View File
@@ -56,6 +56,9 @@ struct ChunkGeometry {
* snapshots let an edited prompt resume below its divergence instead of from zero.
* tip-only skips interval snapshots and keeps the original tail-only chunking. */
bool window_ckpt = false;
/* Window checkpoints at interval boundaries too, not only at the tail: every policy but
* tip-only, which keeps the tail alone and so splits no chunk at the interval. */
bool window_periodic = false;
bool checkpoints() const { return checkpoint_interval > 0; }
};
+16
View File
@@ -202,6 +202,16 @@ struct IPrefixCache {
/* Entries expired by --prefix-cache-ttl; not counted as evictions. */
virtual int64_t expired() const { return 0; }
virtual int64_t ckpt_expired() const { return 0; }
/* Entries and snapshots a client released on purpose (release_session). */
virtual int64_t released() const { return 0; }
virtual int64_t ckpt_released() const { return 0; }
/* Forget one stored conversation now, by the client's label or the engine's session id
* (PrefixCache::release_session). RAD_E_UNSUPPORTED from a cache without a session table. */
virtual int release_session(const std::string& /*label*/, uint64_t /*id*/,
int64_t /*keep_tokens*/, SessionRelease* /*out*/) {
return RAD_E_UNSUPPORTED;
}
/* Tokens of context held only by the cache right now. Blocks a running sequence also reads
* are excluded. Separates a working cache from a leak in the pool figures. */
@@ -488,6 +498,12 @@ struct PCBinding final : IPrefixCache {
}
int64_t expired() const override { return m->stats().expired; }
int64_t ckpt_expired() const override { return m->stats().ckpt_expired; }
int64_t released() const override { return m->stats().released; }
int64_t ckpt_released() const override { return m->stats().ckpt_released; }
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out) override {
return m->release_session(label, id, keep_tokens, out);
}
int64_t held_tokens() const override { return m->unshared_tokens(); }
int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); }
+1
View File
@@ -92,6 +92,7 @@ struct SchedMetrics {
* and reservations that went without a snapshot. */
int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0;
int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */
int64_t prefix_released = 0, prefix_ckpt_released = 0; /* DELETE /sessions */
/* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent
* state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks
* that could not be adopted. `hit_cut_resumed_below` counts those that resumed at a
+72
View File
@@ -0,0 +1,72 @@
/* mtp_couple_bind.h -- the engine's post-commit binding step for a serial drafting row.
*
* Engine::finish_serial_drafter calls this after the commit, once the card's proposal states are
* read back. It decides:
*
* - the position the next build stages the row at: the request's committed output length after
* this commit. It is not rebuilt from the draw's pre-commit base plus the accepted count, which
* differ when a max_tokens or context cut emits fewer tokens than the card accepted;
* - whether the row binds at all: a sequence that is gone from the commit or no longer Running
* will not sample again.
*
* Both come from Scheduler::committed_seq(), filled by commit under the scheduler lock, never from
* the plan's StepEntry::req, which reap() may have freed by now. A header of its own so the rule
* can be tested against a real commit without an Engine (tests/sched_test.cpp).
*/
#pragma once
#include "advance.h"
#include "rad_spechub.h"
#include <cstring>
#include <string>
namespace rad {
/* Where the next build will sample this sequence, after the current step's commit. */
struct MtpCoupleBindPoint {
bool found = false; /* the committed step carried the sequence */
bool live = false; /* and its request was still Running (not finished/cancelled/failed) */
uint64_t n_out = 0; /* its committed output length: what the next build reads as n_out */
};
/* Bind `done` rounds of this row's draw to the positions the next build samples. `rb` is round 1
* of this row in the engine's readback (stride `rb_stride` states), `tok[rd]` the card's token for
* round rd, `S` the card's slot. Fills `out[0, done)` and sets `*n_bound = done`; a sequence that
* is not live binds nothing (`*n_bound = 0`, RAD_OK) and leaves `out` untouched. RAD_E_STATE with
* `why` for a readback that is not this draw's, or is not a state the proposer could have written.
* A sampled round the proposer marked status -1 (a shortlist it could not turn into Q) kept the
* greedy proposal; it is bound as is, the sampler does not couple it, and `*n_malformed` counts it.
* `base` is never read here: it is the draft's coordinate, not the verify's. */
inline int mtp_couple_bind_rounds(const MtpCoupleBindPoint& p, const RadMtpCoupleDraw& d,
const RadMtpCoupleState* rb, int rb_stride, int done,
const StepSlot& S, int64_t vocab, RadMtpCoupleState* out,
int* n_bound, std::string* why, int* n_malformed = nullptr) {
*n_bound = 0;
if (n_malformed) *n_malformed = 0;
if (!p.live) return RAD_OK;
const bool sampled = d.mode == 1;
for (int rd = 1; rd <= done; ++rd) {
const RadMtpCoupleState& st = rb[(size_t)(rd - 1) * (size_t)rb_stride];
const bool malformed = sampled && st.status == -1;
if (std::memcmp(&st.draw, &d, sizeof d) || st.round != rd || st.x != S.tok[rd] ||
(st.status != (sampled ? 1 : 0) && !malformed) ||
(sampled && !malformed && !rad_mtp_couple_state_valid(st, vocab))) {
*why = "MTP coupled: sequence " + std::to_string(d.seq) + " round " +
std::to_string(rd) + " returned status " + std::to_string(st.status) +
" round " + std::to_string(st.round) + " x " + std::to_string(st.x) +
" for card token " + std::to_string(S.tok[rd]) + " (draw " +
(std::memcmp(&st.draw, &d, sizeof d) ? "stale" : "current") +
"); refusing the step";
return RAD_E_STATE;
}
if (malformed && n_malformed) ++*n_malformed;
RadMtpCoupleState b = st;
b.pos = rad_mtp_couple_verify_pos(p.n_out, rd);
out[rd - 1] = b;
}
*n_bound = done;
return RAD_OK;
}
} // namespace rad
+53
View File
@@ -0,0 +1,53 @@
/* mtp_couple_plan.h -- which draw the engine stages for each serial drafting row.
*
* Engine::stage_couple_draws (core/engine_draft.cpp) reads the draw of every sequence on its card
* from the step plan and, for each drafting row, the plan entry naming the row's sequence on the
* row's card. Pure host bookkeeping, so it is tested without a card.
*
* `by_card` has one entry per card slot, indexed by StepEntry::card in [0, max_seqs), the range of
* the StepSlots the advance reads.
*/
#pragma once
#include "batch.h"
#include "scheduler.h" /* Scheduler::SerialRow */
#include "rad_spechub.h"
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
/* Fills `by_card[0, n_card)` from the plan and writes one draw per drafting row to `stage[0, n)`.
* RAD_OK, or RAD_E_STATE with `why` set: the plane is too small for the card slots, or a drafting
* row's card carries no plan entry naming its sequence (a stale row -- the plugin would refuse the
* staged draw, so it is refused here where the row can be named). */
inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Scheduler::SerialRow* rows,
int n, std::vector<RadMtpCoupleDraw>* by_card,
RadMtpCoupleDraw* stage, std::string* why) {
if (!by_card || !stage || !why) return RAD_E_INVAL;
if ((int)by_card->size() < n_card) {
*why = "the draw plane holds " + std::to_string(by_card->size()) +
" card slot(s), the step can use " + std::to_string(n_card);
return RAD_E_STATE;
}
for (int c = 0; c < n_card; ++c) (*by_card)[(size_t)c] = RadMtpCoupleDraw{};
for (const StepEntry& e : plan.e)
if (e.req && e.card >= 0 && e.card < n_card)
(*by_card)[(size_t)e.card] = { e.req->sp.seed, (uint64_t)e.req->output.size(), e.seq,
e.card, e.req->sp.greedy() ? 0u : 1u };
for (int i = 0; i < n; ++i) {
const Scheduler::SerialRow& row = rows[i];
if (row.card < 0 || row.card >= n_card || (*by_card)[(size_t)row.card].seq != row.seq) {
*why = "drafting row " + std::to_string(i) + " (sequence " + std::to_string(row.seq) +
", card " + std::to_string(row.card) + ") has no plan entry on its card";
return RAD_E_STATE;
}
stage[i] = (*by_card)[(size_t)row.card];
}
return RAD_OK;
}
} // namespace rad
+80 -3
View File
@@ -202,6 +202,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
free_cards_[(size_t)c] = (int32_t)(cfg.max_seqs - 1 - c); /* 0 is taken first */
reqs_.reserve((size_t)cfg.max_seqs);
completed_.reserve((size_t)cfg.max_seqs);
committed_.reserve((size_t)cfg.max_seqs);
by_id_.reserve((size_t)cfg.max_seqs * 2);
hit_blocks_.resize(prog.kv_groups.size());
for (auto& v : hit_blocks_) v.reserve(64);
@@ -325,6 +326,25 @@ Request* Scheduler::find(uint64_t id) {
return it == by_id_.end() ? nullptr : reqs_[(size_t)it->second]->req.get();
}
bool Scheduler::running(uint64_t id) const {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
if (it == by_id_.end()) return false;
const SchedReq& s = *reqs_[(size_t)it->second];
return s.req && s.req->state == ReqState::Running;
}
bool Scheduler::committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const {
std::lock_guard<std::mutex> lk(mu_);
for (const CommittedSeq& c : committed_)
if (c.seq == seq) {
if (n_out) *n_out = c.n_out;
if (live) *live = c.live;
return true;
}
return false;
}
int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
@@ -403,6 +423,40 @@ int64_t Scheduler::reset_prefix_cache() {
return dropped;
}
int Scheduler::release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out) {
std::lock_guard<std::mutex> lk(mu_);
if (!pc_ || !cfg_.prefix_cache) return RAD_E_UNSUPPORTED;
if (label.empty() && id == 0) return RAD_E_INVAL;
for (const auto& p : reqs_) {
if (!p || !p->req) continue;
const Request& r = *p->req;
if (r.state == ReqState::Finished || r.state == ReqState::Failed ||
r.state == ReqState::Cancelled)
continue;
if ((id != 0 && r.id == id) || (!label.empty() && r.session_label == label))
return RAD_E_STATE;
}
const int rc = pc_->release_session(label, id, keep_tokens, out);
if (rc == RAD_OK && out) {
if (label.empty())
RAD_INFO("prefix cache: session %llu released: %lld entries (%lld tokens), %lld "
"snapshots; kept %lld tokens as asked, %lld blocks shared, %lld live",
(unsigned long long)id, (long long)out->entries, (long long)out->tokens,
(long long)out->snapshots, (long long)out->kept_tokens,
(long long)out->kept_shared, (long long)out->kept_live);
else
RAD_INFO("prefix cache: session '%s' released (%lld rows): %lld entries (%lld "
"tokens), %lld snapshots; kept %lld tokens as asked, %lld blocks shared, "
"%lld live",
label.c_str(), (long long)out->sessions, (long long)out->entries,
(long long)out->tokens, (long long)out->snapshots,
(long long)out->kept_tokens, (long long)out->kept_shared,
(long long)out->kept_live);
}
return rc;
}
void Scheduler::trim_prefix_cache() {
if (!pc_ || !cfg_.prefix_cache) return;
const std::vector<int32_t>& cg = pc_->cached_groups();
@@ -751,7 +805,7 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
if (geo_.checkpoints()) {
const int64_t I = geo_.checkpoint_interval;
int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */
if (geo_.window_ckpt && cfg_.checkpoint_policy == "tip-only") {
if (geo_.window_ckpt && !geo_.window_periodic) {
/* An explicit tail-only policy should not pay for intermediate
* window copies or chunk splits just to retire those snapshots. */
next = INT64_MAX;
@@ -1882,6 +1936,10 @@ int Scheduler::commit(const StepResult& res) {
}
step_open_ = false;
/* What the serial bind reads after commit, copied here while the Requests are still held:
* reap() may release a finished one before finish_serial_drafter runs. */
committed_.clear();
const int32_t W = conv_window();
/* A mixed step leaves decode rows the same replay factors as a decode step (recurrent path
@@ -1904,6 +1962,7 @@ int Scheduler::commit(const StepResult& res) {
s.pending_free = false;
--n_deferred_;
}
committed_.push_back({e.seq, (uint64_t)r.output.size(), false});
continue;
}
@@ -2060,6 +2119,7 @@ int Scheduler::commit(const StepResult& res) {
} else if (eos) {
close_request(s, ReqState::Finished, "stop", carried);
}
committed_.push_back({e.seq, (uint64_t)r.output.size(), r.state == ReqState::Running});
}
m_.prefill_tokens += step_prefill_tok_;
@@ -2386,8 +2446,12 @@ void Scheduler::serial_end(int rounds_done) {
* also propose. Called while plan() still describes that step, because the context pass mirrors
* it exactly, rejected suffix included: the drafter reads hidden states positionally from its
* own buffer, so batch row i must be buffer row i. The rejected positions lie in [n_computed,
* n_computed + block), which the query pass overwrites before anything reads them, and the
* ensure() below covers them since n_computed + block reaches the trunk step's own end.
* n_computed + the trunk step's block), which a query pass overwrites before anything reads them.
* The ensure() below covers n_computed + `block`; with the block the trunk step verified that
* reaches its end. A short block (rad_drafter_short_block) after a long one does not: rejected
* rows past it fall on pages the commit's rollback freed, whose slot is -1, and every kv_store
* drops a negative slot. That rule is what keeps such a step from writing into another
* sequence's pages.
*
* On the card the step has not committed yet. The step began at n_computed (a row issued ahead
* was staged at its furthest reach; it really continued from the committed end, as commit()
@@ -2503,6 +2567,17 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
return n_draft_rows;
}
int Scheduler::decoded_seqs() const {
std::lock_guard<std::mutex> lk(mu_);
int n = 0;
for (const StepEntry& e : plan_.e) {
if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue;
const SchedReq& s = *reqs_[(size_t)e.slot];
if (s.req && s.req->state == ReqState::Running && s.running) ++n;
}
return n;
}
const Request* Scheduler::block_req(const BlockSeq& d) const { return live_req(d.slot, d.seq); }
const Request* Scheduler::serial_req(const SerialSeq& m) const { return live_req(m.slot, m.seq); }
@@ -2712,6 +2787,8 @@ SchedMetrics Scheduler::metrics_locked() const {
m.prefix_ckpt_refused = cc.refused;
m.prefix_expired = pc_->expired();
m.prefix_ckpt_expired = pc_->ckpt_expired();
m.prefix_released = pc_->released();
m.prefix_ckpt_released = pc_->ckpt_released();
m.prefix_held_tokens = pc_->held_tokens(); }
m.attn_hit_rate = m.prompt_tokens
? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f;
+34
View File
@@ -139,6 +139,15 @@ public:
const int32_t* first_row = nullptr; /* [n_seq] */
};
/* What commit left a sequence at: its committed length and whether it is still Running.
* Copied under the lock in commit because reap() may free the Request before the serial bind
* reads it. */
struct CommittedSeq {
uint64_t seq = 0;
uint64_t n_out = 0;
bool live = false;
};
/* `geo` is the already-resolved chunk geometry. The engine resolves it once because
* PrefixCache::configure runs first and needs its checkpoint interval; pass nullptr to
* resolve one here. */
@@ -167,6 +176,11 @@ public:
* under exactly the load that cancels. */
int cancel(uint64_t id);
Request* find(uint64_t id);
/* Whether the request is still admitted and Running, read under the lock. */
bool running(uint64_t id) const;
/* What the step just committed left for `seq`, copied by commit under the lock. False when
* that step carried no such sequence. */
bool committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const;
/* Requests that reached a terminal state since the last call, oldest first, swapped into
* `out` under the lock (old contents discarded). Only the engine consumes it, to drop
@@ -260,6 +274,13 @@ public:
* cache. Takes the step lock because the step path inserts into the map (live sequences hold
* their own block references). See IScheduler::reset_prefix_cache. */
int64_t reset_prefix_cache();
/* Forget one stored conversation, by label or engine id, keeping its first `keep_tokens`
* (IPrefixCache::release_session). Refused with RAD_E_STATE while a request of that
* conversation is queued or running: its blocks would be skipped as live and its close
* would publish the chain again, so the release would be half done and undone at once.
* Takes the step lock like reset_prefix_cache. */
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out);
/* ---------------------------------------------------------- the step path */
/* One decision, one batch. Null when there is nothing to run, which is not an error. */
@@ -361,6 +382,17 @@ public:
* in the order block_query() emits them. */
int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max,
bool on_card = false);
/* How many running sequences the step just run decoded (produced a token for), the load a
* block drafter's block length is chosen by. Read before block_begin(). */
int decoded_seqs() const;
/* Whether a block drafter runs its short block (--draft-short-from `from`), given whether it
* ran it last step and this step's decoded_seqs(): on from `from`, off again only at two
* below, so a load wavering at the threshold does not switch the pass shape every step. */
static bool short_block_on(bool was_on, int64_t decoded, int64_t from) {
if (decoded >= from) return true;
if (decoded + 2 <= from) return false;
return was_on;
}
const RadBatch* block_context(int step);
const RadBatch* block_query(int step);
void block_end();
@@ -637,6 +669,8 @@ private:
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
bool step_open_ = false;
/* The step just committed: its sequences' committed length and liveness, in plan order. */
std::vector<CommittedSeq> committed_;
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
DecodeFloor decode_floor_;
+20
View File
@@ -108,6 +108,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
o.hit_cut_tokens = m.hit_cut_tokens;
o.prefix_expired = m.prefix_expired;
o.prefix_ckpt_expired = m.prefix_ckpt_expired;
o.prefix_released = m.prefix_released;
o.prefix_ckpt_released = m.prefix_ckpt_released;
o.prefill_tps = m.prefill_tps;
o.decode_tps = m.decode_tps;
@@ -203,6 +205,24 @@ public:
int64_t reset_prefix_cache() override { return s_->reset_prefix_cache(); }
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionReleased* out) override {
SessionRelease r;
const int rc = s_->release_session(label, id, keep_tokens, &r);
if (out) {
out->sessions = r.sessions;
out->entries = r.entries;
out->tokens = r.tokens;
out->device_bytes = r.device_bytes;
out->host_bytes = r.host_bytes;
out->snapshots = r.snapshots;
out->kept_tokens = r.kept_tokens;
out->kept_shared = r.kept_shared;
out->kept_live = r.kept_live;
}
return rc;
}
/* The stored conversations. The tiers keep monotonic timestamps; idle and age are converted
* to "seconds ago" here, so only the monotonic clock is authoritative. */
TierCounters tier_counters() const override {
+136 -15
View File
@@ -11,11 +11,18 @@
* `guidance_scale` (the model's guidance: the denoiser's for a music model, the frame model's for
* a speech one) and, for a model with a denoiser, `num_inference_steps`.
*
* References, for a model that clones a voice (RadAudioGenDecl::tmpl_ref): `references` is an
* array of {"audio", "text"}, a clip of the voice (a data: URL or the base64 of an audio file,
* decoded to mono at the model's rate and padded to whole frames) and what it says; at most the
* model's count of them and seconds together. The prompt is then the references' template, each
* reference rendered from the model's item, its transcript and a row a frame of its clip.
*
* Prompt: the plugin's template with its slots filled, each text first rewritten by the plugin
* into the form the model was trained on (rad_arch_text_prepare). The template is tokenised with
* its special tokens and the texts without, so a caller cannot write the model's control tokens
* into a lyric. A model that declares the unconditional branch's own template gets that one
* rendered from the same texts.
* into a lyric; a model that declares `input_special` has its input tokenised with them too (its
* speaker tags), its prepare() refusing the control tokens. A model that declares the
* unconditional branch's own template gets that one rendered from the same texts.
*
* Response: the whole piece, once it is finished, as `response_format` wav (16-bit PCM, the
* model's rate and channels) or pcm (the same samples raw, little-endian). Streamed as the
@@ -29,6 +36,7 @@
#include "oai.h"
#include "gen/audio.h"
#include "mm/media.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
@@ -109,6 +117,9 @@ int Server::speech_request(const json& body, const std::string& text,
return fail(err_bad("instructions", "this model needs instructions, as a non-empty "
"string: for a song its genre, mood, vocals and "
"instruments"));
if (!inst.empty() && info.tmpl.empty())
return fail(err_unsupported("instructions", "this model takes no instructions; its "
"direction is written in the input"));
if (body.contains("speed") && !body["speed"].is_null() &&
!(body["speed"].is_number() && body["speed"].get<double>() == 1.0))
return fail(err_unsupported("speed", "this model keeps its own tempo; the instructions "
@@ -156,6 +167,8 @@ int Server::speech_request(const json& body, const std::string& text,
if (!body["guidance_scale"].is_number() || !(body["guidance_scale"].get<double>() >= 1.0) ||
body["guidance_scale"].get<double>() > 30.0)
return fail(err_bad("guidance_scale", "expected a number in [1, 30]"));
if (info.branches == 1 && body["guidance_scale"].get<double>() != 1.0)
return fail(err_unsupported("guidance_scale", "this model runs without guidance"));
r->cfg = (float)body["guidance_scale"].get<double>();
}
bool seed_given = false;
@@ -170,33 +183,141 @@ int Server::speech_request(const json& body, const std::string& text,
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
/* ---- the references: a clip of a voice and what it says, each */
struct Ref { std::string text; int64_t frames = 0; };
std::vector<Ref> refs;
if (body.contains("references") && !body["references"].is_null()) {
const json& rs = body["references"];
if (!rs.is_array())
return fail(err_bad("references", "expected an array of {\"audio\", \"text\"}"));
if (!rs.empty() && info.tmpl_ref.empty())
return fail(err_unsupported("references", "this model takes no reference audio; its "
"voice is described in the input"));
if ((int64_t)rs.size() > info.ref_max)
return fail(err_bad("references", "at most " + std::to_string(info.ref_max) +
" references a request"));
const int64_t hop = std::max<int64_t>(1, info.ref_hop);
r->ref_cu.assign(1, 0);
for (size_t i = 0; i < rs.size(); ++i) {
const std::string at = "references[" + std::to_string(i) + "]";
const json& e = rs[i];
if (!e.is_object())
return fail(err_bad(at, "expected an object {\"audio\", \"text\"}"));
for (auto it = e.begin(); it != e.end(); ++it)
if (it.key() != "audio" && it.key() != "text")
return fail(err_bad(at + "." + it.key(), "a reference is its audio and its "
"text"));
if (!e.contains("audio") || !e["audio"].is_string())
return fail(err_bad(at + ".audio", "the clip is required, as a data: URL or "
"base64 of an audio file"));
if (!e.contains("text") || !e["text"].is_string() || blank(e["text"].get<std::string>()))
return fail(err_bad(at + ".text", "the clip's transcript is required, as a "
"non-empty string"));
/* The file: a data: URL, or its base64 alone (as fish-speech's server takes it). */
const std::string& a = e["audio"].get_ref<const std::string&>();
std::vector<uint8_t> bytes;
if (a.rfind("data:", 0) == 0) {
ApiError ue;
if (decode_media_url(a, at + ".audio", &bytes, &ue) < 0) return fail(ue);
} else if (!base64_decode(a, &bytes)) {
return fail(err_bad(at + ".audio", "invalid base64"));
}
/* Mono at the model's rate; one sample past what is left of the budget is decoded,
* so a clip too long is refused rather than cut. */
const int64_t left = info.ref_max_samples - (int64_t)r->ref_audio.size();
std::vector<float> pcm;
std::string dwhy;
if (left < hop)
return fail(err_bad(at + ".audio", "the references are longer than this model "
"takes"));
if (mm::decode_audio(bytes.data(), bytes.size(), (int32_t)info.ref_rate, left + 1,
&pcm, &dwhy) < 0)
return fail(err_bad(at + ".audio", "the clip could not be used: " + dwhy));
if (pcm.empty()) return fail(err_bad(at + ".audio", "the clip holds no audio"));
const int64_t padded = ((int64_t)pcm.size() + hop - 1) / hop * hop;
if (padded > left)
return fail(err_bad(at + ".audio", "the references hold more than " +
rad::fmt("%g", (double)info.ref_max_samples /
(double)info.ref_rate) +
" seconds together; this model takes no "
"more"));
pcm.resize((size_t)padded, 0.0f);
r->ref_audio.insert(r->ref_audio.end(), pcm.begin(), pcm.end());
r->ref_cu.push_back((int32_t)r->ref_audio.size());
Ref ref;
std::string why;
if (deps_.audio->prepare(RAD_TEXT_REFERENCE, e["text"].get<std::string>(), &ref.text,
&why) < 0)
return fail(err_bad(at + ".text", why));
ref.frames = padded / hop;
refs.push_back(std::move(ref));
}
if (refs.empty()) r->ref_cu.clear();
}
if (!refs.empty() && !inst.empty())
return fail(err_unsupported("instructions", "a request with references takes no "
"instructions; the clips set the voice"));
/* ---- the prompt */
std::string i2, t2, why;
if (!inst.empty() && deps_.audio->prepare(RAD_TEXT_INSTRUCTIONS, inst, &i2, &why) < 0)
return fail(err_bad("instructions", why));
if (deps_.audio->prepare(RAD_TEXT_INPUT, text, &t2, &why) < 0)
return fail(err_bad("input", why));
auto encode = [&](const std::string& t, bool special, std::vector<int32_t>* ids_out) {
if (t.empty()) return;
const auto ids = deps_.tok->encode(t, false, /*parse_special=*/special);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
};
auto subst = [](std::string t, const std::string& key, const std::string& v) {
for (size_t p = t.find(key); p != std::string::npos; p = t.find(key, p + v.size()))
t.replace(p, key.size(), v);
return t;
};
/* One reference (ref_item): its header, the transcript in it, tokenised as one segment with
* its special tokens (the speaker tags prepare() allows), a row a frame of its clip, and what
* follows the clip as another segment. */
int64_t frame0 = 0;
auto render_ref = [&](size_t i, std::vector<int32_t>* ids_out) {
static const std::string kAudio = "{audio}";
const std::string idx = std::to_string(i + 1);
const size_t a = info.ref_item.find(kAudio);
encode(subst(subst(info.ref_item.substr(0, a), "{index}", idx), "{text}", refs[i].text),
true, ids_out);
r->ref_frame.resize(ids_out->size(), -1);
for (int64_t f = 0; f < refs[i].frames; ++f) {
ids_out->push_back(0);
r->ref_frame.push_back((int32_t)(frame0 + f));
}
frame0 += refs[i].frames;
encode(subst(info.ref_item.substr(a + kAudio.size()), "{index}", idx), true, ids_out);
};
/* A template a segment at a time: its own text with special tokens, each slot without. */
auto render = [&](const std::string& t, std::vector<int32_t>* ids_out) {
static const std::string kInst = "{instructions}", kInput = "{input}";
static const std::string kInst = "{instructions}", kInput = "{input}",
kRefs = "{references}";
size_t at = 0;
while (at <= t.size()) {
const size_t a = t.find(kInst, at), b = t.find(kInput, at);
const size_t p = std::min(a, b);
const std::string lit =
t.substr(at, p == std::string::npos ? std::string::npos : p - at);
if (!lit.empty()) {
const auto ids = deps_.tok->encode(lit, false, /*parse_special=*/true);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
}
const size_t a = t.find(kInst, at), b = t.find(kInput, at), c = t.find(kRefs, at);
const size_t p = std::min(a, std::min(b, c));
encode(t.substr(at, p == std::string::npos ? std::string::npos : p - at), true,
ids_out);
if (p == std::string::npos) break;
if (p == c) {
for (size_t i = 0; i < refs.size(); ++i) render_ref(i, ids_out);
at = p + kRefs.size();
continue;
}
const bool is_inst = p == a;
const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, /*parse_special=*/false);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
/* The input keeps its special tokens only for a model that asks (its speaker tags);
* the plugin's prepare() has refused the ones a caller may not write. */
encode(is_inst ? i2 : t2, !is_inst && info.input_special, ids_out);
at = p + (is_inst ? kInst : kInput).size();
}
};
render(inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens);
render(!refs.empty() ? info.tmpl_ref : inst.empty() ? info.tmpl_plain : info.tmpl,
&r->tokens);
if (!refs.empty()) r->ref_frame.resize(r->tokens.size(), -1);
if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens);
const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size());
if ((int64_t)n_prompt > info.max_prompt)
@@ -225,7 +346,7 @@ HttpResponse Server::handle_speech(const HttpRequest& req) {
static const char* kKnown[] = {
"model", "input", "instructions", "voice", "response_format", "speed", "stream",
"stream_format", "seed", "max_new_tokens", "duration", "num_inference_steps",
"guidance_scale", "user",
"guidance_scale", "user", "references",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
+81
View File
@@ -150,6 +150,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } };
/* Entries and snapshots removed by --prefix-cache-ttl, from whichever tier held them. */
o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } };
/* And the ones a client gave up on purpose (DELETE /sessions). */
o["released"] = { { "entries", sm.prefix_released }, { "snapshots", sm.prefix_ckpt_released } };
/* Step-thread time spent on tier moves; every request waits through it. */
o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 },
{ "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } };
@@ -179,6 +181,83 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
return HttpResponse::json_body(200, json_dump(o));
}
/* ------------------------------------------------------------------ DELETE /sessions
*
* A client that deletes a conversation, or replaces everything past a prefix of it, knows the
* rest is dead before the TTL does. Named by the label it sent (`session_id`, or Anthropic's
* `metadata.user_id`), or by the engine id `/sessions` shows. `keep_tokens` keeps the chain's
* start. Shared blocks and blocks a live request reads stay; a request of the same conversation
* in flight is a 409, since its close would publish the chain again. */
HttpResponse Server::handle_session_release(const HttpRequest& req) {
if (!deps_.sched)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
const std::string label = req.param("label");
uint64_t id = 0;
const std::string id_s = req.param("id");
if (!id_s.empty()) {
if (id_s.find_first_not_of("0123456789") != std::string::npos || id_s.size() > 19)
return error_response(err_bad("id", "expected the session's engine id, a decimal "
"integer as /sessions reports it"), req.peer);
id = std::stoull(id_s);
if (id == 0) return error_response(err_bad("id", "0 names no session"), req.peer);
}
if (label.empty() && id == 0)
return error_response(err_bad("label", "name the session: DELETE /sessions/<label>, "
"?label=<label> or ?id=<engine id>"), req.peer);
int64_t keep_tokens = 0;
const std::string keep_s = req.param("keep_tokens");
if (!keep_s.empty()) {
if (keep_s.find_first_not_of("0123456789") != std::string::npos || keep_s.size() > 12)
return error_response(err_bad("keep_tokens", "expected a non-negative integer: the "
"prefix to keep, in tokens"), req.peer);
keep_tokens = std::stoll(keep_s);
}
SessionReleased r;
const int rc = deps_.sched->release_session(label, id, keep_tokens, &r);
if (rc == RAD_E_UNSUPPORTED)
return error_response(err_not_implemented(
"this engine has no prefix cache (started with --no-prefix-cache, or the model "
"declares no cacheable KV group)"), req.peer);
const std::string who = label.empty() ? "id " + std::to_string(id) : "'" + label + "'";
if (rc == RAD_E_NOTFOUND) {
ApiError e;
e.status = 404;
e.type = "not_found_error";
e.param = label.empty() ? "id" : "label";
e.message = "no stored session " + who + "; GET /sessions lists them";
return error_response(e, req.peer);
}
if (rc == RAD_E_STATE) {
ApiError e;
e.status = 409;
e.type = "conflict_error";
e.code = "session_in_use";
e.message = "a request of session " + who + " is queued or running; cancel it or wait "
"for it to finish, then release again";
return error_response(e, req.peer);
}
if (rc == RAD_E_INVAL)
return error_response(err_bad("keep_tokens", rad_strerror(rc)), req.peer);
if (rc < 0) return error_response(err_internal(rad_strerror(rc)), req.peer);
json o;
if (!label.empty()) o["label"] = label;
if (id != 0) o["id"] = id;
o["keep_tokens"] = keep_tokens;
o["sessions"] = r.sessions;
o["entries"] = r.entries;
o["tokens"] = r.tokens;
o["device_bytes"] = r.device_bytes;
o["host_bytes"] = r.host_bytes;
o["snapshots"] = r.snapshots;
o["kept"] = { { "tokens", r.kept_tokens }, { "shared", r.kept_shared },
{ "live", r.kept_live } };
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_stats(const HttpRequest&) {
json o;
o["model"] = opt_.model_id;
@@ -234,6 +313,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
o["ckpt_evictions"] = { { "retention", m.prefix_ckpt_retired },
{ "store_full", m.prefix_ckpt_lru } };
o["ckpt_refused"] = m.prefix_ckpt_refused;
o["released"] = { { "entries", m.prefix_released },
{ "snapshots", m.prefix_ckpt_released } };
o["hit_cuts"] = { { "no_snapshot", m.hit_cut_no_snapshot },
{ "windowed_group", m.hit_cut_window },
{ "adopt_failed", m.hit_cut_adopt },
+1 -1
View File
@@ -506,7 +506,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
* anthropic-version and anthropic-beta headers of Anthropic's clients, which nothing reads. */
static const char* const kCorsHeaders =
"Content-Type, Authorization, X-Api-Key, anthropic-version, anthropic-beta";
static const char* const kCorsMethods = "GET, POST, OPTIONS";
static const char* const kCorsMethods = "GET, POST, DELETE, OPTIONS";
/* Whether a request carries the API key: `Authorization: Bearer` (OpenAI; the scheme is
* case-insensitive, RFC 9110) or `X-Api-Key` (Anthropic, also accepted by llama-server). */
+30
View File
@@ -78,6 +78,7 @@ struct SchedMetrics {
int64_t prefix_restore_cuts = 0;
/* Removed by --prefix-cache-ttl, cumulative. Not evictions: nothing wanted the memory. */
int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
int64_t prefix_released = 0, prefix_ckpt_released = 0;
/* Decoupled prefix caching (spec §7.3). `prefix_hit_rate` is the attention hit rate, as in
* vLLM. The linear side hits at a different granularity (whole checkpoints, not blocks), so
* it is reported separately, with token counts and checkpoints written. */
@@ -168,6 +169,17 @@ struct SessionOccupancy {
int64_t host_cap_bytes = 0;
};
/* What a release took out of the store and what it left (PrefixCache::release_session). The
* kept counts are apart on purpose: `shared` blocks belong to another stored conversation too,
* `live` ones to a request still reading them. */
struct SessionReleased {
int64_t sessions = 0;
int64_t entries = 0, tokens = 0;
int64_t device_bytes = 0, host_bytes = 0;
int64_t snapshots = 0;
int64_t kept_tokens = 0, kept_shared = 0, kept_live = 0;
};
/* One in-flight request, for the live request table: shows which request is stuck, e.g. one
* waiting on a prompt that will never fit, which no aggregate metric reveals. */
struct RequestStat {
@@ -225,6 +237,15 @@ public:
* allocated), but it takes the scheduler's lock because a step may be inserting into the map. */
virtual int64_t reset_prefix_cache() { return RAD_E_UNSUPPORTED; }
/* Forgets one stored conversation (DELETE /sessions): every row carrying `label`, or with
* `id` nonzero the row of that engine id; `keep_tokens` leaves the chain's start standing.
* RAD_E_NOTFOUND when nothing matches (404), RAD_E_STATE while a request of that
* conversation is queued or running (409), RAD_E_UNSUPPORTED without a prefix cache (501). */
virtual int release_session(const std::string& /*label*/, uint64_t /*id*/,
int64_t /*keep_tokens*/, SessionReleased* /*out*/) {
return RAD_E_UNSUPPORTED;
}
/* The live request table, oldest first; returns the count. Default: none kept. */
virtual int requests(std::vector<RequestStat>* /*out*/) const { return 0; }
@@ -662,6 +683,15 @@ struct AudioGenInfo {
int64_t sample_rate = 0, channels = 0;
int64_t default_steps = 0, max_lanes = 1; /* default_steps 0: no denoiser */
double default_cfg = 1.0;
/* RadAudioGenDecl::branches (1: no guidance) and ::input_special (the {input} slot is
* tokenised with special tokens). */
int32_t branches = 2;
bool input_special = false;
/* RadAudioGenDecl's references: the prompt with them and one reference ("" when the model
* takes none), the clips' rate and frame, and the most of them and their samples. */
std::string tmpl_ref, ref_item;
int64_t ref_rate = 0, ref_hop = 0, ref_max_samples = 0;
int32_t ref_max = 0;
};
class IAudioGen {
+9
View File
@@ -189,6 +189,8 @@ void Metrics::sample(const SchedMetrics& m) {
c_prefix_ckpt_evict_.advance_to(m.prefix_ckpt_evictions);
c_prefix_expired_.advance_to(m.prefix_expired);
c_prefix_ckpt_expired_.advance_to(m.prefix_ckpt_expired);
c_prefix_released_.advance_to(m.prefix_released);
c_prefix_ckpt_released_.advance_to(m.prefix_ckpt_released);
c_ckpt_retired_.advance_to(m.prefix_ckpt_retired);
c_ckpt_lru_.advance_to(m.prefix_ckpt_lru);
c_ckpt_refused_.advance_to(m.prefix_ckpt_refused);
@@ -438,6 +440,13 @@ std::string Metrics::render() const {
c_ckpt_retired_.get());
labelled("radiance:prefix_cache_ckpt_evictions_by_reason_total", "reason", "store_full",
c_ckpt_lru_.get());
w.help("radiance:prefix_cache_released_total",
"Prefix-cache entries and linear-state snapshots a client released on purpose "
"(DELETE /sessions).", "counter");
labelled("radiance:prefix_cache_released_total", "what", "entries",
c_prefix_released_.get());
labelled("radiance:prefix_cache_released_total", "what", "snapshots",
c_prefix_ckpt_released_.get());
w.counter("radiance:prefix_cache_ckpt_refused_total",
"Checkpoints not written because every snapshot slot was in use by a restore "
"in the same step.", L, c_ckpt_refused_.get());
+1
View File
@@ -151,6 +151,7 @@ private:
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Counter c_prefix_expired_, c_prefix_ckpt_expired_;
Counter c_prefix_released_, c_prefix_ckpt_released_;
Counter c_ckpt_retired_, c_ckpt_lru_, c_ckpt_refused_;
Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_resumed_below_, c_cut_tokens_;
Counter c_restore_cuts_;
+6
View File
@@ -210,6 +210,12 @@ void Server::register_routes() {
[this](const HttpRequest& q) { return handle_control_vector(q); });
router_.post("/admin/control-vector",
[this](const HttpRequest& q) { return handle_control_vector(q); });
/* Forget one stored conversation: by its client label in the path (or `?label=`, for a
* label the path cannot carry), or by engine id with `?id=`. */
router_.add ("DELETE", "/sessions/:label",
[this](const HttpRequest& q) { return handle_session_release(q); });
router_.add ("DELETE", "/sessions",
[this](const HttpRequest& q) { return handle_session_release(q); });
}
/* Workers beyond the admission ceiling. A generation holds its connection's worker for its whole
+1
View File
@@ -330,6 +330,7 @@ private:
* like every other route but the health probes and the page; without a key, POST answers
* loopback clients only. */
HttpResponse handle_control_vector(const HttpRequest& req);
HttpResponse handle_session_release(const HttpRequest& req);
HttpResponse error_response(const ApiError& e, const std::string& peer,
ApiShape shape = ApiShape::OpenAI);
+1 -1
View File
@@ -214,7 +214,7 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
static const char* kFields[] = {
"type", "model", "instructions", "voice", "response_format", "speed", "seed",
"max_new_tokens", "duration", "num_inference_steps", "guidance_scale", "user",
"stream_audio", "split_granularity", "text_input_mode",
"references", "stream_audio", "split_granularity", "text_input_mode",
};
json fields = json::object();
for (auto it = j.begin(); it != j.end(); ++it) {