Archived
merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across
conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
commit
7c3b5ab7d5
285 files changed
+30500
-2898
No files matched your search
@@ -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);
|
||||
@@ -140,6 +141,7 @@ public:
|
||||
int op_reads (rad_op h, const rad_buf* b, int n);
|
||||
int op_writes(rad_op h, const rad_buf* b, int n);
|
||||
int buf_concurrent(rad_buf b);
|
||||
int lane1_window(bool end);
|
||||
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
|
||||
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
@@ -220,6 +222,8 @@ private:
|
||||
/* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
|
||||
* bound when their bytes are in use, so they are live for the whole program. */
|
||||
std::set<rad_buf> concurrent_bufs_;
|
||||
/* The second lane's window (rad_lane1_window_begin), first and last op handle; -1 when none. */
|
||||
int32_t lane1_w0_ = -1, lane1_w1_ = -1;
|
||||
|
||||
/* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found
|
||||
* to consume it. Declaration order is the only link between an op and a group; see
|
||||
@@ -254,7 +258,5 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
|
||||
/* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared
|
||||
* once per layer with one bucket table is one row with a count. */
|
||||
std::string dump_graph_json(const Program& p);
|
||||
void dump_graph (const Program& p, FILE* out,
|
||||
const std::vector<std::string>* errors = nullptr);
|
||||
|
||||
} /* namespace rad */
|
||||
+176
-8
@@ -87,6 +87,7 @@ const char* bld_kv_kind_name(int k) {
|
||||
case RAD_KV_WINDOW: return "window";
|
||||
case RAD_KV_LINEAR: return "linear";
|
||||
case RAD_KV_CONV: return "conv";
|
||||
case RAD_KV_RING: return "ring";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
@@ -336,7 +337,7 @@ rad_buf Builder::decl_buffer(const char* name, const RadBufDecl* d) {
|
||||
rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) {
|
||||
if (finished_) return err(RAD_E_STATE, "decl_kv_group('%s') after declare finished", name ? name : "");
|
||||
if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_kv_group: null name or declaration");
|
||||
if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_CONV)
|
||||
if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_RING)
|
||||
return err(RAD_E_INVAL, "kv group '%s': unknown kind %d", name, d->kind);
|
||||
|
||||
std::string n = scoped(name);
|
||||
@@ -840,6 +841,26 @@ int Builder::buf_concurrent(rad_buf b) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* See rad_lane1_window_begin. The window is the ops declared between the two calls. */
|
||||
int Builder::lane1_window(bool end) {
|
||||
if (finished_) { err(RAD_E_STATE, "rad_lane1_window after declare finished"); return RAD_E_STATE; }
|
||||
const int32_t next = (int32_t)prog_.ops.size(); /* the next op's handle */
|
||||
if (!end) {
|
||||
if (lane1_w0_ >= 0) {
|
||||
err(RAD_E_STATE, "rad_lane1_window_begin called twice: one window a program");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
lane1_w0_ = next;
|
||||
} else {
|
||||
if (lane1_w0_ < 0 || lane1_w1_ >= 0 || next - 1 < lane1_w0_) {
|
||||
err(RAD_E_STATE, "rad_lane1_window_end without a begin, twice, or around no op");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
lane1_w1_ = next - 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* See rad_weight_shard_span. Checked against the declaration here, where the plugin can be named;
|
||||
* the loader checks it against the container. */
|
||||
int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) {
|
||||
@@ -923,7 +944,7 @@ int Builder::kv_group_zero(rad_kvgroup h) {
|
||||
* state is saved and cleared on every rank, so a zero-sized one would mismatch those
|
||||
* copies. */
|
||||
const int kind = prog_.kv_groups[h].decl.kind;
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) {
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW && kind != RAD_KV_RING) {
|
||||
err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged",
|
||||
prog_.kv_groups[h].name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
@@ -942,7 +963,10 @@ int Builder::kv_group_replicated(rad_kvgroup h) {
|
||||
err(RAD_E_STATE, "kv_group_replicated after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) {
|
||||
err(RAD_E_INVAL, "kv_group_replicated: %u is not a declared KV group", (unsigned)h);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Paged groups only: the tiers move blocks. A linear or conv group's state travels in the
|
||||
* checkpoint store, which has no such window. */
|
||||
const int kind = prog_.kv_groups[h].decl.kind;
|
||||
@@ -1204,6 +1228,11 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
|
||||
(long long)d->n_embd);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->one_grid != 0 && d->one_grid != 1) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': one_grid %d is neither 0 nor 1", nm,
|
||||
(int)d->one_grid);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
slot = *d;
|
||||
slot_name = nm;
|
||||
slot.name = nullptr; /* the plugin's storage; the name is the copy */
|
||||
@@ -1389,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;
|
||||
}
|
||||
@@ -1399,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 "
|
||||
@@ -1476,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;
|
||||
}
|
||||
|
||||
@@ -1771,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 "
|
||||
@@ -1814,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;
|
||||
}
|
||||
|
||||
@@ -1906,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);
|
||||
@@ -2108,7 +2228,8 @@ void Builder::finish_kv_groups() {
|
||||
KVGroupInfo& gi = prog_.kv_groups[g];
|
||||
const RadKVGroupDecl& d = gi.decl;
|
||||
|
||||
if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW) && gi.block_size == 0) {
|
||||
if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW || d.kind == RAD_KV_RING) &&
|
||||
gi.block_size == 0) {
|
||||
/* The plugin may never have asked; the manifest still needs the answer. */
|
||||
kv_block_size((rad_kvgroup)g);
|
||||
}
|
||||
@@ -2121,6 +2242,7 @@ void Builder::finish_kv_groups() {
|
||||
switch (d.kind) {
|
||||
case RAD_KV_FULL:
|
||||
case RAD_KV_WINDOW:
|
||||
case RAD_KV_RING:
|
||||
/* One block holds K and V for block_size tokens, the block manager's unit. */
|
||||
gi.bytes_per_block =
|
||||
rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound;
|
||||
@@ -2167,6 +2289,10 @@ void Builder::finish_buffer_liveness() {
|
||||
/* A second lane, signalled by any concurrent buffer, gets a second scratch region
|
||||
* (Program::scratch_regions). */
|
||||
prog_.scratch_regions = concurrent_bufs_.empty() ? 1 : 2;
|
||||
if (lane1_w0_ >= 0 && lane1_w1_ < 0)
|
||||
err(RAD_E_STATE, "rad_lane1_window_begin without rad_lane1_window_end");
|
||||
prog_.lane1_w0 = lane1_w1_ >= 0 ? lane1_w0_ : -1;
|
||||
prog_.lane1_w1 = lane1_w1_;
|
||||
|
||||
/* Each buffer's first and last declaring op, in one pass over the op lists. */
|
||||
const size_t nb = prog_.buffers.size();
|
||||
@@ -2184,11 +2310,19 @@ void Builder::finish_buffer_liveness() {
|
||||
* rule); a buffer on the second lane, whose declared range does not bound when its bytes
|
||||
* are in use; and one with no declared use, since an op may issue any handle in any
|
||||
* order (--debug-graph reports the cost). */
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || concurrent_bufs_.count((rad_buf)i) || first[i] < 0) {
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || first[i] < 0 ||
|
||||
(concurrent_bufs_.count((rad_buf)i) && lane1_w1_ < 0)) {
|
||||
b.first_def = 0;
|
||||
b.last_use = last_op;
|
||||
continue;
|
||||
}
|
||||
/* A concurrent buffer under a declared window (rad_lane1_window_begin): live across the
|
||||
* window, when lane 1 may touch it, and over its own uses. */
|
||||
if (concurrent_bufs_.count((rad_buf)i)) {
|
||||
b.first_def = std::min(first[i], lane1_w0_);
|
||||
b.last_use = std::max(last[i], lane1_w1_);
|
||||
continue;
|
||||
}
|
||||
b.first_def = first[i];
|
||||
b.last_use = last[i];
|
||||
|
||||
@@ -2199,6 +2333,25 @@ void Builder::finish_buffer_liveness() {
|
||||
* output likewise: the engine reads it after the last op. */
|
||||
if ((rad_buf)i == prog_.logits_buf || (rad_buf)i == prog_.pooled_buf) b.last_use = last_op;
|
||||
}
|
||||
|
||||
/* Region 1 holds what an op the second lane may issue asks for (Program::scratch_bytes_lane1):
|
||||
* every transient buffer of such an op is concurrent (Ctx::lane1_ rule 3). Ctx::issue refuses a
|
||||
* larger request on lane 1 by name, so an op that breaks the rule fails rather than overruns. */
|
||||
prog_.scratch_bytes_lane1 = 0;
|
||||
if (prog_.scratch_regions > 1)
|
||||
for (size_t o = 1; o < prog_.ops.size() && o < op_bufs_.size(); ++o) {
|
||||
bool lane1 = true;
|
||||
for (const std::vector<rad_buf>* v : { &op_bufs_[o].reads, &op_bufs_[o].writes })
|
||||
for (rad_buf h : *v)
|
||||
if (prog_.buffers[h].decl.kind == RAD_BUF_TRANSIENT && !concurrent_bufs_.count(h))
|
||||
lane1 = false;
|
||||
if (!lane1) continue;
|
||||
for (const Band& bd : prog_.ops[o].bands)
|
||||
if (bd.dom[RAD_DOMAIN_DEVICE] &&
|
||||
bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes > prog_.scratch_bytes_lane1)
|
||||
prog_.scratch_bytes_lane1 = bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes;
|
||||
}
|
||||
if (prog_.scratch_bytes_lane1 > prog_.scratch_bytes) prog_.scratch_bytes_lane1 = prog_.scratch_bytes;
|
||||
}
|
||||
|
||||
int Builder::finish() {
|
||||
@@ -2331,6 +2484,16 @@ int rad_buf_concurrent(RadBuilder* b, rad_buf buf) {
|
||||
return B(b)->buf_concurrent(buf);
|
||||
}
|
||||
|
||||
int rad_lane1_window_begin(RadBuilder* b) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lane1_window(false);
|
||||
}
|
||||
|
||||
int rad_lane1_window_end(RadBuilder* b) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lane1_window(true);
|
||||
}
|
||||
|
||||
int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->weight_shard_span(w, lo, hi);
|
||||
@@ -2390,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);
|
||||
|
||||
@@ -364,12 +364,6 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
|
||||
return s;
|
||||
}
|
||||
|
||||
void dump_graph(const Program& p, FILE* out, const std::vector<std::string>* errors) {
|
||||
std::string s = dump_graph_str(p, errors);
|
||||
fwrite(s.data(), 1, s.size(), out ? out : stderr);
|
||||
fflush(out ? out : stderr);
|
||||
}
|
||||
|
||||
/* ================================================================== the graph, as JSON
|
||||
*
|
||||
* dump_graph_str's content and more, for the server's Model view. It walks the same Program with
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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,12 @@ 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" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier" },
|
||||
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
|
||||
" pins its host memory at startup (default 4096)" },
|
||||
@@ -155,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" },
|
||||
@@ -438,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;
|
||||
@@ -489,6 +512,25 @@ 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;
|
||||
else if (!std::strcmp(v, "qk")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK;
|
||||
else if (!std::strcmp(v, "pv")) c->attn_prefill_fp8 = RAD_ATTN_FP8_PV;
|
||||
else if (!std::strcmp(v, "both")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV;
|
||||
else {
|
||||
RAD_ERR("--attn-prefill-fp8 takes off, qk, pv or both, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; }
|
||||
else if (S("--embedding-placement") || S("--ngram-placement")) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
@@ -638,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
|
||||
@@ -971,6 +1023,16 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const char* attn_prefill_fp8_name(int bits) {
|
||||
switch (bits) {
|
||||
case 0: return "off";
|
||||
case RAD_ATTN_FP8_QK: return "qk";
|
||||
case RAD_ATTN_FP8_PV: return "pv";
|
||||
case RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV: return "both";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the startup report's rows */
|
||||
namespace {
|
||||
|
||||
@@ -1010,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"); } },
|
||||
@@ -1025,6 +1088,9 @@ 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); } },
|
||||
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
|
||||
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
|
||||
@@ -1061,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); } },
|
||||
|
||||
+24
-39
@@ -1,18 +1,5 @@
|
||||
/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h).
|
||||
*
|
||||
* The format is llama.cpp's `controlvector` package: one `direction.<l>` tensor of unit f32 per
|
||||
* layer, plus three metadata keys. The reader is core/text/gguf.cpp, which already mmaps a GGUF
|
||||
* and computes tensor byte sizes, so nothing here parses bytes by hand.
|
||||
*
|
||||
* The published package (hf.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection) is what the checks
|
||||
* below are written against, and its own JSON states the operation's parameters:
|
||||
*
|
||||
* {"mode": "project", "dir": "per-layer", "scale": 1.0, "layer_range": [4, 44], ...}
|
||||
*
|
||||
* so a file is only accepted for a model whose hidden size equals the directions' width and whose
|
||||
* architecture the file names. Everything else is refused at startup, by name, rather than
|
||||
* steered along a direction from another residual basis.
|
||||
*/
|
||||
/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h). The reader is
|
||||
* core/text/gguf.cpp, which maps the file and sizes its tensors. */
|
||||
#include "cvec.h"
|
||||
|
||||
#include "text/gguf.h"
|
||||
@@ -98,10 +85,10 @@ int control_vector_discover(const std::string& model_path, const std::string& ar
|
||||
}
|
||||
|
||||
|
||||
/* The package's own JSON, if it is beside the vector: `{"mode": "project", "scale": 1.0,
|
||||
* "layer_range": [4, 44]}` is what the published Flash-Next vector ships. It is the only place
|
||||
* the operation's parameters are stated, so they are read from there rather than configured; a
|
||||
* malformed or absent file only means the defaults below. */
|
||||
/* The package's own JSON beside the vector (`<stem>.json`), the only place the operation's
|
||||
* parameters are stated: `{"mode": "project", "scale": 1.0, "layer_range": [4, 44]}` for the
|
||||
* published Flash-Next vector. Absent, the defaults apply. A file that is not JSON or names a mode
|
||||
* other than `project` is refused: the directions were tuned for that operation. */
|
||||
namespace {
|
||||
|
||||
struct PackageJson {
|
||||
@@ -109,8 +96,8 @@ struct PackageJson {
|
||||
float scale = 1.0f;
|
||||
};
|
||||
|
||||
PackageJson read_package_json(const std::string& gguf_path) {
|
||||
PackageJson out;
|
||||
int read_package_json(const std::string& gguf_path, PackageJson* out, std::string* why) {
|
||||
*out = PackageJson{};
|
||||
std::string stem = gguf_path;
|
||||
const size_t dot = stem.find_last_of('.');
|
||||
const size_t slash = stem.find_last_of("/\\");
|
||||
@@ -118,28 +105,28 @@ PackageJson read_package_json(const std::string& gguf_path) {
|
||||
stem = stem.substr(0, dot);
|
||||
const std::string path = stem + ".json";
|
||||
std::ifstream f(path);
|
||||
if (!f) return out;
|
||||
if (!f) return RAD_OK;
|
||||
try {
|
||||
const nlohmann::json j = nlohmann::json::parse(f);
|
||||
if (const auto m = j.find("mode"); m != j.end() && m->is_string() &&
|
||||
m->get<std::string>() != "project") {
|
||||
RAD_WARN("control vector: %s says mode '%s'; only 'project' is implemented, so the "
|
||||
"defaults apply", path.c_str(), m->get<std::string>().c_str());
|
||||
return out;
|
||||
*why = "control vector " + path + ": mode '" + m->get<std::string>() +
|
||||
"'; only 'project' is implemented";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (const auto r = j.find("layer_range"); r != j.end() && r->is_array() && r->size() == 2 &&
|
||||
(*r)[0].is_number_integer() &&
|
||||
(*r)[1].is_number_integer()) {
|
||||
out.first = (*r)[0].get<int>();
|
||||
out.last = (*r)[1].get<int>();
|
||||
out->first = (*r)[0].get<int>();
|
||||
out->last = (*r)[1].get<int>();
|
||||
}
|
||||
if (const auto s = j.find("scale"); s != j.end() && s->is_number())
|
||||
out.scale = (float) s->get<double>();
|
||||
out->scale = (float) s->get<double>();
|
||||
} catch (const std::exception& e) {
|
||||
RAD_WARN("control vector: %s is not readable JSON (%s); the defaults apply", path.c_str(),
|
||||
e.what());
|
||||
*why = "control vector " + path + ": not readable JSON (" + e.what() + ")";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return out;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
@@ -206,16 +193,14 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
}
|
||||
if (n_dir == 0) return fail("control vector " + path + ": the file holds no directions");
|
||||
|
||||
/* The package's parameters: its JSON, else the published selection where the file covers it,
|
||||
* else every direction the file carries. A deployment therefore has nothing to configure, and
|
||||
* a file published with a different selection states it itself. */
|
||||
const PackageJson pj = read_package_json(path);
|
||||
/* The package's parameters: its JSON, else every direction the file carries at scale 1, as
|
||||
* llama.cpp applies a control vector given no layer range. */
|
||||
PackageJson pj;
|
||||
std::string pj_why;
|
||||
if (const int prc = read_package_json(path, &pj, &pj_why); prc != RAD_OK) return fail(pj_why);
|
||||
int first = pj.first, last = pj.last;
|
||||
float scale = pj.scale;
|
||||
if (last < 0) {
|
||||
if (n_model_layers >= 45 && dir_last >= 44) { first = 4; last = 44; }
|
||||
else { first = (int) dir_first; last = (int) dir_last; }
|
||||
}
|
||||
if (last < 0) { first = (int) dir_first; last = (int) dir_last; }
|
||||
if (first < 1 || last < first)
|
||||
return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" +
|
||||
std::to_string(last) + " is empty");
|
||||
|
||||
+18
-32
@@ -1,36 +1,26 @@
|
||||
/* cvec.h -- control vectors: one GGUF direction per layer, projected out of the residual stream.
|
||||
*
|
||||
* ============================== what it is ==============================
|
||||
* The format is llama.cpp's `controlvector` GGUF: `direction.<l>` tensors of f32, n_embd wide. The
|
||||
* operation is llama.cpp's `--cvec-mode project`
|
||||
*
|
||||
* The package at huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection carries one unit
|
||||
* direction per layer (`direction.1` .. `direction.47`, 2560 f32 each) and the configuration its
|
||||
* authors selected: the llama.cpp `--cvec-mode project` operation
|
||||
* h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| * package scale
|
||||
*
|
||||
* h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l|
|
||||
* applied by an architecture plugin that declares RadArchProbe::control_vector_ok (qwen4exp_fp8
|
||||
* issues `hc_project` on every stream of its gated residual). The layer range and scale come from
|
||||
* the package's JSON beside the file; without one, every direction the file carries steers at
|
||||
* scale 1.
|
||||
*
|
||||
* over layers 4..44, applied to every stream of the gated residual. Strata ports the same
|
||||
* package (`data/experimental-speed-projection`) with the same operation, range and per-request
|
||||
* switch; this is that port for radiance, which has its own graph and cannot use llama.cpp's
|
||||
* patch (arch/qwen4exp_fp8 issues `hc_project` from the op vocabulary instead).
|
||||
* The vector shipped in data/vectors/ is a refusal-direction projection for Qwen3.8-Flash-Next:
|
||||
* with it on, the model declines far fewer requests. It is loaded only with --control-vector, and
|
||||
* each request can name its own choice.
|
||||
*
|
||||
* The vector is a refusal-direction projection: with it on the model declines far fewer requests.
|
||||
* Removing refusals removes a safety behaviour, so the default is OFF and every request names its
|
||||
* own choice, and the file is only read when the engine finds one for this container.
|
||||
*
|
||||
* ============================== compatibility, checked, not assumed ==============================
|
||||
*
|
||||
* Nothing here trusts the file's provenance. A vector is refused unless
|
||||
* A file is refused unless
|
||||
*
|
||||
* - `general.architecture` is `controlvector`,
|
||||
* - `controlvector.model_hint`, when present, names this model's architecture plugin
|
||||
* (`qwen4exp`), since a direction from another architecture's residual basis is noise,
|
||||
* - every tensor is `direction.<l>`, F32, one dimension, and exactly the model's `n_embd`,
|
||||
* - `controlvector.model_hint`, when present, is this model's architecture id,
|
||||
* - every tensor is `direction.<l>`, F32, one dimension, exactly the model's `n_embd`, and
|
||||
* 1 <= l < the model's layer count,
|
||||
* - the layer range lies inside the model and every layer in it has a direction.
|
||||
*
|
||||
* The published Flash-Next vector passes all four against a Flash-Next container: 47 tensors of
|
||||
* 2560 f32, hint `qwen4exp`, range 4..44 of 48 layers. A 27B, Gemma or Qwen3.6 container refuses
|
||||
* it at startup with the reason, rather than serving a model whose hidden states are moved along
|
||||
* an unrelated direction.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
@@ -62,12 +52,9 @@ struct ControlVector {
|
||||
}
|
||||
};
|
||||
|
||||
/* Read and validate `path` against a model of `n_embd` and `n_model_layers`.
|
||||
*
|
||||
* The operation's parameters come with the package, never from a command line: `path`'s own
|
||||
* `<stem>.json` (the JSON the vector is published with) supplies `layer_range` and `scale` when it
|
||||
* says `"mode": "project"`. Without one, the range is the published Qwen3.8-Flash-Next selection
|
||||
* (4..44) where the file has directions there, else every layer the file carries, at scale 1. */
|
||||
/* Read and validate `path` against a model of `n_embd` and `n_model_layers`. `path`'s own
|
||||
* `<stem>.json` supplies `layer_range` and `scale`; one that is not JSON or names a mode other than
|
||||
* `project` is refused. Without it, every layer the file carries steers at scale 1. */
|
||||
int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err);
|
||||
|
||||
@@ -77,8 +64,7 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
* already knows the generation-config convention knows this one. */
|
||||
std::string control_vector_sidecar_path(const std::string& model_path);
|
||||
|
||||
/* Resolve `auto`: sets *found to the first candidate that exists and is non-empty, or to "" when
|
||||
* none does. *tried receives the candidates, for the log line that says why the feature is
|
||||
/* Sets *found to the first candidate that exists and is non-empty, or to "" when none does. *tried receives the candidates, for the log line that says why the feature is
|
||||
* unavailable on this deployment. Discovery is a filesystem test only; whether the file is
|
||||
* compatible is control_vector_load's answer. */
|
||||
int control_vector_discover(const std::string& model_path, const std::string& arch,
|
||||
|
||||
+74
-7
@@ -241,6 +241,9 @@ Global& G() {
|
||||
return *g;
|
||||
}
|
||||
|
||||
/* Set by aql_force_host_kargs before the backend starts. */
|
||||
std::atomic<bool> g_force_host_kargs{false};
|
||||
|
||||
std::string agent_isa(hsa_agent_t a) {
|
||||
char name[64] = {0};
|
||||
hsa_agent_get_info(a, HSA_AGENT_INFO_NAME, name);
|
||||
@@ -423,13 +426,10 @@ bool init_devices() {
|
||||
"difference where the slot allows it",
|
||||
i, bus);
|
||||
}
|
||||
/* The fallback on a card that needs none, to measure what reading each dispatch's
|
||||
* arguments across the link costs against the same card's VRAM rings. */
|
||||
const char* force_host_kargs = std::getenv("RADIANCE_DEBUG_AQL_HOST_KARGS");
|
||||
if (force_host_kargs && *force_host_kargs && *force_host_kargs != '0') {
|
||||
if (g_force_host_kargs.load(std::memory_order_acquire) && !g.dev[(size_t)i].host_kargs) {
|
||||
g.dev[(size_t)i].host_kargs = true;
|
||||
RAD_WARN("device: card %d (%s): RADIANCE_DEBUG_AQL_HOST_KARGS puts the kernel argument "
|
||||
"rings in host memory", i, bus);
|
||||
RAD_INFO("device: card %d (%s) keeps kernel arguments in pinned host memory, as a "
|
||||
"test asked", i, bus);
|
||||
}
|
||||
}
|
||||
/* Without the handler a fault falls back to the runtime's own handling, which the
|
||||
@@ -829,7 +829,7 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
|
||||
/* The running kernel and its arguments. A queue's read index stays on a packet until it
|
||||
* completes, so the packet there is in flight. Every pointer-shaped argument word is located
|
||||
* like the address, which names the operand that got a stale or short buffer. Only card
|
||||
* `card`'s queues; arguments are read back through the BAR. */
|
||||
* `card`'s queues; the host reads the arguments at the packet's kernarg_address. */
|
||||
std::lock_guard<std::mutex> sl(G().streams_mu);
|
||||
for (Stream* s : G().streams) {
|
||||
if (s->ord != card) continue;
|
||||
@@ -3049,9 +3049,70 @@ int vres_ord(const void* addr) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The DRM interface version of card `gpu_id`'s render node, false when it cannot be read. */
|
||||
bool drm_version(uint32_t gpu_id, int* major, int* minor, std::string* name) {
|
||||
/* struct drm_version, a layout fixed since DRM's first release. */
|
||||
struct DrmVersion {
|
||||
int major, minor, patch;
|
||||
size_t name_len;
|
||||
char* name;
|
||||
size_t date_len;
|
||||
char* date;
|
||||
size_t desc_len;
|
||||
char* desc;
|
||||
};
|
||||
const int rm = render_minor(gpu_id);
|
||||
if (rm < 0) return false;
|
||||
char path[64];
|
||||
std::snprintf(path, sizeof path, "/dev/dri/renderD%d", rm);
|
||||
const int fd = open(path, O_RDWR | O_CLOEXEC);
|
||||
if (fd < 0) return false;
|
||||
char nm[32] = {0};
|
||||
DrmVersion v{};
|
||||
v.name = nm;
|
||||
v.name_len = sizeof nm - 1;
|
||||
const bool ok = ioctl(fd, _IOWR('d', 0x00, DrmVersion), &v) == 0;
|
||||
close(fd);
|
||||
if (!ok) return false;
|
||||
*major = v.major;
|
||||
*minor = v.minor;
|
||||
*name = std::string(nm, std::min(v.name_len, sizeof nm - 1));
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Whether hsa_amd_vmem mappings on card `dev` return. From HIP 7.16 (ROCm 10.1) the runtime maps
|
||||
* a vmem handle with DRM_AMDGPU_GEM_VA, asks the kernel to signal a VM timeline syncobj once the
|
||||
* page tables are written, and waits on that point with no timeout. amdgpu reads the timeline
|
||||
* fields of GEM_VA from interface 3.64 (Linux 6.16) on; an older kernel ignores them, never
|
||||
* signals the point, and the first commit waits forever in drm_syncobj_array_wait_timeout. The
|
||||
* ROCm 7.2 runtime maps through the KFD and has no such wait. A card that would hang this way
|
||||
* gets no virtual memory management: its pools are carved whole, as on a driver without it. */
|
||||
bool vmem_maps_return(int dev) {
|
||||
static std::once_flag once[kMaxDevices];
|
||||
static bool ok[kMaxDevices];
|
||||
std::call_once(once[dev], [dev] {
|
||||
ok[dev] = true;
|
||||
int hip = 0;
|
||||
if (hipRuntimeGetVersion(&hip) != hipSuccess || hip < 71600000) return;
|
||||
int major = 0, minor = 0;
|
||||
std::string name;
|
||||
if (!drm_version(G().dev[(size_t)dev].kfd_id, &major, &minor, &name) || name != "amdgpu")
|
||||
return;
|
||||
if (major > 3 || (major == 3 && minor >= 64)) return;
|
||||
ok[dev] = false;
|
||||
RAD_WARN("device %d: this kernel's amdgpu interface is %d.%d, and the HIP %d.%d runtime "
|
||||
"waits after every virtual-memory map for a page-table timeline that amdgpu "
|
||||
"signals only from 3.64 (Linux 6.16) on, so a map here would never return. The "
|
||||
"card runs without virtual memory management; a 6.16 or later kernel restores it",
|
||||
dev, major, minor, hip / 10000000, hip / 100000 % 100);
|
||||
});
|
||||
return ok[dev];
|
||||
}
|
||||
|
||||
int64_t a_vmem_granularity(void) {
|
||||
int dev = 0;
|
||||
if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= (int)G().dev.size()) return 0;
|
||||
if (!vmem_maps_return(dev)) return 0;
|
||||
size_t gran = 0;
|
||||
if (hsa_amd_memory_pool_get_info(G().dev[(size_t)dev].vram,
|
||||
HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE, &gran) !=
|
||||
@@ -3550,6 +3611,12 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
|
||||
int64_t aql_pageable_bytes(void) { return aql::g_pageable_bytes.load(std::memory_order_relaxed); }
|
||||
|
||||
int aql_force_host_kargs(void) {
|
||||
if (aql::G().ok) return RAD_E_STATE;
|
||||
aql::g_force_host_kargs.store(true, std::memory_order_release);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int aql_vmem_device_of(const void* addr, int* dev) {
|
||||
const int d = vres_ord(addr);
|
||||
if (d < 0) return RAD_E_NOTFOUND;
|
||||
|
||||
@@ -38,11 +38,9 @@ extern "C" int rad_event_create_as(RadEvent* out, unsigned flags);
|
||||
extern "C" void rad_dev_host_wrote(void);
|
||||
/* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend
|
||||
* lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit.
|
||||
* Only on the AQL backend, whose queues keep the completion counter. On by default where the
|
||||
* model's plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays: the
|
||||
* Gemma 4 31B and 26B) and that drafter decodes speculatively (rad_dev_chain_infer, from the
|
||||
* engine before any row resolves). RADIANCE_CHAIN=0 turns them off and =1 on wherever the backend
|
||||
* chains; `auto` is the default. */
|
||||
* Only on the AQL backend, whose queues keep the completion counter, and only where the model's
|
||||
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
|
||||
* decodes speculatively (rad_dev_chain_infer, from the engine before any row resolves). */
|
||||
extern "C" int rad_dev_chain_enabled(void);
|
||||
extern "C" void rad_dev_chain_infer(int pays);
|
||||
|
||||
@@ -472,6 +470,10 @@ const DeviceBackend* hip_backend_if_present(void);
|
||||
/* The HIP backend with streams, events, copies and fills replaced by AQL packets the engine writes
|
||||
* itself (aql.cpp). Aborts with the reason on a machine it cannot run on. */
|
||||
const DeviceBackend* aql_backend_if_present(void);
|
||||
/* For tests: every card keeps its kernel argument rings and recorded-pass argument blocks in pinned
|
||||
* host memory, the placement a card whose PCI BAR is smaller than its VRAM gets, so that path runs
|
||||
* on any card. Takes effect only before the backend starts; RAD_E_STATE after. */
|
||||
int aql_force_host_kargs(void);
|
||||
/* Bytes copied to or from pageable host memory so far; each such copy is a host wait. */
|
||||
int64_t aql_pageable_bytes(void);
|
||||
/* Fat binaries registered so far, counted whichever backend runs: the registration hooks are this
|
||||
|
||||
@@ -557,7 +557,7 @@ int rad_event_sync(RadEvent e) {
|
||||
}
|
||||
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
|
||||
|
||||
/* Chaining's default, from the engine (rad_dev_chain_infer), and the answer once taken. Only
|
||||
/* Whether launches chain, from the engine (rad_dev_chain_infer), and the answer once taken. Only
|
||||
* where the backend chains: the AQL backend writes the record a chained form reads, while a HIP
|
||||
* launch carries only the kernel's own arguments. */
|
||||
static std::atomic<int> g_chain_pays{0};
|
||||
@@ -569,11 +569,10 @@ void rad_dev_chain_infer(int pays) {
|
||||
int rad_dev_chain_enabled(void) {
|
||||
int on = g_chain.load(std::memory_order_relaxed);
|
||||
if (on < 0) {
|
||||
const char* e = std::getenv("RADIANCE_CHAIN");
|
||||
const bool want = e && *e && std::strcmp(e, "auto") != 0
|
||||
? *e != '0'
|
||||
: g_chain_pays.load(std::memory_order_relaxed) != 0;
|
||||
on = want && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0;
|
||||
on = g_chain_pays.load(std::memory_order_relaxed) != 0 &&
|
||||
std::strcmp(rad::device_backend_name(), "aql") == 0
|
||||
? 1
|
||||
: 0;
|
||||
g_chain.store(on, std::memory_order_relaxed);
|
||||
}
|
||||
return on;
|
||||
|
||||
+61
-43
@@ -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
|
||||
@@ -405,13 +406,9 @@ int Engine::step_loop() {
|
||||
int idle = 0;
|
||||
std::vector<uint64_t> cancel;
|
||||
/* Not in KL mode: its scored rows are copied out of the logits buffer after collection, and a
|
||||
* pass issued ahead would overwrite them. A block drafter pipelines only on the card
|
||||
* (engine_draft.cpp); the host's driver stages from the committed sequence. */
|
||||
block_card_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && !cfg_.kld() &&
|
||||
!embedding_ && [] { const char* v = std::getenv("RADIANCE_DRAFT_BLOCK_HOST");
|
||||
return !(v && *v && *v != '0'); }();
|
||||
pipelining_ = !cfg_.kld() && !embedding_ && (drafter_.kind != RAD_DRAFT_BLOCK || block_card_) &&
|
||||
(serial_drafting() || block_card_ || cfg_.n_spec <= 0);
|
||||
* pass issued ahead would overwrite them. */
|
||||
pipelining_ = !cfg_.kld() && !embedding_ &&
|
||||
(serial_drafting() || block_drafting() || cfg_.n_spec <= 0);
|
||||
const bool t_on = (int)log_level() >= (int)Log::Debug;
|
||||
/* The next step's forward pass when already issued behind the previous step, before its
|
||||
* readback (Scheduler::step_next). */
|
||||
@@ -456,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
|
||||
@@ -530,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);
|
||||
@@ -705,7 +687,8 @@ int Engine::step_loop() {
|
||||
/* Queue the drafter's passes behind the step before waiting: the card computes acceptance
|
||||
* itself and every pass reads it there (sched/advance.h), so one wait covers the whole
|
||||
* step. */
|
||||
st = block_card_ ? issue_block_drafter(b->step, so) : issue_serial_drafter(b->step, so);
|
||||
st = block_drafting() ? issue_block_drafter(b->step, so)
|
||||
: issue_serial_drafter(b->step, so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
st = mark_step_end(b, so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
@@ -717,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);
|
||||
@@ -769,13 +755,10 @@ int Engine::step_loop() {
|
||||
if (t_on) phase_mark(PH_COMMIT);
|
||||
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
|
||||
|
||||
/* The drafter for the next step. The host's block driver runs here, since it stages from
|
||||
* the committed sequence. A serial one, or a block one on the card, already ran; what
|
||||
* remains is to check its acceptance against the host's and publish its proposals. Each
|
||||
* driver returns immediately for a kind that is not its own. */
|
||||
st = drafter_.kind != RAD_DRAFT_BLOCK ? finish_serial_drafter(so)
|
||||
: block_card_ ? finish_block_drafter(so)
|
||||
: run_block_drafter(b->step);
|
||||
/* The drafter for the next step already ran on the card; what remains is to check its
|
||||
* acceptance against the host's and publish its proposals. Each driver returns
|
||||
* immediately for a kind that is not its own. */
|
||||
st = block_drafting() ? finish_block_drafter(so) : finish_serial_drafter(so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
/* The step ends here, after its draft rounds, so step timing includes them
|
||||
* (Scheduler::step_finished). */
|
||||
@@ -1370,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()) {
|
||||
@@ -1491,15 +1493,16 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
auto* b = static_cast<PCBinding<PrefixCache>*>(pc_iface_.get());
|
||||
/* Called inside Scheduler::step() under its lock, which makes touching the cache and rank
|
||||
* 0's manager safe; nothing here may call back into the scheduler. */
|
||||
b->restore_fn = [this, b](const Request& req) {
|
||||
b->restore_fn = [this, b](const Request& req, bool whole_only) -> RestoreResult {
|
||||
const uint64_t t0 = rad_mono_ns();
|
||||
PrefixCache& pc = ranks_[0]->prefix;
|
||||
/* Room is made before anything is planned (PCBinding::restore_plan): a chain the free
|
||||
* list cannot hold would otherwise come back only as far as it reaches. One block
|
||||
* table serves every rank, so what rank 0's cache gives up is room on every rank. */
|
||||
const std::vector<BlockHash> want =
|
||||
b->restore_plan(req, cvec_salt_for(req.sp.use_control_vector));
|
||||
if (want.empty()) return;
|
||||
RestoreResult res = RestoreResult::Whole;
|
||||
const std::vector<BlockHash> want = b->restore_plan(
|
||||
req, cvec_salt_for(req.sp.use_control_vector), whole_only, &res);
|
||||
if (want.empty()) return res;
|
||||
/* The whole chain in one restore. With 4-token blocks a long conversation is tens of
|
||||
* thousands of entries; batched, it is one launch per (group, layer) per staging batch
|
||||
* and one copy per run of arena slots instead of a round trip per entry. */
|
||||
@@ -1510,7 +1513,9 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
if (!ranks_[0]->tierx.plan_promote(h, &j)) break;
|
||||
jobs.push_back(std::move(j));
|
||||
}
|
||||
if (jobs.empty()) return;
|
||||
/* A record still in flight ends the chain here, as a short reservation does below. */
|
||||
if (jobs.size() < want.size()) res = RestoreResult::Cut;
|
||||
if (jobs.empty()) return res;
|
||||
std::vector<char> ok(jobs.size(), 1);
|
||||
for (auto& r : ranks_) {
|
||||
std::vector<char> mine;
|
||||
@@ -1525,7 +1530,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
const std::vector<int32_t>& cg = pc.cached_groups();
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
if (!ok[i]) continue;
|
||||
if (!ok[i]) { res = RestoreResult::Cut; continue; }
|
||||
const int rb = pc.rebind(j.key, j.blocks);
|
||||
if (rb != RAD_OK) {
|
||||
/* No entry to land in: release the reserved blocks and forget the tier record,
|
||||
@@ -1537,6 +1542,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
}
|
||||
}
|
||||
ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0));
|
||||
return res;
|
||||
};
|
||||
/* An eviction that would lose an entry waits for its copy instead. Called by the prefix
|
||||
* cache binding under the scheduler's lock when dropping already-copied entries did not
|
||||
@@ -1690,6 +1696,8 @@ std::string Engine::engine_info() const {
|
||||
e["tensor_parallel"] = cfg_.tp;
|
||||
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. */
|
||||
@@ -2540,6 +2548,7 @@ int Engine::run_server() {
|
||||
in.chunk_bos = gd.chunk_bos;
|
||||
in.chunk_eos = gd.chunk_eos;
|
||||
in.chunk_pad = gd.pad_token;
|
||||
in.cond_opts = gd.cond_opts;
|
||||
image_bridge.drv = img_gen_;
|
||||
image_bridge.proc = mm_proc.get();
|
||||
d.images = &image_bridge;
|
||||
@@ -2570,8 +2579,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 {
|
||||
@@ -2597,6 +2607,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;
|
||||
@@ -2737,8 +2755,8 @@ int Engine::run_server() {
|
||||
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
|
||||
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
|
||||
mapped.c_str());
|
||||
/* What a request naming no effort gets, which a client cannot see: Qwen3.8's template
|
||||
* renders xhigh into a system prompt (#113). */
|
||||
/* What a request naming no effort gets, which a client cannot see: a template may
|
||||
* render a level into a system prompt (Qwen3.8's renders xhigh). */
|
||||
const std::string& dflt = srv.template_default_effort();
|
||||
if (cfg_.reasoning_effort.empty() && !dflt.empty())
|
||||
RAD_INFO("chat: a request naming no reasoning_effort renders as '%s', the "
|
||||
|
||||
+38
-8
@@ -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>
|
||||
@@ -185,7 +186,6 @@ public:
|
||||
std::shared_ptr<void>* hold, std::string* note, std::string* err);
|
||||
/* The adapter files a generator request may name: --lora's and those under --lora-dir. */
|
||||
std::vector<std::string> gen_lora_names() const;
|
||||
bool gen_lora_enabled() const { return lora_gen_; }
|
||||
private:
|
||||
/* A generator's adapter files by name (--lora, POST /v1/load_lora_adapter, --lora-dir), opened
|
||||
* once and kept mapped; compositions read them when a combination is put in a slot. */
|
||||
@@ -339,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. */
|
||||
@@ -374,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);
|
||||
@@ -383,7 +390,7 @@ private:
|
||||
/* The arena level and the followers' pools, before any release that runs a forward pass. */
|
||||
int prepare_release(const RadBatch* b);
|
||||
/* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (the
|
||||
* prompt-lookup drafter and the host's block driver both read the committed sequence). */
|
||||
* prompt-lookup drafter reads the committed sequence). */
|
||||
bool pipelining_ = false;
|
||||
int finish_serial_drafter(const StepOut& so);
|
||||
/* Handed from issue_serial_drafter to finish_serial_drafter: the drafting rows, the rounds
|
||||
@@ -396,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. */
|
||||
@@ -407,19 +433,23 @@ private:
|
||||
void phase_mark(int p);
|
||||
|
||||
/* Block driver (spec §10): a context pass mirroring the step just run, then one pass that
|
||||
* fills every drafted position at once. DFlash2 has this shape. run_block_drafter stages both
|
||||
* after the commit; on the card (`block_card_`, the default), issue_block_drafter queues them
|
||||
* behind the step before its readback and finish_block_drafter publishes the proposals after
|
||||
* the commit, so the step can be issued ahead. RADIANCE_DRAFT_BLOCK_HOST=1 keeps the host's. */
|
||||
int run_block_drafter(int step);
|
||||
* fills every drafted position at once. DFlash2 has this shape. issue_block_drafter queues
|
||||
* both behind the step before its readback and finish_block_drafter publishes the proposals
|
||||
* after the commit, so the step can be issued ahead. */
|
||||
bool block_drafting() const;
|
||||
int block_pass(const RadBatch* db, const char* what, int step);
|
||||
bool block_card_ = false;
|
||||
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. */
|
||||
|
||||
+177
-58
@@ -84,6 +84,25 @@ struct MissReport {
|
||||
}
|
||||
};
|
||||
|
||||
/* The kernels --attn-prefill-fp8 reached: the resolved rows, in any band and domain, that
|
||||
* constrain `prefill_fp8`. An exact kernel ignores the parameter and states no constraint on it. */
|
||||
static std::vector<std::string> prefill_fp8_rows(const Program& p) {
|
||||
std::vector<std::string> names;
|
||||
for (const OpInfo& op : p.ops)
|
||||
for (const Band& band : op.bands)
|
||||
for (const Resolved& r : band.dom) {
|
||||
if (!r || !r.row->info) continue;
|
||||
const RadKernelInfo* k = r.row->info;
|
||||
bool takes = false;
|
||||
for (int c = 0; c < k->n_constraints; ++c)
|
||||
if (k->constraints[c].key && !std::strcmp(k->constraints[c].key, "prefill_fp8"))
|
||||
takes = true;
|
||||
if (takes && std::find(names.begin(), names.end(), k->name) == names.end())
|
||||
names.push_back(k->name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
static MissReport miss_report(const Program& p, bool host_backend) {
|
||||
MissReport r;
|
||||
std::vector<std::string> host_ops; /* in first-seen order */
|
||||
@@ -885,6 +904,10 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.kv_dtype = cfg_.kv_cache_dtype == "bf16" ? RAD_BF16 : RAD_F8E4M3;
|
||||
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;
|
||||
@@ -1019,6 +1042,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
|
||||
@@ -1036,24 +1093,23 @@ int Engine::declare() {
|
||||
cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point"
|
||||
: "this container carries no draft head");
|
||||
}
|
||||
/* Chained launches pay on some speculative steps and cost plain decode (4x R9700: the 31B
|
||||
* with DFlash2 +13%, the 26B-A4B with DFlash +1%, Qwen3.8-27B with DFlash2 even; the 31B with
|
||||
* no drafter -6.5%), so they are on by default only where the model's plugin measured a gain
|
||||
* with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
/* Chained launches pay on some speculative steps and cost plain decode (on 4x R9700 the 31B
|
||||
* with DFlash2 gained 13%, the 26B-A4B with DFlash 1%, Qwen3.8-27B with DFlash2 nothing, and
|
||||
* the 31B without a drafter lost 6.5%), so they are on only where the model's plugin measured a
|
||||
* gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
* speculatively. */
|
||||
{
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
rad_dev_chain_infer(cfg_.n_spec > 0 && pb.chain_pays);
|
||||
const char* e = std::getenv("RADIANCE_CHAIN");
|
||||
const bool pays = cfg_.n_spec > 0 && pb.chain_pays;
|
||||
rad_dev_chain_infer(pays);
|
||||
const bool on = rad_dev_chain_enabled() != 0;
|
||||
const char* why = e && *e && std::strcmp(e, "auto") != 0
|
||||
? (on || *e == '0' ? "RADIANCE_CHAIN says so" : "the backend does not chain")
|
||||
: on ? "the model's plugin measured a gain with its speculative drafter"
|
||||
: "no drafter whose plugin measured a gain with them decodes "
|
||||
"speculatively, or the backend does not chain";
|
||||
const char* why = on ? "the model's plugin measured a gain with its speculative drafter"
|
||||
: pays ? "the device backend does not chain"
|
||||
: "no drafter whose plugin measured a gain with them decodes "
|
||||
"speculatively";
|
||||
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
|
||||
decide("RADIANCE_CHAIN", on ? "1" : "0", why);
|
||||
decide("chained launches", on ? "on" : "off", why);
|
||||
}
|
||||
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
|
||||
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
|
||||
@@ -1072,7 +1128,10 @@ int Engine::declare() {
|
||||
* area, which would need 16x the activation memory on every card. */
|
||||
if (cfg_.mm_max_patches < 0) {
|
||||
const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
|
||||
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0;
|
||||
/* A checkpoint's vision_config states a tower as a flat patch_size, or (Unlimited-OCR's
|
||||
* DeepEncoder) only the per-width tables under a `vision_config.image_size`. */
|
||||
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0 ||
|
||||
rad_meta_geti(&meta_, "vision_config.image_size", 0) > 0;
|
||||
cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0;
|
||||
/* Whole output rows a pass: the plugin's merge, when it states one. */
|
||||
RadArchProbe pb{};
|
||||
@@ -1091,54 +1150,44 @@ int Engine::declare() {
|
||||
: "the model carries no vision tower");
|
||||
}
|
||||
|
||||
/* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions
|
||||
* already divided, spec §9), every rank concurrently on its own thread. Concurrency is
|
||||
* required: kernel init() runs during declare, and a collective's init is a rendezvous
|
||||
* (libr4d's all-reduce publishes its peer scratch pointer and waits for every other rank), so
|
||||
* a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each
|
||||
* thread binds its device first, because the current device is thread-local and the init
|
||||
* allocates on it. */
|
||||
/* Control vectors are resolved here, before any rank declares: the plugin reads the direction
|
||||
* table from RadBuildCtx, so a table that failed validation must stop the server before a graph
|
||||
* is built around it.
|
||||
*
|
||||
* The feature is loaded only when the deployment asks: `--control-vector off|on`. Without it
|
||||
* nothing is looked for, the graph declares no projection op, and a request that asks for one
|
||||
* is refused by name -- so a deployment that does not use the feature pays nothing. With the
|
||||
* flag, the engine looks beside the container (or in the directory, or in
|
||||
* $RADIANCE_HOME/vectors) and uses the file if it is compatible; its operation parameters come
|
||||
* from the package's own JSON. A file that does not fit is reported and skipped -- a sidecar
|
||||
* must never stop a server nobody pointed at it. The flag's value is the startup switch: `off`
|
||||
* leaves requests off until one asks (or the dashboard flips the default), `on` starts them on. */
|
||||
const std::string arch = meta_.arch_id ? meta_.arch_id : "";
|
||||
/* Control vectors are resolved before any rank declares, because the plugin reads the
|
||||
* direction table from RadBuildCtx. Only `--control-vector off|on` loads one; without it
|
||||
* nothing is looked for and the graph declares no projection op. With it, a plugin that does
|
||||
* not apply control vectors (RadArchProbe::control_vector_ok), no file found, or a file that
|
||||
* does not fit this model is refused: the operator asked for the feature. The operation's
|
||||
* parameters come from the package's own JSON. The flag's value is the request default. */
|
||||
if (cfg_.control_vector == "disabled") {
|
||||
RAD_INFO("control vectors: not loaded (no --control-vector); a request that asks for one is "
|
||||
"refused");
|
||||
} else if (!arch.empty()) {
|
||||
} else {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
if (!pb.control_vector_ok) {
|
||||
RAD_ERR("--control-vector %s: the '%s' plugin does not apply control vectors for this "
|
||||
"model", cfg_.control_vector.c_str(), plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const std::string arch = meta_.arch_id ? meta_.arch_id : "";
|
||||
std::string proj_path, tried;
|
||||
(void) control_vector_discover(cfg_.model, arch, cfg_.radiance_home, &proj_path, &tried);
|
||||
if (proj_path.empty()) {
|
||||
RAD_INFO("control vectors: none found (%s)", tried.c_str());
|
||||
} else if (arch != "qwen4exp") {
|
||||
RAD_WARN("control vectors: %s is for this family only (qwen4exp, whose gated residual "
|
||||
"carries the projection op); this container is '%s' -- ignoring it",
|
||||
proj_path.c_str(), arch.c_str());
|
||||
} else {
|
||||
std::string why;
|
||||
const int rc = control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers,
|
||||
&cvec_, &why);
|
||||
if (rc != RAD_OK) {
|
||||
RAD_WARN("%s -- serving without it", why.c_str());
|
||||
cvec_ = ControlVector{};
|
||||
}
|
||||
RAD_ERR("--control-vector %s: no control vector found for this model (looked at %s)",
|
||||
cfg_.control_vector.c_str(), tried.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
std::string why;
|
||||
if (control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, &cvec_, &why) !=
|
||||
RAD_OK) {
|
||||
RAD_ERR("--control-vector %s: %s", cfg_.control_vector.c_str(), why.c_str());
|
||||
cvec_ = ControlVector{};
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (cvec_.loaded()) {
|
||||
cvec_views_.assign(ranks_.size(), RadControlVector{});
|
||||
cvec_salt_ = control_vector_salt(cvec_);
|
||||
/* `--control-vector on` starts the request default on, which is also how `--kld-record`/
|
||||
* `--kld-ref` score the projection itself: those modes serve no request to carry the
|
||||
* switch. The switch still decides per request. */
|
||||
/* The request default; --kld-record / --kld-ref score documents with it, as they serve no
|
||||
* request that could carry the field. */
|
||||
const bool default_on = cfg_.control_vector == "on";
|
||||
cvec_default_.store(default_on);
|
||||
RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- "
|
||||
@@ -1156,6 +1205,13 @@ int Engine::declare() {
|
||||
cvec_default_.store(false);
|
||||
}
|
||||
|
||||
/* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions
|
||||
* already divided, spec §9), every rank concurrently on its own thread. Concurrency is
|
||||
* required: kernel init() runs during declare, and a collective's init is a rendezvous
|
||||
* (libr4d's all-reduce publishes its peer scratch pointer and waits for every other rank), so
|
||||
* a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each
|
||||
* thread binds its device first, because the current device is thread-local and the init
|
||||
* allocates on it. */
|
||||
std::vector<int> st(ranks_.size(), RAD_OK);
|
||||
std::vector<std::thread> th;
|
||||
th.reserve(ranks_.size());
|
||||
@@ -1246,6 +1302,28 @@ int Engine::declare() {
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* --attn-prefill-fp8 is a permission an exact kernel also satisfies, so whether it acts is
|
||||
* read off the resolution: a kernel that implements a lossy leg constrains `prefill_fp8`. A
|
||||
* flag nothing takes stops the start rather than serving the exact form under its name. */
|
||||
if (cfg_.attn_prefill_fp8 != 0) {
|
||||
const std::vector<std::string> rows = prefill_fp8_rows(ranks_[0]->program);
|
||||
const char* mode = attn_prefill_fp8_name(cfg_.attn_prefill_fp8);
|
||||
if (rows.empty() && !cfg_.debug_graph) {
|
||||
RAD_ERR("not starting: --attn-prefill-fp8 %s, but no attention kernel resolved for "
|
||||
"this model takes e4m3 products at its geometry, cache (--kv-cache-dtype %s) "
|
||||
"and kernel libraries; --attn-prefill-fp8 off serves it exactly", mode,
|
||||
cfg_.kv_cache_dtype.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
std::string names;
|
||||
for (const std::string& r : rows) names += (names.empty() ? "" : ", ") + r;
|
||||
RAD_WARN("attention: LOSSY prefill (--attn-prefill-fp8 %s). %s rounded to e4m3 for fp8 "
|
||||
"WMMA in %s, so this process does not compute the same function the exact "
|
||||
"attention does; bands those kernels do not serve stay exact", mode,
|
||||
cfg_.attn_prefill_fp8 == RAD_ATTN_FP8_QK ? "Q.K^T's query is"
|
||||
: cfg_.attn_prefill_fp8 == RAD_ATTN_FP8_PV ? "P.V's probabilities are"
|
||||
: "Q.K^T's query and P.V's probabilities are", names.c_str());
|
||||
}
|
||||
/* Checkpoint weights that cannot be served as stored cannot be loaded; name them all with the
|
||||
* remedy. */
|
||||
if (ckpt_src_) {
|
||||
@@ -1272,6 +1350,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. */
|
||||
@@ -1399,6 +1495,21 @@ void Engine::probe_arena_levels() {
|
||||
}
|
||||
|
||||
/* ================================================================== 5. plan */
|
||||
|
||||
/* R-SWA: a RAD_KV_RING group names its ring's W in the declaration (`window`). Tell the manager
|
||||
* before it plans, so the group is planned for per-sequence windows: sized for the whole context
|
||||
* plus one ring a sequence (the ring in the fixed costs), never capped at the declare-time
|
||||
* window, never snapshotted. Every plan (each sizing probe and the real manager) goes through
|
||||
* here, so they all plan the same bytes. */
|
||||
static int declare_ring_windows(KVManager& kv, const Program& prog) {
|
||||
for (size_t g = 1; g < prog.kv_groups.size(); ++g) {
|
||||
const RadKVGroupDecl& d = prog.kv_groups[g].decl;
|
||||
if (d.kind != RAD_KV_RING) continue;
|
||||
RAD_TRY(kv.declare_runtime_window((int32_t)g, d.window));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::plan() {
|
||||
/* The budget is resolved once, for every rank, before any rank allocates. vram_budget_resolve
|
||||
* folds the smallest capacity with the largest program so one split fits every card, and
|
||||
@@ -1485,7 +1596,8 @@ int Engine::plan() {
|
||||
* memory, and the real pool does not exist yet. */
|
||||
KVManager probe;
|
||||
host_arenas += arena_host_bytes(r->program);
|
||||
if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
|
||||
if (declare_ring_windows(probe, r->program) == RAD_OK &&
|
||||
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
|
||||
ck_slot += probe.checkpoint_bytes();
|
||||
f.kv_ceiling = probe.ceiling(ctx);
|
||||
f.kv_fixed = probe.fixed_bytes();
|
||||
@@ -1621,7 +1733,8 @@ int Engine::plan() {
|
||||
* its carve). */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK ||
|
||||
probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
break;
|
||||
}
|
||||
@@ -2959,6 +3072,7 @@ int Engine::configure_kv() {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
auto& r = ranks_[i];
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(declare_ring_windows(r->kv, r->program));
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
/* A rank plan() re-sized for the common token count must page at least that count (same
|
||||
@@ -3193,13 +3307,16 @@ int Engine::configure_kv() {
|
||||
/* Can the pool hold one max-length sequence? The context limit and KV pool come from unrelated
|
||||
* flags; otherwise such a request is accepted and then refused at admission with a message
|
||||
* about blocks. Only full paged groups apply: a window group costs the window, and a linear
|
||||
* group is O(1) in context. */
|
||||
* group is O(1) in context. A runtime-window (RAD_KV_RING) group is not checked here either:
|
||||
* it is sized for the whole context plus one ring a sequence and its tokens are a per-sequence
|
||||
* reference rather than the pool's capacity, so the comparison would be about the wrong
|
||||
* number. */
|
||||
{
|
||||
const int64_t want = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
for (int32_t g = 0; g < kv.n_groups(); ++g) {
|
||||
const KVGroupPlan* p = kv.plan(g);
|
||||
if (!p || !p->paged() || p->window_blocks > 0) continue;
|
||||
if (!p || !p->paged() || p->window_blocks > 0 || p->runtime_win) continue;
|
||||
const int64_t cap = p->n_blocks * p->block_size;
|
||||
if (cap >= want) continue;
|
||||
/* A hard limit, unlike the backing ratio (how much of every-sequence-at-max_ctx the
|
||||
@@ -3487,16 +3604,18 @@ int Engine::start() {
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
|
||||
/* The most the cache can hold: the whole carve, including lent blocks (a request reclaims them
|
||||
* in the same step). Tokens are the smallest over the full paged groups; a windowed group
|
||||
* bounds history, not capacity. /stats and /metrics report the same numbers (kv_tokens_max,
|
||||
* radiance:kv_cache_max_tokens). */
|
||||
* in the same step). Tokens are the smallest over the full paged groups; a fixed-window group
|
||||
* bounds history, not capacity. A runtime-window (RAD_KV_RING) group does hold its sequences'
|
||||
* references, so it counts like a full group. /stats and /metrics report the same numbers
|
||||
* (kv_tokens_max, radiance:kv_cache_max_tokens). */
|
||||
{
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
int64_t bytes = 0, state = 0, tokens = 0;
|
||||
for (const KVGroupPlan& p : kv.plans()) {
|
||||
bytes += kv.pool_bytes_carved(p.index);
|
||||
if (p.stateful()) state += kv.pool_bytes_carved(p.index);
|
||||
if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue;
|
||||
if (!p.paged() || (p.kind == RAD_KV_WINDOW && !p.runtime_win) || p.block_size <= 0)
|
||||
continue;
|
||||
const int64_t t = p.n_blocks * p.block_size;
|
||||
if (tokens == 0 || t < tokens) tokens = t;
|
||||
}
|
||||
|
||||
+185
-61
@@ -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;
|
||||
}
|
||||
@@ -276,11 +427,8 @@ int Engine::finish_serial_drafter(const StepOut& so) {
|
||||
*
|
||||
* Proposals go out through set_draft() like every other.
|
||||
*
|
||||
* Two drivers run these passes. run_block_drafter, after the step commits, stages both from the
|
||||
* committed sequence and reads the proposals back: two host waits a step with the card idle
|
||||
* between them, and no step issued ahead. The card's driver (issue_block_drafter, the default)
|
||||
* queues both behind the step before its readback, from the card's acceptance, as the serial
|
||||
* driver does; RADIANCE_DRAFT_BLOCK_HOST=1 selects the host's.
|
||||
* Both passes are queued behind the step before its readback, from the card's acceptance, as the
|
||||
* serial driver's are (sched/advance.h), so the next step can be issued ahead of the commit.
|
||||
*/
|
||||
|
||||
/* One drafter pass through the barrier. Neither pass samples (no logits in the context pass; the
|
||||
@@ -306,75 +454,51 @@ int Engine::block_pass(const RadBatch* db, const char* what, int step) {
|
||||
return s;
|
||||
}
|
||||
|
||||
int Engine::run_block_drafter(int step) {
|
||||
if (drafter_.kind != RAD_DRAFT_BLOCK || drafter_.depth <= 0) return RAD_OK;
|
||||
|
||||
const int steps = drafter_.depth;
|
||||
/* The row count is the drafter's (defaulted and checked by declare_drafter). */
|
||||
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
|
||||
std::vector<Scheduler::BlockRow> rows((size_t)cfg_.max_seqs);
|
||||
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
|
||||
rows.data(), (int)rows.size());
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
void* prop = r0.ctx.buf_ptr(drafter_.proposal);
|
||||
if (!prop) {
|
||||
RAD_ERR("drafter '%s': `%s` was declared as the proposal buffer but never planned",
|
||||
drafter_.name, r0.program.buffers[drafter_.proposal].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
|
||||
|
||||
/* Cleared so a query batch that could not be built does not republish the previous step's
|
||||
* proposals. */
|
||||
draft_out_.clear();
|
||||
if (n > 0) {
|
||||
if (const RadBatch* qb = sched_.block_query(step)) {
|
||||
RAD_TRY(block_pass(qb, "query", step));
|
||||
const int64_t n_raw = (int64_t)n * steps;
|
||||
int32_t* const raw = readback_.reserve(n_raw);
|
||||
if (!raw) return RAD_E_NOMEM;
|
||||
RAD_TRY(rad_memcpy_async(raw, prop, n_raw * 4, r0.ctx.stream()));
|
||||
RAD_TRY(rad_stream_sync(r0.ctx.stream()));
|
||||
draft_out_.assign(raw, raw + n_raw);
|
||||
}
|
||||
}
|
||||
sched_.block_end();
|
||||
if (n <= 0 || draft_out_.empty()) return RAD_OK;
|
||||
|
||||
for (int i = 0; i < n; ++i) {
|
||||
/* A request the sampler will not speculate on gets no draft; see finish_serial_drafter. */
|
||||
if (!r0.sampler.allows_speculation(rows[(size_t)i].seq)) continue;
|
||||
sched_.set_draft(rows[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps);
|
||||
}
|
||||
return RAD_OK;
|
||||
bool Engine::block_drafting() const {
|
||||
return drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0;
|
||||
}
|
||||
|
||||
/* The card's driver: both passes behind the step, without waiting. After the trunk's ranks join,
|
||||
* the acceptance runs on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed
|
||||
* end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows.
|
||||
/* Both passes behind the step, without waiting. After the trunk's ranks join, the acceptance runs
|
||||
* on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows.
|
||||
* The query pass's rows are device rows that the card positions at the committed end (ADV_BLOCK),
|
||||
* 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_card_) return RAD_OK;
|
||||
if (!block_drafting()) return RAD_OK;
|
||||
|
||||
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
|
||||
/* 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);
|
||||
|
||||
/* Even when nothing drafts; see run_block_drafter. */
|
||||
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
|
||||
if (n <= 0) return RAD_OK;
|
||||
const RadBatch* qb = sched_.block_query(step);
|
||||
@@ -393,7 +517,7 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
* (a disagreement is a defect and the step is refused, as in finish_serial_drafter), move the
|
||||
* drafter's filled range, and publish each row's proposal from the slots. */
|
||||
int Engine::finish_block_drafter(const StepOut& so) {
|
||||
if (!block_card_) return RAD_OK;
|
||||
if (!block_drafting()) return RAD_OK;
|
||||
if (block_rows_ > 0) {
|
||||
const StepPlan& plan = sched_.plan();
|
||||
for (size_t i = 0; i < plan.e.size(); ++i) {
|
||||
@@ -414,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];
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -124,6 +124,8 @@ int Engine::run_kld() {
|
||||
r->ignore_eos = true;
|
||||
r->sp.temp = 0.0f;
|
||||
r->score = true;
|
||||
/* A loaded control vector scores at the deployment's default (--control-vector on|off). */
|
||||
r->sp.use_control_vector = cvec_default_on();
|
||||
/* --kld-lora-sources: the other documents run as the base, in the same steps. */
|
||||
const bool via = cfg_.kld_lora_sources.empty() ||
|
||||
kld_->source(d).rfind(cfg_.kld_lora_sources, 0) == 0;
|
||||
|
||||
@@ -275,7 +275,11 @@ int Engine::lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>
|
||||
char* da = (char*)P.buffers[lp.a].ptr;
|
||||
char* db = (char*)P.buffers[lp.b].ptr;
|
||||
char* ds = (char*)P.buffers[lp.scale].ptr;
|
||||
if (!da || !db || !ds) { rc = RAD_E_STATE; *err = "a pool has no address"; break; }
|
||||
if (!da || !db || !ds) {
|
||||
rc = RAD_E_STATE;
|
||||
*err = "the adapter pool of '" + lp.weight + "' has no buffer address";
|
||||
break;
|
||||
}
|
||||
da += (int64_t)slot * ab; db += (int64_t)slot * bb; ds += (int64_t)slot * sb;
|
||||
/* A pool this adapter does not touch is zeroed, not left as it was: the bytes are what
|
||||
* the slot's last adapter or the arena held, and a scale of 0 times a NaN is a NaN. */
|
||||
|
||||
+81
-4
@@ -20,6 +20,8 @@
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -47,6 +49,33 @@ int Engine::run_encodes() {
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
const Program& prog = r0.program;
|
||||
|
||||
/* Diagnostic: RADIANCE_DEBUG_MM_BUFFERS names encoder buffers (comma separated, with an
|
||||
* optional `:rows` cap) and each pass writes them, as raw bytes, to `<dump dir>/buf.<name>`.
|
||||
* The pass has finished and been read back, so the copy sees each buffer's last writer; the
|
||||
* tower's per-stage intermediates are tapped inside the pass instead (rad_block_sam.h). */
|
||||
struct DumpBuf { std::string name; int64_t rows; };
|
||||
std::vector<DumpBuf> dump_bufs;
|
||||
static const char* const dump_list = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
|
||||
if (dump_dir && *dump_dir && dump_list) {
|
||||
for (const char* s = dump_list; *s; ) {
|
||||
const char* e = s;
|
||||
while (*e && *e != ',') ++e;
|
||||
std::string want(s, (size_t)(e - s));
|
||||
s = *e ? e + 1 : e;
|
||||
int64_t rows = 0;
|
||||
if (const size_t colon = want.find(':'); colon != std::string::npos) {
|
||||
rows = std::strtoll(want.c_str() + colon + 1, nullptr, 10);
|
||||
want.resize(colon);
|
||||
}
|
||||
if (!want.empty()) dump_bufs.push_back({ want, rows });
|
||||
}
|
||||
}
|
||||
auto answers_to = [](const std::string& name, const std::string& want) {
|
||||
if (name.size() < want.size() ||
|
||||
name.compare(name.size() - want.size(), want.size(), want) != 0) return false;
|
||||
return name.size() == want.size() || name[name.size() - want.size() - 1] == '.';
|
||||
};
|
||||
for (auto& ip : items) {
|
||||
if (ip->encoded) continue;
|
||||
const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder;
|
||||
@@ -74,6 +103,10 @@ int Engine::run_encodes() {
|
||||
|
||||
size_t i = 0;
|
||||
int32_t seg = 0;
|
||||
/* The pass's grid, when the encoder declares that a pass is one geometry
|
||||
* (RadEncoderDecl::one_grid). */
|
||||
const bool one_grid = enc.one_grid != 0;
|
||||
int32_t seg_grid = 0;
|
||||
while (i < mine.size()) {
|
||||
std::vector<BatchBuilder::EncoderPart> parts;
|
||||
int64_t np = 0;
|
||||
@@ -81,16 +114,31 @@ int Engine::run_encodes() {
|
||||
mm::Item& it = *mine[i];
|
||||
const int32_t first = seg;
|
||||
for (; seg < it.n_seg; ++seg) {
|
||||
const int32_t g = it.seg_h(seg);
|
||||
/* The one-output-row view separator (core/mm marks it explicitly) belongs to
|
||||
* the pass of the view before it, so it neither breaks at a "grid change" nor
|
||||
* sets the pass's grid. A square segment that is a real view (a chunked line
|
||||
* of one tile) keeps the ordinary geometry rule below. */
|
||||
const bool sep = it.seg_is_sep(seg);
|
||||
const int64_t seg_p = it.patch_at(seg + 1) - it.patch_at(seg);
|
||||
if (seg_p > max_p) {
|
||||
RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld",
|
||||
(long long)seg_p, (long long)max_p);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (one_grid && !sep && np > 0 && seg_grid != 0 && g != seg_grid) break;
|
||||
if (np + seg_p > max_p) break;
|
||||
np += seg_p;
|
||||
if (!sep) seg_grid = g;
|
||||
}
|
||||
if (seg == first) {
|
||||
/* Nothing of this item packed into the pass: its first segment did not fit
|
||||
* a pass that already has content (a segment larger than the whole pass was
|
||||
* refused above). `seg` addresses a real segment only below `it.n_seg`;
|
||||
* a degenerate zero-segment item leaves seg_grid alone. */
|
||||
if (seg_grid == 0 && seg < it.n_seg) seg_grid = it.seg_h(seg);
|
||||
break;
|
||||
}
|
||||
if (seg == first) break;
|
||||
parts.push_back({ &it, first, seg - first });
|
||||
if (seg == it.n_seg) { ++i; seg = 0; }
|
||||
}
|
||||
@@ -132,6 +180,35 @@ int Engine::run_encodes() {
|
||||
}
|
||||
/* Sync every rank's stream: the next pass rewrites every rank's staging and arena. */
|
||||
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
|
||||
|
||||
if (dump_dir && *dump_dir && !dump_bufs.empty()) {
|
||||
for (const DumpBuf& d : dump_bufs) {
|
||||
for (size_t bi = 1; bi < prog.buffers.size(); ++bi) {
|
||||
const BufferInfo& info = prog.buffers[bi];
|
||||
if (!answers_to(info.name, d.name) || info.bytes <= 0) continue;
|
||||
const int64_t nrow = info.decl.rank >= 1 ? info.decl.shape[0] : 1;
|
||||
const int64_t rowb = nrow > 0 ? info.bytes / nrow : info.bytes;
|
||||
const int64_t rows = d.rows > 0 ? std::min<int64_t>(d.rows, nrow) : nrow;
|
||||
void* ptr = r0.ctx.buf_ptr((rad_buf)bi);
|
||||
std::vector<char> raw((size_t)(rows * rowb));
|
||||
if (!ptr || rad_memcpy_async(raw.data(), ptr, raw.size(),
|
||||
r0.ctx.stream()) < 0)
|
||||
continue;
|
||||
rad_stream_sync(r0.ctx.stream());
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/mm_%016llx%016llx_buf.%s.raw",
|
||||
dump_dir, (unsigned long long)parts.front().item->key_hi,
|
||||
(unsigned long long)parts.front().item->key_lo,
|
||||
info.name.c_str());
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(raw.data(), 1, raw.size(), f);
|
||||
std::fclose(f);
|
||||
RAD_INFO("encoder: wrote %s (%lld rows of %lld bytes)", path,
|
||||
(long long)rows, (long long)rowb);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,9 +220,9 @@ int Engine::run_encodes() {
|
||||
it.pixels.shrink_to_fit();
|
||||
if (dump_dir && *dump_dir) dump(it, ".bf16", it.embd.data(), it.embd.size());
|
||||
}
|
||||
RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(),
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
|
||||
.count());
|
||||
const double ms = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(), ms);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -247,6 +247,9 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
m.n_ff = gi("intermediate_size", gi("moe_intermediate_size", 0));
|
||||
m.n_vocab = gi("vocab_size", 0);
|
||||
m.n_ctx_train = gi("max_position_embeddings", 0);
|
||||
/* The DeepSeek spelling: Unlimited-OCR's decoder is a DeepSeek-V2 MoE and states its expert
|
||||
* count as `n_routed_experts`; a routed config names the count under one of the three and
|
||||
* never under more than one, so the chain is a rename, not a guess. */
|
||||
m.n_expert = gi("num_experts", gi("num_local_experts", gi("n_routed_experts", 0)));
|
||||
m.n_expert_used = gi("num_experts_per_tok", 0);
|
||||
m.n_expert_shared = gi("n_shared_experts", gi("num_shared_experts",
|
||||
@@ -852,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;
|
||||
@@ -895,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() {
|
||||
@@ -2950,7 +3005,6 @@ int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why) {
|
||||
return refuse(RAD_E_FORMAT, "the import rule's form of '" + w->name + "' is malformed");
|
||||
w->enc = e;
|
||||
w->form = f;
|
||||
w->reform = true;
|
||||
w->imported = true;
|
||||
w->trivial = false;
|
||||
w->why = "it is re-expressed by an import rule";
|
||||
|
||||
@@ -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>
|
||||
@@ -212,6 +213,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();
|
||||
|
||||
@@ -220,6 +222,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 */
|
||||
@@ -287,10 +290,9 @@ struct CkptWeight {
|
||||
* values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule
|
||||
* stores it. */
|
||||
std::vector<float> derived;
|
||||
/* An `import` rule's form, applied by ckpt_plane_rows (also `imported`). `rounded` counts the
|
||||
* shipped scales `form.scale` does not hold exactly and `max_rel` is their largest relative
|
||||
* change, both found by ckpt_import_form. */
|
||||
bool reform = false;
|
||||
/* An `import` rule's form, applied by ckpt_plane_rows (the weight is then `imported`).
|
||||
* `rounded` counts the shipped scales `form.scale` does not hold exactly and `max_rel` is their
|
||||
* largest relative change, both found by ckpt_import_form. */
|
||||
ImportForm form{};
|
||||
int64_t rounded = 0;
|
||||
double max_rel = 0;
|
||||
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
|
||||
+207
-45
@@ -64,12 +64,25 @@ namespace {
|
||||
|
||||
constexpr int64_t kAlign = 256;
|
||||
|
||||
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
|
||||
|
||||
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;
|
||||
@@ -77,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;
|
||||
}
|
||||
|
||||
@@ -110,12 +126,22 @@ 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) {
|
||||
bytes[r][0] = off;
|
||||
bytes[r][1] = want[r];
|
||||
off = align_up(off + want[r]);
|
||||
off = align_up(off + want[r], kAlign);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
@@ -123,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);
|
||||
}
|
||||
@@ -136,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;
|
||||
@@ -154,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;
|
||||
@@ -193,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;
|
||||
@@ -224,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)
|
||||
@@ -236,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 "
|
||||
@@ -309,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;
|
||||
@@ -390,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;
|
||||
@@ -412,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);
|
||||
@@ -434,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;
|
||||
@@ -517,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);
|
||||
@@ -530,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) {
|
||||
@@ -549,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) {
|
||||
@@ -577,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);
|
||||
@@ -586,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);
|
||||
@@ -599,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;
|
||||
@@ -618,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;
|
||||
@@ -630,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;
|
||||
@@ -637,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
@@ -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 */
|
||||
|
||||
+10
-3
@@ -13,8 +13,6 @@ namespace {
|
||||
|
||||
constexpr int64_t kAlign = 256;
|
||||
|
||||
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
|
||||
|
||||
/* Upper bound on a reference picture's latent tokens: its area plus slack for rounding its sides
|
||||
* to the size multiple. */
|
||||
int64_t ref_tokens_max(const RadGeneratorDecl& d) {
|
||||
@@ -97,7 +95,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
|
||||
for (int r = 0; r < n; ++r) {
|
||||
bytes[r][0] = off;
|
||||
bytes[r][1] = want[r][1];
|
||||
off = align_up(off + want[r][1]);
|
||||
off = align_up(off + want[r][1], kAlign);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
@@ -121,6 +119,12 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
|
||||
kv_ = kv;
|
||||
ranks_ = ranks;
|
||||
table_ = DiscreteTable{};
|
||||
if (decl_.cond_opts & ~(uint32_t)RAD_GEN_COND_REBALANCE) {
|
||||
RAD_ERR("image generator: '%s' declares conditioning options 0x%x, and this engine knows "
|
||||
"only RAD_GEN_COND_REBALANCE (0x%x)", decl_.name ? decl_.name : "",
|
||||
(unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (discrete()) {
|
||||
std::string why;
|
||||
if (discrete_table(decl_, &table_, &why) < 0) {
|
||||
@@ -258,6 +262,8 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
|
||||
!(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 ||
|
||||
r->scheduler >= RAD_GEN_SCHED_COUNT))
|
||||
return no("the sampler or scheduler is not one this model serves");
|
||||
if ((uint32_t)r->cond_opts & ~decl_.cond_opts)
|
||||
return no("a conditioning option (rebalance) this model does not serve");
|
||||
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (closed_) {
|
||||
@@ -530,6 +536,7 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
|
||||
G.size_px = nullptr;
|
||||
G.entry_h = nullptr;
|
||||
G.tokens_h = nullptr;
|
||||
G.cond_opts = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -125,7 +125,6 @@ private:
|
||||
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE,
|
||||
R_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N };
|
||||
|
||||
int layout_regions();
|
||||
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 {
|
||||
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
|
||||
|
||||
@@ -195,7 +195,6 @@ constexpr int64_t kAlign = 256;
|
||||
* accept up to 4096. */
|
||||
constexpr int64_t kSegCap = 64;
|
||||
|
||||
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
|
||||
|
||||
/* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the
|
||||
* allocation and the VRAM budget. `ep` and `pd` are the conditioning encoder's pass bound and
|
||||
@@ -239,7 +238,7 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
|
||||
for (int r = 0; r < n; ++r) {
|
||||
bytes[r][0] = off;
|
||||
bytes[r][1] = want[r];
|
||||
off = align_up(off + want[r]);
|
||||
off = align_up(off + want[r], kAlign);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
+85
-3
@@ -22,6 +22,13 @@ void take(const char* what, const char* src, double v, double lo, double hi, boo
|
||||
src, what, v, lo_open ? "(" : "[", lo, hi);
|
||||
}
|
||||
|
||||
/* An integer field (a token count), same contract. */
|
||||
void take_i(const char* what, const char* src, int64_t v, int64_t lo, int64_t hi, int* dst) {
|
||||
if (v >= lo && v <= hi) { *dst = (int)v; return; }
|
||||
RAD_WARN("%s states %s %lld, which is outside [%lld, %lld]; ignoring it",
|
||||
src, what, (long long)v, (long long)lo, (long long)hi);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
SamplingParams GenSampling::onto(SamplingParams base) const {
|
||||
@@ -29,16 +36,36 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
|
||||
if (top_p >= 0.0f) base.top_p = top_p;
|
||||
if (min_p >= 0.0f) base.min_p = min_p;
|
||||
if (top_k >= 0) base.top_k = top_k;
|
||||
if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n;
|
||||
if (ngram_window >= 0) base.ngram_window = ngram_window;
|
||||
if (!ngram_whitelist.empty()) base.ngram_whitelist = ngram_whitelist;
|
||||
return base;
|
||||
}
|
||||
|
||||
/* The one-line statement of a served sampling configuration. The wording is pinned by
|
||||
* gen_config_test.cpp (gen_config_reads_the_ngram_ban) -- change it there in the same change.
|
||||
* It spells the values out for a log reader; `onto` fills the fields from defaults. The two
|
||||
* share values, not logic, and the duplication of the ban clause is a string, not a rule. */
|
||||
std::string GenSampling::describe(const SamplingParams& sp) {
|
||||
char buf[200];
|
||||
char buf[320];
|
||||
std::snprintf(buf, sizeof buf, "temperature %.2f, top_k %d%s, top_p %.2f, min_p %.2f",
|
||||
(double)sp.temp, sp.top_k,
|
||||
sp.top_k == 0 ? " (the 1024 most likely tokens, the sampler's candidate width)" : "",
|
||||
(double)sp.top_p, (double)sp.min_p);
|
||||
return buf;
|
||||
std::string s(buf);
|
||||
if (sp.ngram_ban_n > 0) {
|
||||
char ban[96];
|
||||
if (sp.ngram_window > 0)
|
||||
std::snprintf(ban, sizeof ban, ", ngram ban n %d over the last %d tokens",
|
||||
sp.ngram_ban_n, sp.ngram_window);
|
||||
else
|
||||
std::snprintf(ban, sizeof ban, ", ngram ban n %d over the whole sequence",
|
||||
sp.ngram_ban_n);
|
||||
s += ban;
|
||||
if (!sp.ngram_whitelist.empty())
|
||||
s += ", whitelist " + std::to_string(sp.ngram_whitelist.size()) + " ids";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, const std::string& src,
|
||||
@@ -88,6 +115,47 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
|
||||
if (v >= -1) out->top_k = (int)(v < 0 ? 0 : v);
|
||||
else RAD_WARN("%s states top_k %lld, which is not a count; ignoring it", src, (long long)v);
|
||||
}
|
||||
|
||||
/* The windowed no-repeat-n-gram ban. Its checkpoint name in transformers is
|
||||
* no_repeat_ngram_size / no_repeat_ngram_window_size (Unlimited-OCR ships 35 over the last
|
||||
* 128); this sampler's own names are taken too. The reference's negative window means the
|
||||
* whole sequence, which this sampler spells 0. */
|
||||
it = j.find("no_repeat_ngram_size");
|
||||
if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_ban_n");
|
||||
if (it != j.end() && it->is_number_integer())
|
||||
take_i("no_repeat_ngram_size", src, it->get<int64_t>(), 0, 256, &out->ngram_ban_n);
|
||||
|
||||
it = j.find("no_repeat_ngram_window_size");
|
||||
if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_window");
|
||||
if (it != j.end() && it->is_number_integer()) {
|
||||
const int64_t v = it->get<int64_t>();
|
||||
take_i("no_repeat_ngram_window_size", src, v < 0 ? 0 : v, 0, 131072, &out->ngram_window);
|
||||
}
|
||||
|
||||
/* The ban's whitelist, a JSON array of token ids (the reference's whitelist_token_ids).
|
||||
* Values are warned about and dropped, like every other field here: an id is a vocabulary
|
||||
* coordinate, so a negative one is not a value at all. */
|
||||
it = j.find("no_repeat_ngram_whitelist");
|
||||
if (it != j.end() && !it->is_array()) {
|
||||
/* The legacy key is only a problem when nothing rescues it: a config that states a bad
|
||||
* reference name beside a good sampler-spelled one reads the good one, silently. */
|
||||
const auto own = j.find("ngram_whitelist");
|
||||
if (own == j.end() || !own->is_array())
|
||||
RAD_WARN("%s states a no_repeat_ngram_whitelist that is not an array; ignoring it",
|
||||
src);
|
||||
it = own;
|
||||
}
|
||||
if (it != j.end() && it->is_array()) {
|
||||
for (const auto& v : *it) {
|
||||
const int64_t id = v.is_number_integer() ? v.get<int64_t>() : -1;
|
||||
if (id < 0 || id > INT32_MAX) {
|
||||
RAD_WARN("%s states a no_repeat_ngram_whitelist entry outside [0, %d]; ignoring it",
|
||||
src, INT32_MAX);
|
||||
continue;
|
||||
}
|
||||
out->ngram_whitelist.push_back((int)id);
|
||||
}
|
||||
}
|
||||
return out->any();
|
||||
}
|
||||
|
||||
@@ -105,7 +173,9 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
/* Rebuilt as JSON and passed to gen_sampling_parse, so container metadata and the original
|
||||
* file share one set of range checks and one reading of `do_sample`. */
|
||||
nlohmann::json j = nlohmann::json::object();
|
||||
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k" };
|
||||
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k",
|
||||
"no_repeat_ngram_size", "no_repeat_ngram_window_size",
|
||||
"no_repeat_ngram_whitelist" };
|
||||
for (const char* k : kFields) {
|
||||
const char* v = get(k);
|
||||
if (!v || !*v) continue;
|
||||
@@ -114,6 +184,17 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
j[k] = (std::strcmp(v, "0") != 0);
|
||||
continue;
|
||||
}
|
||||
if (std::strcmp(k, "no_repeat_ngram_whitelist") == 0) {
|
||||
/* Not a number: the container's metadata is string-valued, and the whitelist is a
|
||||
* JSON array spelled as JSON text. */
|
||||
try {
|
||||
j[k] = nlohmann::json::parse(v);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_WARN("the container states generation.%s as \"%s\", which is not a JSON "
|
||||
"array of ids (%s); ignoring it", k, v, e.what());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
char* end = nullptr;
|
||||
const double d = std::strtod(v, &end);
|
||||
if (end == v) {
|
||||
@@ -122,6 +203,7 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
continue;
|
||||
}
|
||||
if (std::strcmp(k, "top_k") == 0) j[k] = (int64_t)d;
|
||||
else if (std::strncmp(k, "no_repeat_ngram", 15) == 0) j[k] = (int64_t)d;
|
||||
else j[k] = d;
|
||||
}
|
||||
if (j.empty()) return false;
|
||||
|
||||
+16
-3
@@ -20,17 +20,30 @@
|
||||
namespace rad {
|
||||
|
||||
/* One config's sampler fields. -1 means "not stated", since 0 is a legal value of each (greedy
|
||||
* temperature, top_k off, min_p off). */
|
||||
* temperature, top_k off, min_p off, n-gram ban off). */
|
||||
struct GenSampling {
|
||||
float temp = -1.0f, top_p = -1.0f, min_p = -1.0f;
|
||||
int top_k = -1;
|
||||
/* The windowed no-repeat-n-gram ban (transformers' no_repeat_ngram_size /
|
||||
* no_repeat_ngram_window_size; Unlimited-OCR ships 35 over the last 128). `ngram_window` is
|
||||
* normalized to 0, this sampler's "the whole sequence", when the config states it negative. */
|
||||
int ngram_ban_n = -1, ngram_window = -1;
|
||||
/* The ban's whitelist: token ids the ban must never ban (the reference processor's
|
||||
* `whitelist_token_ids`, removed from the banned set before the -inf writes). Transformers
|
||||
* has no field for it; a container states it as `generation.no_repeat_ngram_whitelist`, a
|
||||
* JSON array of ids. Empty means not stated. */
|
||||
std::vector<int32_t> ngram_whitelist;
|
||||
|
||||
bool any() const { return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0; }
|
||||
bool any() const {
|
||||
return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 ||
|
||||
ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty();
|
||||
}
|
||||
|
||||
/* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */
|
||||
SamplingParams onto(SamplingParams base) const;
|
||||
|
||||
/* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00", for the startup log line. */
|
||||
/* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00, ngram ban n 35 over the last 128
|
||||
* tokens", for the startup log line (the last part only when a ban is on). */
|
||||
static std::string describe(const SamplingParams& sp);
|
||||
};
|
||||
|
||||
|
||||
+2
-7
@@ -39,11 +39,6 @@ bool repo_part(const std::string& p) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& s, const char* suf) {
|
||||
const size_t n = std::strlen(suf);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, suf) == 0;
|
||||
}
|
||||
|
||||
/* <exe>/../libexec/radiance/hfget.sh, which is where the install puts it and where the build
|
||||
* copies it. */
|
||||
std::string hfget_path() {
|
||||
@@ -85,7 +80,7 @@ bool hf_repo_id(const std::string& s) {
|
||||
const std::string owner = s.substr(0, slash), name = s.substr(slash + 1);
|
||||
if (!repo_part(owner) || !repo_part(name)) return false;
|
||||
for (const char* suf : { ".rad", ".safetensors", ".gguf", ".json" })
|
||||
if (ends_with(name, suf)) return false;
|
||||
if (name.ends_with(suf)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -102,7 +97,7 @@ std::string hf_served_path(const std::string& dir, std::string* why) {
|
||||
std::error_code ec;
|
||||
for (const fs::directory_entry& e : fs::directory_iterator(dir, ec)) {
|
||||
std::error_code fe;
|
||||
if (e.is_regular_file(fe) && ends_with(e.path().filename().string(), ".rad"))
|
||||
if (e.is_regular_file(fe) && e.path().filename().string().ends_with(".rad"))
|
||||
rad.push_back(e.path().filename().string());
|
||||
}
|
||||
if (ec) {
|
||||
|
||||
@@ -36,11 +36,6 @@ int fail(std::string* err, int code, const std::string& m) {
|
||||
return code;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& s, const char* p) {
|
||||
const size_t n = std::strlen(p);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, p) == 0;
|
||||
}
|
||||
|
||||
std::string shape_str(const std::vector<int64_t>& s) {
|
||||
std::string r = "[";
|
||||
for (size_t i = 0; i < s.size(); ++i) r += (i ? ", " : "") + std::to_string(s[i]);
|
||||
@@ -290,7 +285,7 @@ int AdapterFile::open(const std::string& path, std::string* err) {
|
||||
for (const StTensor& t : st_.tensors()) {
|
||||
const Suffix* hit = nullptr;
|
||||
for (const Suffix& s : kSuffix)
|
||||
if (ends_with(t.name, s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s;
|
||||
if (t.name.ends_with(s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s;
|
||||
if (!hit) {
|
||||
skipped_.push_back({ t.name, "not an adapter tensor" });
|
||||
continue;
|
||||
@@ -610,7 +605,7 @@ std::regex pattern(const std::string& from, bool kohya) {
|
||||
}
|
||||
|
||||
std::string module_of(const std::string& src) {
|
||||
return ends_with(src, ".weight") ? src.substr(0, src.size() - 7) : std::string();
|
||||
return src.ends_with(".weight") ? src.substr(0, src.size() - 7) : std::string();
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
+7
-16
@@ -41,15 +41,6 @@ int fail(std::string* err, int code, const std::string& m) {
|
||||
return code;
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const char* p) {
|
||||
const size_t n = std::strlen(p);
|
||||
return s.size() >= n && s.compare(0, n, p) == 0;
|
||||
}
|
||||
bool ends_with(const std::string& s, const char* p) {
|
||||
const size_t n = std::strlen(p);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, p) == 0;
|
||||
}
|
||||
|
||||
std::vector<std::string> split_dots(const std::string& s) {
|
||||
std::vector<std::string> v;
|
||||
size_t at = 0;
|
||||
@@ -64,7 +55,7 @@ std::vector<std::string> split_dots(const std::string& s) {
|
||||
|
||||
/* `<module>.weight` -> module and its leaf; "" when the source is not a `.weight` tensor. */
|
||||
std::string module_of(const std::string& src, std::string* leaf) {
|
||||
if (!ends_with(src, ".weight")) return "";
|
||||
if (!src.ends_with(".weight")) return "";
|
||||
std::string m = src.substr(0, src.size() - 7);
|
||||
if (m.empty()) return "";
|
||||
const size_t d = m.rfind('.');
|
||||
@@ -100,7 +91,7 @@ const char* excluded_weight(const Program& prog, const WeightInfo& w) {
|
||||
return "a drafter / MTP layer (layer group at or above meta.n_layers)";
|
||||
static const char* const kScopes[] = { "draft.", "vision.", "audio.", "mtp." };
|
||||
for (const char* s : kScopes)
|
||||
if (starts_with(w.name, s)) return "a non-trunk builder scope";
|
||||
if (w.name.starts_with(s)) return "a non-trunk builder scope";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -743,9 +734,9 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
|
||||
std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module) {
|
||||
const std::string want[3] = {
|
||||
module,
|
||||
starts_with(module, "model.") && !starts_with(module, "model.language_model.")
|
||||
module.starts_with("model.") && !module.starts_with("model.language_model.")
|
||||
? "model.language_model." + module.substr(6) : "",
|
||||
starts_with(module, "model.language_model.") ? "model." + module.substr(21) : "" };
|
||||
module.starts_with("model.language_model.") ? "model." + module.substr(21) : "" };
|
||||
std::string first;
|
||||
bool any = false;
|
||||
for (const RadNameMap& m : prog.name_map) {
|
||||
@@ -939,7 +930,7 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
|
||||
if (!std::regex_match(k, m, key_re)) {
|
||||
std::string why = "is not a linear LoRA A/B tensor";
|
||||
if (k.find("lora_embedding_") != std::string::npos) why = "is an embedding LoRA tensor";
|
||||
else if (ends_with(k, ".bias")) why = "is a trained bias";
|
||||
else if (k.ends_with(".bias")) why = "is a trained bias";
|
||||
else if (k.find("modules_to_save") != std::string::npos) why = "is a modules_to_save copy";
|
||||
else if (k.find("lora_magnitude_vector") != std::string::npos) why = "is a DoRA magnitude";
|
||||
return fail(err, RAD_E_UNSUPPORTED, st_path + ": tensor " + k + " " + why +
|
||||
@@ -1034,9 +1025,9 @@ int pack_modules(const std::vector<Site>& sites, int max_rank,
|
||||
for (auto& kv : mods) {
|
||||
const AdModule& am = kv.second;
|
||||
std::vector<std::string> cand{ am.name };
|
||||
if (starts_with(am.name, "model.") && !starts_with(am.name, "model.language_model."))
|
||||
if (am.name.starts_with("model.") && !am.name.starts_with("model.language_model."))
|
||||
cand.push_back("model.language_model." + am.name.substr(6));
|
||||
if (starts_with(am.name, "model.language_model."))
|
||||
if (am.name.starts_with("model.language_model."))
|
||||
cand.push_back("model." + am.name.substr(21));
|
||||
std::vector<std::string> hit;
|
||||
for (const std::string& c : cand) if (where.count(c)) hit.push_back(c);
|
||||
|
||||
+261
-16
@@ -2,6 +2,7 @@
|
||||
#include "mem/kv.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
@@ -76,6 +77,7 @@ static const char* kv_kind_name(int k) {
|
||||
case RAD_KV_WINDOW: return "window";
|
||||
case RAD_KV_LINEAR: return "linear";
|
||||
case RAD_KV_CONV: return "conv";
|
||||
case RAD_KV_RING: return "ring";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
@@ -126,7 +128,10 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
KVGroupPlan p;
|
||||
p.index = (int32_t)i;
|
||||
p.name = g.name.empty() ? fmt("kv%zu", i) : g.name;
|
||||
p.kind = g.decl.kind;
|
||||
/* R-SWA: RAD_KV_RING is a window group whose floor is per sequence (declare_runtime_window
|
||||
* / SeqWindow), so it plans as a RAD_KV_WINDOW group with `runtime_win` set below. No
|
||||
* other plan-path code has to know the kind. */
|
||||
p.kind = g.decl.kind == RAD_KV_RING ? RAD_KV_WINDOW : g.decl.kind;
|
||||
p.n_layers = (int64_t)g.layers.size();
|
||||
|
||||
if (p.n_layers <= 0) {
|
||||
@@ -161,7 +166,9 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
}
|
||||
if (p.kind == RAD_KV_WINDOW) {
|
||||
if (g.decl.window <= 0) {
|
||||
RAD_ERR("KV group '%s': RAD_KV_WINDOW with window 0", p.name.c_str());
|
||||
RAD_ERR("KV group '%s': %s with window 0", p.name.c_str(),
|
||||
g.decl.kind == RAD_KV_RING ? "RAD_KV_RING (the ring's W)"
|
||||
: "RAD_KV_WINDOW");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* +1 because a window that is not block-aligned straddles one extra block. */
|
||||
@@ -233,6 +240,28 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
}
|
||||
bundling_ = compare_bundling(bundles);
|
||||
|
||||
/* R-SWA: a declared runtime window turns the group's plan over to per-sequence windows (see
|
||||
* declare_runtime_window). Applied after every declaration above, so a fixed-window group's
|
||||
* plan is exactly what it was. */
|
||||
for (auto& p : plans_) apply_runtime_window(p);
|
||||
/* A RAD_KV_RING group carries a runtime window by its kind, whether or not the caller had a
|
||||
* manager to declare it on first (the engine's sizing probes declare it, but plan_groups must
|
||||
* not depend on that). `window` is the ring's W. */
|
||||
for (size_t i = 1; i < plans_.size(); ++i) {
|
||||
KVGroupPlan& p = plans_[i];
|
||||
if (groups[i].decl.kind != RAD_KV_RING || p.runtime_win) continue;
|
||||
p.runtime_win = true;
|
||||
p.runtime_tokens = groups[i].decl.window;
|
||||
p.win_snap = false;
|
||||
}
|
||||
for (const auto& [g, w] : runtime_decl_) {
|
||||
if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].runtime_win) {
|
||||
RAD_ERR("declare_runtime_window(%d): the group is not a RAD_KV_WINDOW or RAD_KV_RING "
|
||||
"group in this program (a runtime window needs a windowed group)", (int)g);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- fixed costs first: they are not per-token ---- */
|
||||
checkpoint_bytes_ = 0;
|
||||
window_ck_bytes_ = 0;
|
||||
@@ -243,7 +272,7 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
for (size_t i = 1; i < plans_.size(); ++i) {
|
||||
KVGroupPlan& p = plans_[i];
|
||||
p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
|
||||
!groups[i].drafter;
|
||||
!p.runtime_win && !groups[i].drafter;
|
||||
if (p.win_snap && !p.zero && p.n_layers > 0)
|
||||
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
|
||||
}
|
||||
@@ -257,26 +286,107 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT);
|
||||
/* And one unit per paged group, whose size need not be a multiple of the alignment. */
|
||||
for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT;
|
||||
/* A runtime window's ring is per sequence and on top of the context the split sizes: one
|
||||
* ring a sequence, carved as a fixed cost. Its reference is the context itself, which the
|
||||
* split already covers (the group is not capped at window_blocks). */
|
||||
for (const auto& p : plans_)
|
||||
if (p.runtime_win && !p.zero)
|
||||
fixed += align_up(max_seqs_ * p.ring_blocks_max() * p.bytes_per_block, RAD_ALIGN_UNIT);
|
||||
|
||||
fixed_ = fixed;
|
||||
ckpts_ = budget_ckpts;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Windowed groups are capped at window_pool_cap, as in carve(). */
|
||||
/* Windowed groups are capped at window_pool_cap, as in carve(). A runtime-window group is not:
|
||||
* its blocks are the reference (one context a sequence, as a FULL group) plus the ring its fixed
|
||||
* costs already carry. */
|
||||
int64_t KVManager::ceiling(int64_t ctx) const {
|
||||
if (ctx <= 0) return 0;
|
||||
int64_t need = fixed_;
|
||||
for (const auto& p : plans_) {
|
||||
if (!p.paged() || p.block_size <= 0) continue;
|
||||
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
|
||||
if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0)
|
||||
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0)
|
||||
blocks = std::min(blocks, window_pool_cap(p));
|
||||
need += blocks * p.bytes_per_block;
|
||||
}
|
||||
return need;
|
||||
}
|
||||
|
||||
/* Moves a WINDOW group's plan to per-sequence runtime windows (declare_runtime_window). Returns
|
||||
* false for any other group, so plan_groups() can apply it to every plan unconditionally. */
|
||||
bool KVManager::apply_runtime_window(KVGroupPlan& p) const {
|
||||
auto it = runtime_decl_.find(p.index);
|
||||
if (it == runtime_decl_.end() || p.kind != RAD_KV_WINDOW || p.runtime_win) return false;
|
||||
p.runtime_win = true;
|
||||
p.runtime_tokens = it->second;
|
||||
/* The window a sequence may inherit (a fixed-window cap) is no longer the bound, and the
|
||||
* declare-time window is not the sequence's own, so nothing here is snapshot-able. */
|
||||
p.win_snap = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
|
||||
if (g <= 0 || window_tokens <= 0) {
|
||||
RAD_ERR("declare_runtime_window: group %d with a window of %lld (a runtime window needs a "
|
||||
"real group and a positive W)", (int)g, (long long)window_tokens);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const KVGroupPlan* p = plan(g);
|
||||
if (p && p->kind != RAD_KV_WINDOW) {
|
||||
RAD_ERR("group '%s' is not RAD_KV_WINDOW or RAD_KV_RING, so it cannot carry a runtime "
|
||||
"window", p->name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (p && p->runtime_win && p->runtime_tokens != window_tokens) {
|
||||
/* A RAD_KV_RING group's W is its declaration's `window`, and one already planned for
|
||||
* another W has its ring in the fixed costs. */
|
||||
RAD_ERR("declare_runtime_window(%d): group '%s' already carries a runtime window of %lld "
|
||||
"tokens, and its ring is sized for that", (int)g, p->name.c_str(),
|
||||
(long long)p->runtime_tokens);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (configured_) {
|
||||
RAD_ERR("declare_runtime_window(%d) after the carve: the group's blocks and fixed costs "
|
||||
"are already sized for a different window", (int)g);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
runtime_decl_[g] = window_tokens;
|
||||
/* A plan built before the declaration (the engine's probes, or plan_groups() then declare)
|
||||
* is updated in place; the next plan_groups() picks the declaration up on its own.
|
||||
*
|
||||
* A plan set shorter than `g` returns RAD_E_INVAL below with this store kept: deliberate.
|
||||
* The declaration is the caller's standing intent (it survives forget(), whose vectors are
|
||||
* emptied together and are not this map), and the short plan set is the probe ordering the
|
||||
* declaration exists for -- the next plan_groups() applies it to a plan that has the group. */
|
||||
if (!plans_.empty()) {
|
||||
if (g >= (int32_t)plans_.size()) return RAD_E_INVAL;
|
||||
KVGroupPlan& q = plans_[(size_t)g];
|
||||
/* Whether the plan counted this group's window snapshot section (plan_groups' rule). */
|
||||
const bool counted = q.win_snap && !q.zero && q.n_layers > 0;
|
||||
if (!apply_runtime_window(q)) return RAD_OK; /* already applied */
|
||||
/* The cost this declaration adds, against the plan as published: the ring is one a
|
||||
* sequence, and the group gives up its window snapshot section. */
|
||||
fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT);
|
||||
if (counted) {
|
||||
const int64_t was = q.window_blocks * q.bytes_per_block;
|
||||
/* The plan counted this group's snapshot section, so both totals carry `was`.
|
||||
* Saturating hides an accounting bug; surface it in debug builds. */
|
||||
assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was &&
|
||||
"runtime window: snapshot byte totals below the section being removed");
|
||||
window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0;
|
||||
checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t KVManager::runtime_window_tokens(int32_t g) const {
|
||||
const KVGroupPlan* p = plan(g);
|
||||
return p && p->runtime_win ? p->runtime_tokens : 0;
|
||||
}
|
||||
|
||||
/* The vectors parallel to plans_ are filled at different points of the carve, so a partial carve
|
||||
* would leave plans_ passing bounds checks (reserve_block checks plans_, then reads free_usable_)
|
||||
* over empty block state. On failure forget() empties both, so every entry point refuses
|
||||
@@ -329,11 +439,11 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
if (tokens_cap_ > 0 && tokens > tokens_cap_) tokens = tokens_cap_;
|
||||
|
||||
/* A windowed group cannot address past its pool cap; cap it and give the bytes back to
|
||||
* the others. */
|
||||
* the others. A runtime-window group's cap is the context plus its ring (a fixed cost). */
|
||||
int32_t capped = -1;
|
||||
for (int32_t i : open) {
|
||||
const auto& p = plans_[i];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
if (p.kind != RAD_KV_WINDOW || p.runtime_win) continue;
|
||||
if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; }
|
||||
}
|
||||
if (capped < 0) break;
|
||||
@@ -370,7 +480,8 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p);
|
||||
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && b > window_pool_cap(p))
|
||||
return window_pool_cap(p);
|
||||
return b;
|
||||
}
|
||||
|
||||
@@ -509,20 +620,31 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
|
||||
configured_ = true;
|
||||
report_ = bundling_.report();
|
||||
/* A runtime-window group reads as "ring": its window is the sequence's own, not the plan's. */
|
||||
auto kind_of = [](const KVGroupPlan& p) {
|
||||
return p.runtime_win ? "ring" : kv_kind_name(p.kind);
|
||||
};
|
||||
for (const auto& p : plans_) {
|
||||
if (p.paged())
|
||||
report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s "
|
||||
"%7lld blocks = %9s (%lld tokens)\n",
|
||||
p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers,
|
||||
p.name.c_str(), kind_of(p), (long long)p.n_layers,
|
||||
(long long)p.block_size, humanb(p.bytes_per_block).c_str(),
|
||||
(long long)p.n_blocks, humanb(p.pool_bytes).c_str(),
|
||||
(long long)(p.n_blocks * p.block_size));
|
||||
else
|
||||
report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n",
|
||||
p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers,
|
||||
p.name.c_str(), kind_of(p), (long long)p.n_layers,
|
||||
humanb(p.bytes_per_state).c_str(),
|
||||
(long long)p.n_states, humanb(p.pool_bytes).c_str());
|
||||
}
|
||||
for (const auto& p : plans_) {
|
||||
if (!p.runtime_win) continue;
|
||||
report_ += fmt(" %-14s runtime window W=%lld: a sequence keeps its reference and a ring "
|
||||
"of at most %lld block(s), rewritten in place\n",
|
||||
p.name.c_str(), (long long)p.runtime_tokens,
|
||||
(long long)p.ring_blocks_max());
|
||||
}
|
||||
/* The pool's address range, so a GPU fault address can be placed in the carve. */
|
||||
report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n",
|
||||
pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(),
|
||||
@@ -805,7 +927,17 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const {
|
||||
const KVGroupPlan* p = plan(g);
|
||||
if (!p || !p->paged() || n_tokens <= 0) return 0;
|
||||
int64_t n = ceil_div(n_tokens, p->block_size);
|
||||
if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p));
|
||||
if (p->kind == RAD_KV_WINDOW) {
|
||||
if (p->runtime_win) {
|
||||
/* The reference's blocks up to n, plus one ring. Without a sequence the floor is
|
||||
* unknown, so the whole context is the bound on the reference. */
|
||||
const int64_t ring = p->ring_blocks_max();
|
||||
const int64_t ctx = max_ctx_ > 0 ? max_ctx_ : n_tokens;
|
||||
n = std::min(n, ceil_div(ctx, p->block_size)) + ring;
|
||||
} else {
|
||||
n = std::min(n, window_seq_cap(*p));
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -836,6 +968,7 @@ int KVManager::add_sequence(uint64_t id) {
|
||||
s.id = id;
|
||||
s.blocks.resize(plans_.size());
|
||||
s.first_block_pos.assign(plans_.size(), 0);
|
||||
s.win.resize(plans_.size());
|
||||
s.state.assign(plans_.size(), -1);
|
||||
s.dirty_from.assign(plans_.size(), 0);
|
||||
seqs_.emplace(id, std::move(s));
|
||||
@@ -853,6 +986,9 @@ int KVManager::preempt(uint64_t id) {
|
||||
for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b);
|
||||
s->blocks[g].clear();
|
||||
s->first_block_pos[g] = 0;
|
||||
/* The runtime window goes with the blocks: re-admission re-arms it at the prompt end
|
||||
* (the scheduler's admission path calls set_window again before the KV grows). */
|
||||
s->win[g] = SeqWindow{};
|
||||
s->dirty_from[g] = 0;
|
||||
/* The recurrent state goes too (see preempt in kv.h, spec §7.1). */
|
||||
if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; }
|
||||
@@ -870,6 +1006,12 @@ int KVManager::rollback(uint64_t id, int64_t n_tokens) {
|
||||
if (n_tokens < 0) return RAD_E_INVAL;
|
||||
/* Nothing to free; RAD_OK so "every draft accepted" needs no special path in the caller. */
|
||||
if (n_tokens >= s->n_tokens) return RAD_OK;
|
||||
/* A runtime-windowed sequence unwinds nothing: the ring's slots are reused once it is full,
|
||||
* so the slots a rejected verify wrote may already hold newer keys. The scheduler gates
|
||||
* drafting on has_runtime_window, so this refuses rather than corrupts, and only a caller
|
||||
* that drafts beside a runtime window can reach it. */
|
||||
for (const SeqWindow& w : s->win)
|
||||
if (w.set) return RAD_E_UNSUPPORTED;
|
||||
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const auto& p = plans_[g];
|
||||
@@ -899,6 +1041,80 @@ int64_t KVManager::first_block_pos(uint64_t id, int32_t g) const {
|
||||
return s->first_block_pos[(size_t)g];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the runtime window */
|
||||
|
||||
int KVManager::set_window(uint64_t id, int64_t visible_lo, int64_t window_tokens) {
|
||||
if (!configured_) return RAD_E_STATE;
|
||||
Seq* s = find(id);
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
if (visible_lo < 0 || window_tokens <= 0) return RAD_E_INVAL;
|
||||
/* The reference is written linearly, so the floor cannot be behind KV the sequence already
|
||||
* holds: rebasing would have to move blocks the ring has not been shaped for. */
|
||||
if (visible_lo < s->n_tokens) {
|
||||
RAD_ERR("sequence %llu: runtime window floor %lld is behind its %lld held tokens",
|
||||
(unsigned long long)id, (long long)visible_lo, (long long)s->n_tokens);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
bool any = false;
|
||||
/* With a declared runtime window in the program, arm exactly the declared groups: a plain
|
||||
* fixed-window group beside them is carved for its fixed window, and arming it silently
|
||||
* converts it. With none declared this is the caller-sizes-the-pool path kv.h states, and
|
||||
* every windowed group arms as before. */
|
||||
bool declared = false;
|
||||
for (const KVGroupPlan& p : plans_)
|
||||
if (p.kind == RAD_KV_WINDOW && p.runtime_win) declared = true;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
if (declared && !p.runtime_win) {
|
||||
RAD_ERR("sequence %llu: set_window meets fixed-window group '%s' beside a declared "
|
||||
"runtime window; its pool is carved for its fixed window and the mix is not "
|
||||
"supported", (unsigned long long)id, p.name.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
SeqWindow w;
|
||||
w.set = true;
|
||||
w.window = window_tokens;
|
||||
w.visible_lo = visible_lo;
|
||||
/* Whole blocks: the ring starts at the first boundary at or after the floor, and the
|
||||
* tokens in [visible_lo, ring_pos) stay in the reference's last block (SeqWindow). The
|
||||
* ring itself must span all of W: the frozen tokens are the oldest of the tail, so a
|
||||
* smaller ring would lose the last W - span positions. */
|
||||
w.ring_pos = ceil_div(visible_lo, p.block_size) * p.block_size;
|
||||
w.ring_blocks = ceil_div(window_tokens, p.block_size);
|
||||
if (w.ring_blocks < 1) w.ring_blocks = 1; /* the ring always has somewhere to write */
|
||||
/* What the sequence can hold: the reference's blocks, then the whole ring. */
|
||||
const int64_t need = w.ring_pos / p.block_size + w.ring_blocks;
|
||||
if (p.n_blocks > 0 && need > p.n_blocks) return RAD_E_FULL;
|
||||
s->win[g] = w;
|
||||
any = true;
|
||||
}
|
||||
if (!any) return RAD_E_UNSUPPORTED;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool KVManager::runtime_window(uint64_t id, int32_t g, SeqWindow* out) const {
|
||||
const Seq* s = find(id);
|
||||
if (!s || g < 0 || g >= (int32_t)s->win.size() || !s->win[(size_t)g].set) return false;
|
||||
if (out) *out = s->win[(size_t)g];
|
||||
return true;
|
||||
}
|
||||
|
||||
bool KVManager::has_runtime_window(uint64_t id) const {
|
||||
const Seq* s = find(id);
|
||||
if (!s) return false;
|
||||
for (const SeqWindow& w : s->win) if (w.set) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* What ensure() must have in the table for `n_tokens`: the reference grows linearly until the
|
||||
* floor, then the ring fills up to its whole span and never grows again. */
|
||||
int64_t KVManager::window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens) {
|
||||
const int64_t ref = w.ring_pos / p.block_size;
|
||||
if (n_tokens <= w.ring_pos) return ceil_div(n_tokens, p.block_size);
|
||||
return ref + std::min(w.ring_blocks, ceil_div(n_tokens - w.ring_pos, p.block_size));
|
||||
}
|
||||
|
||||
int64_t KVManager::seq_tokens(uint64_t id) const { const Seq* s = find(id); return s ? s->n_tokens : 0; }
|
||||
|
||||
int64_t KVManager::take_table_changes(uint64_t id, int32_t g) const {
|
||||
@@ -1023,11 +1239,15 @@ int64_t KVManager::step_blocks(const KVGroupPlan& p) const {
|
||||
/* Slides from the step's first query, not its last. The query at keep_from reads keys down to
|
||||
* keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later
|
||||
* (window_blocks - 1 >= window / block). A target from the step's end is the same for a decode
|
||||
* step but drops keys the earlier rows of a prefill chunk still need. */
|
||||
* step but drops keys the earlier rows of a prefill chunk still need.
|
||||
*
|
||||
* A sequence with a runtime window is left alone. Its visible set is anchored at 0, so nothing in
|
||||
* the table is below a sliding floor to recycle; the ring's blocks are rewritten in place and
|
||||
* the table never moves (SeqWindow). */
|
||||
void KVManager::recycle_window(Seq* s, int64_t keep_from) {
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const auto& p = plans_[g];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
if (p.kind != RAD_KV_WINDOW || s->win[g].set) continue;
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t target = std::max<int64_t>(first,
|
||||
keep_from / p.block_size - (p.window_blocks - 1));
|
||||
@@ -1066,7 +1286,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
|
||||
const auto& p = plans_[g];
|
||||
if (p.paged()) {
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t want = ceil_div(n_tokens, p.block_size) - first;
|
||||
int64_t want = s->win[g].set
|
||||
? window_table_len(p, s->win[g], n_tokens) - first
|
||||
: ceil_div(n_tokens, p.block_size) - first;
|
||||
need[g] = want - (int64_t)s->blocks[g].size();
|
||||
if (need[g] < 0) need[g] = 0;
|
||||
/* Copy-on-write: the partial block is the only one a write reaches; if it is shared,
|
||||
@@ -1102,7 +1324,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
|
||||
}
|
||||
}
|
||||
}
|
||||
int64_t want = ceil_div(n_tokens, p.block_size) - first;
|
||||
int64_t want = s->win[g].set
|
||||
? window_table_len(p, s->win[g], n_tokens) - first
|
||||
: ceil_div(n_tokens, p.block_size) - first;
|
||||
if ((int64_t)s->blocks[g].size() < want)
|
||||
s->dirty_from[g] = std::min<int64_t>(s->dirty_from[g],
|
||||
(int64_t)s->blocks[g].size());
|
||||
@@ -1126,6 +1350,10 @@ int KVManager::adopt(uint64_t id, int32_t g, const std::vector<int32_t>& blocks,
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
const KVGroupPlan* p = plan(g);
|
||||
if (!p || !p->paged()) return RAD_E_INVAL;
|
||||
/* A runtime window's table is its own reference plus ring, laid out against a floor no cache
|
||||
* entry knows (set_window), so blocks adopted from a prefix hit would sit at the wrong
|
||||
* positions. Prefix publish is skipped for such a sequence; this is the backstop. */
|
||||
if (s->win[(size_t)g].set) return RAD_E_STATE;
|
||||
/* Whole blocks only (see adopt in kv.h). */
|
||||
if (n_tokens % p->block_size != 0) return RAD_E_INVAL;
|
||||
if ((int64_t)blocks.size() != n_tokens / p->block_size) return RAD_E_INVAL;
|
||||
@@ -1146,6 +1374,14 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
|
||||
Seq* pa = find(parent);
|
||||
if (!pa) return RAD_E_NOTFOUND;
|
||||
if (seqs_.count(child)) return RAD_E_DUPLICATE;
|
||||
/* The window is runtime data: a child that shared the table without it would read the ring
|
||||
* as if it were a reference. A forking model (speculative decoding) does not carry one. */
|
||||
for (const SeqWindow& w : pa->win)
|
||||
if (w.set) {
|
||||
RAD_ERR("sequence %llu: fork refused, it carries a runtime window",
|
||||
(unsigned long long)parent);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* Pass 1: the child needs its own state slot in every stateful group before anything is
|
||||
* shared (see fork in kv.h, spec §7.3). */
|
||||
@@ -1160,6 +1396,7 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
|
||||
if (plans_[g].paged()) {
|
||||
ch->blocks[g] = pa->blocks[g];
|
||||
ch->first_block_pos[g] = pa->first_block_pos[g];
|
||||
ch->win[g] = pa->win[g];
|
||||
for (int32_t b : ch->blocks[g]) add_ref(g, b);
|
||||
} else {
|
||||
grab_state((int32_t)g, &ch->state[g]);
|
||||
@@ -1189,7 +1426,10 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
|
||||
if (p.paged()) {
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t want = ceil_div(n_tokens, p.block_size) - first;
|
||||
if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p));
|
||||
if (p.kind == RAD_KV_WINDOW) {
|
||||
if (s->win[g].set) want = window_table_len(p, s->win[g], n_tokens) - first;
|
||||
else want = std::min(want, window_seq_cap(p));
|
||||
}
|
||||
int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */
|
||||
if (extra > available_blocks((int32_t)g)) return false;
|
||||
} else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false;
|
||||
@@ -1369,6 +1609,9 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out)
|
||||
out->clear();
|
||||
const Seq* s = find(id);
|
||||
if (!s || pos <= 0) return false;
|
||||
/* A runtime window is excluded from window snapshots (set_window): the window length is
|
||||
* runtime data and the table is a reference plus a ring, not [lo, pos). */
|
||||
for (const SeqWindow& w : s->win) if (w.set) return false;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.win_snap) continue;
|
||||
@@ -1390,6 +1633,8 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out)
|
||||
int KVManager::seed_window(uint64_t id, int64_t pos) {
|
||||
Seq* s = find(id);
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
/* A sequence with a runtime window is never resumed from a window snapshot (set_window). */
|
||||
for (const SeqWindow& w : s->win) if (w.set) return RAD_E_STATE;
|
||||
/* Check every group before taking anything, as ensure() does. */
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
|
||||
+113
-3
@@ -11,6 +11,10 @@
|
||||
* RAD_KV_LINEAR per-sequence, fixed size: the GDN recurrent state
|
||||
* RAD_KV_CONV per-sequence, fixed size: a rolling window of conv_width-1 + n_spec entries
|
||||
*
|
||||
* A RAD_KV_RING group is a RAD_KV_WINDOW whose floor is per sequence and set at runtime (R-SWA,
|
||||
* see SeqWindow); it is planned as a WINDOW group with `runtime_win` set, so no kind of its own
|
||||
* reaches the plan.
|
||||
*
|
||||
* The two stateful kinds are also allocated, mapped and freed here, so one allocator decides what
|
||||
* a sequence owns. With two, a freed sequence's state slot could still be handed to the next
|
||||
* request by the other.
|
||||
@@ -50,6 +54,45 @@ struct BundleComparison {
|
||||
};
|
||||
BundleComparison compare_bundling(const std::vector<int64_t>& bundles);
|
||||
|
||||
/* ------------------------------------------------------------------ the runtime window */
|
||||
/* A sequence's per-sequence window on a RAD_KV_WINDOW group, set at runtime (R-SWA, the
|
||||
* "reference + ring" attention of Unlimited-OCR: a full causal prefill over the prompt and image
|
||||
* tokens, then a ring of W decode slots right after it, rewritten in place forever).
|
||||
*
|
||||
* A fixed sliding window (`KVGroupPlan::window_blocks`, gemma4's) keeps the last W tokens: the
|
||||
* table starts where the window begins and blocks leave from its front. A runtime window instead
|
||||
* retains the whole prefill as the reference and appends into a ring after it:
|
||||
*
|
||||
* visible = [0, visible_lo) U [visible_lo, visible_lo + W)
|
||||
*
|
||||
* `visible_lo` is the sequence's own prefill length (image tokens included), so the visible set is
|
||||
* per sequence. The reference is never recycled and first_block_pos stays 0 (the table still
|
||||
* starts at position 0); only the ring's slot mapping recycles, so RoPE positions keep increasing
|
||||
* with the token's own position and a decode query sees the whole reference plus the ring.
|
||||
*
|
||||
* Blocks are whole, so the ring can start only on a block boundary: it starts at
|
||||
* `ring_pos = ceil(visible_lo / block) * block` with `ceil(W / block)` blocks, and the tokens in
|
||||
* [visible_lo, ring_pos) stay in the reference's last block (they are the oldest of the tail and
|
||||
* are never rewritten). The visible tail is therefore W .. W + block - 1 tokens when W is a block
|
||||
* multiple -- with block_size 128 = W the 128-256 token granularity of the plan, exact even when
|
||||
* the floor is not aligned -- and up to one block more otherwise, always a superset of the
|
||||
* reference implementation's last W. The ring's blocks hold the newest positions in place (no
|
||||
* block is allocated past them, so the sequence's bytes are flat once the floor is set):
|
||||
*
|
||||
* block index = ring_pos / block + ((pos - ring_pos) / block) % ring_blocks
|
||||
*
|
||||
* A sequence with a runtime window is excluded from prefix-cache reuse, window snapshots, forking
|
||||
* and speculative rollback: all three assume the declare-time window, and the runtime length is
|
||||
* not in any cache key (see KVManager::set_window). */
|
||||
struct SeqWindow {
|
||||
bool set = false;
|
||||
int64_t window = 0; /* W as set */
|
||||
int64_t visible_lo = 0; /* the retained reference ends here */
|
||||
int64_t ring_pos = 0; /* block-aligned first ring token position */
|
||||
int64_t ring_blocks = 0; /* whole blocks the ring holds */
|
||||
int64_t ring_span(int64_t block) const { return ring_blocks * block; }
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ per-group plan */
|
||||
struct KVGroupPlan {
|
||||
int32_t index = -1; /* position in Program::kv_groups */
|
||||
@@ -62,6 +105,18 @@ struct KVGroupPlan {
|
||||
int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */
|
||||
int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */
|
||||
int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */
|
||||
/* WINDOW: sequences may be given a runtime window (declare_runtime_window). Such a group is
|
||||
* sized for the whole context plus one ring per sequence instead of being capped at
|
||||
* window_blocks, its window is not snapshotted, and a sequence armed with one is bounded by
|
||||
* its own reference + ring rather than by window_blocks. */
|
||||
bool runtime_win = false;
|
||||
int64_t runtime_tokens = 0; /* the W set_window arms a sequence with */
|
||||
/* The most ring blocks one sequence needs: ceil(W / block), the reference's fraction d of
|
||||
* the ring's first block being frozen in it (see SeqWindow). */
|
||||
int64_t ring_blocks_max() const {
|
||||
return runtime_tokens > 0 && block_size > 0
|
||||
? (runtime_tokens + block_size - 1) / block_size : 0;
|
||||
}
|
||||
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a
|
||||
* trunk group of a model with no linear state. A drafter's window is recomputed by draft
|
||||
* refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither
|
||||
@@ -206,9 +261,49 @@ public:
|
||||
/* Recycles a committed chunk's window blocks. ensure() keeps a chunk's blocks beside the
|
||||
* window and only the next ensure() recycles them, so a prefill waiting for its next chunk
|
||||
* would hold a whole chunk of blocks; several such prefills can exhaust the pool. The
|
||||
* scheduler calls this when it advances n_computed, passing the new n_computed. */
|
||||
* scheduler calls this when it advances n_computed, passing the new n_computed.
|
||||
*
|
||||
* A sequence with a runtime window retains its reference and rewrites its ring in place, so
|
||||
* nothing below the floor may be recycled and this is a no-op for it. */
|
||||
void trim_window(uint64_t seq, int64_t keep_from);
|
||||
|
||||
/* ---------------- the runtime window (R-SWA; see SeqWindow) ---------------- */
|
||||
/* Mark a WINDOW group as carrying per-sequence runtime windows of `window_tokens`. Call before
|
||||
* plan_groups()/configure(): it changes the plan (the group is sized for the whole context
|
||||
* plus one ring a sequence, its window is not snapshotted, and the ring joins the fixed
|
||||
* costs), so a group declared after the plan is refused. A fixed-window group is untouched.
|
||||
*
|
||||
* A group that is not marked still accepts set_window() -- the caller then sizes the pool
|
||||
* itself, e.g. by declaring the group's window as the whole context -- and each sequence's
|
||||
* capacity is checked at set_window()/ensure() against the blocks actually carved. Once any
|
||||
* group is marked, set_window() arms only marked groups: a plain fixed-window group beside a
|
||||
* declared runtime window is refused, not silently converted (its pool is carved for the
|
||||
* fixed window). */
|
||||
int declare_runtime_window(int32_t group, int64_t window_tokens);
|
||||
|
||||
/* Give a sequence a runtime window with `visible_lo` (its prefill length, image tokens
|
||||
* included) as the retained reference's end and a ring of `window_tokens` after it. Every
|
||||
* paged WINDOW group of the sequence gets the same floor. Call it before the sequence's KV
|
||||
* grows past `visible_lo` -- at admission, where the scheduler knows the prompt length -- so
|
||||
* the reference is written linearly and no checkpoint can be reserved for it (a snapshot
|
||||
* would describe a window the sequence no longer has).
|
||||
*
|
||||
* RAD_E_UNSUPPORTED no windowed group, or the fixed/runtime-window mix above;
|
||||
* RAD_E_INVAL a negative floor or a window of 0;
|
||||
* RAD_E_STATE the sequence already holds tokens past the floor;
|
||||
* RAD_E_FULL the reference plus the ring exceeds what this group carved. */
|
||||
int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens);
|
||||
|
||||
/* The sequence's window in `group`, or false when it has none (a fixed-window group keeps
|
||||
* KVGroupPlan::window_blocks and first_block_pos). The step batch maps a ring position with
|
||||
* SeqWindow's rule; every other position maps as (pos - first_block_pos) / block_size. */
|
||||
bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const;
|
||||
/* Whether any group has a runtime window set for the sequence. Prefix publish, checkpoint
|
||||
* reservation and snapshots are skipped for it (see set_window). */
|
||||
bool has_runtime_window(uint64_t seq) const;
|
||||
/* The W declare_runtime_window gave the group, 0 if it carries no runtime windows. */
|
||||
int64_t runtime_window_tokens(int32_t group) const;
|
||||
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
|
||||
* block size: a partial block is never shared, because the next token written into it would
|
||||
* corrupt the cache entry. Bumps each block's refcount. */
|
||||
@@ -363,7 +458,11 @@ public:
|
||||
/* The absolute token position block_table(seq, group)[0] covers: zero for a FULL group, the
|
||||
* recycled prefix for a WINDOW group. The slot mapping is (pos - first_block_pos) /
|
||||
* block_size; without the offset a sliding-window sequence writes to the wrong slot once it
|
||||
* passes its window. */
|
||||
* passes its window.
|
||||
*
|
||||
* A sequence with a runtime window (set_window) keeps 0 for the group's whole life: its table
|
||||
* is [reference][ring] from position 0 and only the ring's slot index recycles (SeqWindow),
|
||||
* so the mapping above holds for the reference and SeqWindow's rule for the ring. */
|
||||
int64_t first_block_pos(uint64_t seq, int32_t group) const;
|
||||
|
||||
/* The first table entry changed since the last call; entries below it are unchanged, and
|
||||
@@ -461,6 +560,9 @@ private:
|
||||
* for a windowed group. 0 for kUnboundedTokens, which is not a count. */
|
||||
int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const;
|
||||
void forget();
|
||||
/* Turns a WINDOW group into a runtime-window one (declare_runtime_window). Returns false for a
|
||||
* group that is not windowed. */
|
||||
bool apply_runtime_window(KVGroupPlan& p) const;
|
||||
|
||||
/* One traversal serving both checkpoint directions; see checkpoint_save. */
|
||||
int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save,
|
||||
@@ -471,6 +573,7 @@ private:
|
||||
int64_t n_tokens = 0;
|
||||
std::vector<std::vector<int32_t>> blocks; /* per group */
|
||||
std::vector<int64_t> first_block_pos; /* WINDOW: token pos of blocks[0] */
|
||||
std::vector<SeqWindow> win; /* per group: the runtime window, if any */
|
||||
std::vector<int32_t> state; /* per group, -1 when not stateful */
|
||||
/* Per group, the lowest table entry written since the batch builder last staged this
|
||||
* sequence. An append or truncation lowers it to where it touched; a shift lowers it to
|
||||
@@ -486,8 +589,12 @@ private:
|
||||
void drop_state(int32_t g, int32_t s);
|
||||
Seq* find(uint64_t seq);
|
||||
const Seq* find(uint64_t seq) const;
|
||||
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */
|
||||
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. A runtime window
|
||||
* (SeqWindow) is not trimmed: its reference must stay and its ring rewrites slots in place. */
|
||||
void recycle_window(Seq* s, int64_t keep_from);
|
||||
/* The table length a runtime-windowed sequence needs to hold `n_tokens`: the reference's
|
||||
* blocks, then the ring's up to its whole span. */
|
||||
static int64_t window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens);
|
||||
|
||||
std::vector<KVGroupPlan> plans_;
|
||||
std::vector<std::vector<int32_t>> free_blocks_; /* per group */
|
||||
@@ -515,6 +622,9 @@ private:
|
||||
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */
|
||||
int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */
|
||||
int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */
|
||||
/* declare_runtime_window(): group -> W. Survives forget(), which plan_groups() calls at its
|
||||
* start: it is a declaration about the program, not about a plan. */
|
||||
std::unordered_map<int32_t, int64_t> runtime_decl_;
|
||||
|
||||
/* ---- the loan (see the public block) ----
|
||||
*
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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. */
|
||||
|
||||
+96
-7
@@ -368,11 +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);
|
||||
if (it != map_.end() && it->second.in_lru) 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;
|
||||
@@ -462,8 +467,9 @@ void PrefixCache::take_over(uint64_t session, const std::vector<BlockHash>& hs,
|
||||
|
||||
std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t fit) const {
|
||||
int64_t fit, bool* cut) const {
|
||||
std::vector<BlockHash> out;
|
||||
if (cut) *cut = false;
|
||||
if (!enabled_ || !tiers_ || tokens.empty()) return out;
|
||||
|
||||
/* Only blocks a hit can use: one token must remain, so a prompt ending on a block boundary
|
||||
@@ -488,13 +494,16 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
if (out.empty() || (int64_t)out.size() <= fit) return out;
|
||||
|
||||
/* Restored up to `fit`, the hit ends at the first entry left behind. */
|
||||
++stats_.restore_cuts;
|
||||
if (cut) *cut = true;
|
||||
int64_t keep = std::max<int64_t>(0, fit);
|
||||
if (has_linear_) {
|
||||
const auto best = deepest_ckpt(hs, at[(size_t)keep] * block_size_);
|
||||
const int64_t upto = best == ck_by_prefix_.end() ? 0 : best->second.pos / block_size_;
|
||||
keep = std::lower_bound(at.begin(), at.begin() + keep, upto) - at.begin();
|
||||
}
|
||||
RAD_DEBUG("prefix cache: restore of %zu entries cut to %lld: the pool holds %lld of them, and "
|
||||
"the hit ends at token %lld", out.size(), (long long)keep,
|
||||
(long long)std::max<int64_t>(0, fit), (long long)(at[(size_t)keep] * block_size_));
|
||||
out.resize((size_t)keep);
|
||||
return out;
|
||||
}
|
||||
@@ -508,7 +517,8 @@ int64_t PrefixCache::restore_room() const {
|
||||
|
||||
int64_t PrefixCache::trim_for(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm, int64_t n_blocks) {
|
||||
if (!enabled_ || n_blocks <= 0) return 0;
|
||||
/* Without a host tier a trim erases, and making room for a restore must lose nothing. */
|
||||
if (!enabled_ || n_blocks <= 0 || !tiers_ || !tiers_->host_on()) return 0;
|
||||
const std::vector<BlockHash> hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_);
|
||||
std::unordered_set<BlockHash, BlockHashHash> spare(hs.begin(), hs.end());
|
||||
for (const auto& h : held_) spare.insert(h.first);
|
||||
@@ -981,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 */
|
||||
+40
-9
@@ -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:
|
||||
@@ -256,20 +273,19 @@ public:
|
||||
* on a miss or token mismatch. Separate from lookup because lookup is const and has no
|
||||
* device; a promotion allocates blocks and runs a scatter between steps.
|
||||
*
|
||||
* `fit` is how many entries the pool can take. A longer chain is cut, and counted
|
||||
* (Stats::restore_cuts): with recurrent state at the deepest snapshot the shorter prefix
|
||||
* reaches, since the hit resumes there and blocks past it would come back for nothing;
|
||||
* without, at `fit`. */
|
||||
* `fit` is how many entries the pool can take. A longer chain is cut, and `*cut` set: with
|
||||
* recurrent state at the deepest snapshot the shorter prefix reaches, since the hit resumes
|
||||
* there and blocks past it would come back for nothing; without, at `fit`. */
|
||||
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t fit = INT64_MAX) const;
|
||||
int64_t fit = INT64_MAX, bool* cut = nullptr) const;
|
||||
/* Entries a restore can place now: free blocks against the carve, the least over the cached
|
||||
* groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */
|
||||
int64_t restore_room() const;
|
||||
/* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks
|
||||
* would only have to come back too) and every chain a waiting request holds (hold()), whose
|
||||
* next attempt would restore it again. Nothing is lost; the reserve's trim after the next
|
||||
* publish puts the pool's free quarter back. */
|
||||
* next attempt would restore it again. Only entries whose host copy has landed leave VRAM,
|
||||
* so nothing is lost; with no host tier it takes nothing. */
|
||||
int64_t trim_for(const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks);
|
||||
|
||||
@@ -315,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). */
|
||||
@@ -357,8 +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;
|
||||
/* Restores from the host tier cut short because the pool could not hold the chain. */
|
||||
int64_t restore_cuts = 0;
|
||||
/* Entries and snapshots a client released (release_session). */
|
||||
int64_t released = 0, ckpt_released = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
|
||||
|
||||
@@ -82,9 +82,8 @@ struct VramFacts {
|
||||
bool lends = false;
|
||||
/* A loaded control vector's direction table: device bytes the engine already holds, which are
|
||||
* not part of the program or the pools and must not shrink what the plan may claim. It comes
|
||||
* out of the headroom, as every deployment keeps that unclaimed. Without this, a deployment
|
||||
* that merely *offers* a vector would plan its expert cache against a smaller card than one
|
||||
* that does not, which is exactly the difference "off == stock" cannot allow. */
|
||||
* out of the headroom, as every deployment keeps that unclaimed, so a deployment that only
|
||||
* offers a vector plans its expert cache against the same card as one that does not. */
|
||||
int64_t held_out = 0;
|
||||
/* Integrated graphics: host memory the card must leave to the host, since device memory is
|
||||
* host memory there. 0 on a discrete card. */
|
||||
|
||||
+12
-5
@@ -33,11 +33,18 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
|
||||
while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s;
|
||||
const int64_t within = first + k - patch_at(s);
|
||||
const int64_t bw = seg_w(s) / merge;
|
||||
const int64_t in_col = within % merge;
|
||||
const int64_t in_row = (within / merge) % merge;
|
||||
const int64_t blk = within / (merge * merge);
|
||||
const int64_t row = (blk / bw) * merge + in_row;
|
||||
const int64_t col = (blk % bw) * merge + in_col;
|
||||
int64_t row, col;
|
||||
if (patch_raster) {
|
||||
/* Raster order is its own inverse: patch i is row i / w, column i % w. */
|
||||
row = within / seg_w(s);
|
||||
col = within % seg_w(s);
|
||||
} else {
|
||||
const int64_t in_col = within % merge;
|
||||
const int64_t in_row = (within / merge) % merge;
|
||||
const int64_t blk = within / (merge * merge);
|
||||
row = (blk / bw) * merge + in_row;
|
||||
col = (blk % bw) * merge + in_col;
|
||||
}
|
||||
planes[k] = (int32_t)row;
|
||||
planes[count + k] = (int32_t)col;
|
||||
planes[2 * count + k] = seg_h(s);
|
||||
|
||||
+6
-1
@@ -46,7 +46,12 @@ int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRG
|
||||
/* Encodes `px`, [h, w, ch] 8-bit with ch 3 (RGB) or 4 (RGBA), as an image file; `format` is png,
|
||||
* jpeg or webp. `quality` 0..100 applies to jpeg and lossy webp (0 or above 100 picks the
|
||||
* format's default); png is lossless and webp is lossless at 100. jpeg refuses alpha. Returns
|
||||
* RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode. */
|
||||
* RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode.
|
||||
*
|
||||
* Lossless webp is written by libwebp; FFmpeg's native VP8L decoder refuses some valid
|
||||
* libwebp streams ("Invalid data", reproducible with ffmpeg 8.0.1 on a low-colour picture),
|
||||
* so an FFmpeg-based consumer may not read every lossless file this writes. libwebp and
|
||||
* browsers do. */
|
||||
int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
|
||||
int32_t quality, std::vector<uint8_t>* out, std::string* why);
|
||||
|
||||
|
||||
+693
-55
@@ -6,10 +6,19 @@
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
#if defined(__x86_64__) || defined(__i386__) || defined(_M_X64)
|
||||
#include <immintrin.h>
|
||||
#define RAD_MM_HAVE_AVX2 1
|
||||
#endif
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
@@ -41,6 +50,49 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) {
|
||||
}
|
||||
|
||||
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
/* Unlimited-OCR: one processor class, two modes, both stated in preprocessor_config.json and
|
||||
* processor_config.json (`processor.*`). Every key has the reference's default, so a container
|
||||
* converted before the tower landed still states a processor. */
|
||||
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "unlimited_ocr")) {
|
||||
family = Family::UnlimitedOcr;
|
||||
patch = (int32_t)rad_meta_geti(&m, "processor.patch_size",
|
||||
rad_meta_geti(&m, "vision_config.patch_size", 16));
|
||||
downsample = (int32_t)rad_meta_geti(&m, "processor.downsample_ratio", 4);
|
||||
merge = downsample;
|
||||
temporal = 1;
|
||||
base_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.height", 1024);
|
||||
tile = (int32_t)rad_meta_geti(&m, "preprocessor.tile_size", 640);
|
||||
/* The base mode's whole view: what the reference states for its input, and what the
|
||||
* preprocessor's `size` is. Multi-page inference may ask for the tile instead. */
|
||||
image_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.width", base_size);
|
||||
crop_mode = meta_bool(m, "preprocessor.crop_to_patches", true);
|
||||
if (const char* t = rad_meta_gets(&m, "processor.image_token", nullptr); t && *t)
|
||||
image_token = t;
|
||||
min_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.min_patches", 2);
|
||||
max_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.max_patches", 32);
|
||||
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
|
||||
if (!read_triple(m, "preprocessor.image_mean", mean)) mean[0] = mean[1] = mean[2] = 0.5f;
|
||||
if (!read_triple(m, "preprocessor.image_std", stdv)) stdv[0] = stdv[1] = stdv[2] = 0.5f;
|
||||
/* 3 is PIL's bicubic, the only filter this processor stages. */
|
||||
const int64_t resample = rad_meta_geti(&m, "preprocessor.resample", 3);
|
||||
if (resample != 3) {
|
||||
if (why) *why = "the container resamples pictures with filter " +
|
||||
std::to_string(resample) + "; this processor stages PIL's bicubic (3)";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* No video; the bands only have to be consistent for check(). */
|
||||
const int64_t f2 = (int64_t)factor() * factor();
|
||||
image_min_pixels = video_min_pixels = f2;
|
||||
image_max_pixels = video_max_pixels = (int64_t)base_size * base_size;
|
||||
min_frames = 1;
|
||||
std::string bad;
|
||||
if (check(&bad) < 0) {
|
||||
if (why) *why = "the container's Unlimited-OCR processor configuration is "
|
||||
"inconsistent: " + bad;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* LFM2-VL states its processor twice, in config.json and in processor_config.json's
|
||||
* image_processor; the latter is what the reference processor reads, so it goes first. */
|
||||
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) {
|
||||
@@ -260,6 +312,20 @@ int VisionConfig::check(std::string* why) const {
|
||||
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
|
||||
return no("max_pixels_tolerance and max_num_patches must be positive");
|
||||
}
|
||||
if (family == Family::UnlimitedOcr) {
|
||||
if (patch <= 0 || downsample <= 0 || merge != downsample)
|
||||
return no("the tower's geometry (patch_size " + std::to_string(patch) +
|
||||
", downsample_ratio " + std::to_string(downsample) +
|
||||
") does not cut a whole merged patch");
|
||||
if (base_size <= 0 || base_size % factor() || image_size <= 0 || image_size % factor())
|
||||
return no("the global view's side (" + std::to_string(base_size) + " and " +
|
||||
std::to_string(image_size) + " pixels) is not a whole number of merged "
|
||||
"patches");
|
||||
if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor())
|
||||
return no("the tiling (min_patches " + std::to_string(min_tiles) + ", max_patches " +
|
||||
std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) +
|
||||
") is not a range of whole merged patches");
|
||||
}
|
||||
if (family == Family::Glm5Next && (min_image_tokens < 1 || max_image_tokens < min_image_tokens))
|
||||
return no("the image token band [" + std::to_string(min_image_tokens) + ", " +
|
||||
std::to_string(max_image_tokens) + "] is empty");
|
||||
@@ -533,69 +599,314 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== AVX2 resample helpers
|
||||
*
|
||||
* The two passes below are fixed-point int32 per tap. Integer addition is exact and associative at
|
||||
* these magnitudes (the coefficients of one output sum to 1 << prec and 255 << prec is about
|
||||
* 1.07e9, so no wrapper), so evaluating eight output pixels at once in any tap order is the same
|
||||
* function as the scalar loop; the rounding is only the final shift and clip. The horizontal pass
|
||||
* has variable tap counts and arbitrary stride-3 starts, so its lanes gather one 32-bit word per
|
||||
* tap (the RGB bytes of a pixel) and mask off inactive taps; the vertical pass reads whole rows,
|
||||
* where eight pixels are 24 contiguous bytes.
|
||||
*
|
||||
* Dispatch is local rather than through libavx: this file is core host code, and the AVX2 bodies
|
||||
* are target-attributed so the baseline object they live in still cannot execute AVX2 before the
|
||||
* check. mm_force_scalar() selects the scalar path for the bit-exactness test. */
|
||||
|
||||
static std::atomic<bool> g_force_scalar{ false };
|
||||
|
||||
void mm_force_scalar(bool on) { g_force_scalar.store(on, std::memory_order_relaxed); }
|
||||
|
||||
static bool mm_use_avx2() {
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
static const bool cpu = [] {
|
||||
__builtin_cpu_init();
|
||||
return __builtin_cpu_supports("avx2");
|
||||
}();
|
||||
return cpu && !g_force_scalar.load(std::memory_order_relaxed);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(RAD_MM_HAVE_AVX2)
|
||||
#define RAD_MM_AVX2 __attribute__((target("avx2")))
|
||||
#define RAD_MM_INLINE_AVX2 __attribute__((target("avx2"), always_inline)) inline
|
||||
#define RAD_MM_EXTRACT16(v) _mm256_extracti128_si256((v), 1)
|
||||
|
||||
/* Eight RGB pixels from 24 contiguous bytes (bytes 0..23 of p). */
|
||||
RAD_MM_INLINE_AVX2 void load_rgb8(const uint8_t* p, __m256i* r, __m256i* g, __m256i* b) {
|
||||
const __m128i a = _mm_loadu_si128((const __m128i*)p);
|
||||
const __m128i c = _mm_loadl_epi64((const __m128i*)(p + 16));
|
||||
const __m128i mr0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mg0 = _mm_setr_epi8(1, 4, 7, 10, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mb0 = _mm_setr_epi8(2, 5, 8, 11, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mr1 = _mm_setr_epi8(2, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mg1 = _mm_setr_epi8(0, 3, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mb1 = _mm_setr_epi8(1, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i rb = _mm_or_si128(_mm_shuffle_epi8(a, mr0), _mm_slli_si128(_mm_shuffle_epi8(c, mr1), 6));
|
||||
const __m128i gb = _mm_or_si128(_mm_shuffle_epi8(a, mg0), _mm_slli_si128(_mm_shuffle_epi8(c, mg1), 5));
|
||||
const __m128i bb = _mm_or_si128(_mm_shuffle_epi8(a, mb0), _mm_slli_si128(_mm_shuffle_epi8(c, mb1), 5));
|
||||
*r = _mm256_cvtepu8_epi32(rb);
|
||||
*g = _mm256_cvtepu8_epi32(gb);
|
||||
*b = _mm256_cvtepu8_epi32(bb);
|
||||
}
|
||||
|
||||
/* Eight rounded, clipped int32 sums written as eight RGB triplets (exactly 24 bytes). */
|
||||
RAD_MM_INLINE_AVX2 void store_rgb8(uint8_t* o, __m256i s0, __m256i s1, __m256i s2, int prec) {
|
||||
const __m256i sh = _mm256_set1_epi32(prec);
|
||||
const __m256i v0 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s0, sh), _mm256_setzero_si256()),
|
||||
_mm256_set1_epi32(255));
|
||||
const __m256i v1 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s1, sh), _mm256_setzero_si256()),
|
||||
_mm256_set1_epi32(255));
|
||||
const __m256i v2 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s2, sh), _mm256_setzero_si256()),
|
||||
_mm256_set1_epi32(255));
|
||||
const __m128i r16 = _mm_packus_epi32(_mm256_castsi256_si128(v0), RAD_MM_EXTRACT16(v0));
|
||||
const __m128i g16 = _mm_packus_epi32(_mm256_castsi256_si128(v1), RAD_MM_EXTRACT16(v1));
|
||||
const __m128i b16 = _mm_packus_epi32(_mm256_castsi256_si128(v2), RAD_MM_EXTRACT16(v2));
|
||||
const __m128i r8 = _mm_packus_epi16(r16, r16);
|
||||
const __m128i g8 = _mm_packus_epi16(g16, g16);
|
||||
const __m128i b8 = _mm_packus_epi16(b16, b16);
|
||||
/* Layout [r0..r3 g0..g3 b0..b3] then shuffle to 12 RGB bytes; twice for eight pixels.
|
||||
* Mask the low four bytes before shifting, or each shift would overwrite the previous
|
||||
* channel's bytes. */
|
||||
const __m128i low4 = _mm_set_epi64x(0, 0xffffffffll);
|
||||
const __m128i m = _mm_setr_epi8(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11, -1, -1, -1, -1);
|
||||
const __m128i lo = _mm_shuffle_epi8(
|
||||
_mm_or_si128(_mm_or_si128(_mm_and_si128(r8, low4),
|
||||
_mm_slli_si128(_mm_and_si128(g8, low4), 4)),
|
||||
_mm_slli_si128(_mm_and_si128(b8, low4), 8)),
|
||||
m);
|
||||
const __m128i hi = _mm_shuffle_epi8(
|
||||
_mm_or_si128(_mm_or_si128(_mm_and_si128(_mm_srli_si128(r8, 4), low4),
|
||||
_mm_slli_si128(_mm_and_si128(_mm_srli_si128(g8, 4), low4), 4)),
|
||||
_mm_slli_si128(_mm_and_si128(_mm_srli_si128(b8, 4), low4), 8)),
|
||||
m);
|
||||
_mm_storel_epi64((__m128i*)o, lo);
|
||||
_mm_storeu_si32(o + 8, _mm_srli_si128(lo, 8));
|
||||
_mm_storel_epi64((__m128i*)(o + 12), hi);
|
||||
_mm_storeu_si32(o + 20, _mm_srli_si128(hi, 8));
|
||||
}
|
||||
|
||||
/* One horizontal row, eight output pixels a step. plans is [group][tap] of eight (offset, coeff,
|
||||
* mask) int32s. The gather reads four bytes at the last input pixel's B channel, so the caller
|
||||
* keeps the buffer's final row on the scalar path. */
|
||||
RAD_MM_AVX2 void hpass_row(const uint8_t* row, uint8_t* o, int32_t ngroups, int32_t ksh,
|
||||
int prec, const int32_t* plans) {
|
||||
const __m256i zero = _mm256_setzero_si256();
|
||||
const __m256i round = _mm256_set1_epi32(1 << (prec - 1));
|
||||
const __m256i mask8 = _mm256_set1_epi32(0xff);
|
||||
for (int32_t g = 0; g < ngroups; ++g) {
|
||||
__m256i s0 = round, s1 = round, s2 = round;
|
||||
const int32_t* pl = plans + (size_t)g * (size_t)ksh * 24;
|
||||
for (int32_t t = 0; t < ksh; ++t, pl += 24) {
|
||||
const __m256i off = _mm256_loadu_si256((const __m256i*)pl);
|
||||
const __m256i coef = _mm256_loadu_si256((const __m256i*)(pl + 8));
|
||||
const __m256i msk = _mm256_loadu_si256((const __m256i*)(pl + 16));
|
||||
const __m256i word = _mm256_mask_i32gather_epi32(zero, (const int*)row, off, msk, 1);
|
||||
const __m256i r = _mm256_and_si256(word, mask8);
|
||||
const __m256i gg = _mm256_and_si256(_mm256_srli_epi32(word, 8), mask8);
|
||||
const __m256i bb = _mm256_and_si256(_mm256_srli_epi32(word, 16), mask8);
|
||||
s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, coef));
|
||||
s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(gg, coef));
|
||||
s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(bb, coef));
|
||||
}
|
||||
store_rgb8(o + (size_t)g * 24, s0, s1, s2, prec);
|
||||
}
|
||||
}
|
||||
|
||||
/* One vertical row: every tap is a whole source row, eight output pixels at a time. */
|
||||
RAD_MM_AVX2 void vpass_row(const Frame& src, int32_t ymin, int32_t ymax, const int32_t* k,
|
||||
uint8_t* o, int prec) {
|
||||
const __m256i round = _mm256_set1_epi32(1 << (prec - 1));
|
||||
int32_t xx = 0;
|
||||
for (; xx + 8 <= src.w; xx += 8) {
|
||||
__m256i s0 = round, s1 = round, s2 = round;
|
||||
for (int32_t y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
|
||||
__m256i r, g, b;
|
||||
load_rgb8(p, &r, &g, &b);
|
||||
const __m256i kk = _mm256_set1_epi32(k[y]);
|
||||
s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, kk));
|
||||
s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(g, kk));
|
||||
s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(b, kk));
|
||||
}
|
||||
store_rgb8(o + (size_t)xx * 3, s0, s1, s2, prec);
|
||||
}
|
||||
for (; xx < src.w; ++xx) {
|
||||
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
|
||||
for (int32_t y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
|
||||
s0 += p[0] * k[y];
|
||||
s1 += p[1] * k[y];
|
||||
s2 += p[2] * k[y];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, prec);
|
||||
o[xx * 3 + 1] = clip8(s1, prec);
|
||||
o[xx * 3 + 2] = clip8(s2, prec);
|
||||
}
|
||||
}
|
||||
|
||||
/* One patch row: for each channel, P strided source bytes through that channel's LUT. lut32 is
|
||||
* the same LUT as 32-bit words, so one gather gets all three channels' table entries. */
|
||||
RAD_MM_AVX2 void patch_row(const uint8_t* row, uint16_t* dst, int32_t P, size_t chstride,
|
||||
const uint32_t* lut32, const uint16_t* lut) {
|
||||
for (int32_t x = 0; x + 8 <= P; x += 8) {
|
||||
__m256i r, g, b;
|
||||
load_rgb8(row + (size_t)x * 3, &r, &g, &b);
|
||||
const __m256i idx[3] = { r, g, b };
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
const __m256i ii = _mm256_add_epi32(idx[ch], _mm256_set1_epi32(ch * 256));
|
||||
const __m256i v = _mm256_i32gather_epi32((const int*)lut32, ii, 4);
|
||||
const __m128i h = _mm_packus_epi32(_mm256_castsi256_si128(v), RAD_MM_EXTRACT16(v));
|
||||
_mm_storeu_si128((__m128i*)(dst + (size_t)ch * chstride + x), h);
|
||||
}
|
||||
}
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int32_t x = (P / 8) * 8; x < P; ++x)
|
||||
dst[(size_t)ch * chstride + x] = lut[ch * 256 + row[(size_t)x * 3 + ch]];
|
||||
}
|
||||
#endif /* RAD_MM_HAVE_AVX2 */
|
||||
|
||||
/* One pass over an axis. `horizontal` reads rows [y0, y0 + rows) of `src` and writes w columns;
|
||||
* `vertical` reads rows from `shift` on and writes h rows. Both accumulate in fixed point and
|
||||
* round each output to eight bits, as Pillow does -- the intermediate's rounding is part of the
|
||||
* function, and the scalar tap order must not change.
|
||||
*
|
||||
* Both passes are row-independent: every output row reads only its own input rows and writes only
|
||||
* its own output row, in the same per-tap order, so splitting the rows across threads is bit-exact
|
||||
* (the goldens pin it). */
|
||||
static void run_rows(int32_t rows, const std::function<void(int32_t)>& row) {
|
||||
unsigned hw = std::thread::hardware_concurrency();
|
||||
const int32_t nt = (int32_t)std::min<int32_t>(rows, (int32_t)std::min<unsigned>(hw ? hw : 1, 8));
|
||||
if (nt <= 1) {
|
||||
for (int32_t y = 0; y < rows; ++y) row(y);
|
||||
return;
|
||||
}
|
||||
std::vector<std::thread> ts;
|
||||
ts.reserve((size_t)nt);
|
||||
for (int32_t t = 0; t < nt; ++t)
|
||||
ts.emplace_back([&row, t, nt, rows] { for (int32_t y = t; y < rows; y += nt) row(y); });
|
||||
for (std::thread& th : ts) th.join();
|
||||
}
|
||||
|
||||
static void pass_horizontal(const Frame& src, int32_t y0, int32_t rows, int32_t w,
|
||||
const std::vector<int32_t>& bh, const std::vector<int32_t>& kh,
|
||||
int32_t ksh, int prec, Frame* out) {
|
||||
out->w = w;
|
||||
out->h = rows;
|
||||
out->rgb.assign((size_t)w * (size_t)rows * 3, 0);
|
||||
const bool simd = mm_use_avx2();
|
||||
const int32_t ngroups = simd ? w / 8 : 0;
|
||||
std::vector<int32_t> plans;
|
||||
if (ngroups) {
|
||||
plans.resize((size_t)ngroups * (size_t)ksh * 24);
|
||||
for (int32_t g = 0; g < ngroups; ++g)
|
||||
for (int32_t t = 0; t < ksh; ++t) {
|
||||
int32_t* p = plans.data() + ((size_t)g * (size_t)ksh + (size_t)t) * 24;
|
||||
for (int32_t j = 0; j < 8; ++j) {
|
||||
const int32_t xx = g * 8 + j;
|
||||
const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
|
||||
const bool on = t < xmax;
|
||||
p[j] = on ? (xmin + t) * 3 : 0;
|
||||
p[8 + j] = on ? kh[(size_t)xx * (size_t)ksh + (size_t)t] : 0;
|
||||
p[16 + j] = on ? -1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto scalar_row = [&](const uint8_t* row, uint8_t* o, int32_t x0) {
|
||||
for (int32_t xx = x0; xx < w; ++xx) {
|
||||
const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
|
||||
const int32_t* k = kh.data() + (size_t)xx * (size_t)ksh;
|
||||
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
|
||||
for (int32_t x = 0; x < xmax; ++x) {
|
||||
const uint8_t* p = row + (size_t)(x + xmin) * 3;
|
||||
s0 += p[0] * k[x];
|
||||
s1 += p[1] * k[x];
|
||||
s2 += p[2] * k[x];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, prec);
|
||||
o[xx * 3 + 1] = clip8(s1, prec);
|
||||
o[xx * 3 + 2] = clip8(s2, prec);
|
||||
}
|
||||
};
|
||||
run_rows(rows, [&](int32_t yy) {
|
||||
const uint8_t* row = src.rgb.data() + (size_t)(yy + y0) * (size_t)src.w * 3;
|
||||
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)w * 3;
|
||||
/* The gather reads one byte past the row, which stays in the buffer on every row but its
|
||||
* last; that one stays scalar. */
|
||||
if (!ngroups || yy + y0 == src.h - 1) { scalar_row(row, o, 0); return; }
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
hpass_row(row, o, ngroups, ksh, prec, plans.data());
|
||||
scalar_row(row, o, ngroups * 8);
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
static void pass_vertical(const Frame& src, int32_t shift, int32_t h,
|
||||
const std::vector<int32_t>& bv, const std::vector<int32_t>& kv,
|
||||
int32_t ksv, int prec, Frame* out) {
|
||||
out->w = src.w;
|
||||
out->h = h;
|
||||
out->rgb.assign((size_t)src.w * (size_t)h * 3, 0);
|
||||
const bool simd = mm_use_avx2();
|
||||
run_rows(h, [&](int32_t yy) {
|
||||
const int32_t ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
|
||||
const int32_t* k = kv.data() + (size_t)yy * (size_t)ksv;
|
||||
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)src.w * 3;
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
if (simd) { vpass_row(src, ymin, ymax, k, o, prec); return; }
|
||||
#endif
|
||||
(void)simd;
|
||||
for (int32_t xx = 0; xx < src.w; ++xx) {
|
||||
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
|
||||
for (int32_t y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
|
||||
s0 += p[0] * k[y];
|
||||
s1 += p[1] * k[y];
|
||||
s2 += p[2] * k[y];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, prec);
|
||||
o[xx * 3 + 1] = clip8(s1, prec);
|
||||
o[xx * 3 + 2] = clip8(s2, prec);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) {
|
||||
if (in.w == w && in.h == h) { *out = in; return; }
|
||||
std::vector<int32_t> bh, kh, bv, kv;
|
||||
int ph = kPrec, pv = kPrec;
|
||||
const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph);
|
||||
const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv);
|
||||
const bool need_h = w != in.w, need_v = h != in.h;
|
||||
|
||||
/* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */
|
||||
const int y_first = bv[0];
|
||||
const int y_last = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1];
|
||||
const bool need_h = w != in.w;
|
||||
const bool need_v = h != in.h;
|
||||
/* Pillow's pass order (libImaging/Resample.c): vertical first when the height shrinks and by
|
||||
* more than twice what the width does, so the horizontal pass runs over fewer rows. The
|
||||
* intermediate is eight bits, so the order changes the picture: both are the reference's.
|
||||
* torchvision's on a uint8 tensor (ATen's CPU kernel) is horizontal first at every size. */
|
||||
const bool horizontal_first =
|
||||
torch || !((int64_t)in.h - h > 0 && (int64_t)in.h - h > 2 * ((int64_t)in.w - w));
|
||||
|
||||
Frame tmp;
|
||||
const Frame* src = ∈
|
||||
if (need_h && need_v) {
|
||||
if (horizontal_first) {
|
||||
/* Only the source rows the vertical pass reads are resampled horizontally. */
|
||||
const int32_t y0 = bv[0];
|
||||
const int32_t rows = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1] - y0;
|
||||
pass_horizontal(in, y0, rows, w, bh, kh, ksh, ph, &tmp);
|
||||
pass_vertical(tmp, y0, h, bv, kv, ksv, pv, out);
|
||||
} else {
|
||||
pass_vertical(in, 0, h, bv, kv, ksv, pv, &tmp);
|
||||
pass_horizontal(tmp, 0, h, w, bh, kh, ksh, ph, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (need_h) {
|
||||
const int rows = need_v ? y_last - y_first : in.h;
|
||||
const int y0 = need_v ? y_first : 0;
|
||||
tmp.w = w;
|
||||
tmp.h = rows;
|
||||
tmp.rgb.assign((size_t)w * rows * 3, 0);
|
||||
for (int yy = 0; yy < rows; ++yy) {
|
||||
const uint8_t* row = in.rgb.data() + (size_t)(yy + y0) * in.w * 3;
|
||||
uint8_t* o = tmp.rgb.data() + (size_t)yy * w * 3;
|
||||
for (int xx = 0; xx < w; ++xx) {
|
||||
const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
|
||||
const int32_t* k = kh.data() + (size_t)xx * ksh;
|
||||
int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0;
|
||||
for (int x = 0; x < xmax; ++x) {
|
||||
const uint8_t* p = row + (size_t)(x + xmin) * 3;
|
||||
s0 += p[0] * k[x];
|
||||
s1 += p[1] * k[x];
|
||||
s2 += p[2] * k[x];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, ph);
|
||||
o[xx * 3 + 1] = clip8(s1, ph);
|
||||
o[xx * 3 + 2] = clip8(s2, ph);
|
||||
}
|
||||
}
|
||||
src = &tmp;
|
||||
}
|
||||
if (!need_v) { *out = std::move(tmp); return; }
|
||||
const int shift = need_h ? y_first : 0;
|
||||
out->w = src->w;
|
||||
out->h = h;
|
||||
out->rgb.assign((size_t)src->w * h * 3, 0);
|
||||
for (int yy = 0; yy < h; ++yy) {
|
||||
const int ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
|
||||
const int32_t* k = kv.data() + (size_t)yy * ksv;
|
||||
uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3;
|
||||
for (int xx = 0; xx < src->w; ++xx) {
|
||||
int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0;
|
||||
for (int y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3;
|
||||
s0 += p[0] * k[y];
|
||||
s1 += p[1] * k[y];
|
||||
s2 += p[2] * k[y];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, pv);
|
||||
o[xx * 3 + 1] = clip8(s1, pv);
|
||||
o[xx * 3 + 2] = clip8(s2, pv);
|
||||
}
|
||||
pass_horizontal(in, 0, in.h, w, bh, kh, ksh, ph, out);
|
||||
return;
|
||||
}
|
||||
pass_vertical(in, 0, h, bv, kv, ksv, pv, out);
|
||||
}
|
||||
|
||||
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
|
||||
@@ -795,6 +1106,19 @@ int Processor::init(const VisionConfig& cfg,
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (cfg.family == Family::UnlimitedOcr) {
|
||||
/* The vocabulary spells the marker (`processor.image_token`), and every placeholder of a
|
||||
* picture is that same id: there is nothing else to resolve. */
|
||||
if (!token_id) return RAD_E_INVAL;
|
||||
if (cfg_.tok_image < 0) cfg_.tok_image = token_id(cfg_.image_token);
|
||||
if (cfg_.tok_image < 0) return RAD_E_NOTFOUND;
|
||||
/* A tile's line and the global view are each one segment, so each must fit one pass. */
|
||||
const int64_t q = cfg.tile / cfg.patch;
|
||||
const int64_t g = std::max(cfg.base_size, cfg.image_size) / cfg.patch;
|
||||
if (q * (q + 4) > cfg.max_patches || g * (g + 4) > cfg.max_patches) return RAD_E_INVAL;
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The largest image one encoder pass takes, in pixels. Lowering the band's ceiling to it makes
|
||||
* smart_resize keep every image inside a pass. */
|
||||
const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
|
||||
@@ -844,6 +1168,75 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32
|
||||
}
|
||||
}
|
||||
|
||||
/* Unlimited-OCR's ratios of one tile count tie only when they are each other's transpose: two
|
||||
* ratios of the same count are equally near an aspect only if one mirrors the other about it. So
|
||||
* the reference's set order matters for exactly the (c, r) pairs below, the tall ones (c < r)
|
||||
* its `sorted(set(...), key=area)` visits after their wide transpose -- the order CPython's set
|
||||
* has for the 2..32-tile range the checkpoint states. It comes from the reference itself
|
||||
* (tests/mkuocrgolden.py dumps it); outside that range the wide side is taken as last. */
|
||||
static constexpr int8_t kTallLast[][2] = {
|
||||
{1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14},
|
||||
{1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4},
|
||||
{2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16},
|
||||
{3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8},
|
||||
};
|
||||
bool uocr_tall_last(int32_t c, int32_t r) {
|
||||
for (const auto& p : kTallLast)
|
||||
if (p[0] == c && p[1] == r) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* One n defers at most its divisor pairs with c < n/c, at most the divisors below its square
|
||||
* root. Over the 2..32-tile range the checkpoints state the table is built for, no n defers
|
||||
* more than this; uocr_grid's deferred buffer is sized from it and the static_assert below
|
||||
* keeps the bound checked against the table, not empirical. */
|
||||
static constexpr int32_t deferred_pairs_max(int32_t max_n) {
|
||||
int32_t best = 0;
|
||||
for (int32_t n = 2; n <= max_n; ++n) {
|
||||
int32_t cnt = 0;
|
||||
for (const auto& p : kTallLast)
|
||||
if (p[0] < p[1] && (int32_t)p[0] * (int32_t)p[1] == n) ++cnt;
|
||||
if (cnt > best) best = cnt;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
static_assert(deferred_pairs_max(32) <= 8,
|
||||
"uocr_grid's 8-slot deferred buffer must cover the stated 2..32 tile range");
|
||||
|
||||
void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
|
||||
int32_t* cols, int32_t* rows) {
|
||||
*cols = *rows = 1;
|
||||
if (h <= 0 || w <= 0 || min_tiles < 1 || max_tiles < min_tiles) return;
|
||||
const double aspect = (double)w / (double)h;
|
||||
const double area = (double)w * (double)h;
|
||||
const double half = 0.5 * (double)tile * (double)tile;
|
||||
double best = INFINITY;
|
||||
for (int32_t n = min_tiles; n <= max_tiles; ++n) {
|
||||
int32_t deferred[8]; /* the transposed ratios the reference visits last */
|
||||
int32_t n_deferred = 0;
|
||||
auto visit = [&](int32_t c, int32_t r) {
|
||||
const double diff = std::fabs(aspect - (double)c / (double)r);
|
||||
if (diff < best) {
|
||||
best = diff; *cols = c; *rows = r;
|
||||
} else if (diff == best && area > half * (double)n) {
|
||||
*cols = c; *rows = r;
|
||||
}
|
||||
};
|
||||
for (int32_t c = 1; c <= n; ++c) {
|
||||
if (n % c) continue;
|
||||
if (c < n / c && uocr_tall_last(c, n / c)) {
|
||||
/* Defensive: the static_assert proves 8 covers the stated 2..32 range. Beyond
|
||||
* it the reference's tie order is not guaranteed, and a drop is a last resort
|
||||
* against overflow, not a designed path. */
|
||||
if (n_deferred < 8) deferred[n_deferred++] = c;
|
||||
continue;
|
||||
}
|
||||
visit(c, n / c);
|
||||
}
|
||||
for (int32_t k = 0; k < n_deferred; ++k) visit(deferred[k], n / deferred[k]);
|
||||
}
|
||||
}
|
||||
|
||||
/* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles
|
||||
* in row-major order, then the thumbnail. Within a segment, patches are in merge-block order (each
|
||||
* merge x merge block consecutive, dy then dx, as the projector's pixel unshuffle reads them, so
|
||||
@@ -921,6 +1314,240 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::strin
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size,
|
||||
int32_t* image_size, std::string* why) {
|
||||
auto no = [why](const std::string& w) {
|
||||
if (why) *why = w;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
if (c.family != Family::UnlimitedOcr) return no("this model has one picture mode, not two");
|
||||
const int32_t F = c.factor();
|
||||
const bool cr = mode.kind == ImageMode::Base ? false
|
||||
: mode.kind == ImageMode::Gundam ? true
|
||||
: mode.several ? false
|
||||
: c.crop_mode;
|
||||
const int32_t bs = mode.base_size > 0 ? mode.base_size : c.base_size;
|
||||
const int32_t is = mode.image_size > 0 ? mode.image_size : c.image_size;
|
||||
if (cr) {
|
||||
/* The crops are the tile the checkpoint was trained at; the reference's image_size is
|
||||
* that same number, so a request may only restate it. */
|
||||
if (bs % F)
|
||||
return no("base_size " + std::to_string(bs) + " is not a whole number of merged "
|
||||
"patches (" + std::to_string(F) + ")");
|
||||
if (bs < 4 * F)
|
||||
return no("base_size " + std::to_string(bs) + " is under two output rows");
|
||||
if (bs / c.patch != 64 && bs / c.patch != 40)
|
||||
return no("the DeepEncoder serves base grids 64 and 40 (base_size 1024 or 640); "
|
||||
"base_size " + std::to_string(bs) + " is neither");
|
||||
if (mode.image_size > 0 && mode.image_size != c.tile)
|
||||
return no("crop mode cuts pictures into " + std::to_string(c.tile) + "-pixel tiles; "
|
||||
"image_size " + std::to_string(mode.image_size) + " is not one");
|
||||
*crop = true; *base_size = bs; *image_size = c.tile;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (is % F)
|
||||
return no("image_size " + std::to_string(is) + " is not a whole number of merged patches "
|
||||
"(" + std::to_string(F) + ")");
|
||||
if (is < 4 * F) return no("image_size " + std::to_string(is) + " is under two output rows");
|
||||
if (is / c.patch != 64 && is / c.patch != 40)
|
||||
return no("the DeepEncoder serves base grids 64 and 40 (image_size 1024 or 640); "
|
||||
"image_size " + std::to_string(is) + " is neither");
|
||||
if (mode.base_size > 0 && mode.base_size != bs)
|
||||
return no("the base mode pads a page to image_size, not base_size");
|
||||
*crop = false; *base_size = bs; *image_size = is;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows) {
|
||||
bool crop = false;
|
||||
int32_t bs = 0, is = 0;
|
||||
if (uocr_mode(c, mode, &crop, &bs, &is, nullptr) < 0) return -1;
|
||||
const int32_t P = c.patch, D = c.downsample;
|
||||
/* The global view: `g` lines of `g` features, each followed by a newline, then the view
|
||||
* separator (`[tok] * g + [tok]) * g + [tok]`). */
|
||||
const int32_t g = (crop ? bs : is) / P / D;
|
||||
int64_t t = (int64_t)(g + 1) * g + 1;
|
||||
/* The local views, when the picture is tiled: one line per feature row holding every tile's
|
||||
* row, a newline after it (`[tok] * q * cols + [tok]) * q * rows`). */
|
||||
if (crop && (int64_t)cols * rows > 1) {
|
||||
const int32_t q = c.tile / P / D;
|
||||
t += (int64_t)(q * cols + 1) * q * rows;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out) {
|
||||
/* ImageOps.pad: contain() fits the picture inside w x h at its own aspect (PIL's bicubic,
|
||||
* rounded as its round() does), then it is pasted centred on `fill`. */
|
||||
int32_t nw = w, nh = h;
|
||||
if (in.w > 0 && in.h > 0) {
|
||||
const double im_ratio = (double)in.w / (double)in.h;
|
||||
const double dst_ratio = (double)w / (double)h;
|
||||
if (im_ratio != dst_ratio) {
|
||||
if (im_ratio > dst_ratio) {
|
||||
nh = (int32_t)pyround((double)in.h / (double)in.w * (double)w);
|
||||
if (nh == 0) nh = 1;
|
||||
} else {
|
||||
nw = (int32_t)pyround((double)in.w / (double)in.h * (double)h);
|
||||
if (nw == 0) nw = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
const Frame* src = ∈
|
||||
Frame fitted;
|
||||
if (nw != in.w || nh != in.h) {
|
||||
resize_bicubic(in, nw, nh, &fitted);
|
||||
src = &fitted;
|
||||
}
|
||||
out->w = w;
|
||||
out->h = h;
|
||||
out->rgb.assign((size_t)w * (size_t)h * 3, fill);
|
||||
const int32_t x = nw != w ? (int32_t)pyround((double)(w - nw) * 0.5) : 0;
|
||||
const int32_t y = nw != w ? 0 : (int32_t)pyround((double)(h - nh) * 0.5);
|
||||
for (int32_t yy = 0; yy < src->h; ++yy)
|
||||
std::memcpy(out->rgb.data() + ((size_t)(y + yy) * (size_t)w + (size_t)x) * 3,
|
||||
src->rgb.data() + (size_t)yy * (size_t)src->w * 3, (size_t)src->w * 3);
|
||||
}
|
||||
|
||||
/* Unlimited-OCR's picture processor, the reference's infer() and infer_multi() exactly: the
|
||||
* global view is the picture ImageOps.pad-ed to base_size (in the base mode, to image_size,
|
||||
* squared first when that side is a tile or less), and in the gundam mode a picture larger than a
|
||||
* tile is cut the way dynamic_preprocess cuts it. Each view is staged as its feature grid plus
|
||||
* `downsample` patch columns nothing is read from, because the reference's layout puts a newline
|
||||
* after every line of features: one output row per downsample x downsample patches, and the last
|
||||
* column's rows are where those newlines go. The segments are, in the reference's order, the
|
||||
* local grid's lines (one per tile row; a line wider than a pass is cut into chunks of whole
|
||||
* tiles, its last chunk carrying the newline column), then the global view's grid, then the view
|
||||
* separator's single row. */
|
||||
int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
|
||||
std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
const int32_t P = c.patch, M = c.merge;
|
||||
bool crop = false;
|
||||
int32_t base_size = 0, image_size = 0;
|
||||
RAD_TRY(uocr_mode(c, mode, &crop, &base_size, &image_size, why));
|
||||
if (f.w <= 0 || f.h <= 0) {
|
||||
if (why) *why = "the picture has no size";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int32_t q = c.tile / P; /* a tile's patch rows */
|
||||
int32_t cols = 1, rows = 1;
|
||||
const bool tiled = crop && (f.w > c.tile || f.h > c.tile);
|
||||
if (tiled) uocr_grid(f.h, f.w, c.min_tiles, c.max_tiles, c.tile, &cols, &rows);
|
||||
|
||||
/* The global view. The base mode squares a page of a tile or less before padding it, as the
|
||||
* reference's multi-page path does. */
|
||||
Frame global;
|
||||
if (crop) {
|
||||
pad_bicubic(f, base_size, base_size, 127, &global);
|
||||
} else if (image_size <= c.tile) {
|
||||
/* The reference's multi-page path squares the page first, so a non-square page is
|
||||
* aspect-distorted by this resize, and the pad below is a no-op by construction (the
|
||||
* square already is the pad target). Square-first kept for reference parity. */
|
||||
Frame sq;
|
||||
resize_bicubic(f, image_size, image_size, &sq);
|
||||
pad_bicubic(sq, image_size, image_size, 127, &global);
|
||||
} else {
|
||||
pad_bicubic(f, image_size, image_size, 127, &global);
|
||||
}
|
||||
const int32_t g = (crop ? base_size : image_size) / P;
|
||||
if ((int64_t)g * (g + 4) > c.max_patches) {
|
||||
if (why) *why = "the global view's " + std::to_string((long long)g * (g + 4)) +
|
||||
" patches are more than one encoder pass holds (" +
|
||||
std::to_string(c.max_patches) + ")";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ToTensor then Normalize, in f32: (u / 255 - mean) / std, rounded to bf16. */
|
||||
uint16_t lut[3][256];
|
||||
uint32_t lut32[3 * 256];
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int v = 0; v < 256; ++v) {
|
||||
const float p = (float)v / 255.0f;
|
||||
lut[ch][v] = rad_f32_to_bf16((p - c.mean[ch]) / c.stdv[ch]);
|
||||
lut32[ch * 256 + v] = lut[ch][v];
|
||||
}
|
||||
const bool simd = mm_use_avx2();
|
||||
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Image;
|
||||
it->patch_dim = c.patch_dim();
|
||||
it->rope_1d = true;
|
||||
it->patch_raster = true;
|
||||
int64_t seg_row = 0;
|
||||
/* One segment of `gh` x `gw` patches from (x0, y0) of `src`, of which the first `real_w`
|
||||
* patches a row carry pixels; the rest are the newline column. */
|
||||
auto append = [&](const Frame& src, int32_t x0, int32_t y0, int32_t gh, int32_t gw,
|
||||
int32_t real_w, bool sep = false) {
|
||||
it->segments.push_back({ gh, gw, it->n_patch, sep });
|
||||
it->seg_at.push_back((int32_t)seg_row);
|
||||
it->expand.insert(it->expand.end(), (size_t)(gh / M) * (size_t)(gw / M), c.tok_image);
|
||||
seg_row += (int64_t)(gh / M) * (gw / M);
|
||||
it->n_patch += (int64_t)gh * gw;
|
||||
const size_t at = it->pixels.size();
|
||||
it->pixels.resize(at + (size_t)gh * (size_t)gw * (size_t)it->patch_dim, 0);
|
||||
uint16_t* dst = it->pixels.data() + at;
|
||||
/* Each patch row writes its own disjoint run of dst, in the same order, so splitting the
|
||||
* rows across threads is bit-exact. */
|
||||
run_rows(gh, [&](int32_t py) {
|
||||
for (int32_t px = 0; px < real_w; ++px) {
|
||||
uint16_t* pp = dst + ((size_t)py * (size_t)gw + (size_t)px) * (size_t)it->patch_dim;
|
||||
const int32_t py0 = y0 + py * P, px0 = x0 + px * P;
|
||||
for (int y = 0; y < P; ++y) {
|
||||
const uint8_t* row = src.rgb.data() +
|
||||
((size_t)(py0 + y) * (size_t)src.w + (size_t)px0) * 3;
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
if (simd) {
|
||||
patch_row(row, pp + (size_t)y * P, P, (size_t)P * P, lut32, &lut[0][0]);
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
(void)simd;
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
const uint8_t* r = row + (size_t)ch;
|
||||
uint16_t* q = pp + ((size_t)ch * P + (size_t)y) * P;
|
||||
for (int x = 0; x < P; ++x) q[x] = lut[ch][r[(size_t)x * 3]];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (tiled) {
|
||||
Frame big;
|
||||
resize_bicubic(f, cols * c.tile, rows * c.tile, &big);
|
||||
/* A chunk of a line must fit one pass: q rows of q patches a tile, plus the newline
|
||||
* column its last chunk holds. */
|
||||
int64_t per_row = c.max_patches / q;
|
||||
const int64_t chunk = per_row > 4 ? (per_row - 4) / q : 0;
|
||||
if (chunk < 1) {
|
||||
if (why) *why = "one encoder pass holds no line of " + std::to_string(q) +
|
||||
"-patch tiles (" + std::to_string(c.max_patches) + " patches)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int32_t r = 0; r < rows; ++r)
|
||||
for (int32_t c0 = 0; c0 < cols; c0 += (int32_t)chunk) {
|
||||
const int32_t n = std::min<int32_t>((int32_t)chunk, cols - c0);
|
||||
const bool last = c0 + n == cols;
|
||||
append(big, c0 * c.tile, r * c.tile, q, q * n + (last ? 4 : 0), q * n);
|
||||
}
|
||||
}
|
||||
append(global, 0, 0, g, g + 4, g);
|
||||
/* The view separator: one output row, from a grid of exactly one merged cell and no pixels. */
|
||||
append(global, 0, 0, M, M, 0, /*sep=*/true);
|
||||
|
||||
it->n_seg = (int32_t)it->segments.size();
|
||||
it->grid_t = 1;
|
||||
it->grid_h = it->segments[0].h;
|
||||
it->grid_w = it->segments[0].w;
|
||||
it->rows_h = it->grid_h / M;
|
||||
it->rows_w = it->grid_w / M;
|
||||
it->seg_rows = it->rows_h * it->rows_w;
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GLM-5.3's image processor (transformers' Glm5NextImageProcessor, torchvision backend): the
|
||||
* picture, resized only when its size changes, in the top left of a canvas of zero bytes, which
|
||||
* the normalisation turns into each channel's -mean / std as it does the reference's padding. */
|
||||
@@ -960,11 +1587,17 @@ int Processor::image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::s
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
|
||||
const ImageMode& mode) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (mode.kind != ImageMode::Default && c.family != Family::UnlimitedOcr) {
|
||||
if (why) *why = "this model has one picture mode; images_config names one of two";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why);
|
||||
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
|
||||
if (c.family == Family::Glm5Next) return image_glm5next(f, out, why);
|
||||
if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why);
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
|
||||
&h, &w, why));
|
||||
@@ -1140,7 +1773,12 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
|
||||
}
|
||||
|
||||
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
|
||||
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels) const {
|
||||
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels,
|
||||
const ImageMode& mode) const {
|
||||
if (mode.kind != ImageMode::Default && cfg_.family != Family::UnlimitedOcr) {
|
||||
if (why) *why = "this model has one picture mode; images_config names one of two";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (image_tokens != 0) {
|
||||
if (cfg_.family == Family::Glm5Next) {
|
||||
if (why) *why = "this model's image token budget is the server's (--image-tokens), "
|
||||
@@ -1169,7 +1807,7 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
|
||||
}
|
||||
if (cfg_.family == Family::Gemma4)
|
||||
return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why);
|
||||
return image_from(f, out, why);
|
||||
return image_from(f, out, why, mode);
|
||||
}
|
||||
|
||||
int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
|
||||
|
||||
+74
-5
@@ -56,6 +56,18 @@ enum class Kind { Image, Video, Audio };
|
||||
* own, followed by the whole picture at the budgeted size as a thumbnail. Patches
|
||||
* (y, x, channel) normalised by the mean and deviation, resized with torchvision's
|
||||
* fixed-point bicubic; images only, and the tokens rotate at their positions.
|
||||
* UnlimitedOcr
|
||||
* Unlimited-OCR's DeepSeek-OCR shape, in the checkpoint's two modes (ImageMode): the
|
||||
* picture padded (ImageOps.pad) to base_size x base_size on a 127 grey as the global
|
||||
* view, and, in the gundam mode, a picture larger than one tile cut into min_tiles..
|
||||
* max_tiles tile x tile crops at the tile in the ratio nearest its own (its
|
||||
* dynamic_preprocess). The SAM neck downsamples by `downsample`, so patch * downsample
|
||||
* is one output row. A view's rows are laid out as the reference's feature grid plus a
|
||||
* column of newlines, which is why every segment carries `downsample` extra patch
|
||||
* columns that nothing is read from: patches are raster order (Item::patch_raster), one
|
||||
* patch (channel, y, x), each value (u / 255 - mean) / std in f32, rounded to bf16.
|
||||
* Every placeholder is one id (the picture marker itself); the tokens rotate at their
|
||||
* positions.
|
||||
* Glm5Next GLM-5.3's: a canvas whose sides are multiples of patch * merge and whose tokens fall
|
||||
* in [min_image_tokens, max_image_tokens] (the sides rounded up, a picture under the
|
||||
* floor grown, one over the budget fitted by the reference's search); the picture keeps
|
||||
@@ -64,7 +76,7 @@ enum class Kind { Image, Video, Audio };
|
||||
* bottom, is zero bytes. Patches as QwenVL's. Images only, spelled <begin_of_image>
|
||||
* placeholders <end_of_image>, the tokens at their positions (the language model has no
|
||||
* rotary). */
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, Glm5Next };
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next };
|
||||
|
||||
struct VisionConfig {
|
||||
Family family = Family::QwenVL;
|
||||
@@ -91,6 +103,17 @@ struct VisionConfig {
|
||||
double max_pixels_tolerance = 0.0;
|
||||
int64_t max_segment_patches = 0;
|
||||
|
||||
/* UnlimitedOcr: the two modes' sizes, from the checkpoint's preprocessor config. The gundam
|
||||
* mode pads the global view to `base_size` and cuts crops at `tile`; the base mode (a page of
|
||||
* a multi-page document) pads the whole picture to `image_size`. `downsample` is the SAM
|
||||
* neck's ratio: one output row is `patch * downsample` pixels a side. `crop_mode` is the
|
||||
* deployment's mode when a request names none. */
|
||||
int32_t base_size = 0, image_size = 0, downsample = 0;
|
||||
bool crop_mode = false;
|
||||
/* The vocabulary's spelling of the picture marker (`processor.image_token`); every
|
||||
* placeholder of a picture is that one id. */
|
||||
std::string image_token = "<image>";
|
||||
|
||||
/* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image
|
||||
* is one segment and a segment is never split, so the image band's ceiling is lowered to fit
|
||||
* it. `max_source_pixels` bounds what the decoder may hold before any resize. */
|
||||
@@ -112,6 +135,20 @@ struct VisionConfig {
|
||||
int from_meta(const RadModelMeta& m, std::string* why);
|
||||
};
|
||||
|
||||
/* Which picture processor a request gets, for a checkpoint that has more than one: Unlimited-OCR
|
||||
* states two modes and the reference names them gundam (one picture: the global view at base_size
|
||||
* plus crops) and base (a page of a multi-page document: the global view only, at image_size).
|
||||
* `Default` is the deployment's (`VisionConfig::crop_mode`), or base when `several` says the
|
||||
* request carries more than one picture; a request may pick either mode and, with it, the sizes
|
||||
* the checkpoint states differently. `base_size` and `image_size` of 0 keep the mode's own. A
|
||||
* processor with one mode refuses a named mode and ignores `several`. */
|
||||
struct ImageMode {
|
||||
enum Kind : int32_t { Default = 0, Gundam = 1, Base = 2 };
|
||||
int32_t kind = Default;
|
||||
int32_t base_size = 0, image_size = 0;
|
||||
bool several = false;
|
||||
};
|
||||
|
||||
/* The audio feature extractor family, from the container's audio_config.model_type. The
|
||||
* families differ in the spectrogram and in how a clip's frames are laid out for the encoder;
|
||||
* the Item they produce is shared.
|
||||
@@ -204,14 +241,20 @@ struct Item {
|
||||
* thumbnail): each is `h` x `w` patches starting at patch `patch0`. Empty means every segment
|
||||
* is grid_h x grid_w. The rest of the engine reads segments only through the accessors below,
|
||||
* so both forms look alike. */
|
||||
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; };
|
||||
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; bool sep = false; };
|
||||
std::vector<Segment> segments;
|
||||
/* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
|
||||
* on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */
|
||||
bool rope_1d = false;
|
||||
/* Patches are in raster order (row by row), not merge-block order: the coordinate planes
|
||||
* invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */
|
||||
bool patch_raster = false;
|
||||
|
||||
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
|
||||
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
|
||||
/* The one-output-row view separator (Unlimited-OCR stages it as a merge-grid cell of zeros).
|
||||
* A square segment is not enough: a chunked line of one tile is q x q too. */
|
||||
bool seg_is_sep(int32_t s) const { return !segments.empty() && segments[(size_t)s].sep; }
|
||||
/* Segment s's first patch and first output row; s == n_seg is the end of the item. */
|
||||
int64_t patch_at(int32_t s) const {
|
||||
if (segments.empty()) return (int64_t)s * grid_h * grid_w;
|
||||
@@ -319,13 +362,15 @@ public:
|
||||
|
||||
/* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a
|
||||
* processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first
|
||||
* scales a larger picture down to that area with PIL's bicubic. */
|
||||
* scales a larger picture down to that area with PIL's bicubic. `mode` picks one of the
|
||||
* checkpoint's picture modes where it has more than one (Unlimited-OCR). */
|
||||
int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr<Item>* out,
|
||||
std::string* why, int64_t max_pixels = 0) const;
|
||||
std::string* why, int64_t max_pixels = 0, const ImageMode& mode = ImageMode{}) const;
|
||||
int video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* From an already-decoded picture or frame list; for tests. */
|
||||
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
|
||||
const ImageMode& mode = ImageMode{}) const;
|
||||
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* A picture in the video VAE's own form: decoded under the same `max_source_pixels` guard as
|
||||
@@ -381,6 +426,8 @@ private:
|
||||
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_unlimitedocr(const Frame& f, const ImageMode& mode, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
|
||||
int32_t tok_thumbnail_ = -1;
|
||||
@@ -444,6 +491,28 @@ void cap_area(const Frame& in, int64_t max_pixels, Frame* out);
|
||||
* aspect, the larger grid of two equally near when the picture fills over half of it. */
|
||||
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
|
||||
int32_t* cols, int32_t* rows);
|
||||
/* Whether the reference's ratio set visits the tall side (c, r), c < r, of a transposed pair after
|
||||
* the wide one: the only tie two ratios of one tile count can have. From the reference itself. */
|
||||
bool uocr_tall_last(int32_t c, int32_t r);
|
||||
/* Unlimited-OCR's tile grid (its dynamic_preprocess): the min..max-tile grid nearest the picture's
|
||||
* aspect, the one whose area the picture covers over half of when two are equally near, exactly
|
||||
* as the reference's set ordering resolves it. The reference calls it only for a picture larger
|
||||
* than one tile; this answers for any size. */
|
||||
void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
|
||||
int32_t* cols, int32_t* rows);
|
||||
/* The placeholders a picture takes: the global view's rows plus its separator, and, when tiled,
|
||||
* one line of `cols` tiles per feature row with a newline after it. `cols` * `rows` is the tile
|
||||
* grid. */
|
||||
int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows);
|
||||
/* The mode `mode` resolves to for this deployment; RAD_E_INVAL names an unsupported size. */
|
||||
int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size,
|
||||
int32_t* image_size, std::string* why);
|
||||
/* Runs the resample and patch staging on their scalar path even where AVX2 is available, for a
|
||||
* test that compares the two; process-wide. */
|
||||
void mm_force_scalar(bool on);
|
||||
/* PIL's ImageOps.pad: `in` fitted inside w x h keeping its aspect (its bicubic), centred on `fill`
|
||||
* in the channels' order (127 127 127 for the reference's 0.5 mean). */
|
||||
void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out);
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
@@ -461,6 +461,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;
|
||||
@@ -471,7 +474,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);
|
||||
}
|
||||
|
||||
+45
-5
@@ -129,6 +129,8 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
|
||||
* embedding takes Ram or Vram. */
|
||||
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
|
||||
const char* table_placement_name(TablePlacement p);
|
||||
/* --attn-prefill-fp8's spelling of RAD_ATTN_FP8_* bits: off, qk, pv or both. */
|
||||
const char* attn_prefill_fp8_name(int bits);
|
||||
/* --draft-window: how many drafts a step verifies per sequence (core/sched/draft.h).
|
||||
* Fixed every sequence drafts --num-speculative-tokens.
|
||||
* Adaptive that is the ceiling; head depth per step and each sequence's stop follow measured
|
||||
@@ -390,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.
|
||||
@@ -414,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. */
|
||||
@@ -456,6 +461,14 @@ public:
|
||||
* region safely through in-order launch; a second lane is a second stream and needs its own.
|
||||
* Two when the architecture declared a buffer rad_buf_concurrent. */
|
||||
int32_t scratch_regions = 1;
|
||||
/* Region 1's size when there are two: the largest device scratch of an op the second lane may
|
||||
* issue. By Ctx::lane1_'s rule 3 such an op touches only rad_buf_concurrent buffers, so an op
|
||||
* with any other transient buffer never runs there; one naming no transient buffer counts.
|
||||
* At most scratch_bytes; -1 (a program not built by the Builder) means scratch_bytes. */
|
||||
int64_t scratch_bytes_lane1 = -1;
|
||||
/* The second lane's window (rad_lane1_window_begin): the first and last op handle lane 1 may run;
|
||||
* -1 when the architecture declared none (concurrent buffers then live for the whole program). */
|
||||
int32_t lane1_w0 = -1, lane1_w1 = -1;
|
||||
|
||||
/* Everything that resolved to nothing, reported whole rather than stopping at the first
|
||||
* failure (spec §3.1). Structured because the domains are reported differently: a device miss
|
||||
@@ -620,11 +633,22 @@ struct SamplingParams {
|
||||
|
||||
/* The control vector (core/cvec.h): whether this request's steps project the vector found for
|
||||
* this deployment out of the residual stream. The server sets it from the request's
|
||||
* `control_vector` field (`experimental_speed_projection` is Strata's spelling of the same
|
||||
* switch), or from the deployment's runtime default when the request names none; it needs no
|
||||
* reload and leaves the graph untouched. A deployment with no vector refuses `true` at
|
||||
* admission rather than serving the stock model. */
|
||||
* `control_vector` field, or from the deployment's runtime default when the request names
|
||||
* none. A deployment with no vector refuses `true` at admission. */
|
||||
bool use_control_vector = false;
|
||||
/* The windowed no-repeat-ngram ban (core/sample/sampler.h, `sample_ngram_ban`): a token that
|
||||
* would complete an `ngram_ban_n`-gram already present in the last `ngram_window` tokens of
|
||||
* the sequence is banned. `ngram_ban_n` 0 is off, the default; `ngram_window` <= 0 searches
|
||||
* the whole staged history (the un-windowed processor). Unlimited-OCR's generation_config
|
||||
* asks for 35 and 128 (the model card's document mode uses 1024). */
|
||||
int ngram_ban_n = 0;
|
||||
int ngram_window = 0;
|
||||
/* The ids exempt from that ban: the reference processor's whitelist
|
||||
* (SlidingWindowNoRepeatNgramProcessor's `whitelist_token_ids`, whose set is removed from
|
||||
* the banned set after it is built -- modeling_unlimitedocr.py:359,379). Global token ids,
|
||||
* duplicates ignored. Empty (the default) is off: the ban is then bit-identical to the
|
||||
* no-whitelist form. */
|
||||
std::vector<int32_t> ngram_whitelist;
|
||||
};
|
||||
|
||||
/* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers
|
||||
@@ -741,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.
|
||||
@@ -787,6 +814,11 @@ 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. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
int64_t host_pool_mib = 0;
|
||||
int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */
|
||||
/* File tier for weights: what fits in neither the VRAM slab nor the pinned host pool is read
|
||||
@@ -881,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) ----------------
|
||||
*
|
||||
|
||||
+12
-5
@@ -5,15 +5,18 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions) {
|
||||
int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions,
|
||||
int64_t scratch_bytes1) {
|
||||
release();
|
||||
if (plan_bytes < 0 || scratch_bytes < 0 || regions < 1) return RAD_E_INVAL;
|
||||
if (scratch_bytes1 < 0 || scratch_bytes1 > scratch_bytes) scratch_bytes1 = scratch_bytes;
|
||||
|
||||
/* Scratch starts on a page boundary, so a workspace gets 4 KiB alignment for at most one
|
||||
* page of padding. */
|
||||
const int64_t off = align_up(plan_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t tail = pitch * regions;
|
||||
const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t pitch1 = align_up(scratch_bytes1, RAD_ALIGN_UNIT);
|
||||
const int64_t tail = pitch + pitch1 * (regions - 1);
|
||||
int64_t total = off + tail;
|
||||
|
||||
/* Never zero bytes: a null base would turn a plan bug into an anonymous segfault. */
|
||||
@@ -33,6 +36,8 @@ int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions
|
||||
scratch_off_ = off;
|
||||
scratch_bytes_ = scratch_bytes;
|
||||
scratch_pitch_ = pitch;
|
||||
scratch_bytes1_ = regions > 1 ? scratch_bytes1 : 0;
|
||||
scratch_pitch1_ = regions > 1 ? pitch1 : 0;
|
||||
scratch_regions_ = regions;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -87,8 +92,10 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out)
|
||||
/* The staging region sits above every buffer, so it is a separate term. */
|
||||
if (P.arena_stage_bytes > 0 && P.arena_stage_off >= 0)
|
||||
dev_bytes = std::max(dev_bytes, P.arena_stage_off + P.arena_stage_bytes);
|
||||
int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) +
|
||||
align_up(P.scratch_bytes, RAD_ALIGN_UNIT) * std::max<int64_t>(P.scratch_regions, 1);
|
||||
const int64_t s1 = P.scratch_bytes_lane1 < 0 || P.scratch_bytes_lane1 > P.scratch_bytes
|
||||
? P.scratch_bytes : P.scratch_bytes_lane1;
|
||||
int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) + align_up(P.scratch_bytes, RAD_ALIGN_UNIT) +
|
||||
align_up(s1, RAD_ALIGN_UNIT) * (std::max<int64_t>(P.scratch_regions, 1) - 1);
|
||||
if (total == 0) total = RAD_ALIGN_UNIT; /* Arena::init's floor, for the same reason */
|
||||
if (dev_out) *dev_out = dev_bytes;
|
||||
if (total_out) *total_out = total;
|
||||
|
||||
+13
-4
@@ -25,18 +25,25 @@ public:
|
||||
Arena& operator=(const Arena&) = delete;
|
||||
|
||||
/* `kind` is a RAD_MEM_* class: RAD_MEM_DEVICE for the device arena, RAD_MEM_HOST for the
|
||||
* second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions of
|
||||
* `scratch_bytes` each sit at the tail, one per lane. */
|
||||
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1);
|
||||
* second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions sit at the
|
||||
* tail, one per lane: region 0 of `scratch_bytes`, the others of `scratch_bytes1` (-1: the same;
|
||||
* Program::scratch_bytes_lane1). */
|
||||
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1,
|
||||
int64_t scratch_bytes1 = -1);
|
||||
void release();
|
||||
|
||||
char* base() const { return base_; }
|
||||
/* Region `r`, or region 0 when the arena holds fewer. */
|
||||
void* scratch(int r = 0) const {
|
||||
if (!base_) return nullptr;
|
||||
return base_ + scratch_off_ + (r > 0 && r < scratch_regions_ ? r * scratch_pitch_ : 0);
|
||||
return base_ + scratch_off_ +
|
||||
(r > 0 && r < scratch_regions_ ? scratch_pitch_ + (r - 1) * scratch_pitch1_ : 0);
|
||||
}
|
||||
/* Region 0's size (the program's largest kernel), or region `r`'s. */
|
||||
int64_t scratch_bytes() const { return scratch_bytes_; }
|
||||
int64_t scratch_bytes(int r) const {
|
||||
return r > 0 && r < scratch_regions_ ? scratch_bytes1_ : scratch_bytes_;
|
||||
}
|
||||
int scratch_regions() const { return scratch_regions_; }
|
||||
int64_t bytes() const { return bytes_; }
|
||||
bool live() const { return base_ != nullptr; }
|
||||
@@ -48,6 +55,8 @@ private:
|
||||
int64_t scratch_off_ = 0;
|
||||
int64_t scratch_bytes_ = 0;
|
||||
int64_t scratch_pitch_ = 0; /* scratch_bytes_ padded to RAD_ALIGN_UNIT */
|
||||
int64_t scratch_bytes1_ = 0; /* each region past 0 */
|
||||
int64_t scratch_pitch1_ = 0;
|
||||
int scratch_regions_ = 1;
|
||||
};
|
||||
|
||||
|
||||
+17
-5
@@ -153,13 +153,20 @@ int Ctx::bind_arena() {
|
||||
int64_t dev_bytes = 0, total = 0;
|
||||
arena_plan_bytes(P, &dev_bytes, &total);
|
||||
|
||||
RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1)));
|
||||
RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1),
|
||||
P.scratch_bytes_lane1));
|
||||
/* The arena is in no pool and scales with max_tok, so core/mem/vram_budget.cpp charges it by
|
||||
* name rather than leaving it to --gpu-headroom-mib. This log line must agree with that
|
||||
* charge. */
|
||||
RAD_INFO("arena: %s device + %d x %s scratch = %s, charged to the VRAM budget before it was "
|
||||
"split", humanb(dev_bytes).c_str(), arena_.scratch_regions(),
|
||||
humanb(P.scratch_bytes).c_str(), humanb(total).c_str());
|
||||
if (arena_.scratch_regions() > 1)
|
||||
RAD_INFO("arena: %s device + %s scratch + %s for the second lane = %s, charged to the VRAM "
|
||||
"budget before it was split", humanb(dev_bytes).c_str(),
|
||||
humanb(P.scratch_bytes).c_str(), humanb(arena_.scratch_bytes(1)).c_str(),
|
||||
humanb(total).c_str());
|
||||
else
|
||||
RAD_INFO("arena: %s device + %s scratch = %s, charged to the VRAM budget before it was "
|
||||
"split", humanb(dev_bytes).c_str(), humanb(P.scratch_bytes).c_str(),
|
||||
humanb(total).c_str());
|
||||
|
||||
if (host_hw > 0) {
|
||||
/* RAD_MEM_HOST_MAPPED, not RAD_MEM_HOST: nothing copies between the two arenas, so device
|
||||
@@ -333,6 +340,8 @@ int Ctx::bind_ops() {
|
||||
p.billed = (oi.op == "all_reduce");
|
||||
p.collective = p.billed;
|
||||
p.lora_site = oi.lora_site;
|
||||
p.order = oi.anchor > 0 && (size_t)oi.anchor < P.ops.size() ? P.ops[(size_t)oi.anchor].index
|
||||
: oi.index;
|
||||
|
||||
for (const Band& b : oi.bands) band_table_.push_back(b.hi);
|
||||
|
||||
@@ -908,6 +917,7 @@ int Ctx::lane_join(int from, int to) {
|
||||
RAD_TRY(rad_event_record(lane_ev_[from], fs));
|
||||
RAD_TRY(rad_event_wait(ts, lane_ev_[from]));
|
||||
scratch_open_[from] = false; /* `to` is now behind every scratch user `from` issued */
|
||||
if (from == 1 && to == 0) lane1_pending_ = false;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -918,7 +928,7 @@ int Ctx::lane_join(int from, int to) {
|
||||
* field added to RadBatch changes its size: decide whether the key must read it, then update the
|
||||
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
|
||||
* (below). */
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 336,
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 360,
|
||||
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
|
||||
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
|
||||
@@ -949,6 +959,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
|
||||
/* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the
|
||||
* two are different passes. The slots themselves are read on the card. */
|
||||
ptr(b->lora_slot);
|
||||
/* Zero issues no projection op (RadBatch::control_vector). */
|
||||
mix((uint64_t)b->control_vector);
|
||||
for (int g = 0; g < b->n_kv_groups; ++g) {
|
||||
const RadKVGroupBatch& k = b->kv[g];
|
||||
mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table);
|
||||
|
||||
+13
-2
@@ -94,6 +94,9 @@ struct OpPlan {
|
||||
bool billed = false;
|
||||
/* Runtime LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */
|
||||
int32_t lora_site = -1;
|
||||
/* Its position in the declared order, or its anchor's for a core-appended op: what the second
|
||||
* lane's window (Program::lane1_w0..lane1_w1) is checked against. */
|
||||
int32_t order = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ routing handoff */
|
||||
@@ -294,6 +297,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_; }
|
||||
@@ -552,6 +557,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;
|
||||
|
||||
@@ -578,7 +586,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);
|
||||
@@ -625,7 +632,8 @@ private:
|
||||
* 3. The buffer planner packs from one linear order, so two lanes can alias arena bytes
|
||||
* through buffers with disjoint declared lifetimes. The architecture passes every buffer
|
||||
* its second lane touches to `rad_buf_concurrent`, which makes it live for the whole
|
||||
* program.
|
||||
* program, or, where the architecture declares the second lane's window
|
||||
* (rad_lane1_window_begin / _end), across the window and its own declared uses.
|
||||
*
|
||||
* 4. A slice must land in the same bucket-table band as the whole, or it picks a kernel with
|
||||
* a different summation order and silently changes output. `--debug-graph` prints a model's
|
||||
@@ -647,6 +655,9 @@ 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; 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;
|
||||
* on each lane those complete no later than the last one. So a device op with a host-domain
|
||||
|
||||
+32
-2
@@ -592,6 +592,25 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
? "has no host kernel for this band, and the placement planner put "
|
||||
"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 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) {
|
||||
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_ && outside) {
|
||||
const int js = lane_join(1, 0);
|
||||
if (js < 0)
|
||||
return abort_step_msg(h, js, "joining the second lane outside its window failed");
|
||||
}
|
||||
}
|
||||
if (lane_ == 1) lane1_pending_ = true;
|
||||
|
||||
/* The row's DIV on the ranged parameter held at the band's upper bound, maybe not here. */
|
||||
if (ip.ranged_div > 1 && n % ip.ranged_div != 0)
|
||||
return abort_step_msg(h, RAD_E_SHAPE,
|
||||
@@ -884,7 +903,18 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
* correctness. That also covers lane 0 before lane 1 exists, since a lane built later has
|
||||
* nothing ordering it behind lane 0's earlier work. */
|
||||
if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST && arena_.scratch_regions() > 1) {
|
||||
/* Per-lane regions: nothing to order. */
|
||||
/* Per-lane regions: nothing to order. Region 1 holds what an op the second lane may issue
|
||||
* asked for at declare (Program::scratch_bytes_lane1); a larger request there comes from an
|
||||
* op with a transient buffer outside rad_buf_concurrent, which breaks Ctx::lane1_'s rule 3
|
||||
* in its buffers too, so it is refused by name rather than let overrun the region. */
|
||||
if (ip.args.scratch_bytes > arena_.scratch_bytes(lane_)) {
|
||||
return abort_step_msg(h, RAD_E_SCRATCH,
|
||||
fmt("kernel %s at n=%lld asks for %lld bytes of scratch on lane %d, whose region "
|
||||
"holds %lld: an op on the second lane may touch only buffers named to "
|
||||
"rad_buf_concurrent (Ctx::lane1_ rule 3)",
|
||||
ip.row && ip.row->info ? ip.row->info->name : "?", (long long)n,
|
||||
(long long)ip.args.scratch_bytes, lane_, (long long)arena_.scratch_bytes(lane_)));
|
||||
}
|
||||
ip.args.scratch = scratch_take(lane_, ip.args.scratch_bytes);
|
||||
} else if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST) {
|
||||
ip.args.scratch = scratch_take(0, ip.args.scratch_bytes);
|
||||
@@ -1058,7 +1088,7 @@ void* Ctx::scratch_take(int region, int64_t bytes) {
|
||||
constexpr int64_t kAlign = 256;
|
||||
const int64_t need = (bytes + kAlign - 1) / kAlign * kAlign;
|
||||
int64_t off = scratch_cur_[region];
|
||||
if (off + need > arena_.scratch_bytes()) off = 0;
|
||||
if (off + need > arena_.scratch_bytes(region)) off = 0;
|
||||
scratch_cur_[region] = off + need;
|
||||
return (char*)arena_.scratch(region) + off;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int3
|
||||
switch (gp->kind) {
|
||||
case RAD_KV_FULL:
|
||||
case RAD_KV_WINDOW:
|
||||
case RAD_KV_RING:
|
||||
b.rank = 4;
|
||||
b.shape[0] = gp->n_blocks;
|
||||
b.shape[1] = d.n_head_kv;
|
||||
|
||||
@@ -226,8 +226,18 @@ int TierExec::device_init() {
|
||||
bool ev = rad_event_create(&ev_compute_) == RAD_OK && rad_event_create(&ev_copy_) == RAD_OK &&
|
||||
rad_event_create(&ev_restore_) == RAD_OK;
|
||||
for (int i = 0; i < kRing && ev; ++i) ev = rad_event_create(&ring_ev_[i]) == RAD_OK;
|
||||
if (verify_rep_) vrep_ = (char*)rad_dev_alloc(copy_idx_ * rep_bytes_, RAD_MEM_HOST_PINNED);
|
||||
if (!stage_ || !idx_dev_ || !idx_host_ || !ev || (verify_rep_ && !vrep_)) {
|
||||
/* The verify scratch is a diagnostic's: without it the replicated groups go unchecked, and
|
||||
* the tiers run as they would without RADIANCE_DEBUG_TIER_VERIFY. */
|
||||
if (verify_rep_) {
|
||||
vrep_ = (char*)rad_dev_alloc(copy_idx_ * rep_bytes_, RAD_MEM_HOST_PINNED);
|
||||
if (!vrep_) {
|
||||
RAD_WARN("kv tiers: RADIANCE_DEBUG_TIER_VERIFY: no pinned host memory (%s) for this "
|
||||
"rank's copy of the replicated groups, so they are not compared",
|
||||
humanb(copy_idx_ * rep_bytes_).c_str());
|
||||
verify_rep_ = false;
|
||||
}
|
||||
}
|
||||
if (!stage_ || !idx_dev_ || !idx_host_ || !ev) {
|
||||
release_device();
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <cfloat>
|
||||
#include <cmath>
|
||||
#include <numeric>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -51,12 +52,6 @@ static uint64_t stream_key(uint32_t stream) {
|
||||
}
|
||||
}
|
||||
|
||||
/* rad_sample_uniform01's bits before the float conversion: one splitmix64 round over
|
||||
* ((seed ^ key) * golden ratio + pos), cheap and stateless enough for a kernel. */
|
||||
uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream) {
|
||||
return rad_sample_splitmix64((seed ^ stream_key(stream)) * 0x9E3779B97F4A7C15ull + pos);
|
||||
}
|
||||
|
||||
float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream) {
|
||||
/* 24 bits: 32 bits divided by 2^32 can round to 1.0f, which walks off the end of an inverse
|
||||
* CDF. Calls rad_sample_uniform01 itself so host and device cannot drift apart. */
|
||||
@@ -526,8 +521,48 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) {
|
||||
return (int32_t)best;
|
||||
}
|
||||
|
||||
/* ================================================================== the chain */
|
||||
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
|
||||
int32_t window, const uint32_t* whitelist, int64_t wl_words) {
|
||||
if (n <= 0 || !history || n_history < (int64_t)n) return;
|
||||
const int64_t len = n_history;
|
||||
const int64_t win = (window > 0 && window < len) ? window : len;
|
||||
const int64_t start = len - win, end = len - n + 1;
|
||||
if (end <= start) return;
|
||||
const int64_t plen = (int64_t)n - 1, p0 = len - plen;
|
||||
|
||||
/* The set of tokens a continuation would complete an n-gram with, as the reference builds it:
|
||||
* every n-gram in the window whose first n-1 tokens equal the current prefix contributes the
|
||||
* token after them. */
|
||||
std::unordered_set<int32_t> banned;
|
||||
for (int64_t idx = start; idx < end; ++idx) {
|
||||
bool match = true;
|
||||
for (int64_t j = 0; j < plen; ++j) {
|
||||
if (history[idx + j] != history[p0 + j]) { match = false; break; }
|
||||
}
|
||||
if (match) banned.insert(history[idx + plen]);
|
||||
}
|
||||
|
||||
/* The reference's `banned.difference_update(self.whitelist)`, before any -inf: a token whose
|
||||
* whitelist bit is set is never banned. A bit past the plane is not set, so a token outside
|
||||
* it stays banned, as an id the reference's set does not contain. */
|
||||
if (whitelist && wl_words > 0) {
|
||||
for (auto it = banned.begin(); it != banned.end();) {
|
||||
const int64_t id = *it;
|
||||
if (id >= 0 && (id >> 5) < wl_words &&
|
||||
(whitelist[(size_t)(id >> 5)] >> ((uint32_t)id & 31u)) & 1u)
|
||||
it = banned.erase(it);
|
||||
else
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (banned.empty()) return;
|
||||
s.sorted = false; /* a -infinity candidate belongs after every finite one */
|
||||
for (Candidate& c : s.c)
|
||||
if (banned.count(c.id) != 0) c.logit = -INFINITY;
|
||||
}
|
||||
|
||||
/* ================================================================== the chain */
|
||||
int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
|
||||
ChainOrder order) {
|
||||
/* Penalties first in both orders: they act on raw logits, the cuts on probabilities. */
|
||||
@@ -547,6 +582,11 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe
|
||||
in.dry_breakers ? *in.dry_breakers : kNone);
|
||||
}
|
||||
|
||||
/* The n-gram ban, after the penalties and before the greedy split: the device chain issues it
|
||||
* there, so a greedy request sees the same masked distribution. Off at ngram_ban_n 0. */
|
||||
host_ngram_ban(s, in.history, in.n_history, sp.ngram_ban_n, sp.ngram_window,
|
||||
in.ngram_whitelist, in.ngram_whitelist_words);
|
||||
|
||||
/* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other
|
||||
* logit to -inf, so a mask applied after it could leave nothing. */
|
||||
if (sp.greedy()) {
|
||||
|
||||
+19
-2
@@ -71,7 +71,6 @@ enum : uint32_t {
|
||||
RAD_RNG_XTC = 1 /* XTC's "does this fire at all" coin */
|
||||
};
|
||||
|
||||
uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream);
|
||||
/* Uniform in [0,1) with 24 bits, the most a float resolves; more would let host and device
|
||||
* disagree in the last place. */
|
||||
float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream);
|
||||
@@ -177,6 +176,19 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep,
|
||||
uint64_t seed, uint64_t pos);
|
||||
|
||||
/* The windowed no-repeat-ngram ban (`sample_ngram_ban`, Unlimited-OCR's
|
||||
* SlidingWindowNoRepeatNgramProcessor): a candidate whose token would complete an `n`-gram the
|
||||
* last `window` tokens of `history` already contain gets -infinity. `n` <= 0 is off, `window` <= 0
|
||||
* is the whole history. It runs after the penalties and DRY and before every cut, so the greedy
|
||||
* path sees it too.
|
||||
*
|
||||
* `whitelist` is the reference's whitelist (a SET bit means exempt from the ban, the same plane
|
||||
* form as host_mask's, word w bit b covering token 32w + b): ids removed from the banned set
|
||||
* before anything is written, as `banned.difference_update(self.whitelist)` does. Null or zero
|
||||
* words is off -- the reference's empty whitelist, the default serving form. */
|
||||
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
|
||||
int32_t window, const uint32_t* whitelist = nullptr, int64_t wl_words = 0);
|
||||
|
||||
/* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf
|
||||
* instead of removing the candidate, so nothing downstream is renumbered. `n_words` is
|
||||
* ceil(n_vocab/32). */
|
||||
@@ -203,7 +215,8 @@ constexpr int64_t kSampleCandidates = 1024;
|
||||
constexpr int64_t kSampleMergeCandidates = 4096;
|
||||
|
||||
enum class ChainOrder {
|
||||
Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
|
||||
/* penalties, DRY, n-gram ban, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
|
||||
Radiance = 0,
|
||||
LlamaCpp = 1 /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */
|
||||
};
|
||||
|
||||
@@ -215,6 +228,10 @@ struct HostRefInput {
|
||||
int64_t total_context = 0; /* DRY's clamp; 0 means use n_history */
|
||||
const uint32_t* bitmask = nullptr; /* grammar mask, or null */
|
||||
int64_t n_words = 0;
|
||||
/* The n-gram ban's whitelist bitmask (a SET bit exempts a token, host_ngram_ban), null =
|
||||
* no exemptions. */
|
||||
const uint32_t* ngram_whitelist = nullptr;
|
||||
int64_t ngram_whitelist_words = 0;
|
||||
uint64_t pos = 0; /* output position: the RNG's second coordinate */
|
||||
const DryBreakers* dry_breakers = nullptr; /* null runs DRY with no breakers */
|
||||
/* The chain's candidate width (SamplerConfig::max_candidates): top-k narrows every row to
|
||||
|
||||
@@ -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
|
||||
+190
-14
@@ -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.
|
||||
@@ -178,7 +179,21 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
/* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never
|
||||
* penalised). Resolved on the host, which has the vocabulary. */
|
||||
buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
/* The n-gram ban's per-row {n-gram length, window}. Its own tiny plane because the params row
|
||||
* is the fixed RadSampleParams wire format every sampler op shares. */
|
||||
buf_ngram_ = decl("sampler.ngram", RAD_I32, rows, 2, RAD_BUF_PERSIST);
|
||||
/* The ban's whitelist bitmask, this rank's shard, shaped like the mask plane: a SET bit
|
||||
* 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()) {
|
||||
@@ -197,7 +212,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
|
||||
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
|
||||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_ngram_ ||
|
||||
!buf_ngram_wl_ || !buf_mask_ ||
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_ ||
|
||||
(vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) {
|
||||
RAD_ERR("sampler: a staging buffer failed to declare");
|
||||
@@ -239,6 +255,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
|
||||
op_penalties_ = op_vocab_off("sample_penalties");
|
||||
op_dry_ = op_vocab_off("sample_dry");
|
||||
op_ngram_ban_ = op_vocab_off("sample_ngram_ban");
|
||||
op_temp_ = op_vocab("sample_temp");
|
||||
op_mask_ = op_vocab("sample_mask");
|
||||
op_topk_ = op_vocab_off("sample_topk");
|
||||
@@ -249,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. */
|
||||
{
|
||||
@@ -308,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). */
|
||||
@@ -320,7 +352,14 @@ int Sampler::stage_alloc() {
|
||||
greedy_ready_ = false;
|
||||
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
|
||||
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
|
||||
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) {
|
||||
@@ -337,10 +376,10 @@ int Sampler::stage_alloc() {
|
||||
}
|
||||
|
||||
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_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_ * 4)).c_str());
|
||||
mask_words_ * 8 + 8)).c_str());
|
||||
stage_free();
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
@@ -353,7 +392,11 @@ void Sampler::stage_free() {
|
||||
if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (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);
|
||||
@@ -366,6 +409,8 @@ void Sampler::stage_free() {
|
||||
cur_stage_ = nullptr;
|
||||
hist_stage_ = nullptr;
|
||||
brk_stage_ = nullptr;
|
||||
ngram_stage_ = nullptr;
|
||||
ngram_wl_stage_ = nullptr;
|
||||
mask_stage_ = nullptr;
|
||||
}
|
||||
|
||||
@@ -373,9 +418,9 @@ Sampler::~Sampler() { stage_free(); }
|
||||
|
||||
/* ================================================================== admission */
|
||||
|
||||
/* Whether the two history stages run, shared by admission, request setup and step staging so
|
||||
* they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY
|
||||
* also requires a positive multiplier; a negative one would reward repetition. */
|
||||
/* Whether the history stages run, shared by admission, request setup and step staging so they
|
||||
* agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY also
|
||||
* requires a positive multiplier; a negative one would reward repetition. */
|
||||
static bool penalties_on(const SamplingParams& sp) {
|
||||
return sp.penalty_last_n != 0 &&
|
||||
(sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f);
|
||||
@@ -385,6 +430,14 @@ static bool dry_on(const SamplingParams& sp) {
|
||||
return sp.dry_multiplier > 0.0f && sp.dry_base >= 1.0f && sp.dry_penalty_last_n != 0;
|
||||
}
|
||||
|
||||
/* The windowed no-repeat-ngram ban: n-gram length 0 is off (the request default). A window <= 0
|
||||
* is legal and means the whole staged history, the un-windowed processor; it is not a separate
|
||||
* switch, because the reference's windowed form is what the model ships and a ban with no window
|
||||
* is still a ban. */
|
||||
static bool ngram_ban_on(const SamplingParams& sp) {
|
||||
return sp.ngram_ban_n > 0;
|
||||
}
|
||||
|
||||
int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
auto refuse = [&](const char* what, int st) {
|
||||
if (why) *why = what;
|
||||
@@ -418,6 +471,12 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
/* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */
|
||||
if (dry_on(sp) && sp.dry_allowed_length < 1)
|
||||
return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL);
|
||||
/* The n-gram ban: an n-gram shorter than 2 is a single-token ban, which the reference defines
|
||||
* (an empty prefix) and this chain implements, so 1 is accepted. A negative n or window has no
|
||||
* meaning; window 0 is the whole staged history. */
|
||||
if (sp.ngram_ban_n < 0) return refuse("ngram_ban_n is negative", RAD_E_INVAL);
|
||||
if (sp.ngram_window < 0)
|
||||
return refuse("ngram_window is negative (0 searches the whole history)", RAD_E_INVAL);
|
||||
if (sp.n_probs > RAD_MAX_LOGPROBS) {
|
||||
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
|
||||
" logprobs alternatives may be asked for";
|
||||
@@ -457,6 +516,7 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_,
|
||||
"sample_temp (over the candidates, for temperature last)");
|
||||
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
|
||||
if (!missing) missing = need(ngram_ban_on(sp), op_ngram_ban_, "sample_ngram_ban");
|
||||
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
|
||||
"sample_mask");
|
||||
if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties");
|
||||
@@ -573,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();
|
||||
@@ -581,8 +655,15 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
n_seq_ = 0;
|
||||
any_brk_ = false;
|
||||
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
|
||||
@@ -635,6 +716,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
const int64_t n_total = n_prompt + n_out;
|
||||
const bool pen = penalties_on(sp);
|
||||
const bool dry = dry_on(sp);
|
||||
const bool ngram = ngram_ban_on(sp);
|
||||
|
||||
auto it = seqs_.find(r->id);
|
||||
SeqState* st = it == seqs_.end() ? nullptr : &it->second;
|
||||
@@ -669,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);
|
||||
@@ -695,6 +801,26 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.dry_penalty_last_n = sp.dry_penalty_last_n;
|
||||
p.mask_row = -1;
|
||||
|
||||
/* The n-gram ban's pair, staged for every row so a row that turns it off cannot inherit
|
||||
* its predecessor's values. */
|
||||
ngram_stage_[2 * row] = (int32_t)sp.ngram_ban_n;
|
||||
ngram_stage_[2 * row + 1] = (int32_t)sp.ngram_window;
|
||||
|
||||
/* The ban's whitelist, cut to this rank's shard like the grammar mask (shard_mask):
|
||||
* global ids outside it exempt nothing here. Every row that runs the ban gets its
|
||||
* words freshly written -- the plane is uploaded whole with the ban, so a row must
|
||||
* never read another request's stale exemptions. */
|
||||
if (ngram) {
|
||||
uint32_t* w = ngram_wl_stage_ + row * mask_words_;
|
||||
std::memset(w, 0, (size_t)mask_words_ * 4);
|
||||
for (int32_t id : sp.ngram_whitelist) {
|
||||
const int64_t at = (int64_t)id - cfg_.vocab_off;
|
||||
if (at < 0 || at >= cfg_.n_vocab_local) continue;
|
||||
w[at >> 5] |= 1u << (uint32_t)(at & 31);
|
||||
any_ngram_wl_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax
|
||||
* writes a column of this rank's shard, not a token id. Top-k plus the merge produce
|
||||
* global ids, and the pick over one candidate is deterministic. A greedy row asking
|
||||
@@ -723,12 +849,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
any_late_ = true;
|
||||
}
|
||||
|
||||
/* History for the penalties and DRY, staged only for rows that run one of them:
|
||||
* prompt, output so far and, at draft position k, the k drafts before it (they are
|
||||
* emitted only if accepted, as one token at a time). Oldest first, truncated to
|
||||
/* History for the penalties, DRY and the n-gram ban, staged only for rows that run one
|
||||
* of them: prompt, output so far and, at draft position k, the k drafts before it (they
|
||||
* are emitted only if accepted, as one token at a time). Oldest first, truncated to
|
||||
* max_hist; penalty_last_n still decides how much counts. Each row owns its row of the
|
||||
* plane, so hist_off stays 0. */
|
||||
if (pen || dry) {
|
||||
* plane, so hist_off stays 0. The n-gram ban's own window is `ngram_window`, applied to
|
||||
* this span, so the reference's update order holds at a verify: position k sees the
|
||||
* drafts before it, as the processor would after emitting them. */
|
||||
if (pen || dry || ngram) {
|
||||
const int64_t len = n_total + k;
|
||||
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
|
||||
int32_t* h = hist_stage_ + row * cfg_.max_hist;
|
||||
@@ -741,6 +869,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.hist_len = (int32_t)take;
|
||||
if (pen) p.flags |= RAD_SP_PENALTY;
|
||||
if (dry && stage_dry(p, h, take, brk, row)) p.flags |= RAD_SP_DRY;
|
||||
/* A row whose history is shorter than its n-gram has nothing to ban (the reference
|
||||
* skips it too), so the op is issued only when some row has a full n-gram. */
|
||||
if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true;
|
||||
}
|
||||
|
||||
if (gr && !dead && gr->constrains()) {
|
||||
@@ -881,7 +1012,17 @@ int Sampler::build_greedy(int64_t n) {
|
||||
n_seq_ = n;
|
||||
any_brk_ = false;
|
||||
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
|
||||
* history that was not staged this step. The exemption plane needs no clear: `run` uploads
|
||||
* it only beside an issued ban, every row that runs the ban has its words rewritten in full
|
||||
* by the build that staged the pair (build_step), and rows below a zeroed pair are skipped
|
||||
* by the op before they read a word. */
|
||||
std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t));
|
||||
if (greedy_ready_) return RAD_OK;
|
||||
for (int64_t i = 0; i < cap; ++i) {
|
||||
DeviceSampleParams& p = greedy_stage_[i];
|
||||
@@ -904,7 +1045,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
const RadStream s = rad_stream(c);
|
||||
|
||||
bool any_mask = false, any_greedy = false, any_chain = false;
|
||||
bool any_penalty = false, any_dry = false, any_xtc = false;
|
||||
bool any_penalty = false, any_dry = false, any_xtc = false, any_ngram = false;
|
||||
bool any_topp = false, any_minp = false, any_typ = false, any_temp = false;
|
||||
for (int64_t i = 0; i < n_seq_; ++i) {
|
||||
const DeviceSampleParams& p = cur_stage_[i];
|
||||
@@ -912,6 +1053,11 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
any_penalty |= (p.flags & RAD_SP_PENALTY) != 0;
|
||||
any_dry |= (p.flags & RAD_SP_DRY) != 0;
|
||||
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
|
||||
/* The pair plane is read directly, not through cur_stage_: it is per-step staging the
|
||||
* LAST builder filled (build_step writes a row's pair, build_greedy zeroes every pair),
|
||||
* so it agrees with cur_stage_ by builder contract. A new builder must keep that
|
||||
* contract: stage the pair with the params, zero it with the greedy ones. */
|
||||
any_ngram |= ngram_stage_[2 * i] > 0;
|
||||
if (p.flags & RAD_SP_GREEDY) any_greedy = true;
|
||||
else {
|
||||
any_chain = true;
|
||||
@@ -941,21 +1087,34 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (late)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
if (any_penalty || any_dry)
|
||||
if (any_penalty || any_dry || any_ngram)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_,
|
||||
n_seq_ * cfg_.max_hist * 4, s));
|
||||
const bool pass_brk = any_dry && any_brk_;
|
||||
if (pass_brk)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_,
|
||||
n_seq_ * cfg_.max_hist, s));
|
||||
/* The ban's whitelist rides with the ban, and only a row that runs the ban reads it. */
|
||||
const bool pass_wl = any_ngram && any_ngram_wl_;
|
||||
if (any_ngram)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_), ngram_stage_,
|
||||
n_seq_ * 2 * (int64_t)sizeof(int32_t), s));
|
||||
if (pass_wl)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_wl_), ngram_wl_stage_,
|
||||
n_seq_ * mask_words_ * 4, s));
|
||||
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_);
|
||||
const RadOperand o_hist = opd_rows(buf_hist_, n_seq_);
|
||||
const RadOperand o_brk = opd_rows(buf_brk_, n_seq_);
|
||||
const RadOperand o_ngram = opd_rows(buf_ngram_, n_seq_);
|
||||
const RadOperand o_ngram_wl = opd_rows(buf_ngram_wl_, n_seq_);
|
||||
const RadOperand o_mask = opd_rows(buf_mask_, n_seq_);
|
||||
const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_);
|
||||
const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_);
|
||||
@@ -983,6 +1142,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (any_dry)
|
||||
RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() }));
|
||||
|
||||
/* The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor),
|
||||
* after the penalties and before every cut: a banned logit is -infinity for the greedy argmax
|
||||
* below as well as for the chain, which is the reference processor's effect on the
|
||||
* distribution. Off (the default) the op is not issued at all, so a request without it
|
||||
* samples exactly as before. */
|
||||
/* The whitelist operand is passed only when some staged row carries exemptions; absent
|
||||
* means nothing is exempt, the reference's empty whitelist and the bit-identical default. */
|
||||
if (any_ngram)
|
||||
RAD_TRY(issue(op_ngram_ban_, { o_logits, o_params, o_hist, o_ngram,
|
||||
pass_wl ? o_ngram_wl : opd_none() }));
|
||||
|
||||
/* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax
|
||||
* and the chain run over the whole batch: the argmax writes every row, then the candidate
|
||||
* stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits
|
||||
@@ -1027,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
|
||||
|
||||
+67
-3
@@ -9,6 +9,7 @@
|
||||
* Chain order (reordering changes which tokens survive):
|
||||
*
|
||||
* penalties (repetition / frequency / presence, then DRY)
|
||||
* the windowed no-repeat-ngram ban
|
||||
* temperature
|
||||
* the grammar mask
|
||||
* top-k
|
||||
@@ -47,6 +48,9 @@
|
||||
* sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout)
|
||||
* sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers?
|
||||
* -> logits (inout)
|
||||
* sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram,
|
||||
* whitelist?
|
||||
* -> logits (inout)
|
||||
* sample_temp M(range) n_vocab logits, params -> logits (inout)
|
||||
* sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout)
|
||||
* sample_topk M(range) n_vocab vocab_off? logits, params -> cand_idx, cand_val,
|
||||
@@ -64,13 +68,16 @@
|
||||
* a verify. `params` is [M] DeviceSampleParams rows. `history` is [M, max_hist] int32 global
|
||||
* token ids, row m addressed by its hist_off/hist_len. `breakers` is [M, max_hist] uint8 beside
|
||||
* it, nonzero where that token is a whole DRY sequence breaker. `bitmask` is [M, mask_words]
|
||||
* uint32, addressed by the row's mask_row. `vocab_off` is this rank's first vocabulary row,
|
||||
* uint32, addressed by the row's mask_row. The ban's `whitelist` is a [M, mask_words] uint32
|
||||
* bitmask (a SET bit exempts that column from the ban) addressed by the row itself, absent when
|
||||
* no staged row carries one. `vocab_off` is this rank's first vocabulary row,
|
||||
* declared only when the vocabulary is split; the three ops that map between token ids and this
|
||||
* rank's logit columns use it. Every op has a libref implementation, which is both its fallback
|
||||
* and its oracle (spec §17).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include "../rad_core.h"
|
||||
#include "grammar.h"
|
||||
@@ -80,6 +87,7 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
@@ -109,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 */
|
||||
@@ -160,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
|
||||
@@ -200,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
|
||||
@@ -218,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
|
||||
@@ -232,6 +274,9 @@ private:
|
||||
/* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */
|
||||
rad_op op_penalties_ = RAD_NULL_HANDLE;
|
||||
rad_op op_dry_ = RAD_NULL_HANDLE;
|
||||
/* The windowed no-repeat-ngram ban (`sample_ngram_ban`), the stage Unlimited-OCR's
|
||||
* generation_config asks for. It reads the same history plane as the two above. */
|
||||
rad_op op_ngram_ban_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */
|
||||
rad_op op_mask_ = RAD_NULL_HANDLE;
|
||||
@@ -244,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 */
|
||||
|
||||
@@ -252,6 +298,10 @@ private:
|
||||
rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */
|
||||
rad_buf buf_hist_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
|
||||
rad_buf buf_ngram_ = RAD_NULL_HANDLE; /* the n-gram ban's {n, window} pair a row */
|
||||
/* The ban's whitelist bitmask, [rows, mask_words] like the grammar mask plane: a SET bit
|
||||
* exempts that column from the ban. Uploaded with the ban, only when a staged row has one. */
|
||||
rad_buf buf_ngram_wl_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_mask_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_cand_i_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
|
||||
@@ -259,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;
|
||||
@@ -275,6 +331,8 @@ private:
|
||||
const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */
|
||||
int32_t* hist_stage_ = nullptr;
|
||||
uint8_t* brk_stage_ = nullptr;
|
||||
int32_t* ngram_stage_ = nullptr; /* [rows][2]: n-gram length, window */
|
||||
uint32_t* ngram_wl_stage_ = nullptr; /* [rows][mask_words] exemption bitmask */
|
||||
uint32_t* mask_stage_ = nullptr;
|
||||
|
||||
int64_t mask_words_ = 0; /* words for this rank's shard; what the mask op indexes */
|
||||
@@ -282,6 +340,12 @@ private:
|
||||
/* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
|
||||
* passed to sample_dry. */
|
||||
bool any_brk_ = false;
|
||||
/* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use,
|
||||
* so this only decides whether that plane is uploaded and the op issued. */
|
||||
bool any_ngram_ = false;
|
||||
/* Whether any banned row this step whitelists a column of this rank's shard; only then is
|
||||
* the exemption plane uploaded and passed to sample_ngram_ban. */
|
||||
bool any_ngram_wl_ = false;
|
||||
|
||||
/* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used
|
||||
* only when the head is sharded; see declare(). */
|
||||
|
||||
@@ -60,6 +60,16 @@ struct AdvGroup {
|
||||
int64_t used_off; /* [n_seq] seqused */
|
||||
int64_t bt_off; /* [n_seq][pitch] block table */
|
||||
int64_t first_off; /* [n_seq] the position each row's block table starts at */
|
||||
/* The runtime window (KVManager::set_window / SeqWindow), so the card computes the same
|
||||
* `used` and slots the host builder staged: a ring sequence keeps its reference and rewrites
|
||||
* a fixed ring of blocks, so its held span stops at its own table and a position past its
|
||||
* ring_pos maps modulo ring_blocks. Without it (ring 0) the advance is the linear mapping, as
|
||||
* before. ring_pos and the table length are per sequence (each prompt has its own floor and
|
||||
* table), ring_blocks is the same for the group (one W). */
|
||||
int32_t ring; /* 1: the group carries runtime windows */
|
||||
int32_t ring_blocks; /* whole blocks the ring holds */
|
||||
int64_t rpos_off; /* [n_seq] the sequence's block-aligned first ring position, 0 if none */
|
||||
int64_t tlen_off; /* [n_seq] the sequence's block-table length in blocks, 0 if none */
|
||||
};
|
||||
|
||||
/* One advance: a mode, the build it patches, and where its inputs are. Passed by value as the
|
||||
|
||||
@@ -30,21 +30,43 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
|
||||
|
||||
/* Every group's slots for the row's `n` positions (from the positions just written) and its
|
||||
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
|
||||
* tables for the furthest reachable position, so only a row whose output is unused hits this. */
|
||||
* tables for the furthest reachable position, so only a row whose output is unused hits this.
|
||||
*
|
||||
* A runtime window (e.ring, KVManager::set_window) must be computed exactly as the host builder
|
||||
* staged it (BatchBuilder::build_groups), because this runs after the build and overwrites what it
|
||||
* wrote:
|
||||
* - `used` stops at the table: the ring reuses its blocks, so the sequence's held span is the
|
||||
* table's, not the context's. Without this the decode walks bt[(used-1)/block] past the end,
|
||||
* reads the -1 padding the builder fills and faults the card on a negative block;
|
||||
* - a position at or past ring_pos lives in the ring, at block
|
||||
* ring_pos/block + ((p - ring_pos)/block) % ring_blocks, not at (p - first)/block, which runs
|
||||
* off the table once the ring wraps. */
|
||||
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) {
|
||||
const AdvGroup* G = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off);
|
||||
const int32_t* pos = adv_i32(a, a.pos_off);
|
||||
for (int g = 0; g < a.n_groups; ++g) {
|
||||
const AdvGroup& e = G[g];
|
||||
const int32_t first = adv_i32(a, e.first_off)[i];
|
||||
adv_i32(a, e.used_off)[i] = base + n - first;
|
||||
/* Per sequence: each prompt has its own floor and its own table (advance.h). */
|
||||
const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0;
|
||||
const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0;
|
||||
const bool ring = e.ring && tlen > 0;
|
||||
int64_t used = (int64_t)base + n - first;
|
||||
if (ring) {
|
||||
const int64_t span = (int64_t)tlen * e.block_size;
|
||||
if (used > span) used = span;
|
||||
}
|
||||
adv_i32(a, e.used_off)[i] = (int32_t)used;
|
||||
if (!e.paged) continue;
|
||||
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
|
||||
int32_t* slot = adv_i32(a, e.slot_off);
|
||||
for (int32_t j = 0; j < n; ++j) {
|
||||
const int32_t p = pos[k + j];
|
||||
const int32_t bi = (p - first) / e.block_size;
|
||||
slot[k + j] = (p >= first && bi < e.pitch && bt[bi] >= 0)
|
||||
int32_t bi = (p - first) / e.block_size;
|
||||
if (ring && p >= rpos && e.ring_blocks > 0)
|
||||
bi = rpos / e.block_size +
|
||||
((p - rpos) / e.block_size) % e.ring_blocks;
|
||||
slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
|
||||
? bt[bi] * e.block_size + p % e.block_size : -1;
|
||||
}
|
||||
}
|
||||
|
||||
+61
-3
@@ -6,6 +6,7 @@
|
||||
#include "device/device.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
|
||||
@@ -112,6 +113,9 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
pair(&s.h_dout, &s.d_dout, S);
|
||||
pair(&s.h_rows, &s.d_rows, 4 * S);
|
||||
pair(&s.h_first, &s.d_first, S * (int64_t)s.groups.size());
|
||||
/* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */
|
||||
pair(&s.h_rpos, &s.d_rpos, S);
|
||||
pair(&s.h_tlen, &s.d_tlen, S);
|
||||
s.h_grp = ::rad::carve<AdvGroup>(h, oh, (int64_t)s.groups.size());
|
||||
s.d_grp = ::rad::carve<AdvGroup>(d, od, (int64_t)s.groups.size());
|
||||
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
|
||||
@@ -686,17 +690,37 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
}
|
||||
|
||||
int64_t t = 0;
|
||||
/* The group's ring block count, read off the first armed sequence: declare_runtime_window
|
||||
* fixes one W per group, so every armed sequence computes the same count. Collected here,
|
||||
* with the table walk that already opens each window, so the group header below needs no
|
||||
* second pass over the plan. */
|
||||
int32_t ring_blocks = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
const StepEntry& e = plan.e[(size_t)i];
|
||||
|
||||
int64_t first = 0;
|
||||
SeqWindow win;
|
||||
bool has_win = false;
|
||||
int64_t bt_len = 0; /* the sequence's block table, in blocks */
|
||||
int64_t table_end = 0; /* the table's last position, for a runtime window's used */
|
||||
if (L.paged) {
|
||||
/* The manager's block table, by sequence id; Request::blocks is not the source
|
||||
* of truth (see IKVManager). */
|
||||
const std::vector<int32_t>& bt = kv.block_table(e.seq, (int32_t)gi);
|
||||
first = kv.first_block_pos(e.seq, (int32_t)gi);
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j)
|
||||
g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j);
|
||||
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
|
||||
if (has_win) {
|
||||
assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks);
|
||||
ring_blocks = (int32_t)win.ring_blocks;
|
||||
}
|
||||
bt_len = (int64_t)bt.size();
|
||||
table_end = bt_len * L.block_size;
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) {
|
||||
const int64_t pos = (int64_t)e.ctx_len + j;
|
||||
g.h_slot[t + j] = has_win
|
||||
? kvgeom_.slot_ring((int)gi, bt, first, pos, win)
|
||||
: kvgeom_.slot((int)gi, bt, first, pos);
|
||||
}
|
||||
/* Restage relative to what the card holds (BtMirror). The same sequence in the
|
||||
* same row keeps entries below the first changed one and below the end of both
|
||||
* old and new tables, so a decode step stages nothing or one appended block. A
|
||||
@@ -737,6 +761,11 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
s.h_convslot[(int64_t)gi * max_seqs_ + i] = st;
|
||||
}
|
||||
s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first;
|
||||
/* The advance recomputes this row's used and slots after the build (advance_impl.h),
|
||||
* so it needs the same per-sequence ring data this build staged: the row's floor and
|
||||
* its table's length, 0 when the sequence has no runtime window. */
|
||||
s.h_rpos[i] = has_win ? (int32_t)win.ring_pos : 0;
|
||||
s.h_tlen[i] = has_win ? (int32_t)bt_len : 0;
|
||||
t += e.n_tokens;
|
||||
|
||||
/* Tokens the sequence holds in this table, not min(length, window). `seqused` counts
|
||||
@@ -745,8 +774,16 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
* unwritten slots at the end of the table, read as the newest context; a non-causal
|
||||
* window group would attend to them. Do not clamp to `window` either: the held span
|
||||
* may exceed it by under a block, and clamping would drop the newest tokens. Attending
|
||||
* a few extra old positions is the cost of paging a window (vLLM does the same). */
|
||||
* a few extra old positions is the cost of paging a window (vLLM does the same).
|
||||
*
|
||||
* A runtime window (R-SWA) has reused its ring's slots once the sequence is past the
|
||||
* ring's span, so the held span is the table's, not the context's: every slot of the
|
||||
* reference and of the ring holds live KV, and the ring's blocks are what a non-causal
|
||||
* decode reads. Before the ring is full the shorter of the two is the written count. */
|
||||
int64_t used = (int64_t)e.ctx_len + e.n_tokens - first;
|
||||
if (has_win) {
|
||||
used = std::min<int64_t>(used, table_end);
|
||||
}
|
||||
if (used < 0) used = 0;
|
||||
g.h_used[i] = (int32_t)used;
|
||||
if (L.paged) {
|
||||
@@ -773,6 +810,15 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
a.used_off = (const char*)g.d_used - d0;
|
||||
a.bt_off = (const char*)g.d_bt - d0;
|
||||
a.first_off = (const char*)(s.d_first + (int64_t)gi * max_seqs_) - d0;
|
||||
/* The runtime window (KVManager::set_window): the advance runs after this build and
|
||||
* overwrites `used` and the slots, so it must reproduce the ring's mapping rather
|
||||
* than the linear one (advance_impl.h). The floor and table length are per sequence
|
||||
* (s.h_rpos / s.h_tlen), the ring's block count is the group's W, collected with the
|
||||
* table walk above. */
|
||||
a.ring = ring_blocks ? 1 : 0;
|
||||
a.ring_blocks = ring_blocks;
|
||||
a.rpos_off = (const char*)s.d_rpos - d0;
|
||||
a.tlen_off = (const char*)s.d_tlen - d0;
|
||||
}
|
||||
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
@@ -872,6 +918,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
int32_t rope_mixed = 0;
|
||||
int64_t n_mm = 0;
|
||||
bool lora_rows = false;
|
||||
int32_t cvec_rows = 0;
|
||||
s.h_cu[0] = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
const StepEntry& e = plan.e[(size_t)i];
|
||||
@@ -905,6 +952,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_lora[k + j] = ls;
|
||||
if (ls >= 0 && e.n_tokens > 0) lora_rows = true;
|
||||
}
|
||||
/* The same rows derive.cpp's projection_on_rows sets (RadBatch::control_vector). */
|
||||
if (e.req && e.req->sp.use_control_vector && e.n_tokens > 0) cvec_rows = 1;
|
||||
/* Rotary position of each row at its own position (draft-head rows rotate at the index
|
||||
* they write, not the token they embed). Three planes of n_tok. */
|
||||
if (mm_on_) {
|
||||
@@ -1113,6 +1162,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
/* Null on a step with no adapter row: the core then issues no adapter op, and the step
|
||||
* runs the same pass as an engine serving no adapters. */
|
||||
B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr;
|
||||
B.control_vector = cvec_rows;
|
||||
B.enc = 0;
|
||||
B.enc_n_patch = 0;
|
||||
B.enc_pixels = nullptr;
|
||||
@@ -1120,6 +1170,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.enc_n_seg = 0;
|
||||
B.enc_cu = nullptr;
|
||||
B.enc_max_seg = 0;
|
||||
B.enc_seg_h = nullptr;
|
||||
B.enc_seg_w = nullptr;
|
||||
B.n_checkpoints = n_ck;
|
||||
B.checkpoint_tok = n_ck ? on_rank(base, b0, s.d_cktok) : nullptr;
|
||||
B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr;
|
||||
@@ -1188,6 +1240,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1;
|
||||
int64_t n_patch = 0, n_seg = 0, max_seg = 0;
|
||||
enc_cu_host_[0] = 0;
|
||||
enc_seg_h_host_.clear();
|
||||
enc_seg_w_host_.clear();
|
||||
for (const EncoderPart& p : parts) {
|
||||
const mm::Item& it = *p.item;
|
||||
if (p.seg0 < 0 || p.n_seg <= 0 || p.seg0 + p.n_seg > it.n_seg) {
|
||||
@@ -1210,6 +1264,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
for (int32_t q = p.seg0; q < p.seg0 + p.n_seg; ++q) {
|
||||
const int64_t seg_p = it.patch_at(q + 1) - it.patch_at(q);
|
||||
enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p;
|
||||
enc_seg_h_host_.push_back(it.seg_h(q));
|
||||
enc_seg_w_host_.push_back(it.seg_w(q));
|
||||
++n_seg;
|
||||
if (seg_p > max_seg) max_seg = seg_p;
|
||||
}
|
||||
@@ -1256,6 +1312,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
B.enc_n_seg = n_seg;
|
||||
B.enc_cu = static_cast<const int32_t*>(enc_cu_dev_[r]);
|
||||
B.enc_max_seg = (int32_t)max_seg;
|
||||
B.enc_seg_h = enc_seg_h_host_.data();
|
||||
B.enc_seg_w = enc_seg_w_host_.data();
|
||||
}
|
||||
out_last_ = out_next_;
|
||||
out_next_ = (out_next_ + 1) % kOut;
|
||||
|
||||
@@ -199,6 +199,11 @@ private:
|
||||
int32_t *h_rows = nullptr, *d_rows = nullptr;
|
||||
int32_t *h_first = nullptr, *d_first = nullptr;
|
||||
AdvGroup *h_grp = nullptr, *d_grp = nullptr;
|
||||
/* [max_seqs] per-sequence runtime-window data for the advance: the block-aligned first
|
||||
* ring position and the block table's length in blocks, 0 when the sequence has no
|
||||
* runtime window (advance.h). Per sequence because each prompt has its own floor. */
|
||||
int32_t *h_rpos = nullptr, *d_rpos = nullptr;
|
||||
int32_t *h_tlen = nullptr, *d_tlen = nullptr;
|
||||
|
||||
char* h_derived = nullptr; /* derivation staging, byte-addressed */
|
||||
/* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos,
|
||||
@@ -328,6 +333,9 @@ private:
|
||||
int32_t* enc_coord_host_ = nullptr;
|
||||
int32_t* enc_cu_host_ = nullptr;
|
||||
std::vector<int32_t> enc_coord_tmp_; /* one item's coordinates; kept for its capacity */
|
||||
/* The pass's per-segment grid, host side (RadBatch::enc_seg_h/w). Filled by build_encoder and
|
||||
* valid until the next build, like the staged coordinates. */
|
||||
std::vector<int32_t> enc_seg_h_host_, enc_seg_w_host_;
|
||||
int64_t last_n_tok_ = 0;
|
||||
struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; };
|
||||
MediaBytes media_bytes(); /* the four per-rank device regions alloc_media reserves */
|
||||
|
||||
+14
-7
@@ -47,12 +47,16 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
* served by a different kernel may differ (§7.2). */
|
||||
bool has_linear = false, has_window = false;
|
||||
for (const KVGroupInfo& kg : prog.kv_groups) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
|
||||
kg.decl.kind == RAD_KV_RING) {
|
||||
if (kg.block_size > 0) {
|
||||
g.attn_block = lcm64(g.attn_block, kg.block_size);
|
||||
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
|
||||
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
|
||||
* snapshot for a prefix hit to resume. */
|
||||
* snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all
|
||||
* (KVManager::declare_runtime_window): its window is each sequence's own prompt
|
||||
* length, which no slot could describe, so it is sized for the context plus a ring
|
||||
* and is never checkpointed. */
|
||||
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
|
||||
has_window = true;
|
||||
}
|
||||
@@ -122,14 +126,15 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
* retention.
|
||||
*
|
||||
* Without linear state there are no checkpoints, except for a trunk window under a prefix
|
||||
* cache, which snapshots the window behind a prompt's tail (window_ckpt) without splitting
|
||||
* chunks. */
|
||||
* cache, which snapshots the window at interval boundaries and the prompt's tail
|
||||
* (window_ckpt). */
|
||||
if ((has_linear || (has_window && cfg.prefix_cache)) && cfg.checkpoint_interval > 0)
|
||||
g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum);
|
||||
else
|
||||
g.checkpoint_interval = 0;
|
||||
g.window_ckpt = !has_linear && g.checkpoint_interval > 0;
|
||||
/* A window snapshot splits no chunk (plan_chunk), so there is no interval grid to span. */
|
||||
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;
|
||||
g.shared_tok = prefill_shared_tok(cfg);
|
||||
@@ -149,9 +154,11 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
|
||||
/* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so
|
||||
* when the interval is below --max-num-batched-tokens, raising the budget does not change the
|
||||
* chunk; the log line makes that visible. A window snapshot splits nothing. */
|
||||
* 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 int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt && span_tok < cfg.max_tok)
|
||||
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 "
|
||||
"interval %lld, max_tok %lld -> prefill chunks of at most %lld%s",
|
||||
|
||||
@@ -51,11 +51,14 @@ struct ChunkGeometry {
|
||||
/* Every contributor by name, for the startup line and the refusal. */
|
||||
std::string why;
|
||||
|
||||
/* No linear state but a sliding window: the checkpoint snapshots only the window behind a
|
||||
* prompt's tail (KVManager::has_window_snapshot). Chunks are not split at the interval, since
|
||||
* a mid-prompt window snapshot gains nothing; the interval is only the shortest prompt worth
|
||||
* a snapshot. */
|
||||
/* No linear state but a sliding window: checkpoints snapshot the window behind an
|
||||
* interval boundary or the prompt's tail (KVManager::has_window_snapshot). Intermediate
|
||||
* 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; }
|
||||
};
|
||||
|
||||
+95
-15
@@ -44,6 +44,24 @@ struct IKVManager {
|
||||
/* After a committed step, a window group frees what no later query can read
|
||||
* (KVManager::trim_window). */
|
||||
virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; }
|
||||
/* R-SWA (KVManager::declare_runtime_window): the W this group arms a sequence with, 0 when it
|
||||
* carries no runtime windows. The scheduler arms every sequence it admits with
|
||||
* set_window(seq, prompt length, W); a manager with no runtime window refuses it and the
|
||||
* scheduler never asks. */
|
||||
virtual int64_t runtime_window_tokens(int32_t group) const { (void)group; return 0; }
|
||||
virtual int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens) {
|
||||
(void)seq; (void)visible_lo; (void)window_tokens;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The sequence's runtime window in `group`, if it has one (KVManager::runtime_window). A
|
||||
* sequence with one is excluded from prefix publish, checkpoint snapshots and speculation:
|
||||
* the window is runtime data and the ring rewrites its slots in place. */
|
||||
virtual bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const {
|
||||
(void)seq; (void)group; (void)out;
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual bool has_runtime_window(uint64_t seq) const { (void)seq; return false; }
|
||||
/* Window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
|
||||
* defaults mean no hit on a windowed trunk is ever resumed. */
|
||||
virtual bool has_window_snapshot() const { return false; }
|
||||
@@ -95,7 +113,11 @@ struct IKVManager {
|
||||
|
||||
/* Absolute token position that block_table(seq, group)[0] covers: zero for a full group,
|
||||
* non-zero for a window group once blocks below the window are recycled. The step batch maps
|
||||
* a slot as `(pos - first_block_pos) / block_size`. */
|
||||
* a slot as `(pos - first_block_pos) / block_size`.
|
||||
*
|
||||
* A sequence with a runtime window (runtime_window) keeps first_block_pos 0 even once the ring
|
||||
* recycles: its table is [reference][ring] from position 0 and the ring's positions map
|
||||
* modulo ring_blocks (SeqWindow), so only the slot index recycles, never the table. */
|
||||
virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* Index of the first entry of block_table(seq, group) changed since the previous call;
|
||||
@@ -110,13 +132,22 @@ struct IKVManager {
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the prefix cache */
|
||||
/* What IPrefixCache::restore did: brought back every entry the tiers hold for the prompt (or there
|
||||
* were none), brought back part of them because the pool could not hold the chain, or, asked for
|
||||
* the whole chain only, left it on the host. */
|
||||
enum class RestoreResult : uint8_t { Whole, Cut, Declined };
|
||||
|
||||
struct IPrefixCache {
|
||||
virtual ~IPrefixCache() = default;
|
||||
|
||||
/* Bring back whatever the idle tiers hold for this prompt, before the lookup. The engine
|
||||
* performs it (it allocates blocks and runs a device scatter). A failure only leaves a
|
||||
* shorter prefix, which is always safe. */
|
||||
virtual void restore(const Request&) {}
|
||||
* shorter prefix, which is always safe. With `whole_only`, a chain the pool cannot be made to
|
||||
* hold whole is left on the host (RestoreResult::Declined). */
|
||||
virtual RestoreResult restore(const Request&, bool whole_only) {
|
||||
(void)whole_only;
|
||||
return RestoreResult::Whole;
|
||||
}
|
||||
/* A step's admissions begin; the last step's lookup results have been consumed. */
|
||||
virtual void begin_step() {}
|
||||
/* Keep this waiting request's chain in VRAM until release(). Called when admission is refused
|
||||
@@ -170,9 +201,17 @@ struct IPrefixCache {
|
||||
virtual CkptCounts ckpt_counts() const { return {}; }
|
||||
/* Entries expired by --prefix-cache-ttl; not counted as evictions. */
|
||||
virtual int64_t expired() const { return 0; }
|
||||
/* Restores the pool could not hold whole (PrefixCache::Stats::restore_cuts). */
|
||||
virtual int64_t restore_cuts() 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. */
|
||||
@@ -215,7 +254,7 @@ struct KVGeom {
|
||||
for (const KVGroupInfo& gi : groups) {
|
||||
G e;
|
||||
e.kind = gi.decl.kind;
|
||||
e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW);
|
||||
e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW || e.kind == RAD_KV_RING);
|
||||
e.block_size = gi.block_size > 0 ? gi.block_size : 1;
|
||||
e.window = gi.decl.window;
|
||||
k.g.push_back(e);
|
||||
@@ -231,6 +270,23 @@ struct KVGeom {
|
||||
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
|
||||
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
|
||||
}
|
||||
|
||||
/* The same slot for a runtime window (SeqWindow): the reference maps linearly (first_pos is
|
||||
* 0 there), and a position at or past the ring's start lives in block
|
||||
* ring_pos/block + ((pos - ring_pos)/block) % ring_blocks, which is what rewrites the ring's
|
||||
* slots in place. ring_pos is block-aligned, so `pos % block` stays the in-block offset. */
|
||||
int32_t slot_ring(int gi, const std::vector<int32_t>& bt, int64_t first_pos, int64_t pos,
|
||||
const SeqWindow& w) const {
|
||||
const G& e = g[(size_t)gi];
|
||||
int64_t bi;
|
||||
if (w.set && pos >= w.ring_pos) {
|
||||
bi = w.ring_pos / e.block_size + ((pos - w.ring_pos) / e.block_size) % w.ring_blocks;
|
||||
} else {
|
||||
bi = (pos - first_pos) / e.block_size;
|
||||
}
|
||||
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
|
||||
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ binding the concrete classes */
|
||||
@@ -246,6 +302,12 @@ struct KVBinding final : IKVManager {
|
||||
int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); }
|
||||
int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); }
|
||||
void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); }
|
||||
int64_t runtime_window_tokens(int32_t g) const override { return m->runtime_window_tokens(g); }
|
||||
int set_window(uint64_t s, int64_t lo, int64_t w) override { return m->set_window(s, lo, w); }
|
||||
bool runtime_window(uint64_t s, int32_t g, SeqWindow* o) const override {
|
||||
return m->runtime_window(s, g, o);
|
||||
}
|
||||
bool has_runtime_window(uint64_t s) const override { return m->has_runtime_window(s); }
|
||||
bool has_window_snapshot() const override { return m->has_window_snapshot(); }
|
||||
int seed_window(uint64_t s, int64_t p) override { return m->seed_window(s, p); }
|
||||
int adopt(uint64_t s, int32_t g, const std::vector<int32_t>& b, int64_t n) override {
|
||||
@@ -344,16 +406,20 @@ struct PCBinding final : IPrefixCache {
|
||||
}
|
||||
|
||||
/* Installed by the engine when the idle tiers are on; empty otherwise. */
|
||||
std::function<void(const Request&)> restore_fn;
|
||||
void restore(const Request& r) override {
|
||||
if (restore_fn) restore_fn(r);
|
||||
std::function<RestoreResult(const Request&, bool whole_only)> restore_fn;
|
||||
RestoreResult restore(const Request& r, bool whole_only) override {
|
||||
return restore_fn ? restore_fn(r, whole_only) : RestoreResult::Whole;
|
||||
}
|
||||
/* The entries restore_fn brings back, in chain order: the whole chain if the pool can be made
|
||||
* to hold it, otherwise cut (PrefixCache::restorable_from). Room is made as evict() makes it,
|
||||
* dropping entries with a landed host copy, then landing pending copies and dropping those, but
|
||||
* never erasing one: a restore is worth no lost conversation. The pool's free quarter can go
|
||||
* to it; the reserve's trim after the next publish frees it again. */
|
||||
std::vector<BlockHash> restore_plan(const Request& r, uint64_t salt) {
|
||||
* dropping entries with a landed host copy, then landing pending copies and dropping those,
|
||||
* but never erasing one, so no other conversation is lost to a restore. The pool's free
|
||||
* quarter can go to it; the reserve's trim after the next publish frees it again. `*res`
|
||||
* says whether the chain was cut; with `whole_only`, a chain that would be cut comes back
|
||||
* empty and Declined, and the room made stays for the next attempt. */
|
||||
std::vector<BlockHash> restore_plan(const Request& r, uint64_t salt, bool whole_only = false,
|
||||
RestoreResult* res = nullptr) {
|
||||
if (res) *res = RestoreResult::Whole;
|
||||
media_keys(r, &mm_, salt);
|
||||
std::vector<BlockHash> want = m->restorable_from(r.prompt, mm_);
|
||||
const int64_t need = (int64_t)want.size() - m->restore_room();
|
||||
@@ -361,7 +427,16 @@ struct PCBinding final : IPrefixCache {
|
||||
const int64_t k = m->trim_for(r.prompt, mm_, need);
|
||||
if (k < need && flush_fn && flush_fn()) (void)m->trim_for(r.prompt, mm_, need - k);
|
||||
/* Landing copies may have moved records; take the chain again against the room made. */
|
||||
return m->restorable_from(r.prompt, mm_, m->restore_room());
|
||||
if (whole_only) {
|
||||
want = m->restorable_from(r.prompt, mm_);
|
||||
if ((int64_t)want.size() <= m->restore_room()) return want;
|
||||
if (res) *res = RestoreResult::Declined;
|
||||
return {};
|
||||
}
|
||||
bool cut = false;
|
||||
want = m->restorable_from(r.prompt, mm_, m->restore_room(), &cut);
|
||||
if (cut && res) *res = RestoreResult::Cut;
|
||||
return want;
|
||||
}
|
||||
void begin_step() override { m->begin_step(); }
|
||||
void hold(const Request& r) override {
|
||||
@@ -422,8 +497,13 @@ struct PCBinding final : IPrefixCache {
|
||||
return { st.ckpt_retired, st.ckpt_lru, st.ckpt_refused };
|
||||
}
|
||||
int64_t expired() const override { return m->stats().expired; }
|
||||
int64_t restore_cuts() const override { return m->stats().restore_cuts; }
|
||||
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); }
|
||||
|
||||
@@ -92,18 +92,20 @@ 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
|
||||
* snapshot more than one checkpoint interval below the hit: the retention ladder had
|
||||
* nothing nearer, or the restore brought back only part of the chain. `hit_cut_tokens` is
|
||||
* the checkpoint shortfall: prompt tokens the attention cache held and the admission
|
||||
* computed again, because the hit resumed at a snapshot below it or was cut to nothing. */
|
||||
* snapshot more than one checkpoint interval below the hit: the previous reply was longer
|
||||
* than an interval (decode writes no snapshot), the retention policy kept nothing nearer, or
|
||||
* a restore was cut (prefix_restore_cuts). `hit_cut_tokens` is the checkpoint shortfall:
|
||||
* prompt tokens the attention cache held and the admission computed again, because the hit
|
||||
* resumed at a snapshot below it or was cut to nothing. */
|
||||
int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
|
||||
int64_t hit_cut_resumed_below = 0;
|
||||
int64_t hit_cut_tokens = 0;
|
||||
/* Restores from the host tier the pool could not hold whole, even after giving up the VRAM
|
||||
* copies of other conversations (PrefixCache::Stats::restore_cuts). */
|
||||
* copies of other conversations, counted once per admission (RestoreResult::Cut). */
|
||||
int64_t prefix_restore_cuts = 0;
|
||||
/* Tokens of context held only by the cache, i.e. what eviction would free. Excludes blocks
|
||||
* shared with a running sequence. Same token axis as the paged groups, so comparable with
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
+174
-17
@@ -70,6 +70,20 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
has_linear_state_ = false;
|
||||
for (const auto& g : kvgeom_.g) if (!g.paged) has_linear_state_ = true;
|
||||
|
||||
/* R-SWA: which groups carry runtime per-sequence windows, and the W they arm a sequence
|
||||
* with. Empty unless the engine declared one (KVManager::declare_runtime_window), so a model
|
||||
* with a fixed window (gemma4) takes none of the runtime-window paths. */
|
||||
rswa_windows_.clear();
|
||||
for (size_t i = 1; i < kvgeom_.g.size(); ++i) {
|
||||
const int64_t w = kv->runtime_window_tokens((int32_t)i);
|
||||
if (w > 0) rswa_windows_.push_back({(int32_t)i, w});
|
||||
}
|
||||
if (!rswa_windows_.empty())
|
||||
RAD_INFO("R-SWA: %zu KV group(s) with a runtime window; a sequence keeps its prompt as the "
|
||||
"reference and decodes into a ring of %lld token(s) after it, and is excluded from "
|
||||
"the prefix cache, checkpoints and speculation",
|
||||
rswa_windows_.size(), (long long)rswa_windows_[0].tokens);
|
||||
|
||||
/* A hit can leave a drafter's own cache short only where a paged group is not prefix-cached
|
||||
* (scheduler.h, hit_holes_draft_). With the cache off cached_groups() is empty and this is
|
||||
* true, which costs nothing: no hits are taken, and every first block pass is at ctx_len 0. */
|
||||
@@ -188,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);
|
||||
@@ -282,6 +297,10 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
s.ckpt_src = -1;
|
||||
s.hit_attn = 0;
|
||||
s.hit_owed = false;
|
||||
/* Slots are reused: a request that inherited `restore_waited` would never wait for a deferred
|
||||
* release and its restore would be cut. */
|
||||
s.restore_waited = false;
|
||||
s.restore_cut = false;
|
||||
s.req->state = ReqState::Waiting;
|
||||
|
||||
/* The step path appends to `output`, so its capacity is settled here, on the arrival thread.
|
||||
@@ -307,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);
|
||||
@@ -385,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();
|
||||
@@ -407,7 +479,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
* and failed requests are published too; their prompts were computed, and a client that hangs
|
||||
* up mid-answer is likely to ask for that prefix again. */
|
||||
if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
|
||||
s.req->n_computed > 0) {
|
||||
s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) {
|
||||
/* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its
|
||||
* table is a reference plus a ring rather than a prefix from position 0, and the window
|
||||
* length is runtime data that no cache key carries; a hit would adopt blocks for a window
|
||||
* this sequence does not have. prefix.cpp already skips a windowed group -- this makes the
|
||||
* policy explicit, rather than a consequence of the kind declared at build time. */
|
||||
const std::vector<int32_t>& cg = pc_->cached_groups();
|
||||
pub_blocks_.assign(cg.size(), {});
|
||||
bool ok = !cg.empty();
|
||||
@@ -466,6 +543,11 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
* refusal leaves the entry without one. */
|
||||
void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok) {
|
||||
int32_t cs = -1;
|
||||
/* R-SWA: a sequence with a runtime window is never checkpointed. The window is runtime data
|
||||
* (the prompt's own length), so a slot would describe a window the sequence does not have, and
|
||||
* the ring is not the [lo, pos) block list a restore seeds. The prefix cache can never reuse
|
||||
* it either, so the copy would be dead weight. */
|
||||
if (kv_->has_runtime_window(r.id)) return;
|
||||
if (pc_->reserve_checkpoint(r, pos, &cs) < 0 || cs < 0) return;
|
||||
e.ckpt_tok = tok;
|
||||
e.ckpt_slot = cs;
|
||||
@@ -700,6 +782,12 @@ int Scheduler::draft_ngram(SchedReq& s, int depth) const {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chunking */
|
||||
int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const {
|
||||
if (rswa_windows_.empty() || !kv_->has_runtime_window(r.id)) return n_target;
|
||||
const int64_t prompt = (int64_t)r.prompt.size();
|
||||
return std::min(n_target, r.n_computed < prompt ? prompt : r.n_computed + 1);
|
||||
}
|
||||
|
||||
/* A prefill chunk splits at the linear-state checkpoint interval so a checkpoint is always
|
||||
* written (spec §7.3; see scheduler.h).
|
||||
*
|
||||
@@ -717,7 +805,18 @@ 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) next = INT64_MAX; /* a window snapshot: the tail 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;
|
||||
} else if (geo_.window_ckpt) {
|
||||
/* A tail-only window snapshot is unreachable after a prompt edit.
|
||||
* Keep interval checkpoints too; the ordinary retention policy bounds
|
||||
* their storage. Preserve the tail before the template's changed suffix,
|
||||
* even when the prompt ends exactly on an interval boundary. */
|
||||
const int64_t tail = tail_checkpoint(n_target);
|
||||
if (tail > n_computed) next = std::min(next, tail);
|
||||
}
|
||||
/* A span (ChunkGeometry::span) starts only on an interval boundary past the first
|
||||
* interval, and its chunk is the span's intervals in a row, each the piece a span of 1
|
||||
* makes a chunk of its own. Not from a prompt's start: the first interval may be served on
|
||||
@@ -731,7 +830,8 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
want = far - n_computed;
|
||||
else if (n_computed + want > next && n_computed + want < n_target)
|
||||
want = (n_computed + want) / I * I - n_computed;
|
||||
if (!geo_.window_ckpt && (n_computed + want) % I == 0) {
|
||||
if ((geo_.window_ckpt && n_computed + want == next) ||
|
||||
(!geo_.window_ckpt && (n_computed + want) % I == 0)) {
|
||||
if (checkpoint_pos) *checkpoint_pos = n_computed + want;
|
||||
} else if (n_computed + want == n_target) {
|
||||
/* Also one at the prompt's tail. The next turn resumes from the deepest snapshot
|
||||
@@ -918,6 +1018,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
|
||||
if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id));
|
||||
|
||||
/* R-SWA: the visible set becomes [0, prompt) plus a ring of W once the prompt is placed. The
|
||||
* floor is this sequence's own prompt length (image tokens included, they are prompt rows),
|
||||
* and it is armed here rather than at the prefill's end so no checkpoint is reserved for the
|
||||
* sequence: a snapshot would describe a window the sequence no longer has (set_window). */
|
||||
for (const RswaWindow& w : rswa_windows_) {
|
||||
const int rc = kv_->set_window(r.id, (int64_t)r.prompt.size(), w.tokens);
|
||||
if (rc < 0) {
|
||||
RAD_WARN("request %llu: runtime window of %lld tokens over a %zu-token prompt: %s",
|
||||
(unsigned long long)r.id, (long long)w.tokens, r.prompt.size(),
|
||||
rad_strerror(rc));
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
|
||||
/* A fresh attempt: nothing looked up or counted yet. A request that kept an earlier
|
||||
* attempt's hit (n_computed > 0) keeps what it found. */
|
||||
if (r.n_computed == 0) {
|
||||
@@ -937,8 +1051,21 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
if (r.n_computed == 0 && cfg_.prefix_cache) {
|
||||
/* Restore before the lookup, which stops at the first block the tiers hold. This is
|
||||
* where a cold session gets its context back for the cost of a copy instead of a
|
||||
* prefill. */
|
||||
pc_->restore(r);
|
||||
* prefill.
|
||||
*
|
||||
* A sequence closed while a step issued ahead still read its blocks keeps them until the
|
||||
* next commit, and the room a restore makes cannot include them yet: a request right
|
||||
* behind another conversation's last turn would come back cut and prefill the rest. Such
|
||||
* a restore waits one step, once, instead of being cut. */
|
||||
const bool whole_only = n_deferred_ > 0 && !s.restore_waited;
|
||||
const RestoreResult rr = pc_->restore(r, whole_only);
|
||||
if (rr == RestoreResult::Declined) {
|
||||
s.restore_waited = true;
|
||||
RAD_DEBUG("admit %llu: the restore waits a step for %d deferred release(s)",
|
||||
(unsigned long long)r.id, n_deferred_);
|
||||
return RAD_E_FULL;
|
||||
}
|
||||
s.restore_cut = rr == RestoreResult::Cut;
|
||||
HitCap cap;
|
||||
if (draft_refill_ > 0) {
|
||||
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
|
||||
@@ -974,8 +1101,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
"below it", (unsigned long long)r.id, (long long)h.n_attn_tokens);
|
||||
} else if (reuse < h.n_attn_tokens) {
|
||||
/* Within an interval of the hit is the ordinary case: a turn's tail past its last
|
||||
* checkpoint. Further down, the snapshots in between are gone, or the attention
|
||||
* blocks reach past what the tiers could restore of the chain. */
|
||||
* checkpoint. Further down, the previous reply was longer than an interval (decode
|
||||
* writes no snapshot), the retention policy kept nothing nearer, or the attention
|
||||
* blocks reach past the snapshot a cut restore stopped at. */
|
||||
if (geo_.checkpoints() && h.n_attn_tokens - reuse > geo_.checkpoint_interval)
|
||||
s.hit_cut = SchedReq::HitCut::ResumedBelow;
|
||||
RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at the snapshot at %lld",
|
||||
@@ -1056,9 +1184,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
* queued behind it takes every token left. The hit is known by now, so the cap applies
|
||||
* to what really has to run. */
|
||||
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
|
||||
want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
|
||||
if (cap < budget && want > 0)
|
||||
admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at);
|
||||
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at);
|
||||
}
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
@@ -1093,6 +1222,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
m_.attn_cached_tokens += s.hit_attn;
|
||||
m_.linear_cached_tokens += r.n_cached;
|
||||
if (s.hit_attn > r.n_cached) m_.hit_cut_tokens += s.hit_attn - r.n_cached;
|
||||
if (s.restore_cut) ++m_.prefix_restore_cuts;
|
||||
switch (s.hit_cut) {
|
||||
case SchedReq::HitCut::NoSnapshot: ++m_.hit_cut_no_snapshot; break;
|
||||
case SchedReq::HitCut::Window: ++m_.hit_cut_window; break;
|
||||
@@ -1254,9 +1384,10 @@ const RadBatch* Scheduler::step() {
|
||||
const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0;
|
||||
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
|
||||
/*rows_only=*/shares == 0);
|
||||
want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
|
||||
if (cap < budget && want > 0 && capped_at < 0) {
|
||||
const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr,
|
||||
const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr,
|
||||
r.checkpoint_at);
|
||||
if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; }
|
||||
}
|
||||
@@ -1476,7 +1607,8 @@ const RadBatch* Scheduler::step() {
|
||||
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
|
||||
int64_t ckpt = -1;
|
||||
const int64_t grown = e.ckpt_slot < 0 && limit > had
|
||||
? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had;
|
||||
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at)
|
||||
: had;
|
||||
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
|
||||
e.n_tokens = (int32_t)grown;
|
||||
e.produces_token = (r.n_computed + grown >= s.seq_len());
|
||||
@@ -1607,7 +1739,7 @@ bool Scheduler::prefill_continues() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
/* Only the step being released has a plan to read. Between a commit and the next step (an
|
||||
* encoder pass is prepared there) `plan_` is the committed step's, whose requests in_step() no
|
||||
* longer holds: a cancel and reap may have released one (#127). */
|
||||
* longer holds: a cancel and reap may have released one. */
|
||||
if (stage_rows_ <= 0 || !step_open_) return false;
|
||||
/* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now
|
||||
* would be dropped by that step. */
|
||||
@@ -1804,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
|
||||
@@ -1826,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;
|
||||
}
|
||||
|
||||
@@ -1982,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_;
|
||||
@@ -2125,7 +2263,10 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
* so the host bounds it by all of them. A mid-prompt chunk verified nothing. */
|
||||
const int64_t vstart = (int64_t)e.ctx_len + e.n_tokens - 1 - e.n_spec;
|
||||
const int64_t head_max = vstart + e.n_spec;
|
||||
bool can_draft = may_draft && e.produces_token;
|
||||
/* A runtime-window (R-SWA) sequence is never drafted for: its rollback refuses (the ring
|
||||
* rewrites slots KVManager::rollback cannot unwind), so a rejected draft would only warn
|
||||
* and waste the draft compute. This is the gate kv.cpp's rollback comment states. */
|
||||
bool can_draft = may_draft && e.produces_token && !kv_->has_runtime_window(r.id);
|
||||
|
||||
/* Lookahead KV: round k writes the head's K and V at head + k - 1, past the committed end,
|
||||
* so blocks must exist up to the furthest head acceptance could leave. The next verify
|
||||
@@ -2305,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()
|
||||
@@ -2422,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); }
|
||||
|
||||
@@ -2631,7 +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_restore_cuts = pc_->restore_cuts();
|
||||
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;
|
||||
|
||||
+65
-10
@@ -111,6 +111,12 @@ struct SchedReq {
|
||||
* snapshot more than an interval below it. */
|
||||
enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt, ResumedBelow };
|
||||
HitCut hit_cut = HitCut::None;
|
||||
/* Admission waited a step for a sequence's deferred release before cutting its restore
|
||||
* (Scheduler::admit_one); it waits once. */
|
||||
bool restore_waited = false;
|
||||
/* That attempt's restore came back cut (SchedMetrics::prefix_restore_cuts, counted once the
|
||||
* admission happens). */
|
||||
bool restore_cut = false;
|
||||
|
||||
/* The whole sequence is prompt ++ output; n_computed indexes into it. */
|
||||
int64_t seq_len() const {
|
||||
@@ -133,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. */
|
||||
@@ -161,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
|
||||
@@ -254,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. */
|
||||
@@ -322,25 +349,27 @@ public:
|
||||
* A block-diffusion drafter (RAD_DRAFT_BLOCK) proposes a whole block of `block` positions in
|
||||
* one pass, so there are no rounds; instead it runs two passes of different shapes.
|
||||
*
|
||||
* block_begin right after commit(), while plan() still describes the step just run.
|
||||
* Reserves the draft KV block the query pass writes, and returns which
|
||||
* sequences may draft.
|
||||
* block_begin right after the step is issued, before commit(), while plan() still
|
||||
* describes it. Reserves the draft KV block the query pass writes, and
|
||||
* returns which sequences may draft.
|
||||
* block_context the context pass, draft_pass -1. Its entries mirror the trunk step's
|
||||
* row for row (BlockSeq).
|
||||
* block_query the query pass, draft_pass +1. One entry per drafting sequence: the
|
||||
* anchor at its next position, then `block - 1` masks; `out_ids` names the
|
||||
* last `depth` rows.
|
||||
* block_end moves the filled range over what actually ran.
|
||||
* block_end after commit(): moves the filled range over what actually ran.
|
||||
*
|
||||
* The drafter writes its proposal to its declared proposal buffer, not through the sampler,
|
||||
* and the engine publishes it through set_draft().
|
||||
*
|
||||
* On the card (`on_card`), block_begin runs before commit() instead, right after the step is
|
||||
* issued, so both passes queue behind it with no readback in between. The context pass is
|
||||
* unchanged: it mirrors the trunk step, whose positions the host knows. The query pass's
|
||||
* anchor depends on acceptance, so its rows are device rows (advance.h, ADV_BLOCK) staged at
|
||||
* the furthest position acceptance could leave, and the reservation covers that far.
|
||||
* block_end still runs after commit().
|
||||
* Both passes queue behind the step with no readback in between. The context pass mirrors the
|
||||
* trunk step, whose positions the host knows. The query pass's anchor depends on acceptance,
|
||||
* so its rows are device rows (advance.h, ADV_BLOCK) staged at the furthest position
|
||||
* acceptance could leave, and the reservation covers that far.
|
||||
*
|
||||
* With `on_card` false, block_begin runs after commit() instead and stages the query pass
|
||||
* from the committed sequence. The engine does not use it; it is the reference the
|
||||
* scheduler's tests hold the card's staging to.
|
||||
*/
|
||||
struct BlockRow {
|
||||
uint64_t seq = 0;
|
||||
@@ -353,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();
|
||||
@@ -397,6 +437,12 @@ public:
|
||||
* --busy-prefill-chunk is off, or when auto has nothing to reserve. */
|
||||
int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve,
|
||||
bool shared = false, bool rows_only = false) const;
|
||||
/* Where a prefill chunk of a `n_target`-token sequence may end. For a sequence with a runtime
|
||||
* window (IKVManager::set_window) a chunk ends at the prompt, and past it the output a
|
||||
* recompute replays runs one token a step: the ring rewrites its slots in place, so a
|
||||
* multi-token chunk past the floor would overwrite keys its own earlier rows still read, while
|
||||
* one token a step attends as its decode step did. Otherwise `n_target`. */
|
||||
int64_t chunk_end(const Request& r, int64_t n_target) const;
|
||||
|
||||
private:
|
||||
Program* prog_ = nullptr;
|
||||
@@ -429,6 +475,13 @@ private:
|
||||
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
|
||||
* Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
|
||||
bool hit_holes_trunk_ = false;
|
||||
/* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a
|
||||
* sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does
|
||||
* not declare one, in which case admission and commit are exactly as before. A sequence with
|
||||
* one keeps its prompt as a reference and decodes into a ring after it; it is excluded from
|
||||
* prefix publish, checkpoints and speculation (the window is runtime data). */
|
||||
struct RswaWindow { int32_t group = -1; int64_t tokens = 0; };
|
||||
std::vector<RswaWindow> rswa_windows_;
|
||||
/* Draft refill: the drafter's window where a hit can leave a hole in a windowed block
|
||||
* drafter's cache, else 0. The drafter would be declined until its window slid past the hole,
|
||||
* which on a chat's follow-up turn is most of the reply, so the hit ends one window before the
|
||||
@@ -616,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_;
|
||||
|
||||
|
||||
+36
-4
@@ -35,6 +35,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
|
||||
@@ -107,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;
|
||||
@@ -202,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 {
|
||||
@@ -708,10 +729,21 @@ public:
|
||||
std::shared_ptr<mm::Item>* out, std::string* why) override {
|
||||
if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; }
|
||||
if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why);
|
||||
return k == MediaKind::Image
|
||||
? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
|
||||
opts.max_pixels)
|
||||
: p_->video(bytes.data(), bytes.size(), out, why);
|
||||
if (k == MediaKind::Video) return p_->video(bytes.data(), bytes.size(), out, why);
|
||||
mm::ImageMode mode;
|
||||
mode.kind = (int32_t)opts.image_mode;
|
||||
mode.base_size = opts.image_base_size;
|
||||
mode.image_size = opts.image_size;
|
||||
mode.several = opts.several_pictures;
|
||||
/* The host share of a picture (decode, resample, patch staging), apart from the tower
|
||||
* pass engine_mm.cpp times. */
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const int rc = p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
|
||||
opts.max_pixels, mode);
|
||||
RAD_DEBUG("mm: host processor %lld bytes -> %.1f ms (rc %d)", (long long)bytes.size(),
|
||||
std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - t0).count(), rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
|
||||
|
||||
+143
-18
@@ -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;
|
||||
@@ -339,9 +460,13 @@ HttpResponse Server::handle_speech(const HttpRequest& req) {
|
||||
std::string pcm;
|
||||
for (const gen::AudioChunk& c : chunks) append_pcm16(c.samples, &pcm);
|
||||
const double secs = (double)pcm.size() / 2.0 / (double)(info.channels * info.sample_rate);
|
||||
RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s%s", secs,
|
||||
(long long)ticket->frames, (long long)ticket->windows,
|
||||
(double)(ticket->t_done_ns - ticket->t_submit_ns) * 1e-9,
|
||||
auto sec = [](int64_t a, int64_t b) { return a > 0 && b >= a ? (double)(b - a) * 1e-9 : 0.0; };
|
||||
RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s: queue and prompt %.1f s, "
|
||||
"first audio %.1f s, frames %.1f s%s", secs, (long long)ticket->frames,
|
||||
(long long)ticket->windows, sec(ticket->t_submit_ns, ticket->t_done_ns),
|
||||
sec(ticket->t_submit_ns, ticket->t_prompt_ns),
|
||||
sec(ticket->t_submit_ns, ticket->t_first_audio_ns),
|
||||
sec(ticket->t_prompt_ns, ticket->t_frames_ns),
|
||||
ticket->model_ended ? "" : " (the request's length)");
|
||||
HttpResponse res;
|
||||
res.status = 200;
|
||||
|
||||
+178
-183
@@ -55,6 +55,18 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
|
||||
}
|
||||
|
||||
if (req.method == "POST") {
|
||||
/* The default applies to every client's requests that name no choice, so a server
|
||||
* started without --api-key takes the change from a loopback client only, as it does a
|
||||
* runtime adapter load. */
|
||||
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
|
||||
ApiError e;
|
||||
e.status = 403;
|
||||
e.type = "permission_error";
|
||||
e.message = "without --api-key, the control-vector default is changed only from a "
|
||||
"loopback client; start the server with --api-key to change it from "
|
||||
"elsewhere";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
json body;
|
||||
try {
|
||||
body = json::parse(req.body.empty() ? "{}" : req.body);
|
||||
@@ -138,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 } };
|
||||
@@ -167,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;
|
||||
@@ -222,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 },
|
||||
@@ -568,16 +661,10 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; }
|
||||
.stack { display:grid; gap:14px; }
|
||||
@media (max-width:1000px) {
|
||||
.body { grid-template-columns:minmax(0,1fr); }
|
||||
/* On a phone the page is one column you drag with your thumb. A nested scroller that
|
||||
* refuses to chain (overscroll-behavior:contain, set for the desktop wheel so a scroll
|
||||
* over the request table does not move the page behind it) traps the drag here: you
|
||||
* scroll the card, it bottoms out, and the page will not follow, so you reach for the
|
||||
* margins where no scroller lives to get the page moving again. On narrow screens let
|
||||
* the scroll chain to the document; the desktop containment stays.
|
||||
* .body .hold, not .hold: the base .hold rule is defined LATER in this file, so a bare
|
||||
* .hold override here would match and still LOSE the cascade (equal specificity, later
|
||||
* wins) -- judge slice 31 caught exactly that dead-code trap, and the operator's thumb
|
||||
* confirmed it on the request table. .body .hold wins on specificity regardless of order. */
|
||||
/* In one column a nested scroller with overscroll-behavior:contain (there so a desktop wheel
|
||||
* over the request table does not move the page) traps a touch drag once it bottoms out, so
|
||||
* narrow screens let the scroll chain to the document. `.body .hold` rather than `.hold`: the
|
||||
* base .hold rule comes later in this sheet and would win at equal specificity. */
|
||||
.body .panel > .pbody, .body .hold { overscroll-behavior:auto; }
|
||||
}
|
||||
|
||||
@@ -1488,66 +1575,31 @@ function setMetric(key, value, text) {
|
||||
spark(key, hist[key]);
|
||||
}
|
||||
|
||||
/* BEST / RECENT / NOW ON THE OTHER FOUR TILES, in the shape the decode step established.
|
||||
*
|
||||
* WHAT THESE ARE NOT: engine figures. The engine publishes a floor and a recent window for the
|
||||
* decode step alone (step_ns_decode_best / _recent); for tok/s, requests in flight and acceptance
|
||||
* it publishes ONE figure per poll and nothing older. So these three figures are page-side, and
|
||||
* they mean:
|
||||
* best / highest - the extreme this page session has seen AT THE CURRENT CONCURRENCY.
|
||||
* Resets on reload, not on restart.
|
||||
* recent - the mean over the last 15 s at that concurrency; 5 s on prefill, whose
|
||||
* events are shorter than the window that would fit them. Shorter
|
||||
* than the sparkline on purpose:
|
||||
* a 60 s mean still read 31 tok/s fifty seconds after the lane went
|
||||
* quiet, which is the lane being remembered rather than measured.
|
||||
/* Best / recent / now on the decode, prefill, in-flight and acceptance tiles. The engine
|
||||
* publishes a floor and a recent window only for the decode step; for these it publishes one
|
||||
* figure per poll, so the three figures are the page's own:
|
||||
* best / highest - the extreme this page has seen at the current concurrency; it resets on
|
||||
* reload, not on a server restart. "highest" where more is not better.
|
||||
* recent - the mean of the last RECENT samples at that concurrency.
|
||||
* now - the current value as a percentage of that extreme.
|
||||
* "highest" rather than "best" on the two tiles where more is not better: a lane at its highest
|
||||
* request count is busy, not good. The word carries a direction the number alone does not.
|
||||
* Figures are kept per concurrency ("@cN" past one), because a batched rate read against the
|
||||
* single-stream best reports a batch arriving as a level change. Requests in flight keeps one
|
||||
* bucket, since its value is the concurrency, and it samples idle polls too. Idle polls record
|
||||
* nothing in a concurrency bucket, and the line keeps the last active concurrency's figures
|
||||
* without a now clause. There is no ~99 cap as on the decode step: the extreme comes from the
|
||||
* same series as `now`, so 100% is exact.
|
||||
*
|
||||
* PER-CONCURRENCY BUCKETS, the decode step's structure: a c8 rate read against the
|
||||
* single-stream best reports the batch arriving as a level change -- the mistake that took
|
||||
* the old drift line out. Every figure on the line describes the current concurrency, and
|
||||
* past c1 the line says so ("@c8"). Requests in flight is the exception: its value IS the
|
||||
* concurrency, so bucketing it by concurrency would pin "highest" to the current number
|
||||
* forever -- it keeps one session-wide bucket. While the lane is idle nothing new is
|
||||
* recorded and the line keeps the last active concurrency's figures: frozen, no now clause,
|
||||
* which is what the Decode Step tile does at idle.
|
||||
*
|
||||
* NO ~99 CAP HERE, unlike the decode step. That cap exists because `now` there is a 500 ms poll
|
||||
* mean measured against a 32-step window mean -- different instruments, so a fast stretch can read
|
||||
* faster than the floor without being one. Here the extreme is computed FROM the same series as
|
||||
* `now`, so exceeding it is arithmetically impossible and 100% is exact: you are at your best.
|
||||
*/
|
||||
/* RECENT'S OWN WINDOW, deliberately shorter than the sparkline's. HIST is 60 s and that is right
|
||||
* for a picture -- a sparkline wants the whole minute to show shape. It is wrong for a number:
|
||||
* measured over real traffic (two 5 s bursts inside a quiet minute), a 60 s mean still read 31.7
|
||||
* tok/s fifty seconds after the lane went quiet, and 30 s only brought that to 26.9. Fifteen
|
||||
* seconds decays to zero within a quarter-minute of silence while still tracking the running mean
|
||||
* mid-burst (52.8 against an actual 53.3). Ten and five overshoot -- 79 and 144 against that same
|
||||
* 53 -- which is the current value wearing a different name, and the big number above already is
|
||||
* that. `best`/`highest` stay full-session: an extreme wants every chance to be broken.
|
||||
* Idle polls do not enter an active bucket -- the lane is not at that concurrency while it
|
||||
* sleeps -- but they DO count in requests in flight's window, whose value is meaningful
|
||||
* while nothing runs.
|
||||
*
|
||||
* PREFILL GETS ITS OWN WINDOW (RECENT_PREFILL, 5 s). Measured: small prompts prefill in 1.5-6 s
|
||||
* above 100 tok/s; the operator's compaction reload -- the big one -- runs 7-15 s by his own
|
||||
* count. A 15 s mean cannot report a 7 s event while it is running: it reaches barely half the
|
||||
* peak by the event's end, then spends a quarter-minute averaging it down. Five seconds is
|
||||
* shorter than the shortest event, so `recent` rides the prefill while it happens instead of
|
||||
* diluting it. The engine's own figure is already a windowed rate (its help text: "over the
|
||||
* scheduler's recent window"), so this window sits on top of the engine's smoothing -- it
|
||||
* decides how long the page remembers, not how sharply the engine measures. */
|
||||
const RECENT = 30; /* 15 s at the 500 ms poll WHILE the quantity keeps updating; a quantity
|
||||
that skips polls (acceptance, which only samples when it drafts) spans
|
||||
30 UPDATES, which under sparse drafting is minutes, not 15 s. */
|
||||
const RECENT_PREFILL = 10; /* 5 s: shorter than the shortest prefill event (see above) */
|
||||
* RECENT is shorter than the sparkline's 60 s: a 60 s mean still shows a burst long after the lane
|
||||
* went quiet, and 15 s decays within a quarter-minute while still tracking the mean mid-burst.
|
||||
* Prefill's window is 5 s, so `recent` follows a prefill of several seconds while it runs instead
|
||||
* of diluting it; the engine's prefill rate is itself already windowed. */
|
||||
const RECENT = 30; /* 15 s at the 500 ms poll for a figure sampled every poll; acceptance is
|
||||
sampled only on polls that drafted, so its 30 samples can span minutes */
|
||||
const RECENT_PREFILL = 10; /* 5 s */
|
||||
const extAt = {}, winAt = {};
|
||||
let lastActiveC = 0;
|
||||
/* `win` false records the extreme only. Acceptance keeps its own pooled ring (accPool) and
|
||||
* reads `highest` from extAt, so a window here would be a second, never-read copy of the
|
||||
* same samples -- dead weight that a reviewer reasonably reads as a second figure. */
|
||||
/* `win` false records the extreme only: acceptance pools its window in accPool and reads only
|
||||
* `highest` from extAt. */
|
||||
function noteSample(key, c, value, cap, win) {
|
||||
if (value == null || !finite(value)) return;
|
||||
const e = extAt[key] || (extAt[key] = {});
|
||||
@@ -1558,12 +1610,11 @@ function noteSample(key, c, value, cap, win) {
|
||||
s.push(value); if (s.length > (cap || RECENT)) s.shift();
|
||||
}
|
||||
function triple(key, c, label, fmt, showNow) {
|
||||
/* RECENT IS A WINDOW MEAN, not a window maximum -- a maximum would sit equal to `best` on
|
||||
* any steady lane, and two figures that always agree read as a broken instrument. */
|
||||
/* `recent` is a window mean: a window maximum would equal `best` on any steady lane. */
|
||||
const e = extAt[key];
|
||||
if (!e || !(c in e)) return "";
|
||||
/* A bucket whose extreme is zero still has a story -- requests in flight has seen nothing yet --
|
||||
* so it renders. Only the `now` clause needs a nonzero extreme to divide by. */
|
||||
/* A bucket whose extreme is zero still renders (requests in flight before the first request);
|
||||
* only the `now` clause needs a nonzero extreme to divide by. */
|
||||
const s = winAt[key][c];
|
||||
let sum = 0;
|
||||
for (const v of s) sum += v;
|
||||
@@ -1571,14 +1622,13 @@ function triple(key, c, label, fmt, showNow) {
|
||||
const now = s[s.length - 1];
|
||||
const tag = typeof c === "number" && c > 1 ? "@c" + c : "";
|
||||
let out = label + " " + fmt(e[c]) + " · recent " + fmt(recent);
|
||||
/* THE SAME GUARD THE DECODE STEP USES: no `now` clause while nothing is running. A rate of
|
||||
* zero is the lane being idle, not the lane being slow, and "now 0% of best" reads as a
|
||||
* fault. The "@cN" tag rides the tail, exactly where the decode step puts it. */
|
||||
/* No `now` clause while nothing runs, as on the decode step: a zero rate is an idle lane, and
|
||||
* "now 0% of best" would read as a fault. */
|
||||
if (showNow !== false && e[c] > 0) out += " · now " + Math.round(100 * now / e[c]) + "% of " + label + tag;
|
||||
return out;
|
||||
}
|
||||
/* The acceptance tile's detail line: highest stays the full-session extreme of window ratios
|
||||
* (an extreme is an extreme), but recent and now are POOLED ratios of sums (see above). */
|
||||
/* The acceptance tile's detail line. `highest` is the session's extreme of per-poll ratios;
|
||||
* `recent` is a pooled ratio of sums over the ring (accWindow) and `now` the newest poll's. */
|
||||
function acceptTriple(c, showNow) {
|
||||
const e = extAt["accept"];
|
||||
const ring = accPool[c];
|
||||
@@ -1594,26 +1644,20 @@ function acceptTriple(c, showNow) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/* WINDOWED ACCEPTANCE. The engine's figure is cumulative and exact -- tot_accepted_/tot_drafted_
|
||||
* over the life of the process -- so a best/recent/now line built on it would print the same
|
||||
* number three times and call it a trend. The per-position counters the acceptance chart already
|
||||
* reads are cumulative too, and the DIFFERENCE between two polls is exact acceptance over that
|
||||
* interval, which is the only figure a detail line can move on. Each sample is one poll's delta
|
||||
* (~500 ms, and only when it drafted); `recent` POOLS the last RECENT such deltas AT THAT
|
||||
* CONCURRENCY and `now` is the newest one -- different windows, free to disagree.
|
||||
* The counters go backwards when the engine restarts; that poll resets the window rather than
|
||||
* reporting a negative draft. */
|
||||
/* Acceptance over a window. The engine's draft_accept is accepted / drafted over the life of
|
||||
* the process, so it barely moves on a long-running server. The per-position counters are
|
||||
* cumulative too, and their difference between two polls is the exact conditional acceptance
|
||||
* (accepted / reached) over that interval. Each ring entry is one poll that drafted; the ring is
|
||||
* kept per concurrency and pooled as sum(accepted) / sum(reached), because polls carry unequal
|
||||
* draft counts and a mean of their ratios would weigh a quiet poll like a busy one. */
|
||||
const accPool = {}; /* per concurrency: ring of {dr, da} for the pooled tile window */
|
||||
let accPrev = null, accUp = -1;
|
||||
function accWindow(s) {
|
||||
let reach = 0, hit = 0;
|
||||
for (const p of (s.draft_positions || [])) { reach += p.reached || 0; hit += p.accepted || 0; }
|
||||
/* RESTART DETECTION (2026-10-20, Turnstone audit). Counters going BACKWARDS catches a restart
|
||||
* the page was watching. uptime_s going backwards catches the one it missed: a backgrounded
|
||||
* tab whose accPrev froze while a new process drafted past the old process's lifetime total,
|
||||
* where the delta is positive and the first guard never fires. Either clears every pooled
|
||||
* ring -- a pre-restart pair must not pool with a post-restart one -- and yields no delta,
|
||||
* so the headline reads the idle 0 rather than a dead process's ratio. */
|
||||
/* A server restart: the counters go backwards, or, for a hidden tab that stopped polling while
|
||||
* a new process drafted past the old totals, uptime_s does. Either clears every ring, so counts
|
||||
* from two processes never pool, and yields no delta for this poll. */
|
||||
const up = s.uptime_s;
|
||||
const restart = accPrev !== null && (reach < accPrev.r || hit < accPrev.a ||
|
||||
(typeof up === "number" && up < accUp));
|
||||
@@ -1674,13 +1718,9 @@ function kvPanel(host, keys) {
|
||||
return out;
|
||||
}
|
||||
const totals = kvPanel($("totals"), ["Requests", "Steps"]);
|
||||
/* "Accepted of drafted" is the LIFETIME MARGINAL ratio -- the engine's figure, unchanged, and
|
||||
* the one this panel used to carry as its headline. A bullet now rather than the big number:
|
||||
* see the note at the accept tile. It divides by every token DRAFTED, so it is not comparable
|
||||
* with the live figure above it, which divides by the positions actually REACHED; the two bases
|
||||
* are worked through in README.md, section "Draft acceptance", and both are derivable from the
|
||||
* log. Each label names its own denominator, which is the whole distinction -- so neither needs
|
||||
* a tooltip, and a tooltip would be invisible on the phone anyway. */
|
||||
/* "Accepted of drafted" is the engine's lifetime draft_accept, accepted / drafted. The panel's
|
||||
* big figure divides by the positions reached instead, so the two are not comparable; each label
|
||||
* names its denominator (docs/GUIDE.md, section 6.1). */
|
||||
const spec = kvPanel($("spec"), ["Drafter", "Depth", "Accepted of drafted"]);
|
||||
|
||||
/* ---------------------------------------------------------------- meters */
|
||||
@@ -1915,7 +1955,7 @@ function renderRequests(list, poolTokens) {
|
||||
|
||||
/* ---------------------------------------------------------------- update */
|
||||
let prev = null, prevAt = 0, bars = [], devs = [], layerBars = [];
|
||||
let lastStepMs = null; /* lastTps retired with the per-step freeze (slice 26) */
|
||||
let lastStepMs = null;
|
||||
|
||||
/* The single-stream floor and the engine's most recent window, shown as two numbers with no
|
||||
* verdict. The engine records the fastest single-sequence decode window it has measured
|
||||
@@ -1937,13 +1977,9 @@ function update(s, dt) {
|
||||
* mixed load the answer is the mean of two populations. `step_ns_decode / steps_decode` is
|
||||
* neither -- it is what a decode step cost.
|
||||
*
|
||||
* A window with no decode steps in it reads 0, not the last reading (operator ruling
|
||||
* 2026-10-20, second pass): every other live figure on this page shows 0 when the lane is idle
|
||||
* -- tps() renders 0 as "0" and the engine publishes 0 rates -- so 0 IS the idle signal here,
|
||||
* and the dash stays reserved for a quantity that has no value at all. A held value was the
|
||||
* original sin (a stale number wearing a current name); a dash was an over-correction that
|
||||
* broke the convention. The floor and the engine's recent window below are the engine's own
|
||||
* figures and stay put. */
|
||||
* A window with no decode steps reads 0, the page's idle figure for every live value; a dash
|
||||
* is kept for a quantity that has no value at all, and a held value would present a stale
|
||||
* reading as current. The engine's floor and recent window below keep their values. */
|
||||
const dSteps = prev ? s.steps_decode - prev.steps_decode : 0;
|
||||
const stepMs = dSteps > 0 ? (s.step_ns_decode - prev.step_ns_decode) / 1e6 / dSteps : null;
|
||||
if (stepMs != null) lastStepMs = stepMs;
|
||||
@@ -1967,10 +2003,8 @@ function update(s, dt) {
|
||||
* ~500 ms poll mean and `best` a 32-step window mean, so a short fast stretch can beat the
|
||||
* floor; the figure is capped at 99 and shown as ~99, "at the best", rather than claiming a
|
||||
* record the window cannot confirm. */
|
||||
/* Gated on this window HAVING decode steps, not on the lane being busy: during a
|
||||
* prefill-only stretch the lane is busy, lastStepMs holds the last DECODE poll, and the
|
||||
* headline correctly reads 0 -- printing "now X% of best" under it would put a stale
|
||||
* value under the word "now", the exact defect the idle-0 ruling exists to kill. */
|
||||
/* Only for a window with decode steps in it: during a prefill-only stretch the headline reads
|
||||
* 0 and lastStepMs is an older poll's, which `now` must not show. */
|
||||
if (stepMs != null && s.running > 0) {
|
||||
const k = s.running;
|
||||
if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs;
|
||||
@@ -2022,41 +2056,22 @@ function update(s, dt) {
|
||||
const aw = accWindow(s);
|
||||
const awR = aw ? aw.ratio : null;
|
||||
if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR, null, false);
|
||||
/* POOLED ACCEPTANCE WINDOW (2026-10-20, math audit before the production roll).
|
||||
* triple()'s `recent` averages the per-poll RATIOS; polls carry unequal draft counts, so a
|
||||
* quiet poll and a 500-draft poll would weigh the same -- a mean of ratios, not a ratio of
|
||||
* sums. Measured on a live c8 burst: avg-of-ratios 65.7% vs pooled 54.7%, a 11-point skew
|
||||
* that grows with burstiness. The honest window figure is sum(accepted)/sum(reached) over
|
||||
* the same span, so the tile keeps its own ring of delta pairs per concurrency. */
|
||||
/* The pooled ring (see accWindow), per concurrency. */
|
||||
if (aw != null && aw.dr > 0) {
|
||||
const c = s.running > 0 ? s.running : lastActiveC;
|
||||
const ring = accPool[c] || (accPool[c] = []);
|
||||
ring.push(aw); if (ring.length > RECENT) ring.shift();
|
||||
}
|
||||
/* THE HEADLINE IS THE LIVE WINDOW, not the cumulative ratio. The engine's figure is exact but
|
||||
* cumulative, so on a process that has been up for hours it cannot move: 559 fresh drafts moved
|
||||
* it one point against a 33,000-draft denominator, and it froze outright the moment the lane
|
||||
* went quiet. Every other tile's big number is the current value, and feeding the cumulative one
|
||||
* here also fed the sparkline a quantity that is flat by construction.
|
||||
* Polls with no new drafts read 0 (operator ruling 2026-10-20, second pass): the page's
|
||||
* convention is that a live figure shows 0 when the lane is doing nothing, and the dash is for
|
||||
* quantities with no value at all. The original freeze was the real defect -- a held value
|
||||
* reads as a live measurement of a lane that drafted nothing. The lifetime ratio stays on
|
||||
* /stats and /metrics; what the tile answers is "what is it accepting now", and now, idle,
|
||||
* it is accepting nothing.
|
||||
* THE SPARKLINE'S SCALE IS THE SAME as the other tiles -- 120 samples at the 500 ms poll, 60 s
|
||||
* -- because setMetric samples every poll, idle polls included (0 is a value; see above). The
|
||||
* one difference is the dash case: with no draft head there is no value to push, so those polls
|
||||
* leave a gap and the line stretches over more wall-clock than 60 s. (Judge slice 4C: this
|
||||
* comment claimed a 10 s window, then a drafting-only window; neither sampling scheme exists.) */
|
||||
/* The headline is this poll's conditional acceptance, as every other tile's big number is the
|
||||
* current value; the lifetime ratio stays in the Speculation panel, on /stats and on /metrics.
|
||||
* A poll that drafted nothing reads 0, the page's idle figure, and the dash means there is no
|
||||
* draft head. The sparkline takes a sample every poll, idle ones included, like the other
|
||||
* tiles; without a draft head it takes none. */
|
||||
if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH);
|
||||
else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0));
|
||||
else setMetric("accept", 0, pctn(0, 0)); /* drafted nothing this poll -> 0, the idle figure */
|
||||
/* `now` is shown only when THIS poll drafted. The guard inside acceptTriple (last.dr > 0)
|
||||
* cannot ever be false -- the ring only stores deltas with dr > 0 -- so the freshness test
|
||||
* belongs here, where the poll's own delta is known. Otherwise a busy lane that drafted
|
||||
* nothing this poll shows 0 in the headline and "now Z% of highest" one line below it,
|
||||
* computed from the last drafted delta. highest/recent are session statistics and stay. */
|
||||
/* `now` only when this poll drafted: the ring holds only polls that did, so its newest entry
|
||||
* may be older than this poll, whose headline then reads 0. */
|
||||
$("m-acceptdet").textContent = acceptTriple(cNow, busy && awR != null);
|
||||
M.flight.u.textContent = "/ " + s.queue_cap;
|
||||
|
||||
@@ -2084,11 +2099,9 @@ function update(s, dt) {
|
||||
const kvLive = Math.max(0, (s.kv_tokens_used || 0) - kvCached);
|
||||
mKv.v.textContent = hbOf(s.kv_bytes_used, s.kv_bytes_total, " / ") + " · " + pct(kvFrac);
|
||||
setSplit(mKv, kvLive, kvCached, s.kv_tokens_total || 0);
|
||||
/* WHAT THE SEGMENTS ARE, IN THE WORDS OF WHAT THEY WOULD COST TO RECLAIM, because a dimmer bar
|
||||
is not self-explanatory and the phrase this line used to carry -- "in flight" against "held
|
||||
for the next turn" -- named neither thing it was measuring. The split is by who references
|
||||
the blocks: the first part is context a request on the card is reading and cannot be taken
|
||||
from it, the second is context nothing is reading and the next eviction frees. */
|
||||
/* The segments named by what reclaiming them would cost, since a dimmer bar is not
|
||||
self-explanatory. The split is by who references the blocks: the first part is context a
|
||||
request on the card is reading, the second context nothing reads and the next eviction frees. */
|
||||
mKvSub.textContent = s.kv_tokens_used > 0
|
||||
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
|
||||
: "";
|
||||
@@ -2141,34 +2154,17 @@ function update(s, dt) {
|
||||
* gives tokens a step for the whole batch -- which grows with concurrency and says nothing
|
||||
* about the drafter. What speculation buys is tokens a step for ONE sequence. */
|
||||
const perStep = sps > 0 && s.decode_tps > 0 ? s.decode_tps / sps / seqs : null;
|
||||
/* Reads 0 when this window took no decode steps -- the page's idle figure, same law as
|
||||
* the step tile above it, which this figure is derived from. It used to hold the last
|
||||
* value, so a lane that stopped decoding kept reporting what its steps used to cost.
|
||||
* (Extension of the operator's idle-0 ruling by one figure: same defect, one line down,
|
||||
* flagged by judge slice 26 as "pre-existing, now more visible".) */
|
||||
/* 0 for a window with no decode steps, as on the step tile it derives from. */
|
||||
$("tps_n").firstChild.nodeValue = perStep == null ? "0" : sig3(perStep);
|
||||
/* ACCEPTED IS THE LIVE FIGURE, matching the tile above it. `aw` is the same pooled drafting
|
||||
* window the tile's headline reads, computed earlier in this function -- one derivation, two
|
||||
* readers, so the panel and the tile cannot disagree.
|
||||
* DESIGN DECISION, 10-19, at the Operator's direction: this section shows the REAL-TIME
|
||||
* accepted percentage and the lifetime average sits in the bullets below it. The reasoning is
|
||||
* on the tile; the short form is that a cumulative ratio on a process that has been up for
|
||||
* hours is a number that cannot move, and a headline that cannot move reads as a dead page.
|
||||
* PINNED, NOT PRICED: the Operator may prefer the average back in the big seat, and the swap
|
||||
* is these two lines. What must not happen is the average returning as the headline with no
|
||||
* bullet left behind, because then the live figure is the thing nobody can see.
|
||||
* Nothing drafted this poll reads 0 -- the page's idle figure, same law as the accept tile
|
||||
* (op ruling 2026-10-20, second pass). The defect being fixed is the FREEZE: a held value
|
||||
* reads as a live measurement of a lane that drafted nothing. */
|
||||
/* The same per-poll conditional acceptance as the accept tile's headline (accWindow), so the
|
||||
* two cannot disagree; 0 when this poll drafted nothing. The lifetime ratio is the
|
||||
* "Accepted of drafted" bullet below. */
|
||||
if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0);
|
||||
else $("acc_n").firstChild.nodeValue = pctn(0, 0); /* idle: 0, the page's idle figure */
|
||||
$("specaside").textContent = "depth " + dp.length;
|
||||
spec["Drafter"].textContent = drafterName;
|
||||
spec["Depth"].textContent = dp.length;
|
||||
/* The lifetime marginal, always shown. Judge 22: guarding on >0 conflated "no drafts yet"
|
||||
* with "drafts made, all rejected" -- a drafter that accepts nothing is exactly the case a
|
||||
* reader needs to see, and a dash hid it. 0 is the honest figure for both, and the README's
|
||||
* "Draft acceptance" section says which question this bullet answers. */
|
||||
/* Always shown: 0% is also what a drafter that accepts nothing reads, which a dash would hide. */
|
||||
spec["Accepted of drafted"].textContent = pct(s.draft_accept, 0);
|
||||
}
|
||||
|
||||
@@ -3312,32 +3308,24 @@ async function identify() {
|
||||
} catch (err) { /* the header simply keeps its placeholder */ }
|
||||
}
|
||||
|
||||
/* THE CONTROL VECTOR, asked when the Model view opens. It is not a polled value: it changes only
|
||||
* when this page (or an admin call) flips it, and a control that silently reverted under the
|
||||
* reader would be worse than one that is a second old. A deployment without a control vector
|
||||
* answers 404 and the panel stays hidden. */
|
||||
/* The control vector, read when the Model view opens rather than polled: only this page or an
|
||||
* admin call changes it. 404 means the deployment has none and hides the panel; any other failure
|
||||
* keeps the panel and says why, so a page without the API key does not look like a build without
|
||||
* the feature. */
|
||||
async function loadControlVector() {
|
||||
/* THREE OUTCOMES, and only one of them hides the panel:
|
||||
* 404 this deployment has no control vector -- there is no such control, so it is omitted;
|
||||
* 200 the vector is loaded -- show the switch and its state;
|
||||
* anything else (most often 401, the page has no API key yet) -- the feature may well be
|
||||
* there, so SAY that instead of hiding the control. A control that silently disappears
|
||||
* because the page has not signed in reads exactly like a build without the feature. */
|
||||
try {
|
||||
const r = await api("admin/control-vector");
|
||||
if (r.status === 404) { $("cvpanel").hidden = true; return; }
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
if (!r.ok) { const err = new Error(String(r.status)); err.status = r.status; throw err; }
|
||||
const p = await r.json();
|
||||
$("cvpanel").hidden = false;
|
||||
$("cvbox").disabled = false;
|
||||
$("cvbox").checked = !!p.default;
|
||||
/* The family leads: it is the one term that says whether this file belongs to the model on the
|
||||
* card at all, and it is the loader's own answer, not a label the page invents. */
|
||||
/* The family the loader validated the file against, then its range and scale. */
|
||||
$("cvsum").textContent = (p.arch ? p.arch + " \u00b7 " : "") + "layers " + p.first +
|
||||
"\u2013" + p.last + " \u00b7 " + p.mode + " \u00b7 scale " + p.scale;
|
||||
/* New requests only, because a running request keeps the choice it was admitted with; and a
|
||||
* session whose context already holds a refusal can repeat it, since the refusal is in the
|
||||
* prompt the next turn reads. */
|
||||
/* A running request keeps the choice it was admitted with, and a refusal already in a
|
||||
* session's context is in the prompt the next turn reads. */
|
||||
$("cvnote").textContent = "New requests only. A session with a refusal already in its " +
|
||||
"context may repeat it.";
|
||||
} catch (e) {
|
||||
@@ -3345,9 +3333,10 @@ async function loadControlVector() {
|
||||
$("cvbox").disabled = true;
|
||||
$("cvbox").checked = false;
|
||||
$("cvsum").textContent = "";
|
||||
$("cvnote").textContent =
|
||||
"Sign in with the API key (the field in the header) to read or change this: the vector " +
|
||||
"is present on this deployment, but its state needs the key.";
|
||||
$("cvnote").textContent = e.status === 401
|
||||
? "Sign in with the API key (the field in the header) to read or change this: the vector " +
|
||||
"is present on this deployment, but its state needs the key."
|
||||
: "The server did not report the control vector's state (" + (e.status || e.message) + ").";
|
||||
}
|
||||
}
|
||||
$("cvbox").addEventListener("change", async (e) => {
|
||||
@@ -3360,11 +3349,17 @@ $("cvbox").addEventListener("change", async (e) => {
|
||||
apiKey ? { Authorization: "Bearer " + apiKey } : {}),
|
||||
body: JSON.stringify({ enabled: want }),
|
||||
});
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
if (!r.ok) {
|
||||
let msg = String(r.status);
|
||||
try { const j = await r.json(); if (j && j.error && j.error.message) msg = j.error.message; }
|
||||
catch (_) { /* the status alone */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
const p = await r.json();
|
||||
$("cvbox").checked = !!p.default;
|
||||
} catch (err) {
|
||||
e.target.checked = !want; // the server kept the old value
|
||||
$("cvnote").textContent = "Not changed: " + err.message;
|
||||
} finally {
|
||||
e.target.disabled = false;
|
||||
}
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -527,6 +548,14 @@ struct MediaOpts {
|
||||
/* A picture over this many pixels is first scaled down to that area (PIL's bicubic, sides
|
||||
* truncated), as a model's own pipeline may do before its processor; 0 leaves it as sent. */
|
||||
int64_t max_pixels = 0;
|
||||
/* Which of the checkpoint's picture modes, for one that has two (Unlimited-OCR): 0 is the
|
||||
* processor's choice (mm::ImageMode::Default), 1 gundam, 2 base. */
|
||||
int32_t image_mode = 0;
|
||||
/* The mode's sizes, when the request states them; 0 keeps the mode's own. */
|
||||
int32_t image_base_size = 0, image_size = 0;
|
||||
/* The request carries more than one picture (mm::ImageMode::several): a processor with a
|
||||
* multi-page mode uses it for a picture whose mode the request did not name. */
|
||||
bool several_pictures = false;
|
||||
};
|
||||
|
||||
class IMultimodal {
|
||||
@@ -660,6 +689,8 @@ struct ImageGenInfo {
|
||||
/* The prompt in windows (RadGeneratorDecl::chunk_tokens): tokens a window, its markers and
|
||||
* its padding token; 0 for a prompt read whole. */
|
||||
int32_t chunk_tokens = 0, chunk_bos = 0, chunk_eos = 0, chunk_pad = 0;
|
||||
/* The conditioning options a request may ask for (RadGeneratorDecl::cond_opts, RAD_GEN_COND_*). */
|
||||
uint32_t cond_opts = 0;
|
||||
};
|
||||
|
||||
class IImageGen {
|
||||
@@ -694,6 +725,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 {
|
||||
|
||||
@@ -397,12 +397,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
r.seed = (uint64_t)body["seed"].get<int64_t>();
|
||||
r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
|
||||
}
|
||||
/* Krea 2's fixed tap gains (ConditioningKrea2Rebalance's defaults, arch/krea2); other models
|
||||
* ignore it. */
|
||||
/* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps at
|
||||
* ConditioningKrea2Rebalance's defaults). `false` is accepted everywhere. */
|
||||
if (body.contains("rebalance") && !body["rebalance"].is_null()) {
|
||||
if (!body["rebalance"].is_boolean())
|
||||
return error_response(err_bad("rebalance", "expected true or false"), req.peer);
|
||||
r.rebalance = body["rebalance"].get<bool>();
|
||||
if (r.rebalance && !(info.cond_opts & RAD_GEN_COND_REBALANCE))
|
||||
return error_response(err_unsupported("rebalance", "this model has no rebalance"),
|
||||
req.peer);
|
||||
}
|
||||
if (str("negative_prompt", &r.negative) < 0)
|
||||
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
|
||||
|
||||
+20
-19
@@ -140,8 +140,7 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
g_prefill_tps_.set(m.prefill_tps);
|
||||
g_decode_tps_.set(m.decode_tps);
|
||||
g_draft_accept_.set(m.draft_acceptance);
|
||||
/* Nanoseconds in the scheduler, seconds on the wire: the base unit Prometheus expects, and
|
||||
* what radiance:engine_step_seconds_* already use. */
|
||||
/* Nanoseconds in the scheduler, seconds on the wire, as engine_step_seconds_* use. */
|
||||
g_step_best_.set((double)m.step_ns_decode_best / 1e9);
|
||||
g_step_recent_.set((double)m.step_ns_decode_recent / 1e9);
|
||||
const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS));
|
||||
@@ -190,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);
|
||||
@@ -330,25 +331,17 @@ std::string Metrics::render() const {
|
||||
"Prefill throughput over the scheduler's recent window.", L, g_prefill_tps_.get());
|
||||
w.gauge("radiance:decode_tokens_per_second",
|
||||
"Decode throughput over the scheduler's recent window.", L, g_decode_tps_.get());
|
||||
/* THE DECODE FLOOR, the two figures the dashboard's Decode Step tile shows. They were on
|
||||
* /stats only, and /stats is documented as not a stable API -- so the one figure worth
|
||||
* comparing across restarts was reachable only from the surface automation is told not to
|
||||
* use. Omitted until measured: a floor of 0 seconds is not an unmeasured floor, it is an
|
||||
* infinitely fast one, and a scrape would plot it as a record. Both reset on restart, so a
|
||||
* freshly started server simply has no floor to report yet. */
|
||||
/* The decode floor the dashboard's step tile shows. Each series is omitted until its window
|
||||
* has been measured, because a 0-second step would plot as the fastest ever. */
|
||||
if (g_step_best_.get() > 0)
|
||||
w.gauge("radiance:decode_step_seconds_best",
|
||||
"Fastest single-sequence decode step window this process has run, in seconds "
|
||||
"PER STEP. A mean over 32 consecutive single-stream steps, not a stopwatch "
|
||||
"reading. Not seconds per token: with speculation a step can emit several "
|
||||
"tokens, so per-token time is this divided by (1 + accepted per step), "
|
||||
"not by the accepted figure alone. Resets on restart.", L, g_step_best_.get());
|
||||
"Fastest single-sequence decode window this process has run, in seconds per "
|
||||
"step: the mean of 32 consecutive single-stream steps. With speculation a step "
|
||||
"emits 1 + accepted tokens. Resets on restart.", L, g_step_best_.get());
|
||||
if (g_step_recent_.get() > 0)
|
||||
w.gauge("radiance:decode_step_seconds_recent",
|
||||
"Most recent single-sequence decode step window, in seconds PER STEP (see "
|
||||
"_best: not a token rate). The gap "
|
||||
"to _best tracks what else the machine is doing, not wear; see docs/GUIDE.md. "
|
||||
"Freezes while the lane is idle, because no window is completing.",
|
||||
"Most recent single-sequence decode window, in seconds per step (see _best). "
|
||||
"Holds its value while no single-stream window completes.",
|
||||
L, g_step_recent_.get());
|
||||
w.counter("radiance:engine_steps_total",
|
||||
"Scheduler steps executed. One forward pass of the model, plus whatever draft "
|
||||
@@ -447,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());
|
||||
@@ -463,8 +463,9 @@ std::string Metrics::render() const {
|
||||
c_cut_resumed_below_.get());
|
||||
w.counter("radiance:prefix_restore_cuts_total",
|
||||
"Restores from the host tier the pool could not hold whole, even after giving "
|
||||
"up the VRAM copies of other stored conversations; each came back to a "
|
||||
"snapshot short of its end.", L, c_restore_cuts_.get());
|
||||
"up the VRAM copies of other stored conversations; each came back only in "
|
||||
"part, on a model with recurrent state up to the deepest snapshot the room "
|
||||
"reaches.", L, c_restore_cuts_.get());
|
||||
w.counter("radiance:prefix_hit_cut_tokens_total",
|
||||
"Prompt tokens the attention cache held and admission computed again, because "
|
||||
"the hit resumed at a snapshot below it or reused nothing.", L,
|
||||
|
||||
@@ -113,9 +113,8 @@ private:
|
||||
Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_;
|
||||
Gauge g_kv_max_tokens_, g_kv_max_bytes_;
|
||||
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
|
||||
/* The decode floor, in seconds: the fastest single-sequence window this process has run,
|
||||
* and the most recent one. Both stay 0 until a window of 32 single-stream steps completes,
|
||||
* and both reset on restart -- the render omits them rather than expose an unmeasured 0. */
|
||||
/* The decode floor in seconds: the fastest and the most recent single-sequence window. 0
|
||||
* until a window completes, and render() omits a 0. */
|
||||
Gauge g_step_best_, g_step_recent_;
|
||||
Gauge queue_depth_;
|
||||
/* Per-position conditional draft acceptance (see render() and core/sched/draft.h). */
|
||||
@@ -152,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_;
|
||||
|
||||
+129
-16
@@ -240,7 +240,8 @@ const char* kAcceptedCommon[] = {
|
||||
"dry_sequence_breakers", "samplers",
|
||||
"grammar", "json_schema", "priority", "logprobs", "ignore_eos",
|
||||
"timings_per_token", "return_progress", "session_id", "n_probs",
|
||||
"control_vector", "experimental_speed_projection",
|
||||
"control_vector",
|
||||
"ngram_ban_n", "ngram_window", "ngram_whitelist", "no_repeat_ngram_whitelist",
|
||||
};
|
||||
|
||||
const char* kAcceptedChat[] = {
|
||||
@@ -250,6 +251,8 @@ const char* kAcceptedChat[] = {
|
||||
"thinking_token_budget", "thinking_budget", "thinking_budget_tokens",
|
||||
"reasoning_budget_tokens", "reasoning_format", "continue_final_message",
|
||||
"functions", "function_call",
|
||||
/* Unlimited-OCR's picture modes: which of the checkpoint's two a request's pictures get. */
|
||||
"images_config",
|
||||
};
|
||||
|
||||
/* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the
|
||||
@@ -843,19 +846,12 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
|
||||
/* ignore_eos: generate to max_tokens whatever the model emits. See Request::ignore_eos. */
|
||||
if (!get_bool(b, "ignore_eos", &r->ignore_eos, err)) return RAD_E_INVAL;
|
||||
|
||||
/* The control vector (core/cvec.h): an opt-in per request, and the only place an API client
|
||||
* turns it on when the deployment's default is off. `control_vector` is the field's name;
|
||||
* `experimental_speed_projection` is Strata's spelling of the same switch, kept as an alias so
|
||||
* a client written against that reports what it means -- and read only when the request did not
|
||||
* send the field itself, so the field wins when a body carries both. A JSON null is "not sent",
|
||||
* as everywhere else in this parser. */
|
||||
for (const char* key : { "control_vector", "experimental_speed_projection" }) {
|
||||
const auto it = b.find(key);
|
||||
if (it == b.end() || it->is_null()) continue;
|
||||
/* The control vector (core/cvec.h), per request: absent or null takes the deployment's
|
||||
* default. */
|
||||
if (const auto it = b.find("control_vector"); it != b.end() && !it->is_null()) {
|
||||
bool on = false;
|
||||
if (!get_bool(b, key, &on, err)) return RAD_E_INVAL;
|
||||
if (!get_bool(b, "control_vector", &on, err)) return RAD_E_INVAL;
|
||||
r->control_vector = on ? 1 : 0;
|
||||
break;
|
||||
}
|
||||
|
||||
/* stop: a string or an array of strings. Bounded in count and length because every stop
|
||||
@@ -907,6 +903,95 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
|
||||
auto sid = b.find("session_id");
|
||||
if (sid != b.end() && sid->is_string()) r->session_label = session_label_of(sid->get<std::string>());
|
||||
|
||||
/* The windowed no-repeat-ngram ban (core/sample/sampler.h): `ngram_ban_n` is the banned
|
||||
* n-gram's length and `ngram_window` how far back it looks; the checkpoint's own generation
|
||||
* config asks for 35 and 128 (Unlimited-OCR). The reference spells them
|
||||
* no_repeat_ngram_size and no_repeat_ngram_window_size; both are taken. */
|
||||
i64 = r->sp.ngram_ban_n;
|
||||
if (!get_any(b, { "ngram_ban_n", "no_repeat_ngram_size" }, &i64, nullptr, err))
|
||||
return RAD_E_INVAL;
|
||||
if (i64 < 0 || i64 > 256) {
|
||||
*err = err_bad("ngram_ban_n", "must be in [0, 256]");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
r->sp.ngram_ban_n = (int)i64;
|
||||
i64 = r->sp.ngram_window;
|
||||
if (!get_any(b, { "ngram_window", "no_repeat_ngram_window_size" }, &i64, nullptr, err))
|
||||
return RAD_E_INVAL;
|
||||
if (i64 < 0 || i64 > 131072) {
|
||||
/* The reference's negative window spelling belongs to generation_config, where it is
|
||||
* normalized to 0; a request states the whole-sequence form as 0, matching the sampler's
|
||||
* admission check (check_request refuses a negative window). */
|
||||
*err = err_bad("ngram_window", "must be 0 (search the whole sequence) or a count of at "
|
||||
"most 131072 history tokens");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
r->sp.ngram_window = (int)i64;
|
||||
|
||||
/* The ban's whitelist (the reference's `whitelist_token_ids`, which is removed from the
|
||||
* banned set before the -inf writes): token ids the ban must never touch. An array of
|
||||
* non-negative integers; absent, empty or null is off, the reference's empty whitelist and
|
||||
* the form the model's generation_config ships. */
|
||||
auto nwl = b.find("ngram_whitelist");
|
||||
if (nwl == b.end()) nwl = b.find("no_repeat_ngram_whitelist");
|
||||
if (nwl != b.end() && !nwl->is_null()) {
|
||||
if (!nwl->is_array()) {
|
||||
*err = err_bad("ngram_whitelist", "expected an array of integer token ids");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::vector<int32_t> wl;
|
||||
for (const auto& v : *nwl) {
|
||||
int32_t id = 0;
|
||||
if (!token_id(v, &id)) {
|
||||
*err = err_bad("ngram_whitelist",
|
||||
"expected token ids in [0, " + std::to_string(INT32_MAX) + "]");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (wl.size() >= (size_t)1 << 20) {
|
||||
*err = err_bad("ngram_whitelist", "at most 1048576 ids");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
wl.push_back(id);
|
||||
}
|
||||
r->sp.ngram_whitelist = std::move(wl);
|
||||
}
|
||||
|
||||
/* `images_config`: Unlimited-OCR's two picture modes. A string names one ("gundam" for a
|
||||
* single picture -- the global view plus crops --, "base" for a page of a multi-page
|
||||
* document); an object carries the reference runner's own dict. */
|
||||
auto ic = b.find("images_config");
|
||||
if (ic != b.end() && !ic->is_null()) {
|
||||
if (ic->is_string()) {
|
||||
const std::string m = ic->get<std::string>();
|
||||
if (m == "gundam") r->image_mode = 1;
|
||||
else if (m == "base") r->image_mode = 2;
|
||||
else if (!m.empty()) {
|
||||
*err = err_bad("images_config", "expected \"gundam\" or \"base\", got \"" + m +
|
||||
"\"");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else if (ic->is_object()) {
|
||||
const json& o = *ic;
|
||||
int64_t bs = 0, is = 0;
|
||||
if (!get_int(o, "base_size", &bs, err)) return RAD_E_INVAL;
|
||||
if (!get_int(o, "image_size", &is, err)) return RAD_E_INVAL;
|
||||
bool crop = true;
|
||||
if (!get_bool(o, "crop_mode", &crop, err)) return RAD_E_INVAL;
|
||||
if (bs < 0 || bs > 65536 || is < 0 || is > 65536) {
|
||||
*err = err_bad("images_config", "base_size and image_size must be in [0, 65536]");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
r->image_mode = crop ? 1 : 2;
|
||||
r->image_base_size = (int32_t)bs;
|
||||
r->image_size = (int32_t)is;
|
||||
} else {
|
||||
*err = err_bad("images_config",
|
||||
"expected \"gundam\", \"base\", or an object with base_size, "
|
||||
"image_size and crop_mode");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TRY(apply_sampler_order(b, &r->sp, err));
|
||||
|
||||
auto so = b.find("stream_options");
|
||||
@@ -1488,6 +1573,15 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
|
||||
out->text = rendered;
|
||||
auto pm = std::make_shared<mm::PromptMedia>();
|
||||
const std::string marker = RAD_MEDIA_MARKER;
|
||||
/* Whether the request carries several pictures: a processor with a multi-page mode picks it
|
||||
* for a picture whose mode the request did not name (mm::ImageMode::several). */
|
||||
size_t n_images = 0;
|
||||
for (const auto& m : media) n_images += m.first == MediaKind::Image ? 1 : 0;
|
||||
auto opts_for = [&](MediaKind k) {
|
||||
MediaOpts mo = opts;
|
||||
if (k == MediaKind::Image) mo.several_pictures = n_images > 1;
|
||||
return mo;
|
||||
};
|
||||
size_t pos = 0, mi = 0;
|
||||
for (;;) {
|
||||
size_t at = rendered.find(marker, pos);
|
||||
@@ -1507,7 +1601,8 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
|
||||
}
|
||||
std::shared_ptr<mm::Item> item;
|
||||
std::string why;
|
||||
const int s = d.mm->prepare(media[mi].first, media[mi].second, opts, &item, &why);
|
||||
const int s = d.mm->prepare(media[mi].first, media[mi].second, opts_for(media[mi].first),
|
||||
&item, &why);
|
||||
if (s < 0 || !item) {
|
||||
*err = err_bad("messages[].content[]", "the media could not be used: " +
|
||||
(why.empty() ? std::string(rad_strerror(s))
|
||||
@@ -2069,12 +2164,30 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
|
||||
PromptInput p;
|
||||
if (media.empty()) {
|
||||
/* add_special is false: the template renders the model's special tokens, BOS included;
|
||||
* another would shift every position. */
|
||||
/* add_special is false: the template renders the model's special tokens; BOS is placed
|
||||
* below. */
|
||||
p.tokens = d.tok->encode(rendered, false, /*parse_special=*/true);
|
||||
p.text = rendered;
|
||||
} else {
|
||||
RAD_TRY(tokenize_with_media(rendered, d, media, MediaOpts{}, &p, err));
|
||||
MediaOpts mo;
|
||||
mo.image_mode = out->image_mode;
|
||||
mo.image_base_size = out->image_base_size;
|
||||
mo.image_size = out->image_size;
|
||||
RAD_TRY(tokenize_with_media(rendered, d, media, mo, &p, err));
|
||||
}
|
||||
/* A tokenizer that states add_bos gets exactly one BOS in front. The render drops a BOS the
|
||||
* template writes when add_bos is set (ChatTemplate, as llama.cpp's chat does, which leaves it
|
||||
* to the tokenizer), and some templates never write one, so it is added here unless the
|
||||
* prompt already starts with it. A media run's placeholders shift by one with it. */
|
||||
{
|
||||
const ITokenizer::VocabInfo vi = d.tok->vocab_info();
|
||||
if (vi.add_bos && vi.bos >= 0 && (p.tokens.empty() || p.tokens.front() != vi.bos)) {
|
||||
p.tokens.insert(p.tokens.begin(), vi.bos);
|
||||
if (p.media) {
|
||||
for (auto& pl : p.media->items) pl.tok += 1;
|
||||
p.media->layout();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (p.tokens.empty()) {
|
||||
*err = err_bad("messages", "the rendered prompt tokenised to nothing");
|
||||
|
||||
+7
-4
@@ -94,10 +94,8 @@ struct OaiRequest {
|
||||
|
||||
int n = 1;
|
||||
SamplingParams sp;
|
||||
/* The control vector, tri-state: -1 the request named no choice (the deployment's
|
||||
* runtime default applies), 0 it asked for the stock model, 1 for the loaded control vector.
|
||||
* Parsed from `control_vector` (or Strata's `experimental_speed_projection`); a deployment
|
||||
* with no vector refuses 1 rather than silently serving the stock model. */
|
||||
/* `control_vector`, tri-state: -1 not sent (the deployment's runtime default applies), 0 the
|
||||
* stock model, 1 the loaded control vector. A deployment with no vector refuses 1. */
|
||||
int control_vector = -1;
|
||||
int32_t max_tokens = 0;
|
||||
std::vector<std::string> stop;
|
||||
@@ -163,6 +161,11 @@ struct OaiRequest {
|
||||
/* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */
|
||||
int32_t image_tokens = 0;
|
||||
|
||||
/* `images_config`: which of the checkpoint's picture modes a request's pictures get, and the
|
||||
* sizes it states (Unlimited-OCR's gundam and base modes). 0 keeps the processor's choice
|
||||
* (mm::ImageMode::Default). */
|
||||
int32_t image_mode = 0, image_base_size = 0, image_size = 0;
|
||||
|
||||
int n_choices() const { return (int)prompts.size() * n; }
|
||||
};
|
||||
|
||||
|
||||
@@ -98,10 +98,6 @@ int unsettled_for(const std::string& delay) {
|
||||
return 6; /* medium */
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const std::string& p) {
|
||||
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
|
||||
}
|
||||
|
||||
std::string rtrim(std::string s) {
|
||||
while (!s.empty() && std::isspace((unsigned char)s.back())) s.pop_back();
|
||||
return s;
|
||||
@@ -858,7 +854,7 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
|
||||
const std::string text = detok(ids, /*flush=*/true);
|
||||
const size_t at = speech_transcript_start(f, text, forced, /*closed=*/true);
|
||||
const std::string transcript = rtrim(text.substr(std::min(at, text.size())));
|
||||
if (starts_with(transcript, t->sent)) delta(*t, transcript.substr(t->sent.size()));
|
||||
if (transcript.starts_with(t->sent)) delta(*t, transcript.substr(t->sent.size()));
|
||||
ojson o = event("conversation.item.input_audio_transcription.completed");
|
||||
o["item_id"] = t->id;
|
||||
o["content_index"] = 0;
|
||||
@@ -886,13 +882,13 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
|
||||
const size_t a = speech_transcript_start(f, settled_text, forced, /*closed=*/false);
|
||||
const std::string settled = a == std::string::npos ? std::string()
|
||||
: rtrim(settled_text.substr(a));
|
||||
if (settled.size() > t->sent.size() && starts_with(settled, t->sent))
|
||||
if (settled.size() > t->sent.size() && settled.starts_with(t->sent))
|
||||
delta(*t, settled.substr(t->sent.size()));
|
||||
const std::string all_text = detok(ids, /*flush=*/false);
|
||||
const size_t b = speech_transcript_start(f, all_text, forced, /*closed=*/false);
|
||||
const std::string all = b == std::string::npos ? std::string()
|
||||
: rtrim(all_text.substr(b));
|
||||
const std::string tentative = starts_with(all, t->sent) ? all.substr(t->sent.size())
|
||||
const std::string tentative = all.starts_with(t->sent) ? all.substr(t->sent.size())
|
||||
: std::string();
|
||||
if (tentative != t->tentative) {
|
||||
ojson o = event("radiance.input_audio_transcription.tentative");
|
||||
|
||||
@@ -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
|
||||
@@ -297,8 +303,8 @@ std::vector<std::string> Server::probe_reasoning_efforts() {
|
||||
if (text == plain) same.push_back(w);
|
||||
}
|
||||
/* The level a request naming none gets: the one level whose render is the same. A template may
|
||||
* spend it in a system prompt the client never sees (#113: Qwen3.8's is xhigh). Several, or
|
||||
* none, say nothing. */
|
||||
* spend it in a system prompt the client never sees (Qwen3.8's is xhigh). Several, or none,
|
||||
* say nothing. */
|
||||
if (same.size() == 1) template_default_effort_ = same[0];
|
||||
lim_.reasoning_efforts = set;
|
||||
return set;
|
||||
@@ -467,9 +473,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
}
|
||||
|
||||
/* The control vector: the request's own choice, else the deployment's runtime default. A
|
||||
* deployment with no vector refuses the on state by name -- serving the stock model while the
|
||||
* client believes it asked for the vector would be a silent lie about what produced the text.
|
||||
* (Naming: `control_vector` is the field, `experimental_speed_projection` its alias.) */
|
||||
* deployment with no vector refuses the on state by name rather than serve the stock model. */
|
||||
bool projection_on = false;
|
||||
{
|
||||
const bool named = r.control_vector >= 0;
|
||||
|
||||
@@ -331,8 +331,10 @@ private:
|
||||
HttpResponse handle_sessions(const HttpRequest& req);
|
||||
/* The control vector's runtime switch (dashboard.cpp): GET reports the state, POST
|
||||
* {"enabled": bool} sets the default for requests that name no choice. Guarded by the API key
|
||||
* like every other route but the health probes and the page. */
|
||||
* 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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+1
-1
@@ -134,7 +134,7 @@ static size_t json_depth(const ojson& root) {
|
||||
/* The conversation with every system message merged, in order, into one at its head, or false
|
||||
* when that is the conversation already (none, or one leading) or a system message carries more
|
||||
* than text. The Chat Completions API places no constraint on system messages, while many
|
||||
* templates raise unless there is exactly one, first (#137). */
|
||||
* templates raise unless there is exactly one, first. */
|
||||
static bool lead_system(const ojson& messages, ojson* out) {
|
||||
if (!messages.is_array()) return false;
|
||||
std::string text;
|
||||
|
||||
@@ -41,14 +41,10 @@ bool occurs_inside(const std::string& inner, const std::string& outer) {
|
||||
return !inner.empty() && outer.size() > inner.size() && outer.find(inner, 1) != std::string::npos;
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const std::string& p) {
|
||||
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
|
||||
}
|
||||
|
||||
/* Two delimiters an automaton scanning for both cannot report in start order: one begins or
|
||||
* occurs inside the other. */
|
||||
bool confusable(const std::string& a, const std::string& b) {
|
||||
return starts_with(a, b) || starts_with(b, a) || occurs_inside(a, b) || occurs_inside(b, a);
|
||||
return a.starts_with(b) || b.starts_with(a) || occurs_inside(a, b) || occurs_inside(b, a);
|
||||
}
|
||||
|
||||
std::string show(const std::string& s) { return nlohmann::json(s).dump(); }
|
||||
|
||||
@@ -72,8 +72,8 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
|
||||
const char* base = std::strrchr(file, '/');
|
||||
base = base ? base + 1 : file;
|
||||
|
||||
/* A line longer than the stack buffer is formatted again in full: a trace row of many values
|
||||
* (RADIANCE_DUMP_HEAD) was cut at 4 KiB without a mark (#113). */
|
||||
/* A line longer than the stack buffer is formatted again in full, so a trace row of many
|
||||
* values (RADIANCE_DUMP_HEAD) is never cut at 4 KiB. */
|
||||
char buf[4096];
|
||||
std::string big;
|
||||
va_list ap, ap2;
|
||||
|
||||
Reference in new issue
Block a user