Archived
radiance 2.1.0
New models. Recursive Flint (39.8B, about 2.5B active) by everplays (#422): `arch/flint`, as an IQ8R container with rotated int8 experts or a four-bit one, with a sink-aware WMMA prefill attention and the fused attention prologue at `rotary_dim` 0. Meta Muse Glimmer 30B by launch80_assets (#423): bf16, an int4 trunk or IQ8R, its windowed vision tower, its DFlash drafter, the ATEM tool dialect and context extension. Ling-3.0-tiny by RikshaDriver (#441): served from its GGUF releases or as IQ8R on `bailing_hybrid`, with six more libr3d kernels. Block FP8, MXFP4 and NVFP4 conversions of the three are not served. IQ8R containers of all three (round to nearest, no calibration) are on Hugging Face under StillDeadcode: flint-iq8r, muse-glimmer-30b-iq8r-dflash and ling-3.0-tiny-iq8r. They were checked for sane answers on two R9700; nothing was benchmarked, and Muse Glimmer's pictures, video and tool calls were not tried. Speech. Breeze-TTS-2 clones a voice from a reference recording and its transcript, with an optional delivery direction, by farcryjohn (#436). The published Breeze container needs converting again with the updated recipe before it can. Tools. A model entry with `diagnose: DIR` runs a fixed workload on the engine instead of serving and writes a report: step times, tokens a step, draft acceptance, TTFT and prefill rates by category, concurrency and prompt length, and with `diagnose-baseline` a token-for-token comparison against an earlier report (docs/DIAGNOSE.md), by Code000 (#418). Scheduler. `mixed-step-target-ms` holds a mixed prefill and decode step to a service time, off by default, by tnhnyzc (#413). `scheduler.stuck-exit` (60s by default, 0 never) ends the process when the device has advanced nothing for that long, so a restart policy brings a hung server back (#409, #415, #428). Fixed. Draft trees with the int8 KV cache, which stopped Gemma 4 31B with DFlash2 on its first request (#454, diagnosed by aelfwyne). The expert loan held at zero by a few leftover cache blocks after long sessions (#455, diagnosed by thekk1). The mapped tier's pages kept in the page cache across a load and a restore, by C_Tamas (#421). Replayed tool calls with blank arguments, and arguments that are not JSON refused naming the call, by dschmitz (#444). The dashboard's card temperature reads the junction sensor, by dschmitz (#453). The VRAM shortfall report says what the KL mode needs, by baKon (#448). The out-of-tree plugin test builds its plugins in parallel and takes its toolchain from the tree. Plugin ABI 40: out-of-tree plugins need to be rebuilt. Thanks to @everplays, @launch80_assets, @RikshaDriver, @farcryjohn, @Code000, @tnhnyzc, @C_Tamas, @dschmitz, @baKon, @aelfwyne and @thekk1.
This commit is contained in:
1 parent
ddcb9c69bb
commit
2a2b756371
166 files changed
+20749
-327
No files matched your search
@@ -1550,8 +1550,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
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). */
|
||||
* clip, and the clips' geometry. Two branches may repeat the same reference prompt at
|
||||
* guidance 1; reference CFG would need a separate unconditional frame map and is refused. */
|
||||
if (d->tmpl_ref) {
|
||||
auto once = [](const char* t, const char* k) {
|
||||
const char* a = t ? std::strstr(t, k) : nullptr;
|
||||
@@ -1566,16 +1566,36 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
"{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 "
|
||||
if (!d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 ||
|
||||
d->ref_max <= 0 || d->ref_max_samples < d->ref_hop ||
|
||||
(d->branches != 1 && (!d->neg_tmpl || d->default_cfg != 1.0 ||
|
||||
std::strstr(d->neg_tmpl, "{references}")))) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': references need whole prompts and "
|
||||
"guidance 1 (two branches need a plain negative template); 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->tmpl_ref_instruct || d->neg_tmpl_ref) {
|
||||
auto once = [](const char* t, const char* key) {
|
||||
const char* p = t ? std::strstr(t, key) : nullptr;
|
||||
return p && !std::strstr(p + 1, key);
|
||||
};
|
||||
if (!d->tmpl_ref || !d->tmpl_ref_instruct || !d->neg_tmpl_ref || d->branches == 1 ||
|
||||
!once(d->tmpl_ref_instruct, "{references}") ||
|
||||
!once(d->tmpl_ref_instruct, "{input}") ||
|
||||
!once(d->tmpl_ref_instruct, "{instructions}") ||
|
||||
!once(d->neg_tmpl_ref, "{references}") || !once(d->neg_tmpl_ref, "{input}") ||
|
||||
std::strstr(d->neg_tmpl_ref, "{instructions}")) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': reference direction needs paired "
|
||||
"conditional/reference-only templates with one references/input "
|
||||
"slot each and instructions only in the conditional template", nm);
|
||||
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);
|
||||
@@ -1669,6 +1689,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
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.tmpl_ref_instruct = d->tmpl_ref_instruct ? d->tmpl_ref_instruct : "";
|
||||
prog_.agen_str.neg_tmpl_ref = d->neg_tmpl_ref ? d->neg_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. */
|
||||
@@ -1677,6 +1699,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
prog_.audio_gen.tmpl_plain = nullptr;
|
||||
prog_.audio_gen.neg_tmpl = nullptr;
|
||||
prog_.audio_gen.tmpl_ref = nullptr;
|
||||
prog_.audio_gen.tmpl_ref_instruct = nullptr;
|
||||
prog_.audio_gen.neg_tmpl_ref = nullptr;
|
||||
prog_.audio_gen.ref_item = nullptr;
|
||||
/* Without references the clips' geometry is nothing: the driver stages none. */
|
||||
if (!d->tmpl_ref) {
|
||||
|
||||
@@ -76,6 +76,9 @@ static const Flag g_flags[] = {
|
||||
"of the chunk step's time, auto:SHARE in SHARE of it (0-4];\n"
|
||||
"0 lets every step carry a chunk; served default auto:1\n"
|
||||
"(0 under --deterministic, KL mode, generators)" },
|
||||
{ "--mixed-step-target-ms", "N", "soft duration target in milliseconds for a mixed prefill/decode\n"
|
||||
"step. The scheduler learns an aggregate prefill cap from\n"
|
||||
"completed mixed steps; 0 (default) is off" },
|
||||
{ "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n"
|
||||
"recompute gate before reclaiming cache blocks and\n"
|
||||
"preempting the lowest-priority running request; 0\n"
|
||||
@@ -336,6 +339,25 @@ static const Flag g_flags[] = {
|
||||
{ "--kld-lora-sources", "PREFIX", "--kld-lora only for documents whose source starts with PREFIX; the\n"
|
||||
" rest run as the base, in the same steps (a mixed batch)" },
|
||||
|
||||
{ "--diagnose", "DIR", "instead of serving, run a fixed workload on this engine and write\n"
|
||||
" diagnose.json and diagnose.md to DIR: decode by prompt category,\n"
|
||||
" a concurrency sweep, a prefill sweep with decode at each depth and\n"
|
||||
" a prompt arriving into running streams -- step times, tokens a\n"
|
||||
" step, draft acceptance, TTFT, emission intervals, jitter. Prompts\n"
|
||||
" are salted so the prefix cache serves none of them" },
|
||||
{ "--diagnose-tokens", "N", "tokens a --diagnose decode stream generates (default 256)" },
|
||||
{ "--diagnose-runs", "N", "measured runs of every --diagnose point, after one unmeasured (default 3)" },
|
||||
{ "--diagnose-concurrency", "LIST", "stream counts of the concurrency sweep, comma-separated (default\n"
|
||||
" 1,2,4,8; counts above --max-num-seqs are skipped and reported)" },
|
||||
{ "--diagnose-prefill", "LIST", "prompt lengths of the prefill sweep in tokens, comma-separated\n"
|
||||
" (default 1024,4096,16384,65536; lengths the context cannot hold\n"
|
||||
" are skipped and reported)" },
|
||||
{ "--diagnose-corpus", "FILE", "JSONL of category prompts, one {\"category\", \"messages\" or \"prompt\",\n"
|
||||
" \"max_tokens\"?} a line; default: a built-in set of code, reasoning,\n"
|
||||
" prose, json, file_edit and summarization prompts" },
|
||||
{ "--diagnose-baseline", "FILE", "an earlier diagnose.json of the same workload: compare every request's\n"
|
||||
" tokens with it and fail the run on any difference (parity)" },
|
||||
|
||||
{ "--debug-graph", nullptr, "print the entire declared graph and exit-quality detail" },
|
||||
{ "--debug-selection", nullptr, "print the selection table" },
|
||||
{ "--debug-placement", nullptr, "print the placement plan" },
|
||||
@@ -443,6 +465,25 @@ static bool parse_int(const char* flag, const char* v, int64_t lo, int64_t hi, i
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A comma-separated list of whole numbers (--diagnose-concurrency, --diagnose-prefill). An empty
|
||||
* element, a trailing comma or a value out of range refuses the list rather than dropping it. */
|
||||
static bool parse_int_list(const char* flag, const char* v, int64_t lo, int64_t hi,
|
||||
std::vector<int>* out) {
|
||||
std::vector<int> got;
|
||||
const char* p = v;
|
||||
for (;;) {
|
||||
const char* comma = std::strchr(p, ',');
|
||||
const std::string one(p, comma ? (size_t)(comma - p) : std::strlen(p));
|
||||
int64_t n = 0;
|
||||
if (!parse_int(flag, one.c_str(), lo, hi, &n)) return false;
|
||||
got.push_back((int)n);
|
||||
if (!comma) break;
|
||||
p = comma + 1;
|
||||
}
|
||||
*out = std::move(got);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Sampler defaults are checked against the request range (server::sampler_value_ok) at startup;
|
||||
* an out-of-range default would 400 every request that omits the field. */
|
||||
static bool sampler_num(const char* flag, const char* field, const char* v, double* out) {
|
||||
@@ -589,6 +630,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (!parse_int(a.c_str(), v, 0, 64, &c->prefill_interleave)) return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--mixed-step-target-ms")) { if (!num(0, 60000, &c->mixed_step_target_ms)) return RAD_E_INVAL; }
|
||||
else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; }
|
||||
else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; }
|
||||
else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; }
|
||||
@@ -1090,6 +1132,29 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
c->calib_layer_hi = hi;
|
||||
}
|
||||
else if (S("--kld-out")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_out = v; }
|
||||
else if (S("--diagnose")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose = v; }
|
||||
else if (S("--diagnose-tokens")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
int64_t n = 0;
|
||||
if (!parse_int(a.c_str(), v, 2, 1 << 20, &n)) return RAD_E_INVAL;
|
||||
c->diagnose_tokens = (int)n;
|
||||
}
|
||||
else if (S("--diagnose-runs")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
int64_t n = 0;
|
||||
if (!parse_int(a.c_str(), v, 1, 100, &n)) return RAD_E_INVAL;
|
||||
c->diagnose_runs = (int)n;
|
||||
}
|
||||
else if (S("--diagnose-concurrency")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!parse_int_list(a.c_str(), v, 1, 4096, &c->diagnose_concurrency)) return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--diagnose-prefill")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!parse_int_list(a.c_str(), v, 16, 1 << 24, &c->diagnose_prefill)) return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--diagnose-corpus")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose_corpus = v; }
|
||||
else if (S("--diagnose-baseline")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose_baseline = v; }
|
||||
else if (S("--kld-lora")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora = v; }
|
||||
else if (S("--kld-lora-sources")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora_sources = v; }
|
||||
else if (S("--debug-graph")) { c->debug_graph = true; c->debug_selection = true; }
|
||||
@@ -1219,6 +1284,19 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ONE MODE A RUN. Each replaces serving with its own driver, so two given together would have
|
||||
* to pick one silently; --debug-graph returns before either runs. */
|
||||
if (!c->diagnose_mode() && (!c->diagnose_corpus.empty() || !c->diagnose_baseline.empty())) {
|
||||
RAD_ERR("--diagnose-corpus and --diagnose-baseline belong to the --diagnose workload; give "
|
||||
"--diagnose DIR as well");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c->diagnose_mode() && (c->kld() || c->calib() || c->debug_graph)) {
|
||||
RAD_ERR("--diagnose runs its own workload; it cannot be combined with --kld-record, --kld-ref, "
|
||||
"--calib-corpus or --debug-graph");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Runtime LoRA: the slot flags need slots, the named adapters must fit them, and KL mode's
|
||||
* adapter is one of them. */
|
||||
{
|
||||
@@ -1352,6 +1430,8 @@ const ShowRow kShow[] = {
|
||||
return c.prefill_interleave > 0 ? num(c.prefill_interleave)
|
||||
: c.prefill_interleave < 0 ? "auto:" + std::to_string(c.prefill_interleave_share)
|
||||
: std::string("off"); } },
|
||||
{ "--mixed-step-target-ms", [](const Config& c) {
|
||||
return c.mixed_step_target_ms > 0 ? num(c.mixed_step_target_ms) : std::string("off"); } },
|
||||
{ "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } },
|
||||
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
|
||||
{ "--max-model-len", [](const Config& c) {
|
||||
@@ -1502,6 +1582,19 @@ const ShowRow kShow[] = {
|
||||
{ "--kld-out", [](const Config& c) { return or_none(c.kld_out, "none"); } },
|
||||
{ "--kld-lora", [](const Config& c) { return or_none(c.kld_lora, "none (the base)"); } },
|
||||
{ "--kld-lora-sources", [](const Config& c) { return or_none(c.kld_lora_sources, "every document"); } },
|
||||
{ "--diagnose", [](const Config& c) { return or_none(c.diagnose, "off (serve)"); } },
|
||||
{ "--diagnose-tokens", [](const Config& c) { return num(c.diagnose_tokens); } },
|
||||
{ "--diagnose-runs", [](const Config& c) { return num(c.diagnose_runs); } },
|
||||
{ "--diagnose-concurrency", [](const Config& c) {
|
||||
std::string s;
|
||||
for (int n : c.diagnose_concurrency) s += (s.empty() ? "" : ",") + num(n);
|
||||
return s; } },
|
||||
{ "--diagnose-prefill", [](const Config& c) {
|
||||
std::string s;
|
||||
for (int n : c.diagnose_prefill) s += (s.empty() ? "" : ",") + num(n);
|
||||
return s; } },
|
||||
{ "--diagnose-corpus", [](const Config& c) { return or_none(c.diagnose_corpus, "the built-in set"); } },
|
||||
{ "--diagnose-baseline", [](const Config& c) { return or_none(c.diagnose_baseline, "none"); } },
|
||||
{ "--debug-graph", [](const Config& c) { return onoff(c.debug_graph); } },
|
||||
{ "--debug-selection", [](const Config& c) { return onoff(c.debug_selection); } },
|
||||
{ "--debug-placement", [](const Config& c) { return onoff(c.debug_placement); } },
|
||||
|
||||
+35
-1
@@ -943,6 +943,36 @@ void report_running(int card) {
|
||||
}
|
||||
}
|
||||
|
||||
int64_t stuck_ms();
|
||||
|
||||
std::atomic<bool> g_stuck_watch{false};
|
||||
|
||||
/* Started by a stall verdict, at most one at a time: ends the process once the verdict has stood
|
||||
* for dev_stuck_exit_ms (`scheduler.stuck-exit`; 0 never), and ends itself when the queues move
|
||||
* again. Its own thread, because the threads that noticed the stall are the ones parked in the
|
||||
* wait. Without the exit a hung device left the process up for good: /health answered 503, a
|
||||
* SIGTERM could not drain a thread blocked in the driver, and a restart policy had nothing to
|
||||
* act on. */
|
||||
void stuck_watch() {
|
||||
for (;;) {
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
const int64_t ms = stuck_ms();
|
||||
const int64_t limit = rad::dev_stuck_exit_ms.load(std::memory_order_relaxed);
|
||||
if (limit > 0 && ms >= limit) {
|
||||
dump_queues("the device");
|
||||
fatal("the device has advanced nothing for %lld s (the queue dumps above name the "
|
||||
"packets it is stuck on); exiting so a restart can bring the server back",
|
||||
(long long)(ms / 1000));
|
||||
}
|
||||
if (ms > 0) continue;
|
||||
g_stuck_watch.store(false, std::memory_order_release);
|
||||
/* A verdict that landed between the read above and the store has no watcher yet. */
|
||||
if (!g_stuck_at.load(std::memory_order_acquire) ||
|
||||
g_stuck_watch.exchange(true, std::memory_order_acq_rel))
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand
|
||||
* times a second at most.
|
||||
*
|
||||
@@ -980,7 +1010,11 @@ struct Stall {
|
||||
dump_queues(where);
|
||||
RAD_ERR("device: nothing has advanced in the %u s since: the GPU is not running the "
|
||||
"packet named above -- a hung kernel, or a queue the driver evicted and could "
|
||||
"not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000);
|
||||
"not restore (amdgpu cwsr_enable=0 is one cause). The process exits once this "
|
||||
"has stood for scheduler.stuck-exit (%lld s; 0 never)", kStallMs / 1000,
|
||||
(long long)(rad::dev_stuck_exit_ms.load(std::memory_order_relaxed) / 1000));
|
||||
if (!g_stuck_watch.exchange(true, std::memory_order_acq_rel))
|
||||
std::thread(stuck_watch).detach();
|
||||
return;
|
||||
}
|
||||
sampled = true;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "rad_abi.h"
|
||||
#include "rad_device.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
@@ -447,6 +448,12 @@ std::string dev_dma_lane(int device);
|
||||
* tell. */
|
||||
int64_t dev_stuck_ms();
|
||||
|
||||
/* How long the device may be stuck (dev_stuck_ms) before the backend ends the process, in ms; 0
|
||||
* never. Set from `scheduler.stuck-exit` before serving; a backend that can tell reads it when a
|
||||
* stall is standing. A device that has advanced nothing for a minute is not coming back: the
|
||||
* reported hangs stood for hours, and a stall that clears does so within seconds. */
|
||||
extern std::atomic<int64_t> dev_stuck_exit_ms;
|
||||
|
||||
/* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1
|
||||
* consecutive packets on a queue one carries the barrier bit, so a launched packet still proves
|
||||
* that everything more than that many packets earlier has completed. Argument slots and tape
|
||||
|
||||
@@ -874,6 +874,7 @@ std::string dev_pci_address(int device) {
|
||||
if (!dev()->pci_address) return std::string();
|
||||
return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); });
|
||||
}
|
||||
std::atomic<int64_t> dev_stuck_exit_ms{60000};
|
||||
int64_t dev_stuck_ms() {
|
||||
const auto f = dev()->stuck_ms;
|
||||
return f ? f() : 0;
|
||||
|
||||
@@ -126,6 +126,22 @@ struct Facts {
|
||||
* process reads them only for its own cards. Null reads them for every card. */
|
||||
Facts collect(const std::string& root, const std::vector<std::string>* managed = nullptr);
|
||||
|
||||
/* A CARD'S STATE AT ONE MOMENT, for --diagnose to read before and after each run: a run that
|
||||
* starts hotter, or under a different performance level, than the one it is compared with is
|
||||
* measuring a different card. Read under the same root as collect(); unreadable fields stay unknown.
|
||||
* The power-management files are answered by the SMU under its lock, so this is read between
|
||||
* runs, never during one. */
|
||||
struct CardSample {
|
||||
std::string bdf;
|
||||
int64_t edge_mc = -1, junction_mc = -1, mem_mc = -1; /* hwmon temperatures, millidegrees C */
|
||||
int64_t power_uw = -1; /* power1_average, else power1_input */
|
||||
std::string perf_level; /* power_dpm_force_performance_level: auto, high, profile_peak, ... */
|
||||
std::string sclk_cur, mclk_cur; /* the DPM level marked current, as the driver lists it */
|
||||
int busy_percent = -1;
|
||||
};
|
||||
|
||||
std::vector<CardSample> sample_cards(const std::string& root, const std::vector<std::string>& bdfs);
|
||||
|
||||
/* Fills what only a system call answers for the live process: the memlock limit and whether
|
||||
* io_uring is allowed (a container's seccomp profile may refuse it). */
|
||||
void probe_process(HostFacts* h);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,279 @@
|
||||
/* diagnose.h -- the --diagnose mode's arithmetic and its report.
|
||||
*
|
||||
* `radiance --diagnose DIR` starts the engine as it would to serve, then runs a fixed workload on
|
||||
* itself instead of listening (core/engine_diagnose.cpp) and writes DIR/diagnose.json and
|
||||
* DIR/diagnose.md. This file is the part with no device and no scheduler in it: the step record
|
||||
* the scheduler keeps, the statistics a phase reduces to, and the report. The driver feeds it;
|
||||
* tests/diagnose_test.cpp holds it to hand-computed numbers.
|
||||
*
|
||||
* WHY THE ENGINE MEASURES ITSELF. The numbers an operator wants -- milliseconds a decode step,
|
||||
* tokens a step, how often a draft is taken, how long a prefill takes, how uneven the steps are --
|
||||
* are all known inside the engine exactly, and outside it only through a client's clock and a
|
||||
* stream that delivers a speculative step's tokens in one burst. A client measuring inter-token
|
||||
* latency on a speculating engine is measuring the burst pattern; the engine knows the steps.
|
||||
*
|
||||
* WHAT A PHASE REPORTS, AND FROM WHERE.
|
||||
* - SchedMetrics deltas taken while the engine is idle at the phase's edges: exact counts of
|
||||
* steps by shape, tokens, drafts proposed and accepted, per draft position.
|
||||
* - One StepRecord per step, written by the scheduler (Scheduler::step_finished): what the step
|
||||
* carried and how long it took. From these: the distribution of decode step times, the
|
||||
* interval between consecutive emissions (what a stream sees between token bursts), and the
|
||||
* slowest steps against typical ones.
|
||||
* - Each request's sink: admitted, first token, last token, tokens -- TTFT and stream rate.
|
||||
* A quantity the run cannot measure is reported as absent with the reason, never as 0.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "sched/metrics.h"
|
||||
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace diag {
|
||||
|
||||
struct Facts;
|
||||
struct RunFacts;
|
||||
struct Finding;
|
||||
struct CardSample;
|
||||
|
||||
using json = Json;
|
||||
|
||||
/* ONE ENGINE STEP, as the scheduler commits it. Plain data, fixed size: the scheduler writes one
|
||||
* per step under its own lock into a ring sized at init, so recording costs a store and no
|
||||
* allocation on the step path. */
|
||||
struct StepRecord {
|
||||
int64_t step = 0; /* SchedMetrics::steps after this step: a run-wide ordinal */
|
||||
int32_t phase = 0; /* RAD_PHASE_PREFILL / DECODE / MIXED of the step's plan */
|
||||
int32_t n_seq = 0; /* sequences the step carried */
|
||||
int32_t prefill_tok = 0; /* prompt tokens it computed */
|
||||
int32_t decode_tok = 0; /* tokens it committed to decoding sequences, accepted drafts included */
|
||||
int64_t ns = 0; /* inside the step, the clock SchedMetrics::step_ns charges */
|
||||
int64_t end_ns = 0; /* steady clock when it was committed: emissions are spaced by these */
|
||||
};
|
||||
|
||||
/* A FIXED-CAPACITY RING OF STEP RECORDS with a run-wide sequence number. The writer and every
|
||||
* reader hold the scheduler's lock, so it needs no atomics of its own. A reader asks for what
|
||||
* came after a sequence number it saved; if the ring has lapped since, the records it lost are
|
||||
* counted, not invented. */
|
||||
class StepRing {
|
||||
public:
|
||||
explicit StepRing(size_t capacity = 0) { reset(capacity); }
|
||||
void reset(size_t capacity);
|
||||
|
||||
void push(const StepRecord& r) noexcept;
|
||||
uint64_t count() const { return n_; } /* records ever pushed */
|
||||
size_t capacity() const { return buf_.size(); }
|
||||
|
||||
/* Appends every record with sequence number >= `from` still in the ring to `out`; returns how
|
||||
* many after `from` were overwritten before they could be read. */
|
||||
uint64_t copy_since(uint64_t from, std::vector<StepRecord>* out) const;
|
||||
|
||||
private:
|
||||
std::vector<StepRecord> buf_;
|
||||
uint64_t n_ = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ statistics */
|
||||
|
||||
/* Quantiles by nearest rank over a copy of the samples. `n == 0` means there were none, and every
|
||||
* other field is then meaningless; the JSON form says null rather than 0. */
|
||||
struct Quantiles {
|
||||
int64_t n = 0;
|
||||
double min = 0, p50 = 0, p90 = 0, p99 = 0, max = 0, mean = 0;
|
||||
};
|
||||
Quantiles quantiles(std::vector<double> v);
|
||||
json to_json(const Quantiles& q);
|
||||
|
||||
/* What a request's sink recorded, on one steady-clock axis (Sink::t_start_ns + its offsets). -1
|
||||
* where the sink never saw the event. */
|
||||
struct RequestTiming {
|
||||
int64_t start_ns = -1; /* the sink's construction: before submission */
|
||||
int64_t admitted_ns = -1; /* the scheduler first gave it a step */
|
||||
int64_t first_ns = -1; /* first token */
|
||||
int64_t last_ns = -1; /* last token */
|
||||
int64_t tokens = 0; /* produced */
|
||||
int32_t prompt = 0; /* prompt tokens */
|
||||
int32_t cached = 0; /* of those, served from the prefix cache */
|
||||
int64_t drafted = 0;
|
||||
int64_t accepted = 0;
|
||||
bool ok = false; /* finished on length or stop, not on an error or a cancel */
|
||||
bool stopped = false; /* finished on the model's own end of sequence, not on length */
|
||||
std::vector<int32_t> output; /* the tokens it produced, for the parity comparison */
|
||||
};
|
||||
|
||||
enum class PhaseKind { Decode, Prefill };
|
||||
|
||||
struct PhaseInput {
|
||||
std::string name;
|
||||
PhaseKind kind = PhaseKind::Decode;
|
||||
int streams = 1;
|
||||
int64_t wall_ns = 0;
|
||||
SchedMetrics before, after;
|
||||
std::vector<StepRecord> steps; /* the steps the phase ran, in order */
|
||||
uint64_t steps_lost = 0; /* records the ring overwrote before they were read */
|
||||
std::vector<RequestTiming> requests;
|
||||
/* The serving cards' state before and after the run ({"start": [...], "end": [...]}, each
|
||||
* card_samples_json), null when the driver read none. */
|
||||
json cards;
|
||||
};
|
||||
|
||||
/* The phase's section of the report. Every derived number names what it was derived from. */
|
||||
json phase_report(const PhaseInput& in);
|
||||
|
||||
/* The slowest steps of one shape against the typical ones: the slowest `max(3, 1%)` decode steps
|
||||
* with what they carried, and the median step beside them, so a reader can tell a step that was
|
||||
* slow because it carried more from one that was slow carrying the same. */
|
||||
json slow_steps(const std::vector<StepRecord>& steps, int phase);
|
||||
|
||||
/* DRAFT ACCEPTANCE BY POSITION, POOLED OVER A POINT'S RUNS: at each position the verifies that
|
||||
* reached it and the share of those that took it, summed over the runs rather than a median of
|
||||
* per-run rates, because a run reaches the deep positions only a few times. This is the curve an
|
||||
* adaptive draft depth is tuned against. */
|
||||
json pool_draft_positions(const std::vector<json>& runs);
|
||||
|
||||
/* THE RUNS OF ONE MEASUREMENT POINT, reduced to what a reader compares: for each headline number
|
||||
* of phase_report, the median over the runs and the smallest and largest run. A run that has no
|
||||
* value for a number does not count toward it; a number no run had is null. */
|
||||
json summarize_runs(const std::vector<json>& runs);
|
||||
/* The same over the numbers at the given JSON pointers, keyed by the pointer with '/' as '.'. */
|
||||
json summarize_paths(const std::vector<json>& runs, const std::vector<std::string>& paths);
|
||||
|
||||
/* ------------------------------------------------------------------ reproducibility */
|
||||
|
||||
/* A headline number whose runs spread wider than this, as (max - min) / median, makes the point
|
||||
* UNSTABLE in the report's stability section: the runs disagree by more than most changes a
|
||||
* comparison is run to find. */
|
||||
constexpr double kMaxSpreadPct = 5.0;
|
||||
/* Runs of one report that start this many degrees apart (junction, else edge) began on cards in
|
||||
* different thermal states. */
|
||||
constexpr double kMaxStartTempSpreadC = 10.0;
|
||||
|
||||
/* The cards' samples as JSON: temperatures in degrees C, power in W, the performance level and the
|
||||
* current DPM levels; an unknown field is null. */
|
||||
json card_samples_json(const std::vector<CardSample>& samples);
|
||||
|
||||
/* WHAT THE RUN RAN ON, so two reports can be told comparable or not: the engine build, the host
|
||||
* settings that move a step's time (CPU governor and energy preference, kernel, device runtime,
|
||||
* THP, IOMMU mode) and the serving cards (rank >= 0) with their DPM ranges, power cap against its
|
||||
* default, voltage offset, runtime power management and link. No path and no command line: the
|
||||
* report is pasted into issues. `findings` are the startup report's (diag::check) and are listed
|
||||
* with their fix. `fingerprint` hashes everything but the findings, whose text carries load-
|
||||
* dependent numbers. */
|
||||
json conditions_report(const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
|
||||
|
||||
/* The fields of two reports' `conditions` that differ, as {"field", "now", "baseline"} with the
|
||||
* field as a JSON pointer; empty when they ran under the same conditions. */
|
||||
json conditions_differences(const json& now, const json& base);
|
||||
|
||||
/* RUN-TO-RUN AGREEMENT. For each measured point the headline numbers -- aggregate and per-step
|
||||
* decode rate for each category prompt (its `prompts_summary`; the category's own summary pools
|
||||
* prompts that differ by design) and each concurrency point, TTFT and prefill rate for the prefill sweep, the arriving
|
||||
* prompt's TTFT for interference -- whose spread_pct exceeds `max_spread_pct`. `verdict` is
|
||||
* "stable", "UNSTABLE" or "not judged" (no point has two runs). */
|
||||
json stability_report(const json& report, double max_spread_pct = kMaxSpreadPct);
|
||||
|
||||
/* THE CARDS ACROSS THE MEASURED RUNS: per card the start and end temperatures' range and the
|
||||
* performance levels seen, from each run's `cards`. `warnings` names a start-temperature spread
|
||||
* above kMaxStartTempSpreadC and a performance level that changed during the report. */
|
||||
json thermal_report(const json& report);
|
||||
|
||||
/* A DECODE STALL: what a prompt arriving into running streams costs them. `from`..`to` is the
|
||||
* window from the new request's admission to its first token; the report gives the longest gap
|
||||
* between two emissions that overlaps it, against the median gap of the emissions before it. */
|
||||
json interference_report(const std::vector<StepRecord>& steps, int64_t from_ns, int64_t to_ns);
|
||||
|
||||
/* ------------------------------------------------------------------ parity */
|
||||
|
||||
/* WHAT TWO RUNS OF THE SAME WORKLOAD PRODUCED, COMPARED TOKEN FOR TOKEN. With the same prompts and
|
||||
* the same seed per request, a build whose logits are bit-identical samples identical tokens, at
|
||||
* any temperature -- so every request of the categories, the concurrency sweep and the prefill
|
||||
* sweep is a parity check of the paths it ran: long prefills, attention at depth, batched decode.
|
||||
* The interference point is left out: when its running streams are cancelled depends on timing.
|
||||
*
|
||||
* `now` and `base` are whole reports. Points are matched by their key (category, streams,
|
||||
* requested tokens), runs and requests by position. The result counts identical and differing
|
||||
* requests and names, for each difference, the first token where they part; a point or run that
|
||||
* only one side has is listed as missing rather than counted as either. Two reports of different
|
||||
* workloads (workload.fingerprint) are refused with RAD_E_INVAL: their prompts differ. */
|
||||
/* Beside the tokens it compares each matched point's draft acceptance: identical for
|
||||
* bit-identical builds, and the first number to move when a build computes less accurately. The
|
||||
* overall rate by a one-sided paired t test over the requests (same prompt and seed on both
|
||||
* sides), the positions by the pooled two-proportion z divided by the square root of the
|
||||
* dispersion the requests show; either as unlikely as z below -3 is a drop, listed in
|
||||
* `acceptance_dropped`, and makes `acceptance_verdict` "DROPPED". */
|
||||
int compare_outputs(const json& now, const json& base, json* out, std::string* why);
|
||||
|
||||
/* The part of a report's workload that decides which prompts and seeds it ran: equal fingerprints
|
||||
* mean comparable outputs. */
|
||||
std::string workload_fingerprint(const json& workload_params);
|
||||
|
||||
/* ------------------------------------------------------------------ workload */
|
||||
|
||||
/* ONE PROMPT OF THE CATEGORY WORKLOAD: OpenAI-style chat messages and the category they are
|
||||
* reported under. `max_tokens` 0 means the run's --diagnose-tokens. */
|
||||
struct CorpusEntry {
|
||||
std::string category;
|
||||
json messages;
|
||||
int max_tokens = 0;
|
||||
};
|
||||
|
||||
/* A small built-in corpus, a few prompts in each of the categories a chat deployment typically
|
||||
* serves (code, reasoning, prose, json, file_edit, summarization), so a run without a corpus file
|
||||
* still reports by category. Speculative decoding accepts very differently across these, which is
|
||||
* why one decode number is not enough. */
|
||||
std::vector<CorpusEntry> builtin_corpus();
|
||||
|
||||
/* Reads a corpus file: one JSON object a line, `{"category": "...", "messages": [...]}` or
|
||||
* `{"category": "...", "prompt": "..."}`, optionally with "max_tokens". Blank lines and lines
|
||||
* starting with '#' are skipped. Any other malformed line refuses the file, naming the line. */
|
||||
int load_corpus(const std::string& path, std::vector<CorpusEntry>* out, std::string* why);
|
||||
|
||||
/* THE SAME MESSAGES MADE UNIQUE FROM THEIR FIRST CHARACTER. `tag` is put at the head of the first
|
||||
* message's content, so no two requests of a run share a prefix longer than the chat template's
|
||||
* own opening -- less than one cache block -- and the prefix cache cannot serve one from another.
|
||||
* The tag is deterministic (a request counter), so two builds see the same prompts; a hit from a
|
||||
* cache tier that outlived the process is caught by the driver's check of RequestTiming::cached. */
|
||||
json salt_messages(const json& messages, const std::string& tag);
|
||||
|
||||
|
||||
/* A deterministic document of about `chars` characters: numbered sections of fixed prose, every
|
||||
* section different in its numbers, so a prefix cache cannot serve one run's text to the next
|
||||
* when `salt` differs. Language-neutral enough to tokenise under any vocabulary. */
|
||||
std::string synthetic_document(int64_t chars, uint32_t salt);
|
||||
|
||||
/* The decode prompts, one per stream: fixed instructions that ask for long prose, distinct per
|
||||
* stream so eight streams are eight conversations and not one prompt eight times. */
|
||||
std::string decode_prompt(int stream);
|
||||
|
||||
/* ------------------------------------------------------------------ report */
|
||||
|
||||
/* The environment the workload ran under: the NAMES of the variables in `env` (environ-shaped,
|
||||
* null-terminated) that are on a fixed list of the engine's configuration knobs, sorted. Names
|
||||
* only, never values: a value may be a path, a host name or a token, and the report is pasted into
|
||||
* issues and committed beside a baseline (diag/diag.h's env_names states the same rule for the
|
||||
* startup report).
|
||||
*
|
||||
* A fixed list, not a prefix: a prefix admits every suffix, so `RADIANCE_API_KEY_<anything>` is a
|
||||
* name the report would print. A name the engine does not read as configuration is not reported. */
|
||||
std::vector<std::string> env_allowlist(char* const* env);
|
||||
|
||||
/* The engine section of a report, built from the engine's /server_info object: the model's
|
||||
* architecture, quantisation and shapes, and the cards it ran on. The object itself is not copied,
|
||||
* because its `container` is the model's path and its control vector carries a file, and the report
|
||||
* is pasted into issues: a path names a person's home directory and nothing a reader needs. */
|
||||
json engine_report(const json& server_info);
|
||||
|
||||
/* The Markdown view of a report: one table each for the categories, the concurrency sweep, the
|
||||
* prefill sweep and the interference point, from their `summary` sections plus the driver's
|
||||
* header. It reads only the JSON, so it can be regenerated from a saved diagnose.json; the
|
||||
* per-run detail stays in the JSON. It carries no path either: the header names the model by its
|
||||
* architecture and quantisation (engine_report), never by where it is stored. */
|
||||
std::string render_markdown(const json& report);
|
||||
|
||||
} /* namespace diag */
|
||||
} /* namespace rad */
|
||||
@@ -423,6 +423,48 @@ Facts collect(const std::string& root, const std::vector<std::string>* managed)
|
||||
return f;
|
||||
}
|
||||
|
||||
std::vector<CardSample> sample_cards(const std::string& root, const std::vector<std::string>& bdfs) {
|
||||
/* The line the driver marks with '*', without the mark and the level's index: "2350Mhz". */
|
||||
auto current = [](const std::string& path) {
|
||||
std::istringstream in(slurp(path));
|
||||
std::string l;
|
||||
while (std::getline(in, l)) {
|
||||
if (l.find('*') == std::string::npos) continue;
|
||||
l.erase(std::remove(l.begin(), l.end(), '*'), l.end());
|
||||
const size_t colon = l.find(':');
|
||||
return trim(colon == std::string::npos ? l : l.substr(colon + 1));
|
||||
}
|
||||
return std::string();
|
||||
};
|
||||
std::vector<CardSample> out;
|
||||
for (const std::string& bdf : bdfs) {
|
||||
const std::string dev = root + "/sys/bus/pci/devices/" + bdf;
|
||||
CardSample c;
|
||||
c.bdf = bdf;
|
||||
c.perf_level = line(dev + "/power_dpm_force_performance_level");
|
||||
c.sclk_cur = current(dev + "/pp_dpm_sclk");
|
||||
c.mclk_cur = current(dev + "/pp_dpm_mclk");
|
||||
c.busy_percent = (int)num(dev + "/gpu_busy_percent", -1);
|
||||
for (const std::string& h : list(dev + "/hwmon")) {
|
||||
const std::string hp = dev + "/hwmon/" + h;
|
||||
/* amdgpu labels its sensors; an unlabelled temp1 is the edge sensor. */
|
||||
for (int t = 1; t <= 8; ++t) {
|
||||
const std::string base = hp + "/temp" + std::to_string(t);
|
||||
const int64_t v = num(base + "_input", -1);
|
||||
if (v < 0) continue;
|
||||
const std::string label = line(base + "_label");
|
||||
if (label == "edge" || (label.empty() && t == 1)) c.edge_mc = v;
|
||||
else if (label == "junction") c.junction_mc = v;
|
||||
else if (label == "mem") c.mem_mc = v;
|
||||
}
|
||||
if (c.power_uw < 0) c.power_uw = num(hp + "/power1_average", -1);
|
||||
if (c.power_uw < 0) c.power_uw = num(hp + "/power1_input", -1);
|
||||
}
|
||||
out.push_back(std::move(c));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void probe_process(HostFacts* h) {
|
||||
struct rlimit rl{};
|
||||
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0)
|
||||
|
||||
+16
-4
@@ -2457,12 +2457,14 @@ void Engine::tier_tick() {
|
||||
/* Release an entry once its host copy has landed, if the expert slab can use the blocks; a
|
||||
* later turn restores it with a copy. Otherwise (no lending, or the loan already covers every
|
||||
* slab slot) it stays in VRAM, and a request needing room takes it through trim. Snapshots
|
||||
* are already in host memory. */
|
||||
* are already in host memory. Stragglers with no host copy coming go too (PrefixCache::
|
||||
* drop_clean): a few thousand such tokens near the top of the pool would otherwise hold the
|
||||
* whole loan at zero until the server restarts. */
|
||||
if (lending_) {
|
||||
int64_t ceiling = 0;
|
||||
for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV));
|
||||
const auto lk = sched_.hold();
|
||||
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean();
|
||||
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(ceiling);
|
||||
}
|
||||
|
||||
/* ---- capacity ---------------------------------------------------------------------------- */
|
||||
@@ -2840,11 +2842,14 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
stepped.store(true, std::memory_order_release);
|
||||
});
|
||||
|
||||
if (cfg_.kld() || cfg_.calib()) {
|
||||
if (cfg_.kld() || cfg_.calib() || cfg_.diagnose_mode()) {
|
||||
print_startup_report(RAD_OK);
|
||||
startup_watch_.reset();
|
||||
}
|
||||
int s = cfg_.kld() ? run_kld() : cfg_.calib() ? run_calib() : run_server();
|
||||
int s = cfg_.diagnose_mode() ? run_diagnose()
|
||||
: cfg_.kld() ? run_kld()
|
||||
: cfg_.calib() ? run_calib()
|
||||
: run_server();
|
||||
startup_watch_.reset();
|
||||
|
||||
/* Stop the step loop before the server's storage is destroyed: Request::sink points into it,
|
||||
@@ -3120,6 +3125,11 @@ std::string request_overrides(const Config& c) {
|
||||
return out;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
SamplingParams Engine::sampling_defaults() const {
|
||||
return resolve_sampling_defaults(meta_, file_ != nullptr, cfg_);
|
||||
}
|
||||
|
||||
/* The HTTP server over the engine. `/v1/completions`, `/v1/chat/completions`, `/v1/models`,
|
||||
* `/metrics` and `/health` are live. `/v1/embeddings` answers 501 unless the program is an
|
||||
* embedding program, and so do image, video and audio content parts unless the program declared an
|
||||
@@ -3951,6 +3961,8 @@ int Engine::run_server() {
|
||||
in.branches = ad.branches == 1 ? 1 : 2;
|
||||
in.input_special = ad.input_special != 0;
|
||||
in.tmpl_ref = pg.agen_str.tmpl_ref;
|
||||
in.tmpl_ref_instruct = pg.agen_str.tmpl_ref_instruct;
|
||||
in.neg_tmpl_ref = pg.agen_str.neg_tmpl_ref;
|
||||
in.ref_item = pg.agen_str.ref_item;
|
||||
in.ref_rate = ad.ref_rate;
|
||||
in.ref_hop = ad.ref_hop;
|
||||
|
||||
@@ -788,6 +788,10 @@ private:
|
||||
std::vector<std::unique_ptr<server::Sink>>& sinks, bool fit_pool,
|
||||
const char* tag, int every_s,
|
||||
const std::function<void(size_t, double)>& progress, int* bad);
|
||||
/* --diagnose (core/engine_diagnose.cpp), replacing run_server: runs a fixed workload on this
|
||||
* engine -- decode by prompt category, a concurrency sweep, a prefill sweep, interference --
|
||||
* and writes DIR/diagnose.json and DIR/diagnose.md instead of listening. */
|
||||
int run_diagnose();
|
||||
int score_rows(const RadBatch* b, const StepOut& so);
|
||||
std::unique_ptr<Kld> kld_;
|
||||
std::vector<float*> kld_host_;
|
||||
@@ -800,6 +804,10 @@ private:
|
||||
long long calib_tokens_ = 0;
|
||||
/* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
|
||||
std::string engine_info() const;
|
||||
/* The sampler a request that sends no settings runs with: the container's generation defaults
|
||||
* with the operator's flags over them (resolve_sampling_defaults, engine.cpp). A mode that
|
||||
* builds requests with no client -- --diagnose -- samples with what the server would. */
|
||||
SamplingParams sampling_defaults() const;
|
||||
|
||||
/* ---- startup report inputs (engine_diag.cpp). `decisions_` holds each value startup resolved
|
||||
* and why, recorded where it was resolved; the rest are facts only startup saw. */
|
||||
|
||||
+12
-5
@@ -3551,8 +3551,11 @@ static int sweep_container(RadFile* file, std::vector<LoadRun>& runs,
|
||||
return RAD_OK;
|
||||
}();
|
||||
|
||||
/* Release the page cache of weights never read from the file again, leaving it to the mapped
|
||||
* tier (e.g. a mapped n-gram table, read from its mapping for the process lifetime). */
|
||||
/* Release the page cache of weights never read from the file again. The mapped tier's pages
|
||||
* stay (RadFile::keep_cached, named where load_weights publishes a mapped weight): an n-gram
|
||||
* table is gathered from its mapping on every step, and with its pages dropped the first long
|
||||
* prefill after each load or restore faults them back from the drive (a 103 GiB table: 1460
|
||||
* against 1998 tok/s on a 24k prompt). */
|
||||
file->drop_blob_cache();
|
||||
/* Drain before freeing: a sweep that failed part-way may have copies outstanding. */
|
||||
for (int b = 0; b < kWin; ++b) pool->drain(b);
|
||||
@@ -3683,6 +3686,8 @@ int Engine::load_weights() {
|
||||
int64_t total = 0, n_loaded = 0, n_missing = 0;
|
||||
/* Counted apart from `n_loaded`: mapped weights are published in place, not loaded. */
|
||||
int64_t n_mapped = 0, mapped_bytes = 0;
|
||||
/* Of the container's own bytes, what the mapped tier reads: left in the page cache. */
|
||||
int64_t mapped_kept = 0;
|
||||
|
||||
/* Two phases. The walk decides which rank wants which bytes, where they land, and what is
|
||||
* refused, without touching the disk; sweep_container then reads the container once in file
|
||||
@@ -3870,6 +3875,7 @@ int Engine::load_weights() {
|
||||
* for a row of a few hundred bytes. MADV_RANDOM is per range, so the rest of the
|
||||
* container keeps sequential readahead. The effect shows only with a cold cache. */
|
||||
posix_madvise(w.ptr, (size_t)n, POSIX_MADV_RANDOM);
|
||||
if (file_) mapped_kept = file_->keep_cached(w.host_ptr, n);
|
||||
r->mover.publish_mapped((rad_weight)i, w.ptr);
|
||||
++n_mapped;
|
||||
mapped_bytes += n;
|
||||
@@ -4000,10 +4006,11 @@ int Engine::load_weights() {
|
||||
/* Summed over ranks, which map the same file, so under TP the resident bytes are this
|
||||
* divided by --tp; the message says so. */
|
||||
RAD_INFO("load: %lld weight(s), %s, read in place from the container's mapping -- not "
|
||||
"copied and charged to no pool%s", (long long)n_mapped,
|
||||
humanb(mapped_bytes).c_str(),
|
||||
"copied and charged to no pool%s; %s of the container stays page-cached for them",
|
||||
(long long)n_mapped, humanb(mapped_bytes).c_str(),
|
||||
cfg_.tp > 1 ? " (summed over ranks, which map the same file: the resident bytes "
|
||||
"are that divided by --tp)" : "");
|
||||
"are that divided by --tp)" : "",
|
||||
humanb(mapped_kept).c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,698 @@
|
||||
/* engine_diagnose.cpp -- the --diagnose driver: a fixed workload the engine runs on itself in
|
||||
* place of the HTTP server, and the report it writes. The arithmetic and the report format are
|
||||
* core/diag/diagnose.h's; this file only drives the scheduler and collects what it needs.
|
||||
*
|
||||
* THE WORKLOAD IS A SERVING WORKLOAD. Prompts go through the model's chat template with the
|
||||
* deployment's reasoning default, sampling is the server's default (the same resolve the HTTP
|
||||
* path uses) with a fixed seed per request, and pipelining and drafting stay as configured -- so
|
||||
* what is measured is the engine that serves, not a benchmark mode of it. No HTTP, no stop
|
||||
* strings.
|
||||
*
|
||||
* NOTHING IS SERVED FROM THE PREFIX CACHE. Every prompt is salted at its head with a tag unique to
|
||||
* the request (diag::salt_messages), the cache is emptied before every run, and every request's
|
||||
* cached-token count is checked afterwards: a run the cache served any of is reported, and the
|
||||
* report's verdict says the run is not a measurement. The cache itself stays on, so what it costs
|
||||
* a request that misses -- lookups, publishing, checkpoints -- is measured as a server pays it.
|
||||
*
|
||||
* PARITY. The tag is a counter, not a clock, so two builds run the same workload on the same
|
||||
* prompts with the same seeds, and every request's tokens are in the report. With
|
||||
* --diagnose-baseline the run compares them with an earlier report token for token
|
||||
* (diag::compare_outputs) and fails on any difference.
|
||||
*
|
||||
* Points, each run once unmeasured (first launches of a shape record passes and load code) and
|
||||
* then --diagnose-runs times, every run from an idle engine:
|
||||
* categories one stream a prompt of the corpus, ending on the model's EOS or max tokens
|
||||
* concurrency N streams submitted together, for each N of --diagnose-concurrency;
|
||||
* ignore_eos, so all N decode for the whole run
|
||||
* prefill one prompt of each length of --diagnose-prefill, then a short decode at that
|
||||
* depth
|
||||
* interference streams decoding, then one prompt arriving: its TTFT under load and the gap it
|
||||
* puts into the running streams
|
||||
*/
|
||||
#include "engine_priv.h"
|
||||
#include "diag/diagnose.h"
|
||||
|
||||
#include "build/startup.h"
|
||||
#include "device/device.h"
|
||||
#include "server/adapters.h"
|
||||
#include "server/sink.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
|
||||
extern char** environ;
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
using json = diag::json;
|
||||
|
||||
int64_t steady_ns() {
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
/* The environment knobs that change what is measured, so a report says what it was measured
|
||||
* under: several are read once into statics and cannot be seen any other way. Names only, from the
|
||||
* allowlist in diag/diagnose.cpp; a value may be a path, a host name or a token, and the report is
|
||||
* pasted into issues and committed beside a baseline. */
|
||||
json env_snapshot() { return diag::env_allowlist(environ); }
|
||||
|
||||
/* One request of a run. */
|
||||
struct Job {
|
||||
std::vector<int32_t> prompt;
|
||||
int max_tokens = 0;
|
||||
bool ignore_eos = true;
|
||||
float temp = -1.0f; /* < 0: the server's default */
|
||||
};
|
||||
|
||||
double loadavg1() {
|
||||
FILE* f = std::fopen("/proc/loadavg", "r");
|
||||
if (!f) return -1;
|
||||
double v = -1;
|
||||
if (std::fscanf(f, "%lf", &v) != 1) v = -1;
|
||||
std::fclose(f);
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int Engine::run_diagnose() {
|
||||
namespace fs = std::filesystem;
|
||||
std::error_code ec;
|
||||
fs::create_directories(cfg_.diagnose, ec);
|
||||
if (ec) {
|
||||
RAD_ERR("diagnose: cannot create '%s': %s", cfg_.diagnose.c_str(), ec.message().c_str());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
|
||||
json warnings = json::array();
|
||||
json problems = json::array(); /* what makes the run not a measurement: the verdict */
|
||||
auto warn = [&](const std::string& w) {
|
||||
RAD_WARN("diagnose: %s", w.c_str());
|
||||
warnings.push_back(w);
|
||||
};
|
||||
json not_measured = json::array({
|
||||
"per-kernel device time, launch gaps and host joins: needs dispatch timestamps inside the "
|
||||
"engine (docs/DIAGNOSE.md, step 3); rocprofv3 is not a substitute here",
|
||||
"placement, expert streaming and link counters per phase (docs/DIAGNOSE.md, step 1b)",
|
||||
"op correctness (repeat, oracle) over a step window (docs/DIAGNOSE.md, step 4)",
|
||||
"the HTTP path, detokenisation and streaming to a client: a client-side benchmark measures "
|
||||
"those, and the difference to these numbers is their cost",
|
||||
});
|
||||
|
||||
/* ---- the conditions: what the run ran on, and the serving cards to sample between runs ----
|
||||
* The startup report's machine reading and its findings, taken once before the workload; the
|
||||
* cards' temperatures and performance level again around every run (diag::sample_cards), so a
|
||||
* report shows when two runs, or two reports, were taken on cards in different states. */
|
||||
const diag::Facts facts0 = hardware_facts(/*serving=*/true);
|
||||
const diag::RunFacts rfacts = run_facts(false);
|
||||
const std::vector<diag::Finding> findings = diag::check(facts0, rfacts);
|
||||
std::vector<std::string> serving_bdfs;
|
||||
for (const diag::CardFacts& c : facts0.cards)
|
||||
if (c.rank >= 0) serving_bdfs.push_back(c.bdf);
|
||||
for (const diag::Finding& x : findings)
|
||||
if (x.level >= diag::Finding::Warn && x.id != "profile-ops" && x.id != "prefix-cache-off")
|
||||
warn("machine: " + x.what + " (" + x.fix + ")"); /* those two the mode says below, in its terms */
|
||||
|
||||
/* What makes the numbers depend on more than the build and the machine. Notes, not problems:
|
||||
* each is how the engine serves, and the fix makes it a different engine. */
|
||||
json repro = json::array();
|
||||
{
|
||||
bool heat = false;
|
||||
for (const auto& r : ranks_) heat = heat || r->heat.enabled();
|
||||
if (heat)
|
||||
repro.push_back("placement is dynamic: the heat engine moves experts as it sees routing, so the "
|
||||
"resident set a run starts with depends on the runs before it; --deterministic "
|
||||
"pins the loader's plan for an A/B comparison");
|
||||
if (cfg_.prefill_interleave < 0)
|
||||
repro.push_back("--prefill-interleave auto sizes the decode-only steps between prefill chunks by "
|
||||
"how long a chunk step took, so a long prompt's step sequence depends on timing; "
|
||||
"--prefill-interleave 0 or N fixes it");
|
||||
const std::vector<diag::CardSample> s0 = diag::sample_cards("", serving_bdfs);
|
||||
for (const diag::CardSample& c : s0)
|
||||
if (c.perf_level == "auto")
|
||||
repro.push_back("card " + c.bdf + ": performance level auto, so the firmware picks clocks by "
|
||||
"load, temperature and power; a fixed level (profile_standard in "
|
||||
"power_dpm_force_performance_level) holds them for a comparison, below "
|
||||
"serving clocks");
|
||||
if (cfg_.diagnose_runs < 5)
|
||||
repro.push_back(std::to_string(cfg_.diagnose_runs) + " measured run(s) a point: a spread of so "
|
||||
"few samples says little; --diagnose-runs 5 or more for a comparison");
|
||||
}
|
||||
|
||||
/* ---- prompts: the chat template where the container has one, as the server renders it ---- */
|
||||
server::TokenizerBridge tok(vocab_);
|
||||
server::ChatTemplateBridge chat;
|
||||
const RadChatFormat* fmt = rad_tools_chat_format(plugins_, meta_);
|
||||
const bool use_chat = vocab_ && !vocab_->chat_template().empty() &&
|
||||
chat.init(*vocab_, fmt, plugins_.arch_plugin) >= 0 && chat.ready();
|
||||
if (!use_chat)
|
||||
warn("no usable chat template: prompts are raw text, so draft acceptance and tokens a step "
|
||||
"are not those of chat traffic");
|
||||
|
||||
/* A counter, the same in every process, so a baseline and a candidate see the same prompts.
|
||||
* What the salt cannot cover is the tiers that outlive the process; the cached-token check
|
||||
* after every run catches a hit and refuses the run (below). */
|
||||
uint64_t salt_n = 0;
|
||||
auto render = [&](const json& messages, std::vector<int32_t>* out) -> int {
|
||||
char tag[64];
|
||||
std::snprintf(tag, sizeof tag, "diagnose request %llu", (unsigned long long)++salt_n);
|
||||
const json msgs = diag::salt_messages(messages, tag);
|
||||
if (use_chat) {
|
||||
server::ChatRenderOptions o;
|
||||
const std::string& def = cfg_.reasoning_effort;
|
||||
if (def == "none" || def == "minimal") o.enable_thinking = false;
|
||||
else if (!def.empty()) o.template_kwargs.emplace("reasoning_effort", json(def).dump());
|
||||
server::ChatRender r;
|
||||
std::string why;
|
||||
const int st = chat.apply(msgs, json::array(), o, &r, &why);
|
||||
if (st < 0) {
|
||||
RAD_ERR("diagnose: the chat template refused a workload prompt: %s", why.c_str());
|
||||
return st;
|
||||
}
|
||||
*out = tok.encode(r.prompt, false, /*parse_special=*/true);
|
||||
} else {
|
||||
std::string text;
|
||||
for (const json& m : msgs)
|
||||
if (m["content"].is_string()) text += m["content"].get<std::string>() + "\n\n";
|
||||
*out = tok.encode(text, true, /*parse_special=*/false);
|
||||
}
|
||||
if (out->empty()) {
|
||||
RAD_ERR("diagnose: a workload prompt tokenised to nothing");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
auto user = [](const std::string& text) {
|
||||
return json::array({ json{ { "role", "user" }, { "content", text } } });
|
||||
};
|
||||
|
||||
const int64_t ctx_limit = cfg_.max_ctx > 0 ? (int64_t)cfg_.max_ctx : (int64_t)meta_.n_ctx_train;
|
||||
const int dec_tokens = cfg_.diagnose_tokens;
|
||||
const int runs = cfg_.diagnose_runs;
|
||||
if (cfg_.profile_ops)
|
||||
warn("--profile-ops is on: it turns recorded passes off and adds barriers, so every step time "
|
||||
"here is of a different engine than the one that serves");
|
||||
if (!cfg_.prefix_cache)
|
||||
warn("--no-prefix-cache: requests do not pay the cache's lookups and publishing, which a "
|
||||
"server with the cache on does");
|
||||
const double load0 = loadavg1();
|
||||
const unsigned ncpu = std::max(1u, std::thread::hardware_concurrency());
|
||||
if (load0 > (double)ncpu / 4)
|
||||
warn("the host is busy (load average " + std::to_string(load0) + " on " + std::to_string(ncpu) +
|
||||
" CPUs): the scheduler's planning between steps competes with it, and emission gaps show that");
|
||||
|
||||
/* A prompt of about `want` tokens: a document to summarise, sized by a first render and
|
||||
* scaled, because the template adds tokens of its own and a vocabulary's characters a token is
|
||||
* not known in advance. */
|
||||
auto sized_prompt = [&](int64_t want, uint32_t doc_salt, std::vector<int32_t>* out) -> int {
|
||||
const std::string ask = "Summarise the document above in detail.";
|
||||
int64_t chars = want * 4;
|
||||
for (int pass = 0; pass < 4; ++pass) {
|
||||
RAD_TRY(render(user(diag::synthetic_document(chars, doc_salt) + "\n\n" + ask), out));
|
||||
const int64_t got = (int64_t)out->size();
|
||||
if (got <= want && got >= want - std::max<int64_t>(8, want / 50)) return RAD_OK;
|
||||
chars = std::max<int64_t>(16, (int64_t)((double)chars * (double)want / (double)got * 0.99));
|
||||
}
|
||||
if ((int64_t)out->size() > want) {
|
||||
RAD_ERR("diagnose: could not fit a prefill prompt in %lld tokens", (long long)want);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
|
||||
const SamplingParams sp0 = sampling_defaults();
|
||||
uint64_t next_id = 1;
|
||||
/* TEMPERATURE 1 FOR EVERY REQUEST, whatever the server's default: it is the temperature the
|
||||
* model is served at, and draft acceptance -- what an adaptive draft depth is tuned on -- falls
|
||||
* with temperature, so a greedy workload would tune it for traffic that never comes. top_k,
|
||||
* top_p and min_p stay the server's. Parity does not need greedy: a fixed seed per request
|
||||
* makes bit-identical logits sample identical tokens at any temperature. */
|
||||
const float kTemp = 1.0f;
|
||||
|
||||
/* ---- one run: submit, wait, collect ----
|
||||
* `late` is submitted once every request of `early` has produced `late_after` tokens; the
|
||||
* early requests are cancelled once every late one has produced `late_after` tokens too, so a
|
||||
* stream started only to be interfered with does not decode to its limit. */
|
||||
auto run_set = [&](const std::string& name, diag::PhaseKind kind, const std::vector<Job>& early,
|
||||
const std::vector<Job>& late, int late_after, diag::PhaseInput* in) -> int {
|
||||
for (const auto* set : { &early, &late })
|
||||
for (const Job& jb : *set)
|
||||
if ((int64_t)jb.prompt.size() + jb.max_tokens > ctx_limit) {
|
||||
RAD_ERR("diagnose: %s needs %zu + %d tokens of context and the engine serves %lld",
|
||||
name.c_str(), jb.prompt.size(), jb.max_tokens, (long long)ctx_limit);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
sched_.reset_prefix_cache();
|
||||
const std::vector<diag::CardSample> cards0 = diag::sample_cards("", serving_bdfs);
|
||||
const SchedMetrics before = sched_.metrics();
|
||||
const uint64_t seq0 = sched_.step_record_count();
|
||||
|
||||
std::vector<std::unique_ptr<server::Sink>> sinks;
|
||||
auto submit = [&](const std::vector<Job>& jobs) -> int {
|
||||
std::vector<std::unique_ptr<Request>> reqs;
|
||||
for (const Job& jb : jobs) {
|
||||
sinks.push_back(std::make_unique<server::Sink>((size_t)jb.max_tokens + 64));
|
||||
auto r = std::make_unique<Request>();
|
||||
r->id = next_id++;
|
||||
r->prompt = jb.prompt;
|
||||
r->max_tokens = jb.max_tokens;
|
||||
r->ignore_eos = jb.ignore_eos;
|
||||
r->sp = sp0;
|
||||
if (jb.temp >= 0.0f) r->sp.temp = jb.temp;
|
||||
r->sp.seed = 0x5eedull * 7919ull + r->id; /* fixed per request, so reruns sample alike */
|
||||
r->sink = sinks.back().get();
|
||||
sinks.back()->id = r->id;
|
||||
reqs.push_back(std::move(r));
|
||||
}
|
||||
std::vector<int> rc(reqs.size(), RAD_OK);
|
||||
/* All at once, under one hold of the queue: the streams are admitted into the same steps. */
|
||||
sched_.add_all(reqs.data(), reqs.size(), rc.data());
|
||||
for (int c : rc)
|
||||
if (c < 0) {
|
||||
RAD_ERR("diagnose: the scheduler refused a %s request: %s", name.c_str(), rad_strerror(c));
|
||||
return c;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
auto produced_all = [&](size_t from, size_t to, int64_t n) {
|
||||
for (size_t i = from; i < to; ++i)
|
||||
if (!sinks[i]->done() && sinks[i]->n_produced() < n) return false;
|
||||
return true;
|
||||
};
|
||||
auto wait_until = [&](const std::function<bool()>& ready) -> int {
|
||||
while (!ready()) {
|
||||
const int ls = loop_status_.load(std::memory_order_acquire);
|
||||
if (ls < 0) return ls;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
|
||||
const int64_t t0 = steady_ns();
|
||||
RAD_TRY(submit(early));
|
||||
const size_t n_early = sinks.size();
|
||||
if (!late.empty()) {
|
||||
RAD_TRY(wait_until([&] { return produced_all(0, n_early, late_after); }));
|
||||
RAD_TRY(submit(late));
|
||||
RAD_TRY(wait_until([&] { return produced_all(n_early, sinks.size(), late_after); }));
|
||||
for (size_t i = 0; i < n_early; ++i)
|
||||
if (!sinks[i]->done()) sched_.cancel(sinks[i]->id);
|
||||
}
|
||||
for (size_t first = 0;;) {
|
||||
while (first < sinks.size() && sinks[first]->done()) ++first;
|
||||
if (first == sinks.size()) break;
|
||||
const int ls = loop_status_.load(std::memory_order_acquire);
|
||||
if (ls < 0) return ls;
|
||||
sinks[first]->wait(200);
|
||||
}
|
||||
/* A sink finishes before the step that produced its last token is charged to the
|
||||
* counters, so wait for the scheduler to go idle and its step count to stop moving. */
|
||||
for (uint64_t last = UINT64_MAX;;) {
|
||||
const uint64_t c = sched_.step_record_count();
|
||||
const SchedMetrics m = sched_.metrics();
|
||||
if (c == last && m.running == 0 && m.queue_depth == 0) break;
|
||||
last = c;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
}
|
||||
const std::vector<diag::CardSample> cards1 = diag::sample_cards("", serving_bdfs);
|
||||
*in = diag::PhaseInput{};
|
||||
if (!serving_bdfs.empty())
|
||||
in->cards = { { "start", diag::card_samples_json(cards0) }, { "end", diag::card_samples_json(cards1) } };
|
||||
in->name = name;
|
||||
in->kind = kind;
|
||||
in->streams = (int)sinks.size();
|
||||
in->wall_ns = steady_ns() - t0;
|
||||
in->before = before;
|
||||
in->after = sched_.metrics();
|
||||
in->steps_lost = sched_.step_records(seq0, &in->steps);
|
||||
int bad = 0;
|
||||
for (size_t i = 0; i < sinks.size(); ++i) {
|
||||
const server::Sink& s = *sinks[i];
|
||||
diag::RequestTiming t;
|
||||
const int64_t base = s.t_start_ns();
|
||||
t.start_ns = base;
|
||||
t.admitted_ns = s.t_admitted_ns() >= 0 ? base + s.t_admitted_ns() : -1;
|
||||
t.first_ns = s.t_first_token_ns() >= 0 ? base + s.t_first_token_ns() : -1;
|
||||
t.last_ns = s.t_last_token_ns() >= 0 ? base + s.t_last_token_ns() : -1;
|
||||
t.tokens = s.n_produced();
|
||||
t.prompt = s.n_prompt();
|
||||
t.cached = s.n_cached();
|
||||
t.drafted = s.n_drafted();
|
||||
t.accepted = s.n_draft_accepted();
|
||||
{
|
||||
std::vector<server::SinkToken> toks((size_t)std::max<int64_t>(s.n_produced(), 0) + 1);
|
||||
const size_t got = sinks[i]->read(toks.data(), toks.size());
|
||||
t.output.reserve(got);
|
||||
for (size_t k = 0; k < got; ++k) t.output.push_back(toks[k].token);
|
||||
}
|
||||
const server::Finish f = s.finish_reason();
|
||||
const bool cancelled_by_us = i < n_early && !late.empty() && f == server::Finish::Cancelled;
|
||||
t.ok = f == server::Finish::Length || f == server::Finish::Stop || cancelled_by_us;
|
||||
t.stopped = f == server::Finish::Stop;
|
||||
if (!t.ok) {
|
||||
RAD_ERR("diagnose: a %s request did not finish: %s", name.c_str(),
|
||||
s.why() ? s.why() : rad_strerror(s.status()));
|
||||
++bad;
|
||||
}
|
||||
in->requests.push_back(t);
|
||||
sched_.reap(s.id);
|
||||
}
|
||||
int64_t cached = 0;
|
||||
for (const auto& t : in->requests) cached += t.cached;
|
||||
if (cached > 0)
|
||||
problems.push_back(name + ": the prefix cache served " + std::to_string(cached) +
|
||||
" prompt tokens, so this run measured a cache hit");
|
||||
if (in->steps_lost > 0)
|
||||
problems.push_back(name + ": " + std::to_string(in->steps_lost) +
|
||||
" step records were overwritten before they were read");
|
||||
RAD_INFO("diagnose: %s done in %.2f s", name.c_str(), (double)in->wall_ns / 1e9);
|
||||
return bad ? RAD_E_STATE : RAD_OK;
|
||||
};
|
||||
/* A measured point: one unmeasured run, then `runs` measured ones. `make` builds a run's jobs
|
||||
* fresh each time, so every run has its own salt. */
|
||||
auto measure = [&](const std::string& name, diag::PhaseKind kind,
|
||||
const std::function<int(bool warm, std::vector<Job>*)>& make,
|
||||
std::vector<json>* out) -> int {
|
||||
diag::PhaseInput in;
|
||||
std::vector<Job> jobs;
|
||||
RAD_TRY(make(true, &jobs));
|
||||
RAD_TRY(run_set(name + "/warmup", kind, jobs, {}, 0, &in));
|
||||
for (int r = 0; r < runs; ++r) {
|
||||
jobs.clear();
|
||||
RAD_TRY(make(false, &jobs));
|
||||
RAD_TRY(run_set(name + "/" + std::to_string(r + 1), kind, jobs, {}, 0, &in));
|
||||
out->push_back(diag::phase_report(in));
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
|
||||
/* ---- categories ---- */
|
||||
std::vector<diag::CorpusEntry> corpus;
|
||||
if (!cfg_.diagnose_corpus.empty()) {
|
||||
std::string why;
|
||||
if (diag::load_corpus(cfg_.diagnose_corpus, &corpus, &why) < 0) {
|
||||
RAD_ERR("diagnose: %s", why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else {
|
||||
corpus = diag::builtin_corpus();
|
||||
}
|
||||
std::vector<std::string> cats;
|
||||
for (const auto& e : corpus)
|
||||
if (std::find(cats.begin(), cats.end(), e.category) == cats.end()) cats.push_back(e.category);
|
||||
json categories = json::array();
|
||||
for (const std::string& cat : cats) {
|
||||
std::vector<const diag::CorpusEntry*> es;
|
||||
for (const auto& e : corpus)
|
||||
if (e.category == cat) es.push_back(&e);
|
||||
std::vector<json> rs;
|
||||
/* A category's summary pools its prompts; whether a number repeats is a question about one
|
||||
* prompt's runs, so each prompt is summarised on its own as well (diag::stability_report). */
|
||||
json per_prompt = json::array();
|
||||
for (size_t k = 0; k < es.size(); ++k) {
|
||||
const diag::CorpusEntry& e = *es[k];
|
||||
const size_t from = rs.size();
|
||||
const int mt = e.max_tokens > 0 ? e.max_tokens : dec_tokens;
|
||||
RAD_TRY(measure("category " + cat + " #" + std::to_string(k + 1), diag::PhaseKind::Decode,
|
||||
[&](bool warm, std::vector<Job>* jobs) -> int {
|
||||
Job jb;
|
||||
RAD_TRY(render(e.messages, &jb.prompt));
|
||||
jb.max_tokens = warm ? std::min(mt, 32) : mt;
|
||||
jb.ignore_eos = false; /* the model's own lengths: that is the category */
|
||||
jb.temp = kTemp;
|
||||
jobs->push_back(std::move(jb));
|
||||
return RAD_OK;
|
||||
},
|
||||
&rs));
|
||||
per_prompt.push_back({ { "prompt", (int64_t)k + 1 },
|
||||
{ "summary", diag::summarize_runs(std::vector<json>(rs.begin() + (std::ptrdiff_t)from, rs.end())) } });
|
||||
}
|
||||
int64_t reqs = 0, stopped = 0;
|
||||
for (const json& r : rs) {
|
||||
reqs += r["requests"]["count"].get<int64_t>();
|
||||
stopped += r["requests"]["stopped_on_eos"].get<int64_t>();
|
||||
}
|
||||
categories.push_back({ { "category", cat }, { "prompts", (int64_t)es.size() },
|
||||
{ "requests", reqs }, { "stopped_on_eos", stopped },
|
||||
{ "summary", diag::summarize_runs(rs) }, { "prompts_summary", per_prompt },
|
||||
{ "draft_by_position", diag::pool_draft_positions(rs) }, { "runs", rs } });
|
||||
}
|
||||
|
||||
/* ---- concurrency ---- */
|
||||
json concurrency = json::array();
|
||||
for (int n : cfg_.diagnose_concurrency) {
|
||||
if (n > cfg_.max_seqs) {
|
||||
warn("concurrency " + std::to_string(n) + " skipped: --max-num-seqs is " + std::to_string(cfg_.max_seqs));
|
||||
continue;
|
||||
}
|
||||
std::vector<json> rs;
|
||||
RAD_TRY(measure("concurrency " + std::to_string(n), diag::PhaseKind::Decode,
|
||||
[&](bool warm, std::vector<Job>* jobs) -> int {
|
||||
for (int s = 0; s < n; ++s) {
|
||||
Job jb;
|
||||
RAD_TRY(render(corpus[(size_t)s % corpus.size()].messages, &jb.prompt));
|
||||
jb.max_tokens = warm ? std::min(dec_tokens, 32) : dec_tokens;
|
||||
jb.ignore_eos = true; /* every stream decodes the whole run */
|
||||
jb.temp = kTemp;
|
||||
jobs->push_back(std::move(jb));
|
||||
}
|
||||
return RAD_OK;
|
||||
},
|
||||
&rs));
|
||||
concurrency.push_back({ { "streams", n }, { "summary", diag::summarize_runs(rs) },
|
||||
{ "draft_by_position", diag::pool_draft_positions(rs) }, { "runs", rs } });
|
||||
}
|
||||
|
||||
/* ---- prefill ---- */
|
||||
const int depth_tokens = std::min(dec_tokens, 64);
|
||||
json prefill = json::array();
|
||||
uint32_t doc_salt = 1;
|
||||
for (int want : cfg_.diagnose_prefill) {
|
||||
if ((int64_t)want + depth_tokens > ctx_limit) {
|
||||
warn("prefill " + std::to_string(want) + " skipped: the engine serves " + std::to_string(ctx_limit) +
|
||||
" tokens of context");
|
||||
continue;
|
||||
}
|
||||
std::vector<json> rs;
|
||||
int64_t got = 0;
|
||||
RAD_TRY(measure("prefill " + std::to_string(want), diag::PhaseKind::Prefill,
|
||||
[&](bool warm, std::vector<Job>* jobs) -> int {
|
||||
Job jb;
|
||||
RAD_TRY(sized_prompt(want, doc_salt++, &jb.prompt));
|
||||
got = (int64_t)jb.prompt.size();
|
||||
jb.max_tokens = warm ? 1 : depth_tokens;
|
||||
jb.ignore_eos = true;
|
||||
jb.temp = kTemp;
|
||||
jobs->push_back(std::move(jb));
|
||||
return RAD_OK;
|
||||
},
|
||||
&rs));
|
||||
prefill.push_back({ { "requested_tokens", want }, { "prompt_tokens", got },
|
||||
{ "summary", diag::summarize_runs(rs) }, { "runs", rs } });
|
||||
}
|
||||
|
||||
/* ---- interference: a prompt arriving into running streams ---- */
|
||||
json interference = nullptr;
|
||||
{
|
||||
const int streams = (int)std::min<int64_t>(4, cfg_.max_seqs - 1);
|
||||
/* The arriving prompt: the longest measured prefill up to 16k, so its idle TTFT is known. */
|
||||
const json* pick = nullptr;
|
||||
for (const json& p : prefill)
|
||||
if (p["requested_tokens"].get<int>() <= 16384) pick = &p;
|
||||
if (!pick && !prefill.empty()) pick = &prefill[0];
|
||||
if (streams < 1 || !pick) {
|
||||
not_measured.push_back("a prompt arriving into running streams: needs --max-num-seqs of 2 or "
|
||||
"more and a measured prefill length");
|
||||
} else {
|
||||
const int want = (*pick)["requested_tokens"].get<int>();
|
||||
/* The running streams must outlast the arrival's prefill; they are cancelled once it has
|
||||
* decoded a little, so their limit only has to be out of reach. */
|
||||
const int run_tokens = (int)std::min<int64_t>(1 << 16, ctx_limit / 2);
|
||||
const int after = 16;
|
||||
std::vector<json> rs;
|
||||
for (int r = -1; r < runs; ++r) {
|
||||
std::vector<Job> early, late(1);
|
||||
for (int s = 0; s < streams; ++s) {
|
||||
Job jb;
|
||||
RAD_TRY(render(corpus[(size_t)s % corpus.size()].messages, &jb.prompt));
|
||||
jb.max_tokens = run_tokens;
|
||||
jb.ignore_eos = true;
|
||||
jb.temp = kTemp;
|
||||
early.push_back(std::move(jb));
|
||||
}
|
||||
RAD_TRY(sized_prompt(want, doc_salt++, &late[0].prompt));
|
||||
late[0].max_tokens = after;
|
||||
late[0].ignore_eos = true;
|
||||
late[0].temp = kTemp;
|
||||
diag::PhaseInput in;
|
||||
const std::string name = "interference/" + (r < 0 ? std::string("warmup") : std::to_string(r + 1));
|
||||
RAD_TRY(run_set(name, diag::PhaseKind::Decode, early, late, after, &in));
|
||||
if (r < 0) continue;
|
||||
const diag::RequestTiming& a = in.requests.back();
|
||||
json x;
|
||||
x["arrival_ttft_ms"] = a.admitted_ns >= 0 && a.first_ns >= 0
|
||||
? json(std::round((double)(a.first_ns - a.admitted_ns) / 1e3) / 1e3)
|
||||
: json(nullptr);
|
||||
/* The running streams' steps only: the arrival's own decode would fill the gap. */
|
||||
x["interference"] = diag::interference_report(in.steps, a.admitted_ns, a.first_ns);
|
||||
x["phase"] = diag::phase_report(in);
|
||||
rs.push_back(x);
|
||||
}
|
||||
json idle = nullptr;
|
||||
const json& ps = (*pick)["summary"];
|
||||
if (ps.contains("requests.ttft_ms.p50") && ps["requests.ttft_ms.p50"].is_object())
|
||||
idle = ps["requests.ttft_ms.p50"]["median"];
|
||||
interference = { { "streams", streams }, { "prompt_tokens", (*pick)["prompt_tokens"] },
|
||||
{ "idle_ttft_ms", idle },
|
||||
{ "summary", diag::summarize_paths(rs, { "/arrival_ttft_ms",
|
||||
"/interference/typical_gap_ms",
|
||||
"/interference/longest_gap_ms",
|
||||
"/interference/stall_ratio" }) },
|
||||
{ "runs", rs } };
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the report ---- */
|
||||
json rep;
|
||||
{
|
||||
/* The engine's /server_info is not spliced in: its container is the model's path and its
|
||||
* control vector carries a file (diag::engine_report says what is kept). */
|
||||
const json info = json::parse(engine_info(), nullptr, /*allow_exceptions=*/false);
|
||||
json eng = info.is_object() ? diag::engine_report(info) : json::object();
|
||||
eng["tp"] = cfg_.tp;
|
||||
eng["backend"] = device_is_host() ? "host" : "device";
|
||||
eng["plan"] = cfg_.deterministic ? "deterministic (static placement)" : "dynamic placement";
|
||||
eng["max_num_seqs"] = cfg_.max_seqs;
|
||||
eng["context"] = ctx_limit;
|
||||
rep["engine"] = eng;
|
||||
}
|
||||
json w;
|
||||
w["description"] = std::string(use_chat ? "chat-templated" : "raw-text") + " prompts, each salted at its head; " +
|
||||
std::to_string(runs) + " measured run(s) a point after one unmeasured; categories from " +
|
||||
(cfg_.diagnose_corpus.empty() ? std::string("the built-in corpus")
|
||||
: std::string("the external corpus (its contents are in "
|
||||
"workload.fingerprint)")) +
|
||||
" up to " + std::to_string(dec_tokens) + " tokens, ending on EOS; concurrency streams " +
|
||||
std::to_string(dec_tokens) + " tokens with ignore_eos; prefill then " +
|
||||
std::to_string(depth_tokens) + " tokens of decode; temperature 1 with the server's "
|
||||
"top_k/top_p/min_p and a fixed seed per request; prefix cache emptied before every run";
|
||||
w["sampling"] = { { "temp", kTemp }, { "top_k", sp0.top_k }, { "top_p", sp0.top_p }, { "min_p", sp0.min_p } };
|
||||
w["reasoning_effort"] = cfg_.reasoning_effort;
|
||||
w["runs"] = runs;
|
||||
w["tokens"] = dec_tokens;
|
||||
{
|
||||
/* What decides the prompts and the seeds: two reports with the same fingerprint ran the
|
||||
* same requests in the same order. */
|
||||
json fp;
|
||||
json c = json::array();
|
||||
for (const auto& e : corpus) c.push_back({ e.category, e.messages, e.max_tokens });
|
||||
fp["corpus"] = c;
|
||||
fp["tokens"] = dec_tokens;
|
||||
fp["runs"] = runs;
|
||||
fp["concurrency"] = cfg_.diagnose_concurrency;
|
||||
fp["prefill"] = cfg_.diagnose_prefill;
|
||||
fp["max_num_seqs"] = cfg_.max_seqs;
|
||||
fp["context"] = ctx_limit;
|
||||
fp["chat_template"] = use_chat;
|
||||
fp["reasoning_effort"] = cfg_.reasoning_effort;
|
||||
fp["sampling"] = w["sampling"];
|
||||
w["fingerprint"] = diag::workload_fingerprint(fp);
|
||||
}
|
||||
rep["workload"] = w;
|
||||
const double load1 = loadavg1();
|
||||
if (load1 > (double)ncpu / 4)
|
||||
warn("the host was busy at the end (load average " + std::to_string(load1) + " on " +
|
||||
std::to_string(ncpu) + " CPUs)");
|
||||
json envj;
|
||||
envj["variables"] = env_snapshot();
|
||||
envj["loadavg_start"] = load0;
|
||||
envj["loadavg_end"] = load1;
|
||||
envj["cpus"] = ncpu;
|
||||
rep["environment"] = envj;
|
||||
rep["conditions"] = diag::conditions_report(facts0, rfacts, findings);
|
||||
{
|
||||
const json measured = { { "categories", categories }, { "concurrency", concurrency },
|
||||
{ "prefill", prefill }, { "interference", interference } };
|
||||
rep["stability"] = diag::stability_report(measured);
|
||||
for (const json& u : rep["stability"]["unstable"]) {
|
||||
char b[256];
|
||||
std::snprintf(b, sizeof b, "%s: %s spread %.1f%% over %s runs (median %s), above %.0f%%",
|
||||
u["point"].get<std::string>().c_str(), u["metric"].get<std::string>().c_str(),
|
||||
u["spread_pct"].get<double>(), u["runs"].dump().c_str(), u["median"].dump().c_str(),
|
||||
diag::kMaxSpreadPct);
|
||||
warn(b);
|
||||
}
|
||||
rep["thermal"] = diag::thermal_report(measured);
|
||||
for (const json& w : rep["thermal"]["warnings"]) warn(w.get<std::string>());
|
||||
}
|
||||
rep["reproducibility"] = repro;
|
||||
rep["verdict"] = problems.empty() ? std::string("valid") : std::string("NOT A MEASUREMENT -- see problems");
|
||||
rep["problems"] = problems;
|
||||
for (const auto& p : problems) warnings.push_back(p);
|
||||
rep["warnings"] = warnings;
|
||||
rep["categories"] = categories;
|
||||
rep["concurrency"] = concurrency;
|
||||
rep["prefill"] = prefill;
|
||||
rep["interference"] = interference;
|
||||
rep["not_measured"] = not_measured;
|
||||
|
||||
bool parity_ok = true;
|
||||
if (!cfg_.diagnose_baseline.empty()) {
|
||||
std::ifstream f(cfg_.diagnose_baseline);
|
||||
const json base = json::parse(f, nullptr, /*allow_exceptions=*/false);
|
||||
std::string why;
|
||||
json cmp;
|
||||
if (!f.is_open() || base.is_discarded()) {
|
||||
why = "the baseline file is not readable JSON";
|
||||
} else if (diag::compare_outputs(rep, base, &cmp, &why) == RAD_OK) {
|
||||
cmp["baseline"] = "an earlier report";
|
||||
rep["parity"] = cmp;
|
||||
parity_ok = cmp["verdict"] == "identical" && cmp["acceptance_verdict"] == "no drop";
|
||||
RAD_INFO("diagnose: parity %s, %lld of %lld requests identical; draft acceptance: %s",
|
||||
cmp["verdict"].get<std::string>().c_str(), (long long)cmp["identical"].get<int64_t>(),
|
||||
(long long)cmp["compared"].get<int64_t>(), cmp["acceptance_verdict"].get<std::string>().c_str());
|
||||
}
|
||||
if (!why.empty()) {
|
||||
rep["parity"] = { { "baseline", "an earlier report" },
|
||||
{ "verdict", "not compared: " + why } };
|
||||
parity_ok = false;
|
||||
RAD_ERR("diagnose: %s", why.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
const fs::path dir(cfg_.diagnose);
|
||||
{
|
||||
std::ofstream f(dir / "diagnose.json");
|
||||
f << rep.dump(2) << "\n";
|
||||
if (!f) {
|
||||
RAD_ERR("diagnose: cannot write %s", (dir / "diagnose.json").c_str());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
}
|
||||
{
|
||||
std::ofstream f(dir / "diagnose.md");
|
||||
f << diag::render_markdown(rep);
|
||||
if (!f) {
|
||||
RAD_ERR("diagnose: cannot write %s", (dir / "diagnose.md").c_str());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
}
|
||||
RAD_INFO("diagnose: report in %s", (dir / "diagnose.md").c_str());
|
||||
return problems.empty() && parity_ok ? RAD_OK : RAD_E_STATE;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -215,7 +215,7 @@ int Engine::tree_compact(int rows) {
|
||||
const int64_t row = bits > 0 ? b->shape[3] * bits / 8 : 0;
|
||||
int32_t layers = 0;
|
||||
for (int32_t s : b->layer_slot) layers += s >= 0;
|
||||
if (row <= 0 || row % 16 || (bits != 8 && bits != 16 && bits != 32) ||
|
||||
if (row <= 0 || row % 4 || (bits != 8 && bits != 16 && bits != 32) ||
|
||||
(b->bytes && (int64_t)layers * b->layer_stride > b->bytes)) {
|
||||
RAD_ERR("speculation: KV group %zu's cache (%s, %lld-byte rows) is not one a tree's "
|
||||
"acceptance can move", g, rad_dtype_name(b->dtype), (long long)row);
|
||||
|
||||
@@ -113,4 +113,5 @@ struct TierPump {
|
||||
* still hold the previous step's values when the step loop dumps. */
|
||||
void dump_buffers(Ctx& ctx, int step, const char* phase = "");
|
||||
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -403,10 +403,12 @@ int Reader::read_scheduler(const Item& sec, FleetConfig* out) {
|
||||
if (k == "load-timeout") s = duration(it, &out->load_timeout_ms);
|
||||
else if (k == "drain-timeout") s = duration(it, &out->drain_timeout_ms);
|
||||
else if (k == "keepalive") s = duration(it, &out->keepalive_ms);
|
||||
else if (k == "stuck-exit") s = duration(it, &out->stuck_exit_ms);
|
||||
else if (k == "warm-up") s = boolean(it, &out->warm_up);
|
||||
else {
|
||||
return fail(it.node, "scheduler." + k + " is not a scheduler key" +
|
||||
suggest(k, { "load-timeout", "drain-timeout", "keepalive", "warm-up" }));
|
||||
suggest(k, { "load-timeout", "drain-timeout", "keepalive",
|
||||
"stuck-exit", "warm-up" }));
|
||||
}
|
||||
if (s < 0) return s;
|
||||
}
|
||||
@@ -834,6 +836,7 @@ void print_reference(FILE* to) {
|
||||
" load-timeout: DURATION how long a request waits for its model (default 120s)\n"
|
||||
" drain-timeout: DURATION how long a model being evicted may finish requests (30s)\n"
|
||||
" keepalive: DURATION SSE comment interval while a request waits (10s)\n"
|
||||
" stuck-exit: DURATION a device stuck this long ends the process (60s; 0 never)\n"
|
||||
" warm-up: true|false fill free VRAM, then host RAM, with models at start (true)\n"
|
||||
"\ndefaults: any model key, merged under every model\n"
|
||||
"\nmodels:\n"
|
||||
|
||||
@@ -104,6 +104,9 @@ struct FleetConfig {
|
||||
int64_t load_timeout_ms = 120000;
|
||||
int64_t drain_timeout_ms = 30000;
|
||||
int64_t keepalive_ms = 10000;
|
||||
/* A device that has advanced nothing for this long ends the process, so a restart policy can
|
||||
* bring the server back (dev_stuck_exit_ms); 0 never. */
|
||||
int64_t stuck_exit_ms = 60000;
|
||||
/* Once the listener is open and nothing waits, unpinned models load one at a time into free
|
||||
* VRAM and park to host memory and the disk tier as later ones displace them, so a first
|
||||
* request finds its model parked rather than cold (docs/MULTIMODEL.md §8.6). */
|
||||
|
||||
+20
-1
@@ -142,6 +142,23 @@ double sysfs_number(const std::string& path) {
|
||||
return f >> v ? v : -1;
|
||||
}
|
||||
|
||||
/* A card's temperature in millidegrees: the sensor its driver labels `junction`, else temp1. amdgpu
|
||||
* labels three, edge (temp1), junction and mem, and throttles on the junction, the hottest spot on
|
||||
* the die: under a decode load an R9700 read 56 C at the edge and 75-77 C at the junction. A driver
|
||||
* that labels none, or no junction, keeps temp1. -1 when neither can be read. */
|
||||
double card_temp_mc(const std::string& hwmon) {
|
||||
for (int i = 1; i <= 8; ++i) {
|
||||
const std::string t = hwmon + "/temp" + std::to_string(i);
|
||||
std::ifstream f(t + "_label");
|
||||
std::string label;
|
||||
if (!(f >> label)) continue;
|
||||
if (label != "junction") continue;
|
||||
if (const double mc = sysfs_number(t + "_input"); mc >= 0) return mc;
|
||||
break;
|
||||
}
|
||||
return sysfs_number(hwmon + "/temp1_input");
|
||||
}
|
||||
|
||||
/* What the driver reports of a card right now: busy share, power and temperature, on the routes of
|
||||
* a dashboard being watched and nowhere on a request's path. A card that reports none adds none. */
|
||||
void card_telemetry(int card, json& o) {
|
||||
@@ -156,7 +173,7 @@ void card_telemetry(int card, json& o) {
|
||||
double uw = sysfs_number(hp + "/power1_average");
|
||||
if (uw < 0) uw = sysfs_number(hp + "/power1_input");
|
||||
if (uw >= 0) o["power_w"] = uw / 1e6;
|
||||
if (const double mc = sysfs_number(hp + "/temp1_input"); mc >= 0) o["temp_c"] = mc / 1000.0;
|
||||
if (const double mc = card_temp_mc(hp); mc >= 0) o["temp_c"] = mc / 1000.0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -502,6 +519,7 @@ private:
|
||||
|
||||
Fleet::Fleet(FleetConfig fc)
|
||||
: fc_(std::move(fc)), front_(transport_options(fc_), fc_.keepalive_ms) {
|
||||
dev_stuck_exit_ms.store(fc_.stuck_exit_ms, std::memory_order_relaxed);
|
||||
bool any = false;
|
||||
int64_t head = 0;
|
||||
for (const ModelEntry& e : fc_.models) {
|
||||
@@ -2301,6 +2319,7 @@ std::string Fleet::reload() {
|
||||
front_.update(e.name, e.aliases, nf.load_timeout_ms, required);
|
||||
}
|
||||
fc_ = std::move(nf);
|
||||
dev_stuck_exit_ms.store(fc_.stuck_exit_ms, std::memory_order_relaxed);
|
||||
for (const ModelEntry& e : fc_.models)
|
||||
if (e.pin) demand(e.name);
|
||||
RAD_INFO("reload: %s applied, %zu model(s)", fc_.path.c_str(), fc_.models.size());
|
||||
|
||||
+244
-13
@@ -347,6 +347,7 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
* pass through in the free-form list. */
|
||||
const std::string a = out->arch;
|
||||
if (a == "hy_v3") out->arch = "hyv3";
|
||||
if (a == "bailingmoe3") out->arch = "bailinghybrid";
|
||||
auto gi = [&](const char* suffix, int64_t dflt) -> int64_t {
|
||||
int64_t v = 0;
|
||||
return g.get_i64(a + "." + suffix, &v) ? v : dflt;
|
||||
@@ -443,6 +444,57 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
out->kv("attention_bias", "0");
|
||||
out->kv("mlp_bias", "0");
|
||||
}
|
||||
if (a == "bailingmoe3") {
|
||||
/* Ling 3.0 (the arch alias above): the release GGUF spells the family's keys
|
||||
* bailingmoe3.*, and the plugin (arch/bailing_hybrid) reads them as the checkpoint's
|
||||
* config.json names, so the reader re-spells them here and one plugin serves both
|
||||
* formats. eps and rope_theta take the generic paths above. Four of the family's
|
||||
* design choices the GGUF does not carry are Ling 3.0's, stated as constants. */
|
||||
if (gi("kda.head_dim", 0) <= 0 || gi("rope.dimension_count", 0) <= 0 ||
|
||||
gi("attention.key_length_mla", 0) <= gi("rope.dimension_count", 0))
|
||||
return RAD_E_FORMAT;
|
||||
out->kv("num_attention_heads", fmt("%lld", (long long)m.n_head));
|
||||
/* The typed head_dim the generic pass fell back to (the MLA query width) is not the
|
||||
* KDA head the plugin asserts; rad-convert publishes the typed fields before the kv
|
||||
* table, and lookups take the first row, so the typed field must carry the 128. */
|
||||
out->m.head_dim = (int)gi("kda.head_dim", 0);
|
||||
out->kv("head_dim", fmt("%lld", (long long)gi("kda.head_dim", 0)));
|
||||
/* The GGUF's key_length_mla is the full query (nope + rotary); the plugin's
|
||||
* qk_nope_head_dim is the rotary part subtracted. */
|
||||
out->kv("qk_nope_head_dim",
|
||||
fmt("%lld", (long long)(gi("attention.key_length_mla", 0) - gi("rope.dimension_count", 0))));
|
||||
out->kv("qk_rope_head_dim", fmt("%lld", (long long)gi("rope.dimension_count", 0)));
|
||||
out->kv("v_head_dim", fmt("%lld", (long long)gi("attention.value_length_mla", 0)));
|
||||
out->kv("kv_lora_rank", fmt("%lld", (long long)gi("attention.kv_lora_rank", 0)));
|
||||
out->kv("q_lora_rank", fmt("%lld", (long long)gi("attention.q_lora_rank", 0)));
|
||||
out->kv("num_experts", fmt("%lld", (long long)m.n_expert));
|
||||
out->kv("num_experts_per_tok", fmt("%lld", (long long)m.n_expert_used));
|
||||
out->kv("n_group", fmt("%lld", (long long)gi("expert_group_count", 0)));
|
||||
out->kv("topk_group", fmt("%lld", (long long)gi("expert_group_used_count", 0)));
|
||||
out->kv("moe_intermediate_size", fmt("%lld", (long long)gi("expert_feed_forward_length", 0)));
|
||||
out->kv("moe_shared_expert_intermediate_size",
|
||||
fmt("%lld", (long long)gi("expert_shared_feed_forward_length", 0)));
|
||||
out->kv("num_shared_experts", fmt("%lld", (long long)m.n_expert_shared));
|
||||
out->kv("intermediate_size", fmt("%lld", (long long)m.n_ff));
|
||||
out->kv("first_k_dense_replace", fmt("%lld", (long long)gi("leading_dense_block_count", 0)));
|
||||
out->kv("short_conv_kernel_size", fmt("%lld", (long long)gi("ssm.conv_kernel", 0)));
|
||||
out->kv("kda_lower_bound", fmt("%.17g", gf("kda.gate_lower_bound", 0.0)));
|
||||
out->kv("routed_scaling_factor", fmt("%.17g", gf("expert_weights_scale", 1.0)));
|
||||
out->kv("norm_topk_prob", fmt("%lld", (long long)gi("expert_weights_norm", 0)));
|
||||
out->kv("kda_safe_gate", fmt("%lld", (long long)gi("kda.safe_gate", 0)));
|
||||
out->kv("layer_group_size", "4");
|
||||
out->kv("no_kda_lora", "1");
|
||||
out->kv("rope_interleave", "1");
|
||||
out->kv("gated_attention_proj_granularity_type", "head_wise");
|
||||
out->kv("num_nextn_predict_layers", "0");
|
||||
/* The plugin picks its checkpoint names from this: the GGUF spells the family's tensors
|
||||
* blk. and ssm. names (and carries the layouts bailingmoe3_layouts rebuilds), the safetensors
|
||||
* their config.json spellings. */
|
||||
out->kv("gguf_source", "1");
|
||||
std::string gating = "sigmoid";
|
||||
g.get_str("bailingmoe3.expert_gating_func", &gating);
|
||||
out->kv("score_function", gating);
|
||||
}
|
||||
|
||||
/* Everything else, stringified, for the plugin. Arrays are summarised (small integer arrays
|
||||
* spelled out); tokenizer keys are skipped, since the vocab has its own section. */
|
||||
@@ -497,7 +549,9 @@ int Checkpoint::open_gguf(const std::string& path) {
|
||||
index_.emplace(s.name, tensors_.size());
|
||||
tensors_.push_back(std::move(s));
|
||||
}
|
||||
return meta_from_gguf(gguf_, &meta_);
|
||||
RAD_TRY(meta_from_gguf(gguf_, &meta_));
|
||||
if (meta_.arch == "bailinghybrid") RAD_TRY(bailingmoe3_layouts());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
|
||||
@@ -557,6 +611,7 @@ int shard_list(const std::string& dir, const std::string& index, bool index_give
|
||||
|
||||
} /* namespace */
|
||||
|
||||
|
||||
/* A JSON file flattened under `prefix`; absent is not an error when `optional`. */
|
||||
static int meta_merge_json_file(const std::string& path, const std::string& prefix, bool optional,
|
||||
MetaOwn* out) {
|
||||
@@ -1382,10 +1437,13 @@ void Checkpoint::detect_import() {
|
||||
"; it is read in groups of 16";
|
||||
if (algos.empty() && import_why_.empty())
|
||||
import_why_ = "ModelOpt's quantization_config names no quant_algo";
|
||||
/* W4A16_NVFP4 is the same NVFP4 weight with bf16 activations, which is what this reader
|
||||
* serves either way: activations are quantised from their own values, never from a stored
|
||||
* input scale. NVIDIA's Muse Glimmer release states it per layer beside FP8. */
|
||||
for (const std::string& a : algos)
|
||||
if (a != "NVFP4" && a != "FP8" && import_why_.empty())
|
||||
import_why_ = "ModelOpt's quant_algo '" + a + "' is not one this reads; NVFP4 "
|
||||
"and FP8 (per tensor), alone or per layer, are";
|
||||
if (a != "NVFP4" && a != "W4A16_NVFP4" && a != "FP8" && import_why_.empty())
|
||||
import_why_ = "ModelOpt's quant_algo '" + a + "' is not one this reads; NVFP4, "
|
||||
"W4A16_NVFP4 and FP8 (per tensor), alone or per layer, are";
|
||||
if (import_why_.empty()) import_ = Import::ModelOpt;
|
||||
else import_why_ = "modelopt: " + import_why_;
|
||||
} else if (qm == "paroquant") {
|
||||
@@ -2970,9 +3028,17 @@ namespace {
|
||||
/* ---------------------------------------------------------------- GGUF block types
|
||||
*
|
||||
* ggml block types decodable to f32. Their geometry lives in core/text; decoding lives here, where
|
||||
* weights are read. Q4_K and Q6_K are the K-quants this HYV3 GGUF adapter needs. */
|
||||
* weights are read. Q4_K, Q5_K and Q6_K are the K-quants the GGUF releases ship, IQ4_NL the
|
||||
* non-linear 4-bit. */
|
||||
enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7,
|
||||
GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q6_K = 14, GGML_BF16 = 30 };
|
||||
GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q5_K = 13, GGML_Q6_K = 14, GGML_BF16 = 30,
|
||||
GGML_IQ4_NL = 20 };
|
||||
|
||||
/* IQ4_NL's non-linear levels (llama.cpp's kvalues_iq4nl), one per 4-bit code. */
|
||||
static const int8_t kIq4NlLevels[16] = {
|
||||
-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113
|
||||
};
|
||||
|
||||
|
||||
int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); };
|
||||
@@ -3032,13 +3098,7 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
const uint8_t* qs = p + 16;
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
uint32_t sc, mn;
|
||||
if (j < 4) {
|
||||
sc = scales[j] & 63u;
|
||||
mn = scales[j + 4] & 63u;
|
||||
} else {
|
||||
sc = (scales[j + 4] & 15u) | ((uint32_t)(scales[j - 4] >> 6) << 4);
|
||||
mn = (scales[j + 4] >> 4) | ((uint32_t)(scales[j] >> 6) << 4);
|
||||
}
|
||||
ggml_planes::k4_scale_min(j, scales, &sc, &mn);
|
||||
const float ds = d * (float)sc, ms = dmin * (float)mn;
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
const int v = j * 32 + l;
|
||||
@@ -3049,7 +3109,33 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
case GGML_Q5_K:
|
||||
/* block: d, dmin, scales[12], qh[32], qs[128]. The fifth bit of value v is bit
|
||||
* (v/64)*2 + (v%64)/32 of qh's byte (v/64)*32 + v%32. */
|
||||
for (int64_t b = 0; b < n / 256; ++b, p += 176) {
|
||||
const float d = half(p), dmin = half(p + 2);
|
||||
const uint8_t* scales = p + 4;
|
||||
const uint8_t* qh = p + 16;
|
||||
const uint8_t* qs = p + 48;
|
||||
for (int j = 0; j < 256; j += 64) {
|
||||
const int hb = j / 64;
|
||||
const uint32_t u1 = 1u << (2 * hb), u2 = 1u << (2 * hb + 1);
|
||||
uint32_t sc1, m1, sc2, m2;
|
||||
ggml_planes::k4_scale_min(j / 32, scales, &sc1, &m1);
|
||||
ggml_planes::k4_scale_min(j / 32 + 1, scales, &sc2, &m2);
|
||||
const float d1 = d * (float)sc1, m1f = dmin * (float)m1;
|
||||
const float d2 = d * (float)sc2, m2f = dmin * (float)m2;
|
||||
const uint8_t* ql = qs + (j / 2);
|
||||
/* The 32 qh bytes are shared across all four 64-blocks; only the mask moves. */
|
||||
for (int l = 0; l < 32; ++l)
|
||||
dst[b * 256 + j + l] = d1 * (float)((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0)) - m1f;
|
||||
for (int l = 0; l < 32; ++l)
|
||||
dst[b * 256 + j + 32 + l] = d2 * (float)((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2f;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
case GGML_Q6_K:
|
||||
/* block: ql[128], qh[64], scales[16], d. */
|
||||
for (int64_t b = 0; b < n / 256; ++b, p += 210) {
|
||||
const uint8_t* ql = p;
|
||||
const uint8_t* qh = p + 128;
|
||||
@@ -3064,6 +3150,16 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
case GGML_IQ4_NL:
|
||||
for (int64_t b = 0; b < n / 32; ++b, p += 18) {
|
||||
const float d = half(p);
|
||||
const uint8_t* qs = p + 2;
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
dst[b * 32 + j] = d * (float)kIq4NlLevels[qs[j] & 0x0F];
|
||||
dst[b * 32 + j + 16] = d * (float)kIq4NlLevels[qs[j] >> 4];
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
default:
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -3433,6 +3529,141 @@ int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
int Checkpoint::bailingmoe3_layouts() {
|
||||
/* The release GGUF keeps layouts the plugin's names cannot spell through the row and slice
|
||||
* maps. The MLA layers' latent projections are head-last: k_b [128, 512, heads] and
|
||||
* v_b [512, 128, heads] (a 128-row k block and a 128-row v block a head), where the plugin
|
||||
* reads one interleaved kv_b [heads * 2 * 128, 512] -- head h's k rows [2 * 128 * h,
|
||||
* + 128), its v rows the next 128. The MoE layers' routed stacks are expert-last (gate and
|
||||
* up [ff, emb, E], down [emb, ff, E]); the reader's fastest-first flip orients them, and
|
||||
* the block's split-stacked source slices one expert off the flipped [E, ...] stack, so
|
||||
* they stay where they are. Everything the flip already hands over in the plugin's
|
||||
* orientation (the shared expert, the KDA and the norms) needs only a name, which the
|
||||
* plugin takes from the gguf_source meta. */
|
||||
const int64_t n_layer = meta_.m.n_layers;
|
||||
const char* grp_s = meta_.get("layer_group_size");
|
||||
const int64_t group = grp_s ? std::stoll(grp_s) : 4;
|
||||
const char* dense_s = meta_.get("first_k_dense_replace");
|
||||
const int64_t dense = dense_s ? std::stoll(dense_s) : 1;
|
||||
const char* heads_s = meta_.get("num_attention_heads");
|
||||
const int64_t heads = heads_s ? std::stoll(heads_s) : 16;
|
||||
const char* latent_s = meta_.get("kv_lora_rank");
|
||||
const int64_t latent = latent_s ? std::stoll(latent_s) : 512;
|
||||
const char* ff_s = meta_.get("moe_intermediate_size");
|
||||
const int64_t ff = ff_s ? std::stoll(ff_s) : 512;
|
||||
/* The experts' third axis is the embedding width, not the dense feed-forward's. */
|
||||
const int64_t emb = meta_.m.n_embd;
|
||||
const char* nexp_s = meta_.get("num_experts");
|
||||
const int64_t n_expert = nexp_s ? std::stoll(nexp_s) : 0;
|
||||
if (n_layer < 1 || group < 2 || heads < 1 || latent < 1 || ff < 1 || emb < 1)
|
||||
return RAD_E_FORMAT;
|
||||
|
||||
/* Decode a whole source tensor to f32: a block type row by row, a plain one a copy. */
|
||||
auto whole = [&](const SrcTensor* t, std::vector<float>& dst) -> int {
|
||||
const int64_t n = t->numel();
|
||||
dst.resize((size_t)n);
|
||||
return piece_f32(*t, 0, n, dst.data());
|
||||
};
|
||||
auto add = [&](const std::string& name, std::vector<int64_t> shape,
|
||||
std::vector<float>&& v) -> int {
|
||||
if (index_.count(name)) return RAD_OK; /* the checkpoint already spells it */
|
||||
SrcTensor s;
|
||||
s.name = name;
|
||||
s.rad_dtype = RAD_F32;
|
||||
s.shape = std::move(shape);
|
||||
s.owned = std::move(v);
|
||||
s.data = s.owned.data();
|
||||
s.bytes = (int64_t)(s.owned.size() * sizeof(float));
|
||||
index_.emplace(s.name, tensors_.size());
|
||||
tensors_.push_back(std::move(s));
|
||||
return RAD_OK;
|
||||
};
|
||||
|
||||
/* The exporter's ssm_a is exp(A_log) (llama.cpp's bailingmoe3 modify_tensors); the KDA
|
||||
* kernel exponentiates internally, so the container wants the log values back. */
|
||||
for (int64_t l = 0; l < n_layer; ++l) {
|
||||
if ((l + 1) % group == 0) continue; /* the MLA layers carry no ssm_a */
|
||||
const SrcTensor* sa = find(fmt("blk.%lld.ssm_a", (long long)l));
|
||||
if (!sa) continue;
|
||||
std::vector<float> a3, raw;
|
||||
RAD_TRY(whole(sa, a3));
|
||||
raw.resize(a3.size());
|
||||
for (size_t i = 0; i < a3.size(); ++i)
|
||||
raw[i] = std::logf(a3[i] > 0.0f ? a3[i] : 1.0f);
|
||||
RAD_TRY(add(fmt("blk.%lld.ssm_a_raw", (long long)l), sa->shape, std::move(raw)));
|
||||
}
|
||||
|
||||
for (int64_t l = 1; l < n_layer; ++l) {
|
||||
if ((l + 1) % group) continue; /* the MLA layers */
|
||||
const std::string kn = fmt("blk.%lld.attn_k_b.weight", (long long)l);
|
||||
const std::string vn = fmt("blk.%lld.attn_v_b.weight", (long long)l);
|
||||
const SrcTensor* k = find(kn);
|
||||
const SrcTensor* v = find(vn);
|
||||
if (!k || !v) continue;
|
||||
if (k->shape.size() != 3 || v->shape.size() != 3 || k->shape[0] != heads ||
|
||||
k->shape[1] != latent || k->shape[2] != 128 || v->shape[0] != heads ||
|
||||
v->shape[1] != 128 || v->shape[2] != latent)
|
||||
return RAD_E_SHAPE;
|
||||
std::vector<float> k3, v3, fused;
|
||||
RAD_TRY(whole(k, k3));
|
||||
RAD_TRY(whole(v, v3));
|
||||
fused.assign((size_t)(heads * (2 * 128) * latent), 0.0f);
|
||||
for (int64_t h = 0; h < heads; ++h)
|
||||
for (int64_t d = 0; d < 128; ++d) {
|
||||
/* k_b's head block [latent, 128] transposed into the 128 k rows. */
|
||||
for (int64_t l2 = 0; l2 < latent; ++l2)
|
||||
fused[((h * 2 + 0) * 128 + d) * latent + l2] = k3[((h * latent + l2) * 128) + d];
|
||||
/* v_b's head block [128, latent] already runs its v rows. */
|
||||
std::memcpy(&fused[((h * 2 + 1) * 128 + d) * latent],
|
||||
&v3[((h * 128 + d) * latent)], (size_t)latent * sizeof(float));
|
||||
}
|
||||
RAD_TRY(add(fmt("blk.%lld.attn_kv_b.weight", (long long)l),
|
||||
{ heads * 2 * 128, latent }, std::move(fused)));
|
||||
/* q_b is one [heads * (nope + rope), q_lora] matrix the plugin row-maps; a quantised
|
||||
* source cannot be row-mapped, so split it into the plain nope and rope blocks. The
|
||||
* per-head boundary comes from the meta the reader republished, so the split only runs
|
||||
* when the geometry is the one the plugin will consume. */
|
||||
const char* nps = meta_.get("qk_nope_head_dim"), *rps = meta_.get("qk_rope_head_dim");
|
||||
const int64_t qn = nps ? std::stoll(nps) : 0, qr = rps ? std::stoll(rps) : 0;
|
||||
const SrcTensor* qb = find(fmt("blk.%lld.attn_q_b.weight", (long long)l));
|
||||
if (qb && qb->shape.size() == 2 && qb->shape[1] > 0 && qn > 0 && qr > 0 &&
|
||||
qb->shape[0] == heads * (qn + qr)) {
|
||||
const int64_t ql = qb->shape[1], w = qn + qr;
|
||||
std::vector<float> q3, nblk, rblk;
|
||||
RAD_TRY(whole(qb, q3));
|
||||
nblk.assign((size_t)(heads * qn) * ql, 0.0f);
|
||||
rblk.assign((size_t)(heads * qr) * ql, 0.0f);
|
||||
for (int64_t h = 0; h < heads; ++h) {
|
||||
std::memcpy(&nblk[(h * qn) * ql], &q3[(h * w) * ql], (size_t)(qn * ql) * sizeof(float));
|
||||
std::memcpy(&rblk[(h * qr) * ql], &q3[(h * w + qn) * ql], (size_t)(qr * ql) * sizeof(float));
|
||||
}
|
||||
RAD_TRY(add(fmt("blk.%lld.attn_q_b_nope.weight", (long long)l), { heads * qn, ql }, std::move(nblk)));
|
||||
RAD_TRY(add(fmt("blk.%lld.attn_q_b_rope.weight", (long long)l), { heads * qr, ql }, std::move(rblk)));
|
||||
}
|
||||
}
|
||||
for (int64_t l = dense; l < n_layer; ++l) {
|
||||
if (n_expert < 1) continue;
|
||||
/* The routed stacks stay where they are: the block's split-stacked source
|
||||
* (gate, up, down per expert, a dim-0 slice each) slices the reader's flipped
|
||||
* [E, ff, emb] / [E, emb, ff] tensors directly. Only the shared expert needs
|
||||
* re-spelling under the block's prefix: copies, the reader's flip already
|
||||
* orienting them. */
|
||||
const char* sh[3] = { "ffn_gate_shexp", "ffn_up_shexp", "ffn_down_shexp" };
|
||||
const char* shd[3] = { "mlp.shared_experts.gate_proj.weight",
|
||||
"mlp.shared_experts.up_proj.weight",
|
||||
"mlp.shared_experts.down_proj.weight" };
|
||||
for (int q = 0; q < 3; ++q) {
|
||||
const SrcTensor* t = find(fmt("blk.%lld.%s.weight", (long long)l, sh[q]));
|
||||
if (!t) continue;
|
||||
std::vector<float> v;
|
||||
RAD_TRY(whole(t, v));
|
||||
RAD_TRY(add(fmt("blk.%lld.%s", (long long)l, shd[q]), t->shape, std::move(v)));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
|
||||
std::string* why) {
|
||||
auto refuse = [&](int rc, std::string m) {
|
||||
|
||||
@@ -49,6 +49,10 @@ struct SrcTensor {
|
||||
std::vector<int64_t> shape; /* row-major */
|
||||
const void* data = nullptr;
|
||||
int64_t bytes = 0;
|
||||
/* Owned payload for a derived tensor: a checkpoint's layout rebuilt at load time (the Ling
|
||||
* GGUF's head-last k_b/v_b fused into the plugin's interleaved kv_b, its expert-last stacks
|
||||
* regrouped per expert). When non-empty `data` points here and `rad_dtype` is RAD_F32. */
|
||||
std::vector<float> owned;
|
||||
/* GPTQ-packed (auto_gptq's layout, shared by AutoRound's `auto_round:auto_gptq` export):
|
||||
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along K
|
||||
* from the low bits up, unsigned with zero point 2^(bits-1). The tensor described is the
|
||||
@@ -220,6 +224,13 @@ private:
|
||||
int add_torch_files();
|
||||
int open_gguf(const std::string& path);
|
||||
void detect_import();
|
||||
/* The Ling GGUF's layouts the plugin's names expect, rebuilt at load so the container's
|
||||
* recipe never sees the source layout: the KDA layers' ssm_a (the exporter's exp(A_log))
|
||||
* logged back to ssm_a_raw, the MLA layers' head-last k_b and v_b fused into one
|
||||
* interleaved kv_b, the quantised q_b split into the plugin's nope and rope blocks, and
|
||||
* the shared experts re-spelled under the block's mlp.shared_experts prefix. The routed
|
||||
* stacks stay where the reader's fastest-first flip leaves them. */
|
||||
int bailingmoe3_layouts();
|
||||
|
||||
enum Kind { None, Gguf, SafeT } kind_ = None;
|
||||
std::string path_, dir_, tok_dir_, meta_dir_;
|
||||
|
||||
+62
-3
@@ -71,13 +71,72 @@ int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool rad_blob_range(const uint8_t* base, int64_t size, const void* p, int64_t n,
|
||||
int64_t* off, int64_t* len) {
|
||||
if (!base || size <= 0 || !p || n <= 0) return false;
|
||||
const uintptr_t lo = (uintptr_t)base, a = (uintptr_t)p;
|
||||
const uint64_t hi = (uint64_t)lo + (uint64_t)size, end = (uint64_t)a + (uint64_t)n;
|
||||
if (a < lo || end > hi || end < (uint64_t)a) return false; /* outside, or wraps */
|
||||
if (off) *off = (int64_t)(a - lo);
|
||||
if (len) *len = n;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::pair<int64_t, int64_t>> rad_keep_complement(
|
||||
int64_t tables, int64_t size, std::vector<std::pair<int64_t, int64_t>> keep) {
|
||||
/* Clamp to the blob, drop empties, sort and merge: the caller may hand in one range per rank,
|
||||
* and every rank publishes the same table. */
|
||||
std::vector<std::pair<int64_t, int64_t>> k;
|
||||
k.reserve(keep.size());
|
||||
for (const auto& r : keep) {
|
||||
const int64_t a = std::max(r.first, tables), b = std::min(r.first + r.second, size);
|
||||
if (b > a) k.emplace_back(a, b);
|
||||
}
|
||||
std::sort(k.begin(), k.end());
|
||||
size_t m = 0;
|
||||
for (size_t i = 0; i < k.size(); ++i) {
|
||||
if (m && k[i].first <= k[m - 1].second) k[m - 1].second = std::max(k[m - 1].second, k[i].second);
|
||||
else k[m++] = k[i];
|
||||
}
|
||||
k.resize(m);
|
||||
/* Whole pages only, so a page that holds kept bytes stays: a gap's start rounds up and its
|
||||
* end rounds down (the blob's own end is the mapping's). */
|
||||
const int64_t pg = 4096;
|
||||
std::vector<std::pair<int64_t, int64_t>> out;
|
||||
auto gap = [&](int64_t a, int64_t b) {
|
||||
a = (a + pg - 1) / pg * pg;
|
||||
if (b < size) b = b / pg * pg;
|
||||
if (b > a) out.emplace_back(a, b - a); /* (offset, bytes), as `keep` is written */
|
||||
};
|
||||
int64_t cur = tables;
|
||||
for (const auto& r : k) {
|
||||
if (r.first > cur) gap(cur, r.first);
|
||||
cur = std::max(cur, r.second);
|
||||
}
|
||||
if (cur < size) gap(cur, size);
|
||||
return out;
|
||||
}
|
||||
|
||||
int64_t RadFile::keep_cached(const void* p, int64_t n) {
|
||||
int64_t off = 0, len = 0;
|
||||
if (rad_blob_range(base_, size_, p, n, &off, &len) &&
|
||||
std::find(keep_.begin(), keep_.end(), std::make_pair(off, len)) == keep_.end())
|
||||
keep_.emplace_back(off, len);
|
||||
int64_t kept = 0;
|
||||
for (const auto& r : keep_) kept += r.second;
|
||||
return kept;
|
||||
}
|
||||
|
||||
void RadFile::drop_blob_cache() const {
|
||||
if (!base_ || !hdr_ || fd_ < 0) return;
|
||||
const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_;
|
||||
if (tables >= size_) return;
|
||||
/* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. */
|
||||
::madvise(base_ + tables, (size_t)(size_ - tables), MADV_DONTNEED);
|
||||
::posix_fadvise(fd_, (off_t)tables, (off_t)(size_ - tables), POSIX_FADV_DONTNEED);
|
||||
/* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. Only the
|
||||
* ranges that are not kept (keep_cached); with none kept this is the whole blob. */
|
||||
for (const auto& r : rad_keep_complement(tables, size_, keep_)) {
|
||||
::madvise(base_ + r.first, (size_t)r.second, MADV_DONTNEED);
|
||||
::posix_fadvise(fd_, (off_t)r.first, (off_t)r.second, POSIX_FADV_DONTNEED);
|
||||
}
|
||||
}
|
||||
|
||||
/* Advisory, with no madvise: the load reads with pread and never maps these pages. The one region
|
||||
|
||||
+23
-1
@@ -68,8 +68,14 @@ public:
|
||||
|
||||
/* Drop the blob from the page cache and this process's page tables, so a container larger
|
||||
* than RAM does not leave the cache full of pages nothing will read. Only the blob: the tables
|
||||
* are small and read constantly. Advisory; the kernel may decline. */
|
||||
* are small and read constantly. The ranges named to keep_cached() are left alone, on whole
|
||||
* pages. Advisory; the kernel may decline either way. */
|
||||
void drop_blob_cache() const;
|
||||
/* Names [p, p + n) as read through the mapping for the engine's life (the mapped tier: an
|
||||
* n-gram table), so no drop_blob_cache() frees its pages: a gather from dropped pages starts
|
||||
* cold, from the drive. An address outside the container is ignored (a copy in RAM, or a
|
||||
* table read from its own file). Returns the bytes now kept. */
|
||||
int64_t keep_cached(const void* p, int64_t n);
|
||||
|
||||
/* Drop one range of the blob behind a single forward cursor. A buffered front-to-back read of
|
||||
* a container larger than RAM otherwise builds reclaim pressure that slows the read itself.
|
||||
@@ -153,6 +159,7 @@ private:
|
||||
std::string path_;
|
||||
uint8_t* base_ = nullptr;
|
||||
int64_t size_ = 0;
|
||||
std::vector<std::pair<int64_t, int64_t>> keep_; /* keep_cached: (blob offset, bytes) */
|
||||
int fd_ = -1;
|
||||
|
||||
const RadFileHeader* hdr_ = nullptr;
|
||||
@@ -168,6 +175,21 @@ private:
|
||||
std::unordered_map<std::string_view, int64_t> by_name_;
|
||||
};
|
||||
|
||||
/* The blob range [*off, *off + *len) a pointer covers, when it lies wholly inside the container
|
||||
* [base, base + size): what a load records for the mapped tier. False when the address is not in
|
||||
* the blob (a copy in RAM under `ngram-placement: ram`, or a table read from its own file under
|
||||
* `disk=DIR`), where keeping it would name bytes that belong to something else. */
|
||||
bool rad_blob_range(const uint8_t* base, int64_t size, const void* p, int64_t n,
|
||||
int64_t* off, int64_t* len);
|
||||
|
||||
/* The ranges of [tables, size) a page-cache drop must free when `keep` stays: the complement of
|
||||
* the keep ranges as (offset, bytes), the same convention `keep` uses. Page-rounded the way the
|
||||
* drop needs it -- a gap's start rounds up and its end down, so a page holding kept bytes is never
|
||||
* dropped. Unsorted, overlapping and out-of-range input is merged and clamped; a keep list covering
|
||||
* the whole blob gives no ranges. */
|
||||
std::vector<std::pair<int64_t, int64_t>> rad_keep_complement(
|
||||
int64_t tables, int64_t size, std::vector<std::pair<int64_t, int64_t>> keep);
|
||||
|
||||
/* ================================================================== writer */
|
||||
/* Streaming writer: the blob is never held in RAM (a checkpoint may be 100 GB). The tables
|
||||
* (strings, directory, planes, encodings, vocab, profile) are in memory; ~50k directory rows for a
|
||||
|
||||
@@ -71,6 +71,8 @@ struct AudioRequest {
|
||||
std::vector<float> ref_audio;
|
||||
std::vector<int32_t> ref_cu;
|
||||
std::vector<int32_t> ref_frame;
|
||||
/* Reference-direction guidance: the negative prompt's own map into the same clips. */
|
||||
std::vector<int32_t> neg_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 */
|
||||
|
||||
@@ -292,7 +292,10 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
|
||||
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()) {
|
||||
if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty() ||
|
||||
!r->neg_ref_frame.empty()) {
|
||||
if (nb_ == 2 && r->cfg != 0.0f && r->cfg != 1.0f && r->neg_ref_frame.empty())
|
||||
return no("voice cloning requires guidance_scale 1; reference CFG is not served");
|
||||
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() &&
|
||||
@@ -303,6 +306,10 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
|
||||
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 && !r->neg_ref_frame.empty()) {
|
||||
ok = nb_ == 2 && neg_own_ && (int64_t)r->neg_ref_frame.size() == Tn;
|
||||
for (int32_t f : r->neg_ref_frame) ok = ok && f >= -1 && f < 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, " +
|
||||
@@ -707,12 +714,24 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
|
||||
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]);
|
||||
/* At guidance 1 the driver runs the conditional prompt in both branches. Its audio
|
||||
* rows must be duplicated too, not silently turned into text in the second branch. */
|
||||
if (nb_ > 1) {
|
||||
if (j.cfg == 1.0f)
|
||||
h_rfrm_.insert(h_rfrm_.end(), q.ref_frame.begin() + p0,
|
||||
q.ref_frame.begin() + p0 + cb[1]);
|
||||
else if (!q.neg_ref_frame.empty())
|
||||
h_rfrm_.insert(h_rfrm_.end(), q.neg_ref_frame.begin() + p0,
|
||||
q.neg_ref_frame.begin() + p0 + cb[1]);
|
||||
else
|
||||
h_rfrm_.resize((size_t)rows, -1);
|
||||
}
|
||||
std::memcpy(hptr<int32_t>(R_RFRM), h_rfrm_.data(), h_rfrm_.size() * 4);
|
||||
reg_[R_RFRM].used = (int64_t)h_rfrm_.size() * 4;
|
||||
}
|
||||
if (upload() < 0) return nullptr;
|
||||
base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch);
|
||||
@@ -721,6 +740,7 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
out_[r].gen = RAD_GEN_PASS_PROMPT;
|
||||
RadAudioGenBatch& A = aout_[r];
|
||||
A.prompt_cu_h = cu;
|
||||
A.n_lane = 1;
|
||||
A.lane_h = h_lane_.data();
|
||||
A.last_h = h_last_.data();
|
||||
|
||||
+3
-3
@@ -58,11 +58,11 @@ int main(int argc, char** argv) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* An offline mode (KL scoring, calibration) or the graph dump runs one engine to its end and
|
||||
* serves nothing; every other configuration is served by the fleet. */
|
||||
/* An offline mode (KL scoring, calibration, the diagnose workload) or the graph dump runs one
|
||||
* engine to its end and serves nothing; every other configuration is served by the fleet. */
|
||||
bool offline = false;
|
||||
for (const rad::fleet::ModelEntry& m : fleet.models)
|
||||
offline |= m.cfg.kld() || m.cfg.calib() || m.cfg.debug_graph;
|
||||
offline |= m.cfg.kld() || m.cfg.calib() || m.cfg.diagnose_mode() || m.cfg.debug_graph;
|
||||
if (!offline) return rad::fleet::run(fleet);
|
||||
if (fleet.models.size() != 1) {
|
||||
RAD_ERR("%s: an offline mode or the graph dump runs one model; the file names %zu",
|
||||
|
||||
@@ -822,6 +822,22 @@ int64_t KVManager::total_blocks(int32_t g) const {
|
||||
int64_t KVManager::live_blocks(int32_t g) const {
|
||||
return (g >= 0 && g < (int32_t)live_.size()) ? live_[(size_t)g] : 0;
|
||||
}
|
||||
int64_t KVManager::live_blocks_at(int32_t g, int64_t tokens) const {
|
||||
if (g < 0 || g >= (int32_t)plans_.size()) return 0;
|
||||
return plans_[(size_t)g].n_blocks - lent_blocks((size_t)g, tokens);
|
||||
}
|
||||
int64_t KVManager::straggler_mark(int32_t g) const {
|
||||
if (g < 0 || g >= (int32_t)plans_.size()) return 0;
|
||||
const int64_t top = held_top((size_t)g), per = bucket_blocks_[(size_t)g];
|
||||
const auto& h = held_hist_[(size_t)g];
|
||||
int64_t mark = top, best = 0, held = 0;
|
||||
for (int64_t b = (top + per - 1) / per; b-- > 0;) {
|
||||
held += h[(size_t)b];
|
||||
const int64_t gain = top - b * per - kStragglerCost * held;
|
||||
if (gain > best) { best = gain; mark = b * per; }
|
||||
}
|
||||
return mark;
|
||||
}
|
||||
int64_t KVManager::held_top_blocks(int32_t g) const {
|
||||
return (g >= 0 && g < (int32_t)plans_.size()) ? held_top((size_t)g) : 0;
|
||||
}
|
||||
|
||||
@@ -508,6 +508,18 @@ public:
|
||||
|
||||
/* Blocks of a group the cache may hand out: the carve less the loan. */
|
||||
int64_t live_blocks(int32_t group) const;
|
||||
/* The same under a loan of `tokens`: the first block of the group that loan would take. A
|
||||
* group that does not lend answers its whole carve. */
|
||||
int64_t live_blocks_at(int32_t group, int64_t tokens) const;
|
||||
/* Where a group's stragglers start. A loan reaches down only to the highest held block, so a
|
||||
* few held blocks high in the pool keep everything between them and the dense part of the
|
||||
* cache from the expert slab. Giving up the held blocks at or above a mark m extends what
|
||||
* can be lent by (held top - m) blocks at the cost of the blocks held there; the mark is the
|
||||
* m that gains the most over kStragglerCost times that cost, to a bucket of held_hist_. The
|
||||
* held top itself when no m gains anything: a pool held densely up to its top has no
|
||||
* stragglers, and the edge of a dense part is never one. Rank 0 only. */
|
||||
int64_t straggler_mark(int32_t group) const;
|
||||
static constexpr int64_t kStragglerCost = 16;
|
||||
|
||||
/* ---------------- flex (docs/MULTIMODEL.md §6) ----------------
|
||||
*
|
||||
|
||||
+13
-2
@@ -356,8 +356,10 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
|
||||
RAD_WARN("kv tiers: %lld entries (%lld tokens of context) got no host copy: the host "
|
||||
"tier (--prefix-cache-mib, %s, %lld tokens) is full of context used more "
|
||||
"recently or nearer the start of its conversation. They stay in VRAM only and "
|
||||
"are prefilled again once VRAM gives them up; a larger --prefix-cache-mib holds "
|
||||
"more. Counted in /sessions moved.held_back",
|
||||
"are prefilled again once VRAM gives them up, which it does for a request that "
|
||||
"needs the room, or where a few of them keep the expert loan from most of the "
|
||||
"pool; a larger --prefix-cache-mib holds more. "
|
||||
"Counted in /sessions moved.held_back",
|
||||
(long long)held, (long long)(held * cfg_.block_tokens),
|
||||
humanb(arena_.cap_bytes()).c_str(),
|
||||
(long long)(arena_.capacity() * cfg_.block_tokens));
|
||||
@@ -375,6 +377,15 @@ void IdleTiers::take_clean(std::vector<BlockHash>* out) {
|
||||
clean_q_.clear();
|
||||
}
|
||||
|
||||
bool IdleTiers::no_copy_coming(const BlockHash& key) const {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(key);
|
||||
if (it == recs_.end()) return false;
|
||||
const Rec& r = it->second;
|
||||
if (r.pending || r.doomed || r.tier != KVTier::Device || r.host_slot >= 0) return false;
|
||||
return !r.queued || (wb_stuck_ && arena_.full());
|
||||
}
|
||||
|
||||
bool IdleTiers::droppable(const BlockHash& key) const {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(key);
|
||||
|
||||
@@ -156,6 +156,10 @@ public:
|
||||
void take_clean(std::vector<BlockHash>* out);
|
||||
/* Host copy landed and no job out: the blocks can leave VRAM at no cost. */
|
||||
bool droppable(const BlockHash& key) const;
|
||||
/* In VRAM only with no host copy coming: none made or on its way, and either none asked for
|
||||
* (a full arena refused it, Stats::held_back) or the queue it waits in has stopped because
|
||||
* the arena is full of entries worth more. */
|
||||
bool no_copy_coming(const BlockHash& key) const;
|
||||
/* The cache released the blocks; the record becomes a host record on the host list. Its
|
||||
* snapshot stays in its store slot. */
|
||||
void drop_commit(const BlockHash& key);
|
||||
|
||||
+50
-2
@@ -796,12 +796,13 @@ int64_t PrefixCache::trim_sparing(int64_t n_entries,
|
||||
return done;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::drop_clean() {
|
||||
int64_t PrefixCache::drop_clean(int64_t loan_goal) {
|
||||
if (!tiers_ || !kv_) return 0;
|
||||
drop_scratch_.clear();
|
||||
tiers_->take_clean(&drop_scratch_);
|
||||
const uint64_t frees = kv_->seq_frees();
|
||||
if (frees != frees_seen_ || released_) {
|
||||
const bool recheck = frees != frees_seen_ || released_;
|
||||
if (recheck) {
|
||||
frees_seen_ = frees;
|
||||
released_ = false;
|
||||
for (const BlockHash& h : drop_wait_) {
|
||||
@@ -830,6 +831,53 @@ int64_t PrefixCache::drop_clean() {
|
||||
tiers_->drop_commit(h);
|
||||
++n;
|
||||
}
|
||||
return n + drop_stragglers(loan_goal, recheck);
|
||||
}
|
||||
|
||||
/* drop_clean's second half: resident entries with no host copy coming that are stragglers inside
|
||||
* a loan of `loan_goal` tokens. One walk of the resident list, taken only while something is held
|
||||
* above a group's mark, and then when a sequence has freed blocks (`recheck`) or the marks have
|
||||
* moved since the last walk, a second or more ago. */
|
||||
int64_t PrefixCache::drop_stragglers(int64_t loan_goal, bool recheck) {
|
||||
if (loan_goal <= 0 || !tiers_->host_on()) return 0;
|
||||
const size_t ng = entry_groups_.size();
|
||||
strag_mark_.assign(2 * ng, 0);
|
||||
bool any = false;
|
||||
for (size_t k = 0; k < ng; ++k) {
|
||||
const int32_t g = entry_groups_[k];
|
||||
const int64_t top = kv_->held_top_blocks(g);
|
||||
const int64_t mark = !kv_->lendable(g) ? INT64_MAX
|
||||
: std::max(kv_->straggler_mark(g), kv_->live_blocks_at(g, loan_goal));
|
||||
strag_mark_[k] = mark;
|
||||
strag_mark_[ng + k] = top;
|
||||
any = any || top > mark;
|
||||
}
|
||||
if (!any) return 0;
|
||||
const uint64_t now = rad_mono_ns();
|
||||
if (!recheck && (strag_mark_ == strag_seen_ || now - strag_ns_ < 1000000000ull)) return 0;
|
||||
strag_seen_ = strag_mark_;
|
||||
strag_ns_ = now;
|
||||
|
||||
int64_t n = 0;
|
||||
for (auto it = lru_.begin(); it != lru_.end();) {
|
||||
const BlockHash h = *it;
|
||||
auto m = map_.find(h);
|
||||
if (m == map_.end()) { ++it; continue; }
|
||||
Entry& e = m->second;
|
||||
bool above = false;
|
||||
for (size_t k = 0; k < ng && k < e.blocks.size(); ++k)
|
||||
above = above || e.blocks[k] >= strag_mark_[k];
|
||||
if (!above || held_.count(h) > 0 || shared_with_live(e) || !tiers_->no_copy_coming(h)) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
release_blocks(e);
|
||||
it = lru_.erase(it);
|
||||
tiers_->forget(h);
|
||||
map_.erase(m);
|
||||
++stats_.evictions;
|
||||
++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
|
||||
+16
-2
@@ -306,8 +306,17 @@ public:
|
||||
int64_t trim(int64_t n_entries);
|
||||
/* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence
|
||||
* reading it. Used when the memory has a better use (the expert slab's loan). Entries still
|
||||
* shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */
|
||||
int64_t drop_clean();
|
||||
* shared are retried after a sequence frees blocks. Returns how many entries left VRAM.
|
||||
*
|
||||
* `loan_goal` is the loan the slab is short of, in tokens (0: none). An entry with no host
|
||||
* copy coming (the host tier is full of context worth more) never becomes clean, and the
|
||||
* loan reaches down only to the highest held block: a few such entries high in the pool keep
|
||||
* the slab from everything below them for as long as the server runs. Where they are
|
||||
* stragglers (KVManager::straggler_mark: giving them up lends at least sixteen blocks for
|
||||
* each one lost) and stand inside `loan_goal`, they are forgotten, and their tokens are
|
||||
* prefilled again if their conversation returns. Context that fills its part of the pool
|
||||
* stays: there the cache is worth more than the loan it holds back. */
|
||||
int64_t drop_clean(int64_t loan_goal = 0);
|
||||
int64_t size() const { return (int64_t)map_.size(); }
|
||||
/* Entries holding blocks in the pool, as opposed to only a copy off the card. */
|
||||
int64_t resident() const { return (int64_t)lru_.size(); }
|
||||
@@ -544,6 +553,11 @@ private:
|
||||
* sequence-free count then. They are rechecked only once that count moves. */
|
||||
std::vector<BlockHash> drop_wait_;
|
||||
std::vector<BlockHash> drop_scratch_;
|
||||
/* drop_stragglers: the marks and held tops it last walked the list for, and when. It walks
|
||||
* again when a sequence frees blocks, or once they have moved and a second has passed. */
|
||||
std::vector<int64_t> strag_mark_, strag_seen_;
|
||||
uint64_t strag_ns_ = 0;
|
||||
int64_t drop_stragglers(int64_t loan_goal, bool recheck);
|
||||
uint64_t frees_seen_ = 0;
|
||||
/* hold(): keys per waiting request, and holders per key. A release also triggers a recheck
|
||||
* of drop_wait_. */
|
||||
|
||||
@@ -152,6 +152,14 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"or free the card.\n"
|
||||
: "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
|
||||
"or free the card.\n";
|
||||
/* KL mode holds a whole-vocabulary row for every scored token and lends no pool back, so
|
||||
* its fixed cost sits far above a serve's at the same flags. Without naming the split, the
|
||||
* operator has no way to know which knob to turn. */
|
||||
const char* kld_hint = cfg.kld()
|
||||
? "KL mode holds a full-vocabulary logits row for every scored token and lends no pool "
|
||||
"back: pass --gpu-headroom-mib and --host-pool-mib explicitly, and lower "
|
||||
"--max-num-batched-tokens (the logits rows scale with it).\n"
|
||||
: "";
|
||||
b.report = fmt(
|
||||
"VRAM does not cover the fixed costs before a single pool is sized:\n"
|
||||
" card total %10s\n"
|
||||
@@ -169,6 +177,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str(), how);
|
||||
if (*kld_hint) b.report += kld_hint;
|
||||
if (log) RAD_ERR("%s", b.report.c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_E_NOMEM;
|
||||
|
||||
+9
-1
@@ -50,7 +50,15 @@ struct MemReader {
|
||||
int64_t pos = 0;
|
||||
};
|
||||
|
||||
int mem_write(void* op, const uint8_t* buf, int n) {
|
||||
/* avio_alloc_context's write_packet takes a const buffer from libavformat 61 and a mutable one
|
||||
* before it; the callback is declared as the library at hand wants it. */
|
||||
#if LIBAVFORMAT_VERSION_MAJOR >= 61
|
||||
using WriteBuf = const uint8_t*;
|
||||
#else
|
||||
using WriteBuf = uint8_t*;
|
||||
#endif
|
||||
|
||||
int mem_write(void* op, WriteBuf buf, int n) {
|
||||
MemFile* f = static_cast<MemFile*>(op);
|
||||
const int64_t end = f->pos + n;
|
||||
if (end > (int64_t)f->data.size()) f->data.resize((size_t)end);
|
||||
|
||||
+389
-8
@@ -50,6 +50,11 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) {
|
||||
return std::strtol(v, nullptr, 10) != 0;
|
||||
}
|
||||
|
||||
/* Muse Glimmer's shipped processor config (processor.image_mean, processor.image_std), over the
|
||||
* reference class's IMAGENET_STANDARD defaults. */
|
||||
static const float kMuseDefaultMean[3] = { 0.5f, 0.5f, 0.5f };
|
||||
static const float kMuseDefaultStd[3] = { 0.5f, 0.5f, 0.5f };
|
||||
|
||||
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
/* Only the requested noncausal Mistral3/Ministral3 wrapper selects this new path. */
|
||||
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "mistral3") &&
|
||||
@@ -303,6 +308,64 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Meta's Muse Glimmer 30B: the vision tower states the patch geometry and the processor
|
||||
* configs the token caps; the markers are numbered by config.json where they are numbered at
|
||||
* all, and the vocabulary spells the rest (resolved at Processor::init). */
|
||||
if (mt && !std::strcmp(mt, "muse_glimmer_vision")) {
|
||||
family = Family::MuseGlimmer;
|
||||
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
|
||||
temporal = (int32_t)rad_meta_geti(&m, "vision_config.patch_temporal",
|
||||
rad_meta_geti(&m, "vision_config.temporal_patch_size", 0));
|
||||
merge = (int32_t)rad_meta_geti(&m, "vision_config.merge_size",
|
||||
rad_meta_geti(&m, "vision_config.spatial_merge_size", 0));
|
||||
if (patch <= 0 || temporal <= 0 || merge <= 0) {
|
||||
if (why) *why = "the container states no vision tower geometry (vision_config."
|
||||
"patch_size, patch_temporal, merge_size)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
|
||||
tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1);
|
||||
if (tok_image < 0 || tok_video < 0) {
|
||||
if (why) *why = "the container states no media token ids (image_token_id, "
|
||||
"video_token_id)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
/* The markers: a container that numbers them wins; the rest the vocabulary resolves. */
|
||||
tok_start = (int32_t)rad_meta_geti(&m, "image_start_token_id", -1);
|
||||
tok_end = (int32_t)rad_meta_geti(&m, "image_end_token_id", -1);
|
||||
tok_video_start = (int32_t)rad_meta_geti(&m, "video_start_token_id", -1);
|
||||
tok_video_end = (int32_t)rad_meta_geti(&m, "video_end_token_id", -1);
|
||||
tok_video_sep = (int32_t)rad_meta_geti(&m, "video_frame_separator_token_id", -1);
|
||||
/* The token caps, in merged tokens: one per picture and one per video frame. */
|
||||
max_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.max_image_tokens",
|
||||
4096);
|
||||
max_frame_rows = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_video_frame_tokens",
|
||||
144);
|
||||
max_frames = (int32_t)rad_meta_geti(&m, "processor.video_processor.num_frames", 96);
|
||||
fps = rad_meta_getf(&m, "processor.video_processor.fps", 2.0);
|
||||
min_frames = temporal;
|
||||
/* The shipped checkpoints (mean and deviation 0.5) over the reference class's
|
||||
* IMAGENET_STANDARD defaults: the config wins, as it does for every family. */
|
||||
if (!read_triple(m, "processor.image_mean", mean)) std::copy(std::begin(kMuseDefaultMean),
|
||||
std::end(kMuseDefaultMean), mean);
|
||||
if (!read_triple(m, "processor.image_std", stdv)) std::copy(std::begin(kMuseDefaultStd),
|
||||
std::end(kMuseDefaultStd), stdv);
|
||||
/* The pixel bands only have to be consistent for check(); the caps size by tokens. */
|
||||
const int64_t f2 = (int64_t)factor() * factor();
|
||||
image_min_pixels = video_min_pixels = f2;
|
||||
image_max_pixels = std::max<int64_t>(f2, (int64_t)std::max(1, max_image_tokens) * f2);
|
||||
video_max_pixels = std::max<int64_t>(f2, (int64_t)std::max(1, max_frame_rows) * f2);
|
||||
std::string bad;
|
||||
if (max_image_tokens < 1 || max_frame_rows < 1)
|
||||
bad = "max_image_tokens and max_video_frame_tokens must be positive";
|
||||
if (bad.empty() && check(&bad) < 0) bad = "the container's Muse Glimmer processor "
|
||||
"configuration is inconsistent: " + bad;
|
||||
if (!bad.empty()) {
|
||||
if (why) *why = bad;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Gemma 4 12B ("unified") has no tower: its embedder takes a whole 48 x 48 pooling window as
|
||||
* one patch, so a patch is a row (merge 1), and its values are u / 255. The sizes are the
|
||||
* same: a window is 48 pixels a side either way. */
|
||||
@@ -644,6 +707,125 @@ std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int
|
||||
return idx;
|
||||
}
|
||||
|
||||
/* CPython's tuple hash (tuplehash, the xxHash-based combination of 3.8 and later) for the
|
||||
* candidates' (grid height, grid width) pairs. Lane = hash(int) = the value itself. */
|
||||
static inline uint64_t py_tuple_hash(int64_t a, int64_t b) {
|
||||
constexpr uint64_t P1 = 0x9E3779B185EBCA87ull, P2 = 0xC2B2AE3D27D4EB4Full,
|
||||
P5 = 0x27D4EB2F165667C5ull;
|
||||
uint64_t acc = P5;
|
||||
for (int64_t v : { a, b }) {
|
||||
acc += (uint64_t)v * P2;
|
||||
acc = (acc << 31) | (acc >> 33);
|
||||
acc *= P1;
|
||||
}
|
||||
acc += (uint64_t)2 ^ (P5 ^ 3527539ull);
|
||||
return acc;
|
||||
}
|
||||
|
||||
/* CPython's set of those pairs, as an 8-slot open table (PySet_MINSIZE) with its probing, and
|
||||
* iteration in slot order -- what `list(set(...))` gives, which fixes which of equally-near
|
||||
* candidate grids Python's `min` keeps. */
|
||||
class PyCandidateSet {
|
||||
public:
|
||||
void add(int64_t h, int64_t w) {
|
||||
for (int32_t s = 0; s < 8; ++s)
|
||||
if (slots_[s].used && slots_[s].h == h && slots_[s].w == w) return;
|
||||
uint64_t hash = py_tuple_hash(h, w), perturb = hash;
|
||||
int32_t i = (int32_t)(hash & 7);
|
||||
for (;;) {
|
||||
if (!slots_[i].used) {
|
||||
slots_[i] = { true, h, w };
|
||||
return;
|
||||
}
|
||||
if (slots_[i].h == h && slots_[i].w == w) return;
|
||||
perturb >>= 5;
|
||||
i = (int32_t)(((uint64_t)i * 5 + perturb + 1) & 7);
|
||||
}
|
||||
}
|
||||
/* In slot order, i from 0 to 7: the next used slot's grid, or false at the end. */
|
||||
bool next(int32_t* i, int64_t* h, int64_t* w) const {
|
||||
for (; *i < 8; ++*i)
|
||||
if (slots_[*i].used) {
|
||||
*h = slots_[*i].h;
|
||||
*w = slots_[*i].w;
|
||||
++*i;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Slot { bool used = false; int64_t h = 0, w = 0; };
|
||||
Slot slots_[8];
|
||||
};
|
||||
|
||||
/* MuseGlimmer{Image,Video}Processor.smart_resize, in Python's doubles: the ideal merged-token
|
||||
* sides are capped to the token budget by area, then the whole grids at their floor and ceiling
|
||||
* are candidates, and the one whose aspect is nearest the picture's own wins. Ties are real --
|
||||
* every square picture's floor and ceiling grids are both exactly nearest -- and the reference
|
||||
* resolves them by iterating the candidates in a CPython set's order, so the set's slot order is
|
||||
* simulated above. The fallback for an empty candidate set is the reference's own, kept for
|
||||
* parity; it cannot fire for a budget of at least one token. */
|
||||
int muse_size(int64_t h, int64_t w, int32_t factor, int64_t max_tokens, int64_t* oh, int64_t* ow,
|
||||
std::string* why) {
|
||||
if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
|
||||
if (max_tokens < 1) { if (why) *why = "the token budget is empty"; return RAD_E_INVAL; }
|
||||
const double f = factor;
|
||||
double ih = (double)h / f;
|
||||
double iw = (double)w / f;
|
||||
const double ratio = ih > 0.0 ? iw / ih : 1.0;
|
||||
if (ih * iw > (double)max_tokens) {
|
||||
ih = std::sqrt((double)max_tokens / ratio);
|
||||
iw = ih * ratio;
|
||||
}
|
||||
const int64_t fh = (int64_t)std::floor(ih), ch = (int64_t)std::ceil(ih);
|
||||
const int64_t fw = (int64_t)std::floor(iw), cw = (int64_t)std::ceil(iw);
|
||||
PyCandidateSet cand;
|
||||
cand.add(fh, fw);
|
||||
cand.add(fh, cw);
|
||||
cand.add(ch, fw);
|
||||
cand.add(ch, cw);
|
||||
const double aspect = (double)h / (double)w;
|
||||
int64_t gh = -1, gw = -1;
|
||||
double best = 0.0;
|
||||
for (int32_t i = 0;;) {
|
||||
int64_t ch2 = 0, cw2 = 0;
|
||||
if (!cand.next(&i, &ch2, &cw2)) break;
|
||||
if (ch2 < 1 || cw2 < 1 || (double)ch2 * (double)cw2 > (double)max_tokens) continue;
|
||||
const double diff = std::fabs((double)ch2 / (double)cw2 - aspect);
|
||||
if (gh < 0 || diff < best) {
|
||||
best = diff;
|
||||
gh = ch2;
|
||||
gw = cw2;
|
||||
}
|
||||
}
|
||||
if (gh < 0) {
|
||||
gh = std::max<int64_t>(1, pyround(ih));
|
||||
gw = std::max<int64_t>(1, pyround(iw));
|
||||
}
|
||||
*oh = gh * factor;
|
||||
*ow = gw * factor;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* MuseGlimmerVideoProcessor.sample_frames: torch.linspace(0, total - 1, n).long(), which
|
||||
* truncates, against the .long() of a float tensor (half ties go toward zero). */
|
||||
std::vector<int64_t> sample_frames_muse(const VideoInfo& info, double fps, int32_t temporal,
|
||||
int32_t num_frames) {
|
||||
const int64_t total = info.n_frames;
|
||||
if (total <= 0) return {};
|
||||
const double vfps = info.fps > 0.0 ? info.fps : 24.0;
|
||||
int64_t n = (int64_t)((double)total * fps / vfps); /* Python's int(): toward zero */
|
||||
n = std::min<int64_t>(std::min<int64_t>(n, num_frames), total);
|
||||
n = std::max<int64_t>(temporal, (n / temporal) * temporal);
|
||||
n = std::min<int64_t>(n, total);
|
||||
std::vector<int64_t> idx((size_t)n);
|
||||
if (n == 1) { idx[0] = 0; return idx; }
|
||||
const double step = (double)(total - 1) / (double)(n - 1);
|
||||
for (int64_t i = 0; i < n; ++i) idx[(size_t)i] = (int64_t)((double)i * step);
|
||||
return idx;
|
||||
}
|
||||
|
||||
/* ================================================================== the resample
|
||||
*
|
||||
* Pillow's ImagingResample for 8-bit RGB: coefficients in double, normalised per output pixel and
|
||||
@@ -663,6 +845,20 @@ inline double bicubic(double x) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
/* ATen's HelperInterpLanczos filter, which it credits to Pillow's Resample.c: sin(pi x) / (pi x)
|
||||
* windowed by the same at a third. |x| >= 3 contributes nothing. */
|
||||
inline double sinc_lanczos(double x) {
|
||||
if (x == 0.0) return 1.0;
|
||||
x *= 3.14159265358979323846;
|
||||
return std::sin(x) / x;
|
||||
}
|
||||
|
||||
inline double lanczos(double x) {
|
||||
if (x < 0.0) x = -x;
|
||||
if (x >= 3.0) return 0.0;
|
||||
return sinc_lanczos(x) * sinc_lanczos(x / 3.0);
|
||||
}
|
||||
|
||||
inline uint8_t clip8(int32_t v, int prec) {
|
||||
const int32_t s = v >> prec;
|
||||
return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s));
|
||||
@@ -672,10 +868,11 @@ inline uint8_t clip8(int32_t v, int prec) {
|
||||
* `ksize` per row; `*prec` gets their fraction bits. PIL uses a fixed 22; with `torch`, ATen's
|
||||
* per-axis choice: the most bits at which the largest weight still fits an int16. */
|
||||
int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
|
||||
std::vector<int32_t>* kk, bool torch, int* prec) {
|
||||
std::vector<int32_t>* kk, bool torch, int* prec, double (*filter)(double),
|
||||
double support_scale = 2.0) {
|
||||
const double scale = (double)in_size / (double)out_size;
|
||||
const double fscale = scale < 1.0 ? 1.0 : scale;
|
||||
const double support = 2.0 * fscale;
|
||||
const double support = support_scale * fscale;
|
||||
const int ksize = (int)std::ceil(support) * 2 + 1;
|
||||
std::vector<double> k((size_t)ksize), w((size_t)out_size * (size_t)ksize, 0.0);
|
||||
bounds->assign((size_t)out_size * 2, 0);
|
||||
@@ -691,7 +888,7 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
|
||||
double ww = 0.0;
|
||||
int x = 0;
|
||||
for (; x < xmax; ++x) {
|
||||
const double w = bicubic((x + xmin - center + 0.5) * ss);
|
||||
const double w = filter((x + xmin - center + 0.5) * ss);
|
||||
k[(size_t)x] = w;
|
||||
ww += w;
|
||||
}
|
||||
@@ -982,12 +1179,13 @@ static void pass_vertical(const Frame& src, int32_t shift, int32_t h,
|
||||
});
|
||||
}
|
||||
|
||||
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) {
|
||||
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch,
|
||||
double (*filter)(double) = bicubic, double support_scale = 2.0) {
|
||||
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 int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph, filter, support_scale);
|
||||
const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv, filter, support_scale);
|
||||
const bool need_h = w != in.w, need_v = h != in.h;
|
||||
|
||||
/* Pillow's pass order (libImaging/Resample.c): vertical first when the height shrinks and by
|
||||
@@ -1026,6 +1224,20 @@ void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out) {
|
||||
resize_bicubic_impl(in, w, h, out, true);
|
||||
}
|
||||
|
||||
/* The Muse Glimmer reference's resize filter: torchvision's tvF.resize on the uint8 pixels with
|
||||
* InterpolationMode.LANCZOS and antialias=True, CPU (the TorchvisionBackend refuses it anywhere
|
||||
* else and falls back to bicubic). On CPU torchvision sends a uint8 tensor to torch's native
|
||||
* uint8 kernel, which is PIL's two-pass fixed-point scheme with ATen's parameter choices: weights
|
||||
* in double, normalised, quantised to int16 at an adaptive precision (the most bits at which the
|
||||
* largest weight still fits, at most 22), the horizontal pass first, its output rounded to eight
|
||||
* bits and clamped, then the vertical pass; each pass rounds half up and clamps 0..255. That is
|
||||
* resize_bicubic_impl's `torch` branch with the Lanczos filter in place of bicubic -- the same
|
||||
* quantisation, pass order and rounding this file already implements for torchvision's bicubic
|
||||
* (coeffs, kPrec, pass_horizontal, pass_vertical). */
|
||||
void resize_lanczos_torch(const Frame& in, int32_t w, int32_t h, Frame* out) {
|
||||
resize_bicubic_impl(in, w, h, out, true, lanczos, 3.0);
|
||||
}
|
||||
|
||||
/* Python's round(): the nearest integer, a tie to the even one. The default floating-point
|
||||
* environment rounds that way, which nearbyint follows. */
|
||||
static inline int64_t py_round(double x) { return (int64_t)std::nearbyint(x); }
|
||||
@@ -1260,6 +1472,47 @@ void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, It
|
||||
}
|
||||
}
|
||||
|
||||
/* Muse Glimmer's patch rows, in raster order like the reference's processor emits them (row by
|
||||
* row, not merge-block order): the tower's patch GEMM reads each row as one patch and its
|
||||
* coordinate planes/merge op need the raster grid, and the merge is `pixtral_merge`, which packs
|
||||
* each 2x2 block into one row of the reference's pixel_shuffle layout (channel-major). Each
|
||||
* flattened patch is (temporal, channel), not (channel, temporal), and each value is normalised
|
||||
* through the same per-(channel, byte) lookup as patchify's -- the fused (u - 255 mean) /
|
||||
* (255 std) in f32 is the form the reference's rescale-and-normalise gives, byte for byte,
|
||||
* rounded to bf16.
|
||||
*/
|
||||
void patchify_muse(const VisionConfig& c, const std::vector<const Frame*>& frames, Item* it) {
|
||||
const int P = c.patch, T = c.temporal, M = c.merge;
|
||||
const int gh = it->grid_h, gw = it->grid_w;
|
||||
float m255[3], s255[3];
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
m255[ch] = c.mean[ch] * 255.0f;
|
||||
s255[ch] = c.stdv[ch] * 255.0f;
|
||||
}
|
||||
uint16_t lut[3][256];
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int v = 0; v < 256; ++v)
|
||||
lut[ch][v] = rad_f32_to_bf16(((float)v - m255[ch]) / s255[ch]);
|
||||
const int64_t dim = it->patch_dim;
|
||||
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
|
||||
it->patch_raster = true;
|
||||
uint16_t* dst = it->pixels.data();
|
||||
for (int g = 0; g < it->grid_t; ++g)
|
||||
for (int y = 0; y < gh; ++y)
|
||||
for (int x = 0; x < gw; ++x) {
|
||||
const int py0 = y * P, px0 = x * P;
|
||||
for (int t = 0; t < T; ++t) {
|
||||
const Frame& f = *frames[(size_t)(g * T + t)];
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int yy = 0; yy < P; ++yy) {
|
||||
const uint8_t* row = f.rgb.data() +
|
||||
((size_t)(py0 + yy) * f.w + px0) * 3 + ch;
|
||||
for (int xx = 0; xx < P; ++xx) *dst++ = lut[ch][row[xx * 3]];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Gemma 4's patch rows, in merge-block order like patchify's: each pooling window's patches are
|
||||
* consecutive, so the pooler is a mean of k^2 consecutive rows (attention and the position terms
|
||||
* read each patch's own coordinates, so the order is otherwise free). Each row is (y, x, channel);
|
||||
@@ -1436,6 +1689,33 @@ int Processor::init(const VisionConfig& cfg,
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (cfg.family == Family::MuseGlimmer) {
|
||||
/* The markers the container does not number are vocabulary words, refused here so a
|
||||
* missing one fails at startup, not on the first media. An image and a video frame are
|
||||
* one segment each of merged tokens, so the caps are lowered to what a pass holds. */
|
||||
if (cfg_.tok_start < 0 || cfg_.tok_end < 0 || cfg_.tok_video_start < 0 ||
|
||||
cfg_.tok_video_end < 0 || cfg_.tok_video_sep < 0) {
|
||||
if (!token_id) return RAD_E_INVAL;
|
||||
if (cfg_.tok_start < 0) cfg_.tok_start = token_id("<|image_start|>");
|
||||
if (cfg_.tok_end < 0) cfg_.tok_end = token_id("<|image_end|>");
|
||||
if (cfg_.tok_video_start < 0) cfg_.tok_video_start = token_id("<|vid_start|>");
|
||||
if (cfg_.tok_video_end < 0) cfg_.tok_video_end = token_id("<|vid_end|>");
|
||||
if (cfg_.tok_video_sep < 0) cfg_.tok_video_sep = token_id("<|vid_frame_separator|>");
|
||||
if (cfg_.tok_start < 0 || cfg_.tok_end < 0 || cfg_.tok_video_start < 0 ||
|
||||
cfg_.tok_video_end < 0 || cfg_.tok_video_sep < 0)
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
const int64_t pass_tok = cfg.max_patches / ((int64_t)cfg.merge * cfg.merge);
|
||||
if (pass_tok < 1 || (int64_t)cfg_.max_frame_rows * cfg.merge * cfg.merge > cfg.max_patches)
|
||||
return RAD_E_INVAL;
|
||||
if (cfg_.max_image_tokens > pass_tok) cfg_.max_image_tokens = (int32_t)pass_tok;
|
||||
if (cfg_.max_video_patches <= 0)
|
||||
cfg_.max_video_patches =
|
||||
(int64_t)((cfg.max_frames + cfg.temporal - 1) / cfg.temporal) *
|
||||
(int64_t)cfg_.max_frame_rows * cfg.merge * cfg.merge;
|
||||
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. */
|
||||
@@ -2071,6 +2351,96 @@ int Processor::video_radio(const Video& v, std::shared_ptr<Item>* out, std::stri
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Meta's Muse Glimmer image processor (transformers' MuseGlimmerImageProcessor, Torchvision
|
||||
* backend): the picture at muse_size's grid under the token cap, resized with torchvision's
|
||||
* antialiased Lanczos on the uint8 pixels, values (u / 255 - mean) / std in bf16. One segment. */
|
||||
int Processor::image_muse(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(muse_size(f.h, f.w, c.factor(), c.max_image_tokens, &h, &w, why));
|
||||
Frame r;
|
||||
resize_lanczos_torch(f, (int32_t)w, (int32_t)h, &r);
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Image;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = (int32_t)(h / c.patch);
|
||||
it->grid_w = (int32_t)(w / c.patch);
|
||||
finish_item(c, it.get());
|
||||
if (it->n_patch > c.max_patches) {
|
||||
if (why) *why = "the image resizes to more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* An image fills the temporal depth by repetition, as the reference's expand does. */
|
||||
std::vector<const Frame*> frames((size_t)c.temporal, &r);
|
||||
patchify_muse(c, frames, it.get());
|
||||
one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Its video processor: every frame at the first frame's muse_size grid under the per-frame token
|
||||
* cap (the reference resizes the whole stack once), the frames padded to whole temporal groups by
|
||||
* repeating the last, and per group one "Time: T s" stamp -- the group's first frame's time at
|
||||
* the stream's rate, 24 fps when the stream states none -- between <|vid_start|> and
|
||||
* <|vid_end|>, the groups separated by <|vid_frame_separator|>. */
|
||||
int Processor::video_muse(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(muse_size(v.frames[0].h, v.frames[0].w, c.factor(), c.max_frame_rows, &h, &w, why));
|
||||
|
||||
/* Pad the frames and their indices to whole temporal groups by repeating the last. */
|
||||
std::vector<const Frame*> frames;
|
||||
std::vector<int64_t> idx = v.index;
|
||||
for (const Frame& f : v.frames) frames.push_back(&f);
|
||||
while (frames.size() % (size_t)c.temporal != 0 || frames.size() < (size_t)c.temporal) {
|
||||
frames.push_back(frames.back());
|
||||
idx.push_back(idx.empty() ? 0 : idx.back());
|
||||
}
|
||||
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Video;
|
||||
it->grid_t = (int32_t)(frames.size() / (size_t)c.temporal);
|
||||
it->grid_h = (int32_t)(h / c.patch);
|
||||
it->grid_w = (int32_t)(w / c.patch);
|
||||
finish_item(c, it.get());
|
||||
if ((int64_t)it->grid_h * it->grid_w > c.max_patches) {
|
||||
if (why) *why = "a video frame resizes to more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (it->n_patch > c.max_video_patches) {
|
||||
if (why) *why = "the video is over the server's patch budget for one video";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Resize each distinct frame once; padding repeats share the resized copy. */
|
||||
std::vector<Frame> resized(v.frames.size());
|
||||
for (size_t i = 0; i < v.frames.size(); ++i)
|
||||
resize_lanczos_torch(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]);
|
||||
std::vector<const Frame*> rframes;
|
||||
for (const Frame* f : frames) rframes.push_back(&resized[(size_t)(f - v.frames.data())]);
|
||||
patchify_muse(c, rframes, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
|
||||
const double vfps = v.info.fps > 0.0 ? v.info.fps : 24.0;
|
||||
it->expand.push_back(c.tok_video_start);
|
||||
for (int32_t g = 0; g < it->grid_t; ++g) {
|
||||
char ts[64];
|
||||
std::snprintf(ts, sizeof ts, "Time: %.1fs", (double)idx[(size_t)g * c.temporal] / vfps);
|
||||
const std::vector<int32_t> tt = encode_text_ ? encode_text_(ts) : std::vector<int32_t>{};
|
||||
if (tt.empty()) {
|
||||
if (why) *why = "the tokenizer produced nothing for a video timestamp";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
it->expand.insert(it->expand.end(), tt.begin(), tt.end());
|
||||
it->seg_at.push_back((int32_t)it->expand.size());
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_video);
|
||||
it->expand.push_back(g + 1 == it->grid_t ? c.tok_video_end : c.tok_video_sep);
|
||||
}
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
|
||||
const ImageMode& mode) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
@@ -2083,6 +2453,7 @@ int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::strin
|
||||
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::Radio) return image_radio(f, out, why);
|
||||
if (c.family == Family::MuseGlimmer) return image_muse(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,
|
||||
@@ -2177,6 +2548,7 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
|
||||
const VisionConfig& c = cfg_;
|
||||
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
|
||||
if (c.family == Family::Radio) return video_radio(v, out, why);
|
||||
if (c.family == Family::MuseGlimmer) return video_muse(v, out, why);
|
||||
if (c.family == Family::Glm5Next || c.family == Family::Pixtral) {
|
||||
if (why) *why = "this model's processor takes pictures, not video";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -2418,12 +2790,16 @@ int Processor::encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64
|
||||
}
|
||||
|
||||
namespace {
|
||||
struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; };
|
||||
struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; int32_t temporal; };
|
||||
std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
|
||||
const SampleArgs* a = static_cast<const SampleArgs*>(user);
|
||||
return a->gemma4 ? sample_frames_gemma4(info, a->fps, a->hi)
|
||||
: sample_frames(info, a->fps, a->lo, a->hi);
|
||||
}
|
||||
std::vector<int64_t> muse_sample_cb(const VideoInfo& info, const void* user) {
|
||||
const SampleArgs* a = static_cast<const SampleArgs*>(user);
|
||||
return sample_frames_muse(info, a->fps, a->temporal, a->hi);
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
@@ -2434,8 +2810,13 @@ int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Video v;
|
||||
if (cfg_.family == Family::MuseGlimmer) {
|
||||
const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames, false, cfg_.temporal };
|
||||
RAD_TRY(decode_video(bytes, n, muse_sample_cb, &a, cfg_.max_source_pixels, &v, why));
|
||||
return video_from(v, out, why);
|
||||
}
|
||||
const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames,
|
||||
cfg_.family == Family::Gemma4 };
|
||||
cfg_.family == Family::Gemma4, cfg_.temporal };
|
||||
RAD_TRY(decode_video(bytes, n, sample_cb, &a, cfg_.max_source_pixels, &v, why));
|
||||
return video_from(v, out, why);
|
||||
}
|
||||
|
||||
+39
-2
@@ -92,8 +92,20 @@ enum class Kind { Image, Video, Audio };
|
||||
* zero rows ahead of its patches, which the tower fills with its class and register
|
||||
* tokens. Pictures are spelled <img> placeholders </img>; a video one such run a
|
||||
* tubelet, each after its "Frame i sampled at T seconds and frame i+1 ...: " label,
|
||||
* runs joined by a newline. Tokens at their positions (NoPE). */
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral, Radio };
|
||||
* runs joined by a newline. Tokens at their positions (NoPE).
|
||||
* MuseGlimmer Meta's Muse Glimmer 30B: a picture (a video frame the same) resized so both
|
||||
* sides are multiples of patch * merge and its merged-token count stays under the cap
|
||||
* (max_image_tokens, a frame max_frame_rows), to the whole-merged-patch grid whose
|
||||
* aspect is nearest its own (muse_size, no floor band: a small picture is downscaled
|
||||
* onto the grid). Resized with torchvision's antialiased Lanczos on the uint8 pixels
|
||||
* (resize_lanczos_torch); values (u / 255 - mean) / std in f32, rounded to bf16. A
|
||||
* patch row is (frame, channel, y, x), the reference's (temporal, channel), a picture
|
||||
* duplicated to fill the depth. A picture is spelled <image_start> <|patch|>*N
|
||||
* <image_end>; a video one <vid_start>, then per temporal group the text `Time: T s`
|
||||
* and <|video|>*N rows, the groups separated by <|vid_frame_separator|> and closed by
|
||||
* <vid_end>, T the group's first frame time (the reference stamps a group once, after
|
||||
* repeating the last frame to a whole group). */
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral, Radio, MuseGlimmer };
|
||||
|
||||
struct VisionConfig {
|
||||
Family family = Family::QwenVL;
|
||||
@@ -116,6 +128,11 @@ struct VisionConfig {
|
||||
float mean[3] = { 0.5f, 0.5f, 0.5f };
|
||||
float stdv[3] = { 0.5f, 0.5f, 0.5f };
|
||||
int32_t tok_image = -1, tok_video = -1, tok_start = -1, tok_end = -1;
|
||||
/* MuseGlimmer: the video run's own markers, <vid_start>, <vid_end> and the groups'
|
||||
* <|vid_frame_separator|> (a picture shares tok_start and tok_end). A container that numbers
|
||||
* them (`video_start_token_id`, `video_end_token_id`, `video_frame_separator_token_id`)
|
||||
* wins; otherwise the vocabulary resolves the spellings at Processor::init. */
|
||||
int32_t tok_video_start = -1, tok_video_end = -1, tok_video_sep = -1;
|
||||
/* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */
|
||||
int32_t min_tiles = 0, max_tiles = 0, tile = 0;
|
||||
bool use_thumbnail = false;
|
||||
@@ -456,11 +473,13 @@ private:
|
||||
int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_radio(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_muse(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int video_radio(const Video& v, 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;
|
||||
std::vector<int32_t> tok_tiles_;
|
||||
int video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int video_muse(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
VisionConfig cfg_{};
|
||||
AudioConfig acfg_{};
|
||||
@@ -494,6 +513,21 @@ std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int
|
||||
* within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */
|
||||
int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches,
|
||||
int64_t* oh, int64_t* ow, std::string* why);
|
||||
|
||||
/* MuseGlimmer's smart_resize (MuseGlimmer{Image,Video}Processor.smart_resize): the whole
|
||||
* merged-patch grid (`factor` = patch * merge pixels a side, so a grid cell is one output row)
|
||||
* under `max_tokens` merged tokens whose aspect is nearest the picture's own, in Python's
|
||||
* doubles. A picture over the cap scales to the cap first. */
|
||||
int muse_size(int64_t h, int64_t w, int32_t factor, int64_t max_tokens, int64_t* oh, int64_t* ow,
|
||||
std::string* why);
|
||||
|
||||
/* MuseGlimmerVideoProcessor.sample_frames: `total * fps / native` frames, truncated, clamped to
|
||||
* [temporal, min(num_frames, total)] and floored to a whole temporal group, then torch's
|
||||
* linspace(0, total - 1, n) truncated to integers. A stream with no stated rate is taken at
|
||||
* 24 fps. */
|
||||
std::vector<int64_t> sample_frames_muse(const VideoInfo& info, double fps, int32_t temporal,
|
||||
int32_t num_frames);
|
||||
|
||||
/* Radio's tile for a picture of w x h pixels (NVIDIA's _compute_target_patches, Python's
|
||||
* round-half-even included) and for a video frame (_compute_target_patches_video), in patches. */
|
||||
void radio_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp);
|
||||
@@ -503,6 +537,9 @@ void radio_video_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp,
|
||||
* filter's overshoot. Separable, width first, as ATen's CPU kernel; a side that keeps its size is
|
||||
* the identity. */
|
||||
void resize_bicubic_aa_f32(const Frame& in, int32_t w, int32_t h, std::vector<float>* out);
|
||||
/* The Muse Glimmer reference's resize filter, torchvision's antialiased Lanczos on the uint8
|
||||
* pixels (see processor.cpp). */
|
||||
void resize_lanczos_torch(const Frame& in, int32_t w, int32_t h, Frame* out);
|
||||
/* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a
|
||||
* horizontal pass into an 8-bit intermediate and then a vertical one. */
|
||||
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
|
||||
|
||||
@@ -444,6 +444,7 @@ public:
|
||||
struct AudioGenStrings {
|
||||
/* "" for an absent template; tmpl_ref and ref_item RadAudioGenDecl's references */
|
||||
std::string name, tmpl, tmpl_plain, neg_tmpl, tmpl_ref, ref_item;
|
||||
std::string tmpl_ref_instruct, neg_tmpl_ref;
|
||||
} 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. */
|
||||
@@ -848,6 +849,9 @@ struct Config {
|
||||
bool prefill_interleave_set = false;
|
||||
int64_t prefill_interleave = 0; /* --prefill-interleave: decode-only steps between chunks;
|
||||
* -1 auto (Scheduler::interleave_steps) */
|
||||
/* --mixed-step-target-ms: soft duration target for a mixed prefill/decode step. The scheduler
|
||||
* learns an aggregate prefill-row cap from completed mixed steps; 0 keeps the fixed policy. */
|
||||
int64_t mixed_step_target_ms = 0;
|
||||
/* --preempt-wait-ms: how long a preempted prefill may wait for the whole-recompute gate
|
||||
* before the scheduler evicts cache blocks and preempts a lower-priority running request to
|
||||
* make room for it. 0 = fall back on the next step; default 5000 ms. */
|
||||
@@ -1052,6 +1056,22 @@ struct Config {
|
||||
std::string kld_out; /* --kld-out FILE: the report as JSON, rows beside it */
|
||||
bool kld() const { return !kld_record.empty() || !kld_ref.empty(); }
|
||||
|
||||
/* ---------------- DIAGNOSIS (core/diag/diagnose.h, core/engine_diagnose.cpp) ----------------
|
||||
*
|
||||
* A mode, like the KL mode: the engine starts as it would to serve, then runs a fixed workload
|
||||
* on itself -- decode by prompt category, a concurrency sweep, a prefill sweep with decode at
|
||||
* each depth, a prompt arriving into running streams -- and writes DIR/diagnose.json and
|
||||
* DIR/diagnose.md instead of listening. Every point is run once unmeasured and then
|
||||
* `diagnose_runs` times. */
|
||||
std::string diagnose; /* --diagnose DIR */
|
||||
int diagnose_tokens = 256; /* --diagnose-tokens N: tokens a decode stream generates */
|
||||
int diagnose_runs = 3; /* --diagnose-runs N: measured runs a point */
|
||||
std::vector<int> diagnose_concurrency = { 1, 2, 4, 8 }; /* --diagnose-concurrency */
|
||||
std::vector<int> diagnose_prefill = { 1024, 4096, 16384, 65536 }; /* --diagnose-prefill */
|
||||
std::string diagnose_corpus; /* --diagnose-corpus FILE; empty is the built-in one */
|
||||
std::string diagnose_baseline; /* --diagnose-baseline FILE: an earlier diagnose.json to compare outputs with */
|
||||
bool diagnose_mode() const { return !diagnose.empty(); }
|
||||
|
||||
/* --mm-max-patches: the most patches one encoder pass carries, which bounds the largest image
|
||||
* (one image is one pass) and sizes the encoder's activations. -1 is `auto`: the default below
|
||||
* when the container carries a vision tower and 0 when it does not. 0 serves text only and
|
||||
|
||||
@@ -31,7 +31,7 @@ __global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceAr
|
||||
}
|
||||
|
||||
/* ADV_COMPACT: block (x, y) is work item x (a pool, layer and head) of batch row y; its threads
|
||||
* split the K|V row into 16-byte chunks. Chained like the advance where launches chain, every
|
||||
* split the K|V row into 16-byte chunks and its last words. Chained like the advance where launches chain, every
|
||||
* block waiting for the kernels before it and counting itself in after its moves. */
|
||||
constexpr int kCompactThreads = 64;
|
||||
__device__ __forceinline__ void step_compact_body(const rad::AdvanceArgs& a) {
|
||||
|
||||
@@ -320,7 +320,9 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
}
|
||||
|
||||
/* ADV_COMPACT for one (batch row, pool, layer, head): the moves the row's accepted path asks
|
||||
* for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. Node path[t] stored at
|
||||
* for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. A row is whole 32-bit words; the
|
||||
* words past its last whole chunk (an int8 cache's two f16 scales) go with the caller whose chunk
|
||||
* set the next chunk would be in. Node path[t] stored at
|
||||
* base + path[t] and belongs at base + t + 1. path[] increases (a parent's index is below its
|
||||
* child's) and path[t] >= t + 1, so in t order no move overwrites a node a later move still reads:
|
||||
* a destination base + t + 1 is either the node's own place or a place a node already moved out
|
||||
@@ -340,7 +342,8 @@ RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, in
|
||||
const int32_t base = S.head - S.acc;
|
||||
const int32_t bs = e.block_size;
|
||||
char* lay = P.base + (int64_t)l * P.layer_stride;
|
||||
const int32_t chunks = P.row_bytes / 16;
|
||||
const int32_t chunks = P.row_bytes / 16, tail = P.row_bytes % 16 / 4;
|
||||
const bool tails = tail > 0 && chunks % cstep == c0;
|
||||
for (int32_t t = 0; t < np; ++t) {
|
||||
const int32_t src = base + S.path[t], dst = base + t + 1;
|
||||
if (src == dst) continue;
|
||||
@@ -355,6 +358,8 @@ RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, in
|
||||
v3 = from[4 * c + 3];
|
||||
to[4 * c] = v0; to[4 * c + 1] = v1; to[4 * c + 2] = v2; to[4 * c + 3] = v3;
|
||||
}
|
||||
if (tails)
|
||||
for (int32_t j = 0; j < tail; ++j) to[4 * chunks + j] = from[4 * chunks + j];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+88
-2
@@ -43,9 +43,14 @@ struct SchedMetrics {
|
||||
* (Scheduler::step_next). Every other step leaves the card idle during the host's commit and
|
||||
* staging. */
|
||||
int64_t steps_ahead = 0;
|
||||
/* Prefill chunks capped to leave room for decode rows or a waiting admission in the same
|
||||
* step (--busy-prefill-chunk). Zero under `off`. */
|
||||
/* Prefill chunks capped to leave room for other work in the same step, by the fixed busy
|
||||
* policy or the adaptive mixed-step target. */
|
||||
int64_t prefill_chunks_capped = 0;
|
||||
/* --mixed-step-target-ms: mixed steps observed, those over their target, and the current
|
||||
* seeded or learned aggregate prefill-row cap (0 when the policy is disabled). */
|
||||
int64_t mixed_step_target_steps = 0;
|
||||
int64_t mixed_step_target_misses = 0;
|
||||
int64_t mixed_step_target_prefill_cap = 0;
|
||||
|
||||
/* Cumulative nanoseconds spent inside steps, total and for decode steps only. Wall time over
|
||||
* a step count is not a step time: it charges idle gaps between requests to steps and mixes
|
||||
@@ -213,4 +218,85 @@ private:
|
||||
double mean_ = 0.0; /* the rejection reference */
|
||||
};
|
||||
|
||||
/* Feedback controller for --mixed-step-target-ms. Completed mixed-step service time includes the
|
||||
* forward and drafter work, but not queueing or HTTP transport. Scale rows by target/observed when the
|
||||
* target is missed; grow only after three representative steps below 95% of the target and by at
|
||||
* most a quarter of the measured headroom. A one-quantum probe lets a conservative cap recover
|
||||
* when fixed decode cost makes proportional scaling alone predict no larger legal chunk.
|
||||
*
|
||||
* The controller is deliberately model-agnostic. It may take a cap below an expert stager's
|
||||
* throughput floor: satisfying an explicitly requested latency target while decoders are active
|
||||
* is the point of the flag. With the flag off no caller consults it. */
|
||||
struct MixedStepTarget {
|
||||
void reset() { cap_ = 0; good_ = 0; }
|
||||
|
||||
/* A new server has no mixed-step timing yet. Begin at a conservative fraction of that
|
||||
* model's declared mixed-step capacity instead of allowing one unbounded calibration miss;
|
||||
* subsequent observations replace or grow this seed exactly like any learned cap. */
|
||||
void seed(int64_t rows, int64_t quantum, int64_t max_rows) {
|
||||
if (rows <= 0 || max_rows <= 0) return;
|
||||
const int64_t q = quantum > 0 ? quantum : 1;
|
||||
max_rows = std::max<int64_t>(q, max_rows / q * q);
|
||||
rows = std::max<int64_t>(q, rows / q * q);
|
||||
cap_ = std::min(rows, max_rows);
|
||||
good_ = 0;
|
||||
}
|
||||
|
||||
void observe(int64_t rows, int64_t ns, int64_t target_ns, int64_t quantum,
|
||||
int64_t max_rows, bool representative = true) {
|
||||
if (rows <= 0 || ns <= 0 || target_ns <= 0 || max_rows <= 0) return;
|
||||
const int64_t q = quantum > 0 ? quantum : 1;
|
||||
max_rows = max_rows / q * q;
|
||||
if (max_rows < q) max_rows = q;
|
||||
|
||||
long double scaled = (long double)rows * (long double)target_ns / (long double)ns;
|
||||
int64_t want = scaled >= (long double)max_rows ? max_rows : (int64_t)scaled;
|
||||
want = want / q * q;
|
||||
if (want < q) want = q;
|
||||
|
||||
if (cap_ == 0) {
|
||||
cap_ = want;
|
||||
good_ = 0;
|
||||
return;
|
||||
}
|
||||
if (ns > target_ns) {
|
||||
good_ = 0;
|
||||
/* A prompt tail did not exercise a reusable limit. A checkpoint, fixed busy cap or
|
||||
* other policy boundary still leaves the prompt unfinished and is representative:
|
||||
* reducing this controller below that boundary can shorten the next mixed step. */
|
||||
if (!representative) return;
|
||||
/* A representative miss corrects immediately. */
|
||||
if (want < cap_) cap_ = want;
|
||||
return;
|
||||
}
|
||||
/* A short tail did not exercise the cap and cannot justify growing it. Near-target steps
|
||||
* reset the recovery streak; three clearly fast full-cap samples earn one probe. */
|
||||
if (!representative || ns * 20 >= target_ns * 19 || cap_ >= max_rows) {
|
||||
good_ = 0;
|
||||
return;
|
||||
}
|
||||
if (++good_ < 3) return;
|
||||
good_ = 0;
|
||||
const int64_t goal = std::max<int64_t>(want, std::min(max_rows, cap_ + q));
|
||||
int64_t grow = (goal - cap_) / 4;
|
||||
if (grow < q) grow = q;
|
||||
cap_ = cap_ + grow;
|
||||
cap_ = cap_ / q * q;
|
||||
if (cap_ > goal) cap_ = goal;
|
||||
if (cap_ > max_rows) cap_ = max_rows;
|
||||
}
|
||||
|
||||
int64_t cap() const { return cap_; }
|
||||
int64_t limit(int64_t budget, int64_t quantum) const {
|
||||
if (cap_ <= 0 || budget <= 0) return budget;
|
||||
const int64_t q = quantum > 0 ? quantum : 1;
|
||||
const int64_t c = cap_ / q * q;
|
||||
return c > 0 && c < budget ? c : budget;
|
||||
}
|
||||
|
||||
private:
|
||||
int64_t cap_ = 0;
|
||||
int good_ = 0;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+175
-14
@@ -57,6 +57,15 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
cfg_ = cfg;
|
||||
kv_ = kv;
|
||||
pc_ = pc;
|
||||
/* THE STEP RECORD EXISTS ONLY FOR --diagnose. Sized here, once, and never on the serving
|
||||
* path: 64 Ki steps is minutes of decode at any step rate this engine reaches and 2.5 MiB, and
|
||||
* a record a step is work a serving process has no reader for. A reader that falls further
|
||||
* behind is told how many it lost, not handed the wrong ones. The recorder is chosen here so
|
||||
* the step path calls one instead of testing the mode on every step. */
|
||||
if (cfg_.diagnose_mode()) {
|
||||
step_ring_.reset(1u << 16);
|
||||
record_step_ = &Scheduler::record_step;
|
||||
}
|
||||
|
||||
/* The engine resolves the geometry once, because the prefix cache needs its checkpoint
|
||||
* interval first; a caller without one (tests) resolves its own from prog and cfg. Both
|
||||
@@ -143,10 +152,48 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
"prompt unfinished while other sequences decode, decode-only steps follow for up "
|
||||
"to %.2f of the chunk step's measured time (at most %lld steps)",
|
||||
cfg.prefill_interleave_share, (long long)kInterleaveAutoMax);
|
||||
mixed_target_.reset();
|
||||
m_.mixed_step_target_prefill_cap = 0;
|
||||
if (cfg.mixed_step_target_ms > 0) {
|
||||
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
|
||||
/* A mixed step never receives a span's wide lone-prefill budget. Validate the same
|
||||
* shared budget step() will use, or a spanned deployment can start even though no legal
|
||||
* prefill quantum fits beside a decoder. */
|
||||
const int64_t mixed_budget = geo_.shared_tok;
|
||||
const int64_t draft_rows = 1 + std::max<int64_t>(cfg.n_spec, 0);
|
||||
const int64_t mixed_floor = cfg.max_seqs > 1 ? Q + draft_rows : 0;
|
||||
if ((cfg.busy_prefill_chunk > 0 && cfg.busy_prefill_chunk < Q) ||
|
||||
(mixed_floor > 0 && mixed_budget < mixed_floor)) {
|
||||
RAD_ERR("--mixed-step-target-ms needs room for one legal prefill quantum and "
|
||||
"the active decode rows: quantum=%lld, max_seqs=%lld, draft_rows=%lld, "
|
||||
"mixed_step_budget=%lld, max_num_batched_tokens=%lld, busy_prefill_chunk=%lld",
|
||||
(long long)Q, (long long)cfg.max_seqs, (long long)draft_rows,
|
||||
(long long)mixed_budget,
|
||||
(long long)cfg.max_tok, (long long)cfg.busy_prefill_chunk);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t max_prefill_quanta = mixed_budget > draft_rows
|
||||
? (mixed_budget - draft_rows) / Q : 0;
|
||||
if (cfg.max_seqs > 1 && cfg.max_seqs - 1 > max_prefill_quanta)
|
||||
RAD_WARN("--mixed-step-target-ms: this batch budget can carry at most %lld legal "
|
||||
"prefill quantum(s) beside a speculative decode row; with more simultaneous "
|
||||
"prefills, priority and arrival order continue across later steps",
|
||||
(long long)max_prefill_quanta);
|
||||
mixed_target_.seed(std::max<int64_t>(Q, geo_.shared_tok / 4), Q, geo_.shared_tok);
|
||||
m_.mixed_step_target_prefill_cap = mixed_target_.cap();
|
||||
RAD_INFO("scheduler: --mixed-step-target-ms %lld: completed mixed steps teach an adaptive "
|
||||
"aggregate prefill-row cap; while another sequence decodes the cap starts at "
|
||||
"%lld rows and aims for a full mixed-step duration near %lld ms (a soft target)",
|
||||
(long long)cfg.mixed_step_target_ms, (long long)mixed_target_.cap(),
|
||||
(long long)cfg.mixed_step_target_ms);
|
||||
}
|
||||
interleave_left_ = 0;
|
||||
ema_chunk_s_ = 0.0;
|
||||
ema_decode_s_ = 0.0;
|
||||
held_prefill_ = 0;
|
||||
mixed_target_active_ = false;
|
||||
mixed_target_prefill_planned_ = 0;
|
||||
mixed_target_prefill_continues_ = false;
|
||||
draft_refill_ = 0;
|
||||
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
|
||||
hit_holes_draft_) {
|
||||
@@ -1298,23 +1345,24 @@ void Scheduler::set_stage_rows(int64_t rows) {
|
||||
* about the size of the reserve, as the next step's whole chunk. When that would be under the
|
||||
* floor, the interval is split into two chunks at or above the floor instead. */
|
||||
int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t reserve, bool shared, bool rows_only) const {
|
||||
int64_t reserve, bool shared, bool rows_only,
|
||||
int64_t mixed_target_shares, int64_t mixed_target_decode_reserve) const {
|
||||
const int64_t mode = cfg_.busy_prefill_chunk;
|
||||
if (mode == 0 || budget <= 0) return budget;
|
||||
if (budget <= 0 || (mode == 0 && !mixed_target_active_)) return budget;
|
||||
/* Auto holds a chunk back only for work that would otherwise get nothing this step: rows
|
||||
* behind it, or a request waiting to start. Rows planned ahead of it are in the step anyway.
|
||||
* An explicit N trades prefill speed for every other row's latency, so it applies whenever
|
||||
* the chunk shares the step. */
|
||||
if (reserve <= 0 && !(mode > 0 && shared)) return budget;
|
||||
if (reserve <= 0 && !(mode > 0 && shared) && !(mixed_target_active_ && shared)) return budget;
|
||||
reserve = std::max<int64_t>(reserve, 0);
|
||||
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
|
||||
|
||||
int64_t cap = budget - reserve;
|
||||
int64_t cap = mode == 0 ? budget : budget - reserve;
|
||||
if (mode > 0) {
|
||||
/* The operator's number, with no floor; set_stage_rows warns when it is under the
|
||||
* stager's step. */
|
||||
cap = std::min(cap, mode);
|
||||
} else {
|
||||
} else if (mode < 0) {
|
||||
const int64_t floor = std::max(Q, stage_rows_ / Q * Q);
|
||||
cap = std::max(cap, floor);
|
||||
const int64_t remaining = n_target - n_computed;
|
||||
@@ -1331,6 +1379,25 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget
|
||||
if (!rows_only && cap < span && span - cap < floor && span - floor >= floor)
|
||||
cap = span - floor;
|
||||
}
|
||||
/* Apply the decoder reservation after the auto staging floor. Otherwise the floor can raise
|
||||
* a reduced cap back to the whole budget, exclude the decoder, and prevent feedback. */
|
||||
if (mixed_target_active_ && mixed_target_decode_reserve > 0)
|
||||
cap = std::min(cap, budget - mixed_target_decode_reserve);
|
||||
if (mixed_target_active_ && mixed_target_.cap() > 0) {
|
||||
mixed_target_shares = std::max<int64_t>(0, mixed_target_shares);
|
||||
/* Share the aggregate allowance evenly among this prefill and those expected later in
|
||||
* the step. Stable queue order must not let the first request consume the cap while the
|
||||
* others receive only a minimum quantum on every step. If the learned cap cannot hold
|
||||
* one quantum apiece, the effective allowance grows just enough to make progress; this
|
||||
* may miss an impossible target, but it cannot silently starve a queued prompt. */
|
||||
const int64_t floor = mixed_target_prefill_planned_ + (mixed_target_shares + 1) * Q;
|
||||
const int64_t allowance = std::max(mixed_target_.cap(), floor);
|
||||
const int64_t left = std::max<int64_t>(0, allowance - mixed_target_prefill_planned_);
|
||||
const int64_t participants = mixed_target_shares + 1;
|
||||
const int64_t fair = left / participants / Q * Q;
|
||||
if (fair < Q || cap < Q) return 0;
|
||||
cap = std::min(cap, fair);
|
||||
}
|
||||
return std::min(std::max(cap, Q), budget);
|
||||
}
|
||||
|
||||
@@ -1397,7 +1464,8 @@ bool Scheduler::preempt_back() {
|
||||
/* ------------------------------------------------------------------ admission */
|
||||
/* Admission checks the KV budget before a request enters running; a request admitted without the
|
||||
* blocks to run would be preempted on its first step, a full recompute for nothing. */
|
||||
int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve,
|
||||
int64_t mixed_target_shares) {
|
||||
Request& r = *s.req;
|
||||
|
||||
/* A REQUEST THAT WAS PREEMPTED WAITS FOR ROOM FOR THE WHOLE RECOMPUTE, plus one block of
|
||||
@@ -1622,11 +1690,13 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
/* An admission shares the step the same way: otherwise a cold prompt with requests
|
||||
* 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());
|
||||
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
|
||||
false, mixed_target_shares, 0);
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
|
||||
/* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
|
||||
if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
|
||||
if (want <= 0 && cap < budget && prog_->encoder.bidirectional &&
|
||||
(!mixed_target_active_ || r.media))
|
||||
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
|
||||
else if (cap < budget && want > 0)
|
||||
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at, &r);
|
||||
@@ -1775,6 +1845,8 @@ const RadBatch* Scheduler::step() {
|
||||
plan_.spec_is_tree = tree_;
|
||||
step_prefill_tok_ = 0;
|
||||
step_decode_tok_ = 0;
|
||||
mixed_target_prefill_planned_ = 0;
|
||||
mixed_target_prefill_continues_ = false;
|
||||
|
||||
/* A preempted prefill waits for the whole-recompute gate so it cannot loop. That wait is
|
||||
* bounded here, for every overdue preempted request, not only the queue head: a head that
|
||||
@@ -1865,7 +1937,7 @@ const RadBatch* Scheduler::step() {
|
||||
bool any_decoding = false;
|
||||
bool hold_prefill = false;
|
||||
held_prefill_ = 0;
|
||||
if (cfg_.prefill_interleave != 0) {
|
||||
if (cfg_.prefill_interleave != 0 || cfg_.mixed_step_target_ms > 0) {
|
||||
for (int32_t slot : running_) {
|
||||
const SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (!s.req || !s.running) continue;
|
||||
@@ -1875,8 +1947,9 @@ const RadBatch* Scheduler::step() {
|
||||
break;
|
||||
}
|
||||
if (!any_decoding) interleave_left_ = 0;
|
||||
hold_prefill = interleave_left_ > 0;
|
||||
hold_prefill = cfg_.prefill_interleave != 0 && interleave_left_ > 0;
|
||||
}
|
||||
mixed_target_active_ = cfg_.mixed_step_target_ms > 0 && any_decoding;
|
||||
|
||||
/* A span is for a prefill alone in its step (ChunkGeometry::span). A spanned step takes as
|
||||
* long as the intervals it carries, so a decode row riding along would wait that long for its
|
||||
@@ -1920,7 +1993,7 @@ const RadBatch* Scheduler::step() {
|
||||
* to be walked needs 1 + the deepest window it can take, each prefill row a share, plus one
|
||||
* share when a request waits and a slot is free. Counted down as the loop walks, so a row's
|
||||
* reserve is what is behind it. */
|
||||
const bool share_step = cfg_.busy_prefill_chunk != 0;
|
||||
const bool share_step = cfg_.busy_prefill_chunk != 0 || mixed_target_active_;
|
||||
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
|
||||
/* An eighth of this step's budget, which under a span is shared_tok for a shared step. */
|
||||
const int64_t share_tok = std::max<int64_t>(Q, budget / 8 / Q * Q);
|
||||
@@ -1934,6 +2007,10 @@ const RadBatch* Scheduler::step() {
|
||||
if (pf) ++behind_pf; else behind_dec += dec_row_tok;
|
||||
}
|
||||
}
|
||||
const int64_t admit_room = std::min<int64_t>(
|
||||
(int64_t)free_cards_.size(), cfg_.max_seqs - (int64_t)running_.size());
|
||||
const int64_t mixed_target_waits = mixed_target_active_
|
||||
? std::min<int64_t>((int64_t)waiting_.size(), std::max<int64_t>(0, admit_room)) : 0;
|
||||
const bool admit_waits = share_step && !waiting_.empty() && !free_cards_.empty() &&
|
||||
(int64_t)running_.size() < cfg_.max_seqs;
|
||||
/* The first prefill chunk held back this step (its index in plan_.e before the sort) and what
|
||||
@@ -1977,13 +2054,15 @@ const RadBatch* Scheduler::step() {
|
||||
if (prefill && hold_prefill) { ++held_prefill_; ++i; continue; }
|
||||
if (prefill) {
|
||||
const int64_t shares = share_step ? behind_pf + (admit_waits ? 1 : 0) : 0;
|
||||
const int64_t mixed_target_shares = mixed_target_active_ ? behind_pf + mixed_target_waits : 0;
|
||||
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);
|
||||
/*rows_only=*/shares == 0, mixed_target_shares, behind_dec);
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
|
||||
/* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
|
||||
if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
|
||||
if (want <= 0 && cap < budget && prog_->encoder.bidirectional &&
|
||||
(!mixed_target_active_ || r.media))
|
||||
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
|
||||
else if (cap < budget && want > 0 && capped_at < 0) {
|
||||
const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr,
|
||||
@@ -2129,6 +2208,9 @@ const RadBatch* Scheduler::step() {
|
||||
s.sched_tokens = (int32_t)want;
|
||||
plan_.e.push_back(e);
|
||||
plan_.n_tok += want;
|
||||
if (prefill && mixed_target_active_) {
|
||||
mixed_target_prefill_planned_ += want;
|
||||
}
|
||||
if (!prefill && s.n_draft > plan_.n_spec) plan_.n_spec = s.n_draft;
|
||||
budget -= want;
|
||||
++i;
|
||||
@@ -2173,7 +2255,15 @@ const RadBatch* Scheduler::step() {
|
||||
? share_tok : 0;
|
||||
admit_full_ = 0;
|
||||
admit_next_step_ = false;
|
||||
const int as = admit_one(s, budget, areserve);
|
||||
const int64_t mixed_target_shares = mixed_target_active_
|
||||
? std::min<int64_t>(
|
||||
(int64_t)waiting_.size() - (int64_t)at - 1,
|
||||
std::min<int64_t>(
|
||||
cfg_.max_seqs - (int64_t)plan_.e.size() - 1,
|
||||
(int64_t)free_cards_.size() - 1))
|
||||
: 0;
|
||||
const int as = admit_one(s, budget, areserve,
|
||||
std::max<int64_t>(0, mixed_target_shares));
|
||||
/* A preempted request waiting for its whole-recompute gate lets the next one be asked;
|
||||
* an overdue one does not. The room the overdue path made this step is for it, and a
|
||||
* request queued behind it would take that room back: a victim just forced off for it,
|
||||
@@ -2237,6 +2327,9 @@ const RadBatch* Scheduler::step() {
|
||||
s.entry = (int32_t)plan_.e.size();
|
||||
plan_.e.push_back(e);
|
||||
plan_.n_tok += s.sched_tokens;
|
||||
if (mixed_target_active_) {
|
||||
mixed_target_prefill_planned_ += s.sched_tokens;
|
||||
}
|
||||
budget -= s.sched_tokens;
|
||||
took_.push_back(at);
|
||||
++at;
|
||||
@@ -2266,6 +2359,11 @@ const RadBatch* Scheduler::step() {
|
||||
* to it at most. */
|
||||
int64_t limit = std::min(capped_full, had + budget);
|
||||
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
|
||||
if (mixed_target_active_ && mixed_target_.cap() > 0) {
|
||||
const int64_t other = std::max<int64_t>(0, mixed_target_prefill_planned_ - had);
|
||||
const int64_t left = std::max<int64_t>(0, mixed_target_.cap() - other);
|
||||
limit = std::min(limit, std::max(had, left));
|
||||
}
|
||||
int64_t ckpt = -1;
|
||||
const int64_t grown = e.ckpt_slot < 0 && limit > had
|
||||
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at, &r)
|
||||
@@ -2276,6 +2374,7 @@ const RadBatch* Scheduler::step() {
|
||||
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(ckpt - r.n_computed - 1));
|
||||
s.sched_tokens = (int32_t)grown;
|
||||
plan_.n_tok += grown - had;
|
||||
if (mixed_target_active_) mixed_target_prefill_planned_ += grown - had;
|
||||
budget -= grown - had;
|
||||
}
|
||||
if (e.n_tokens < capped_full) ++m_.prefill_chunks_capped;
|
||||
@@ -2313,6 +2412,11 @@ const RadBatch* Scheduler::step() {
|
||||
plan_.phase = any_pf && n_dec ? RAD_PHASE_MIXED
|
||||
: any_pf ? RAD_PHASE_PREFILL
|
||||
: RAD_PHASE_DECODE;
|
||||
if (mixed_target_active_) {
|
||||
mixed_target_prefill_continues_ = false;
|
||||
for (const StepEntry& e : plan_.e)
|
||||
if (e.is_prefill && !e.produces_token) mixed_target_prefill_continues_ = true;
|
||||
}
|
||||
|
||||
/* Step-shape counters. `steps_mixed` / `steps` shows how often a step carries both kinds of
|
||||
* row. `decode_rows_unspeculated` counts every decode row that took no draft, whatever the
|
||||
@@ -2907,6 +3011,18 @@ int Scheduler::commit(StepResult& res) {
|
||||
*
|
||||
* Host timing, always available. Per-op device timing adds synchronisations that change the
|
||||
* mover's slot supply, so profiled runs are not comparable (spec §16). */
|
||||
void Scheduler::record_step(int64_t ns, int64_t end_ns) {
|
||||
diag::StepRecord r;
|
||||
r.step = m_.steps;
|
||||
r.phase = plan_.phase;
|
||||
r.n_seq = (int32_t)plan_.e.size();
|
||||
r.prefill_tok = (int32_t)step_prefill_tok_;
|
||||
r.decode_tok = (int32_t)step_decode_tok_;
|
||||
r.ns = ns;
|
||||
r.end_ns = end_ns;
|
||||
step_ring_.push(r);
|
||||
}
|
||||
|
||||
void Scheduler::step_finished() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (step_start_.time_since_epoch().count() == 0) return; /* no step has run */
|
||||
@@ -2915,6 +3031,9 @@ void Scheduler::step_finished() {
|
||||
const int64_t ns =
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(step_end - step_start_).count();
|
||||
m_.step_ns += ns;
|
||||
mixed_target_observe_locked(ns);
|
||||
(this->*record_step_)(ns, std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
step_end.time_since_epoch()).count());
|
||||
if (plan_.phase == RAD_PHASE_DECODE) {
|
||||
m_.step_ns_decode += ns;
|
||||
/* The single-sequence floor over the step just timed (rad::DecodeFloor). A mixed step
|
||||
@@ -2972,6 +3091,48 @@ void Scheduler::step_finished() {
|
||||
step_start_ = {};
|
||||
}
|
||||
|
||||
/* The mixed-step target's one timing entry point. `step_finished` supplies the live bracket;
|
||||
* note_mixed_step_cost supplies a deterministic bracket to scheduler tests and host simulations. */
|
||||
void Scheduler::mixed_target_observe_locked(int64_t ns) {
|
||||
int64_t rows = 0;
|
||||
for (const StepEntry& e : plan_.e) if (e.is_prefill) rows += e.n_tokens;
|
||||
if (cfg_.mixed_step_target_ms <= 0 || plan_.phase != RAD_PHASE_MIXED ||
|
||||
rows <= 0 || plan_.n_seq_decode <= 0 || ns <= 0) return;
|
||||
|
||||
const int64_t target_ns = cfg_.mixed_step_target_ms * 1000000ll;
|
||||
++m_.mixed_step_target_steps;
|
||||
if (ns > target_ns) ++m_.mixed_step_target_misses;
|
||||
const int64_t before = mixed_target_.cap();
|
||||
mixed_target_.observe(rows, ns, target_ns, std::max<int64_t>(geo_.quantum, 1),
|
||||
geo_.shared_tok, mixed_target_prefill_continues_);
|
||||
m_.mixed_step_target_prefill_cap = mixed_target_.cap();
|
||||
if (mixed_target_.cap() != before && (int)log_level() >= (int)Log::Debug)
|
||||
RAD_DEBUG("scheduler: mixed-step target observed %.2f ms over %lld prefill token(s); "
|
||||
"adaptive mixed-prefill cap %lld -> %lld for a %lld ms target",
|
||||
(double)ns / 1e6, (long long)rows, (long long)before,
|
||||
(long long)mixed_target_.cap(), (long long)cfg_.mixed_step_target_ms);
|
||||
}
|
||||
|
||||
void Scheduler::note_mixed_step_cost(int64_t ns) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
mixed_target_observe_locked(ns);
|
||||
}
|
||||
|
||||
uint64_t Scheduler::step_record_count() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return step_ring_.count();
|
||||
}
|
||||
|
||||
size_t Scheduler::step_record_capacity() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return step_ring_.capacity();
|
||||
}
|
||||
|
||||
uint64_t Scheduler::step_records(uint64_t from, std::vector<diag::StepRecord>* out) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return step_ring_.copy_since(from, out);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the serial drafter */
|
||||
/* Which sequences may take a serial draft after the step just run, and what each needs. Called
|
||||
* while plan() still describes that step, since everything here indexes into it: the head reads
|
||||
|
||||
+37
-2
@@ -17,6 +17,7 @@
|
||||
#include "lookup.h"
|
||||
#include "metrics.h"
|
||||
#include "ngram.h"
|
||||
#include "diag/diagnose.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
@@ -230,6 +231,17 @@ public:
|
||||
void take_completed(std::vector<uint64_t>* out);
|
||||
int reap(uint64_t id);
|
||||
|
||||
/* ---------------------------------------------------------- the step record (--diagnose)
|
||||
*
|
||||
* One diag::StepRecord per committed step, in a ring sized at init and only with --diagnose: a
|
||||
* serving process keeps no ring and records nothing. A reader takes every step a phase ran --
|
||||
* its shape and its time -- without a second clock. Both calls take the lock; `step_records`
|
||||
* appends what came after `from` and returns how many of those the ring overwrote before they
|
||||
* were read (diag/diagnose.h). */
|
||||
uint64_t step_record_count() const;
|
||||
size_t step_record_capacity() const; /* 0 without --diagnose */
|
||||
uint64_t step_records(uint64_t from, std::vector<diag::StepRecord>* out) const;
|
||||
|
||||
/* ---------------------------------------------------------- the lock, for the engine
|
||||
*
|
||||
* Every mutation of the KV manager and the prefix cache happens under this lock; neither has
|
||||
@@ -374,6 +386,9 @@ public:
|
||||
* so the draft rounds are charged to the step (see the definition). Without it the counters
|
||||
* stay correct but there is no timing. */
|
||||
void step_finished();
|
||||
/* Feed the open mixed step a completed service time, as step_finished does. Visible for
|
||||
* deterministic scheduler tests and timed host simulations. */
|
||||
void note_mixed_step_cost(int64_t ns);
|
||||
|
||||
/* ---------------------------------------------------- the serial drafter (spec §10)
|
||||
*
|
||||
@@ -514,7 +529,8 @@ public:
|
||||
* and `shared` says rows are already planned ahead of it. Returns `budget` when
|
||||
* --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;
|
||||
bool shared = false, bool rows_only = false,
|
||||
int64_t mixed_target_shares = 0, int64_t mixed_target_decode_reserve = 0) 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
|
||||
@@ -800,6 +816,13 @@ private:
|
||||
* throughput window; metrics() decays what it reports by this. */
|
||||
std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now();
|
||||
int64_t step_prefill_tok_ = 0, step_decode_tok_ = 0;
|
||||
/* The step record, picked once at init: with --diagnose the ring is sized and record_step is
|
||||
* written into it, without it step_finished calls a no-op. One indirect call a step, no test
|
||||
* of the mode and no ring on the serving path. Callers of step_finished hold mu_. */
|
||||
void record_step(int64_t ns, int64_t end_ns);
|
||||
void record_no_step(int64_t, int64_t) {}
|
||||
void (Scheduler::*record_step_)(int64_t, int64_t) = &Scheduler::record_no_step;
|
||||
diag::StepRing step_ring_;
|
||||
/* --prefill-interleave: decode-only steps still owed before the next chunk, and how many
|
||||
* prefilling requests the last step() held back. step_next_locked stops issuing ahead once
|
||||
* the hold is spent, or the chunk would wait as long as the decoders keep stepping ahead. */
|
||||
@@ -812,6 +835,17 @@ private:
|
||||
static constexpr int64_t kInterleaveAutoMax = 64;
|
||||
double ema_chunk_s_ = 0.0, ema_decode_s_ = 0.0;
|
||||
void step_cost_locked(bool chunk, double seconds);
|
||||
/* --mixed-step-target-ms: learned mixed-step cap and whether this planning pass has a decoder
|
||||
* whose output latency the cap protects. */
|
||||
MixedStepTarget mixed_target_;
|
||||
bool mixed_target_active_ = false;
|
||||
/* Aggregate prefill rows already admitted to this mixed step. The learned cap is a budget
|
||||
* for the step, not a per-request allowance. */
|
||||
int64_t mixed_target_prefill_planned_ = 0;
|
||||
/* At least one prefill in the issued mixed step has work beyond this chunk. Unlike a true
|
||||
* prompt tail, a policy or checkpoint-limited chunk is representative feedback. */
|
||||
bool mixed_target_prefill_continues_ = false;
|
||||
void mixed_target_observe_locked(int64_t ns);
|
||||
/* The throughput window (step_finished): each kind's tokens and the wall time the steps
|
||||
* 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;
|
||||
@@ -875,7 +909,8 @@ private:
|
||||
/* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind
|
||||
* it. `reserve`: tokens of the step to leave for the requests queued behind this one
|
||||
* (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */
|
||||
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0);
|
||||
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0,
|
||||
int64_t mixed_target_shares = 0);
|
||||
/* Positive sentinel from admit_one: the request waits (its context is still being read off
|
||||
* disk, or a preempted prefill has no room yet) and the walk may ask the one behind it. */
|
||||
static constexpr int kAdmitWait = 1;
|
||||
|
||||
@@ -152,6 +152,9 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
|
||||
o.steps_ahead = m.steps_ahead;
|
||||
o.prefill_chunks_capped = m.prefill_chunks_capped;
|
||||
o.steps_held = m.steps_held;
|
||||
o.mixed_step_target_steps = m.mixed_step_target_steps;
|
||||
o.mixed_step_target_misses = m.mixed_step_target_misses;
|
||||
o.mixed_step_target_prefill_cap = m.mixed_step_target_prefill_cap;
|
||||
o.decode_rows_unspeculated = m.decode_rows_unspeculated;
|
||||
o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode;
|
||||
o.step_ns_decode_best = m.step_ns_decode_best;
|
||||
|
||||
+23
-11
@@ -254,9 +254,16 @@ int Server::speech_request(const json& body, const std::string& text,
|
||||
}
|
||||
if (refs.empty()) r->ref_cu.clear();
|
||||
}
|
||||
if (!refs.empty() && !inst.empty())
|
||||
const bool ref_direction = !refs.empty() && !inst.empty();
|
||||
if (ref_direction && info.tmpl_ref_instruct.empty())
|
||||
return fail(err_unsupported("instructions", "a request with references takes no "
|
||||
"instructions; the clips set the voice"));
|
||||
/* A model whose negative template omits the reference has not declared reference CFG.
|
||||
* In particular Breeze's ref_clone_tata is an unguided continuation, not voice design. */
|
||||
if (!refs.empty() && info.branches != 1 && r->cfg > 1.0f &&
|
||||
(!ref_direction || info.neg_tmpl_ref.empty()))
|
||||
return fail(err_unsupported("guidance_scale", "voice cloning requires guidance_scale 1; "
|
||||
"this model has no guided reference template"));
|
||||
|
||||
/* ---- the prompt */
|
||||
std::string i2, t2, why;
|
||||
@@ -277,26 +284,28 @@ int Server::speech_request(const json& body, const std::string& text,
|
||||
/* 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) {
|
||||
auto render_ref = [&](size_t i, std::vector<int32_t>* ids_out,
|
||||
std::vector<int32_t>* frame_map, int64_t& frame0) {
|
||||
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);
|
||||
frame_map->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));
|
||||
frame_map->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) {
|
||||
auto render = [&](const std::string& t, std::vector<int32_t>* ids_out,
|
||||
std::vector<int32_t>* frame_map) {
|
||||
static const std::string kInst = "{instructions}", kInput = "{input}",
|
||||
kRefs = "{references}";
|
||||
size_t at = 0;
|
||||
int64_t frame0 = 0;
|
||||
while (at <= t.size()) {
|
||||
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));
|
||||
@@ -304,7 +313,7 @@ int Server::speech_request(const json& body, const std::string& text,
|
||||
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);
|
||||
for (size_t i = 0; i < refs.size(); ++i) render_ref(i, ids_out, frame_map, frame0);
|
||||
at = p + kRefs.size();
|
||||
continue;
|
||||
}
|
||||
@@ -314,11 +323,14 @@ int Server::speech_request(const json& body, const std::string& text,
|
||||
encode(is_inst ? i2 : t2, !is_inst && info.input_special, ids_out);
|
||||
at = p + (is_inst ? kInst : kInput).size();
|
||||
}
|
||||
if (frame_map) frame_map->resize(ids_out->size(), -1);
|
||||
};
|
||||
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);
|
||||
render(ref_direction ? info.tmpl_ref_instruct : !refs.empty() ? info.tmpl_ref :
|
||||
inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens,
|
||||
refs.empty() ? nullptr : &r->ref_frame);
|
||||
if (ref_direction)
|
||||
render(info.neg_tmpl_ref, &r->neg_tokens, &r->neg_ref_frame);
|
||||
else if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens, nullptr);
|
||||
const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size());
|
||||
if ((int64_t)n_prompt > info.max_prompt)
|
||||
return fail(err_bad("input", "the prompt is " + std::to_string(n_prompt) +
|
||||
|
||||
@@ -372,6 +372,9 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["prefill_chunks_capped"] = m.prefill_chunks_capped;
|
||||
o["steps_decode"] = m.steps_decode;
|
||||
o["steps_held"] = m.steps_held;
|
||||
o["mixed_step_target_steps"] = m.mixed_step_target_steps;
|
||||
o["mixed_step_target_misses"] = m.mixed_step_target_misses;
|
||||
o["mixed_step_target_prefill_cap"] = m.mixed_step_target_prefill_cap;
|
||||
/* Time inside steps. The one rate the page cannot derive: wall clock between polls also
|
||||
* covers idle time (see SchedMetrics::step_ns). */
|
||||
o["step_ns"] = m.step_ns;
|
||||
|
||||
@@ -142,6 +142,9 @@ struct SchedMetrics {
|
||||
int64_t steps_ahead = 0; /* issued behind the step before, ahead of its commit */
|
||||
int64_t prefill_chunks_capped = 0; /* held back for other work in the step (--busy-prefill-chunk) */
|
||||
int64_t steps_held = 0; /* decode-only steps --prefill-interleave inserted */
|
||||
int64_t mixed_step_target_steps = 0; /* mixed steps observed by --mixed-step-target-ms */
|
||||
int64_t mixed_step_target_misses = 0; /* those whose completed wall time exceeded the target */
|
||||
int64_t mixed_step_target_prefill_cap = 0; /* current learned mixed-prefill row cap */
|
||||
int64_t decode_rows_unspeculated = 0;
|
||||
/* Cumulative nanoseconds inside steps, all shapes and decode-only. Wall clock over a step
|
||||
* count is not a step time: the engine idles between turns, and a prefill chunk costs an
|
||||
@@ -753,6 +756,7 @@ struct AudioGenInfo {
|
||||
/* 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;
|
||||
std::string tmpl_ref_instruct, neg_tmpl_ref;
|
||||
int64_t ref_rate = 0, ref_hop = 0, ref_max_samples = 0;
|
||||
int32_t ref_max = 0;
|
||||
};
|
||||
|
||||
@@ -154,6 +154,7 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
/* 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);
|
||||
g_mixed_step_target_cap_.set((double)m.mixed_step_target_prefill_cap);
|
||||
const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS));
|
||||
for (int j = 0; j < seen; ++j) {
|
||||
const int64_t r = m.draft_pos_reached[j];
|
||||
@@ -184,6 +185,8 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
c_steps_ahead_.advance_to(m.steps_ahead);
|
||||
c_prefill_capped_.advance_to(m.prefill_chunks_capped);
|
||||
c_steps_held_.advance_to(m.steps_held);
|
||||
c_mixed_step_target_steps_.advance_to(m.mixed_step_target_steps);
|
||||
c_mixed_step_target_misses_.advance_to(m.mixed_step_target_misses);
|
||||
c_rows_unspec_.advance_to(m.decode_rows_unspeculated);
|
||||
c_step_secs_.advance_to((double)m.step_ns * 1e-9);
|
||||
c_step_secs_decode_.advance_to((double)m.step_ns_decode * 1e-9);
|
||||
@@ -418,6 +421,16 @@ std::string Metrics::render() const {
|
||||
w.counter("radiance:engine_steps_held_total",
|
||||
"Decode-only steps run after a prefill chunk while other sequences decode "
|
||||
"(--prefill-interleave).", L, c_steps_held_.get());
|
||||
w.counter("radiance:mixed_step_target_steps_total",
|
||||
"Mixed prefill/decode steps observed by --mixed-step-target-ms.",
|
||||
L, c_mixed_step_target_steps_.get());
|
||||
w.counter("radiance:mixed_step_target_misses_total",
|
||||
"Mixed steps whose completed service time exceeded --mixed-step-target-ms.",
|
||||
L, c_mixed_step_target_misses_.get());
|
||||
if (g_mixed_step_target_cap_.get() > 0)
|
||||
w.gauge("radiance:mixed_step_target_prefill_cap",
|
||||
"Current learned prefill-row cap used while decode sequences are active.",
|
||||
L, g_mixed_step_target_cap_.get());
|
||||
w.counter("radiance:decode_rows_unspeculated_total",
|
||||
"Decode rows that took no draft, for any reason.",
|
||||
L, c_rows_unspec_.get());
|
||||
|
||||
@@ -149,6 +149,8 @@ private:
|
||||
* rate over a window rather than an average dominated by startup. */
|
||||
Counter c_steps_prefill_, c_steps_mixed_, c_steps_decode_, c_rows_unspec_, c_steps_ahead_;
|
||||
Counter c_prefill_capped_, c_steps_held_;
|
||||
Counter c_mixed_step_target_steps_, c_mixed_step_target_misses_;
|
||||
Gauge g_mixed_step_target_cap_;
|
||||
/* Seconds inside a step, all shapes and decode-only. Wall clock over a step count is not a
|
||||
* step time (see SchedMetrics::step_ns). */
|
||||
Counter c_step_secs_, c_step_secs_decode_;
|
||||
|
||||
+41
-2
@@ -263,6 +263,13 @@ static bool alias_reasoning(const ojson& messages, ojson* out) {
|
||||
}
|
||||
return v;
|
||||
};
|
||||
/* A call that takes no arguments, as clients replay it: null, or the empty or blank string a
|
||||
* client stores from a stream that sent none. */
|
||||
auto no_arguments = [](const ojson& a) {
|
||||
return a.is_null() ||
|
||||
(a.is_string() && a.get_ref<const std::string&>().find_first_not_of(" \t\r\n") ==
|
||||
std::string::npos);
|
||||
};
|
||||
auto needs = [&](const ojson& m) {
|
||||
if (!m.is_object()) return false;
|
||||
const auto rc = m.find("reasoning_content");
|
||||
@@ -283,7 +290,7 @@ static bool alias_reasoning(const ojson& messages, ojson* out) {
|
||||
if (!call.is_object()) continue;
|
||||
const auto fn = call.find("function");
|
||||
if (!call.contains("type") || fn == call.end() || !fn->is_object() ||
|
||||
!fn->contains("arguments") || fn->at("arguments").is_null())
|
||||
!fn->contains("arguments") || no_arguments(fn->at("arguments")))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -336,7 +343,7 @@ static bool alias_reasoning(const ojson& messages, ojson* out) {
|
||||
call.erase("name");
|
||||
call.erase("arguments");
|
||||
}
|
||||
} else if (!fn->contains("arguments") || fn->at("arguments").is_null()) {
|
||||
} else if (!fn->contains("arguments") || no_arguments(fn->at("arguments"))) {
|
||||
(*fn)["arguments"] = "{}";
|
||||
}
|
||||
}
|
||||
@@ -344,6 +351,33 @@ static bool alias_reasoning(const ojson& messages, ojson* out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The first replayed call whose arguments are a string that is not JSON, as
|
||||
* "messages[i].tool_calls[j].function.arguments is not JSON: <why>", or empty when every call's
|
||||
* arguments parse. The template refuses such a conversation with the parser's words alone, which reads as
|
||||
* the template's fault; this names the call. */
|
||||
static std::string bad_arguments(const ojson& messages) {
|
||||
if (!messages.is_array()) return "";
|
||||
for (size_t i = 0; i < messages.size(); ++i) {
|
||||
const ojson& m = messages[i];
|
||||
const auto tcs = m.is_object() ? m.find("tool_calls") : m.end();
|
||||
if (!m.is_object() || tcs == m.end() || !tcs->is_array()) continue;
|
||||
for (size_t j = 0; j < tcs->size(); ++j) {
|
||||
const ojson& tc = (*tcs)[j];
|
||||
const auto fn = tc.is_object() ? tc.find("function") : tc.end();
|
||||
if (!tc.is_object() || fn == tc.end() || !fn->is_object()) continue;
|
||||
const auto args = fn->find("arguments");
|
||||
if (args == fn->end() || !args->is_string()) continue;
|
||||
try {
|
||||
(void)ojson::parse(args->get_ref<const std::string&>());
|
||||
} catch (const std::exception& e) {
|
||||
return "messages[" + std::to_string(i) + "].tool_calls[" + std::to_string(j) +
|
||||
"].function.arguments is not JSON: " + e.what();
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
|
||||
ChatPrompt* out) const {
|
||||
if (!ready()) {
|
||||
@@ -430,6 +464,11 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
}
|
||||
}
|
||||
if (!served) {
|
||||
if (const std::string bad = bad_arguments(msgs); !bad.empty()) {
|
||||
if (!opt.quiet) RAD_WARN("chat: request did not parse: %s", bad.c_str());
|
||||
out->error = bad;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const std::string w = template_words(e.what());
|
||||
if (!opt.quiet) RAD_WARN("chat: the model's chat template refused the request: %s",
|
||||
w.c_str());
|
||||
|
||||
+2
-1
@@ -114,7 +114,8 @@ public:
|
||||
/* Render. `messages` and `tools` are OpenAI-shaped JSON (`tools` may be null or empty).
|
||||
* Returns RAD_OK, RAD_E_INVAL when the request does not parse, or RAD_E_UNSUPPORTED when the
|
||||
* template refuses it (e.g. a system message without a system role, or tools without tool
|
||||
* support). */
|
||||
* support). Replayed history is read in other servers' shapes first: a turn's reasoning under
|
||||
* `reasoning` or `thinking`, and a call whose arguments are null, blank or absent. */
|
||||
int apply(const Json& messages, const Json& tools,
|
||||
const ChatOptions& opt, ChatPrompt* out) const;
|
||||
|
||||
|
||||
@@ -353,6 +353,7 @@ int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string*
|
||||
f.object_bare_keys = c.object_bare_keys != 0;
|
||||
f.reasoning_anywhere = c.reasoning_anywhere != 0;
|
||||
f.arg_json_value_prefix = s(c.arg_json_value_prefix);
|
||||
f.content_open = s(c.content_open);
|
||||
*out = std::move(f);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -468,6 +469,7 @@ std::string chat_format_describe(const ChatFormat& f) {
|
||||
(f.reasoning_anywhere ? " anywhere" : "");
|
||||
else
|
||||
s += " no reasoning";
|
||||
if (!f.content_open.empty()) s += "; content " + show(f.content_open);
|
||||
if (f.has_tools() && !f.section_open.empty())
|
||||
s += "; section " + show(f.section_open) + ".." + show(f.section_close);
|
||||
if (f.has_tools() && f.object_args()) {
|
||||
@@ -498,7 +500,8 @@ std::string chat_format_describe(const ChatFormat& f) {
|
||||
|
||||
std::vector<std::string> chat_format_markers(const ChatFormat& f) {
|
||||
std::vector<std::string> out;
|
||||
for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.section_open,
|
||||
for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.content_open,
|
||||
&f.section_open,
|
||||
&f.section_close, &f.call_open, &f.call_close, &f.name_prefix,
|
||||
&f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix,
|
||||
&f.arg_value_prefix, &f.arg_json_value_prefix,
|
||||
|
||||
@@ -100,6 +100,9 @@ struct ChatFormat {
|
||||
* reasoning there; a close with no block open is dropped. Gemma 4 sometimes writes an empty
|
||||
* block after its answer, or a lone close. Needs `reasoning_open`. */
|
||||
bool reasoning_anywhere = false;
|
||||
/* A header the model writes first when it answers without reasoning; dropped when the reply
|
||||
* starts with it. Empty: none. */
|
||||
std::string content_open;
|
||||
|
||||
/* ------------------------------------------------------------------ tool calls
|
||||
* `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the
|
||||
|
||||
+149
-9
@@ -1063,7 +1063,8 @@ int ReplyParser::create(std::shared_ptr<const ReplyFormat> fmt, const ReplyOptio
|
||||
/* A response format replaces the call grammar outright; the calls are not parsed. */
|
||||
P.calls = want_calls && !opt.response_format;
|
||||
P.breaks = want_calls && F.f.has_reasoning() && !F.f.reasoning_breaks.empty();
|
||||
P.pure = !F.f.has_reasoning() && !want_calls && !opt.response_format;
|
||||
P.pure = !F.f.has_reasoning() && !want_calls && !opt.response_format &&
|
||||
F.f.content_open.empty();
|
||||
P.anywhere = F.f.reasoning_anywhere && F.f.has_reasoning() && opt.extract_reasoning &&
|
||||
!opt.response_format;
|
||||
|
||||
@@ -1093,6 +1094,7 @@ enum class St : uint8_t {
|
||||
LeadWs, /* whitespace before the reply proper: dropped */
|
||||
ThinkOpen, /* the core of reasoning_open */
|
||||
ThinkOpenWs, /* the optional whitespace that ends reasoning_open */
|
||||
ContentOpen, /* content_open, the header of a reply that does not reason */
|
||||
Think, /* reasoning text */
|
||||
ThinkCloseWs, /* the optional whitespace that ends reasoning_close */
|
||||
Text, /* content, watching for the call opener when calls are on */
|
||||
@@ -1149,6 +1151,7 @@ struct ReplyStream::Impl {
|
||||
explicit Impl(const ReplyParser::Impl& p) : P(p), F(p.fmt->impl()) {
|
||||
content.init(P.terminators.empty() ? nullptr : &P.terms, &P.terminators);
|
||||
st = P.pure ? St::Text : St::LeadWs;
|
||||
think_hold_on = P.calls && !F.f.reasoning_breaks.empty();
|
||||
if (P.anywhere) {
|
||||
text_dfa = P.calls ? &F.text_think : &F.think_only;
|
||||
n_open = P.calls ? F.openers.size() : 0;
|
||||
@@ -1211,6 +1214,16 @@ struct ReplyStream::Impl {
|
||||
std::string vheld;
|
||||
size_t vs_pos = 0;
|
||||
bool fenced = false;
|
||||
/* Channel-scoped protocols (Muse): with tools on, a trailing `to=NAME<|message|>` while
|
||||
* reasoning streams is the handoff to a tool call, not reasoning text. The reasoning's
|
||||
* tail is held until it cannot grow into framing or a header; a completed tool-channel
|
||||
* header is dropped along with everything after it -- the section opener is where the
|
||||
* call machinery takes over. Without the hold the header lands in the reasoning stream,
|
||||
* and a model that hesitates at the handoff repeats it (observed on Muse Glimmer: three
|
||||
* or four `to=read<|message|>` headers before the section, under speculative decoding). */
|
||||
bool think_hold_on = false;
|
||||
std::string think_hold;
|
||||
bool think_handoff = false;
|
||||
|
||||
/* The argument object being read: its open brackets; whether a key (not a value) is being
|
||||
* read; a separator read but not yet written (written only once the next member shows the
|
||||
@@ -1293,12 +1306,108 @@ struct ReplyStream::Impl {
|
||||
|
||||
void think_out(const char* p, size_t n) {
|
||||
if (n == 0) return;
|
||||
if (think_handoff) return; /* past the tool-channel header: call framing, dropped */
|
||||
touch(0);
|
||||
if (think_text) { msg.reasoning.append(p, n); return; }
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
if (!is_blank((unsigned char)p[i])) { think_text = true; break; }
|
||||
think_pend.append(p, n);
|
||||
if (think_text) { msg.reasoning += think_pend; think_pend.clear(); }
|
||||
if (!think_hold_on) {
|
||||
if (think_text) { msg.reasoning.append(p, n); return; }
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
if (!is_blank((unsigned char)p[i])) { think_text = true; break; }
|
||||
think_pend.append(p, n);
|
||||
if (think_text) { msg.reasoning += think_pend; think_pend.clear(); }
|
||||
return;
|
||||
}
|
||||
touch(0);
|
||||
think_hold.append(p, n);
|
||||
flush_think_hold(false);
|
||||
}
|
||||
|
||||
void emit_reasoning_upto(size_t emit) {
|
||||
if (emit == 0) return;
|
||||
const std::string part = think_hold.substr(0, emit);
|
||||
if (think_text) { msg.reasoning += part; }
|
||||
else {
|
||||
for (size_t i = 0; i < part.size(); ++i)
|
||||
if (!is_blank((unsigned char)part[i])) { think_text = true; break; }
|
||||
think_pend += part;
|
||||
if (think_text) { msg.reasoning += think_pend; think_pend.clear(); }
|
||||
}
|
||||
}
|
||||
|
||||
/* The handoff position from the last `<|eom|>`: the tail reads as the tool-channel
|
||||
* header -- optional `<|start|>assistant`, ws, `to=`, recipient name bytes (never
|
||||
* `user`: that transition matches the reply close above and is consumed by it), then
|
||||
* `<|message|>` or a prefix of it while the header streams. npos: no handoff. */
|
||||
size_t tool_handoff_at() const {
|
||||
static const std::string eom = "<|eom|>", start = "<|start|>assistant", to = "to=";
|
||||
/* The framing is bounded (terminator + assistant + `to=` + a recipient + the message
|
||||
* marker); scanning only the tail keeps a byte-at-a-time stream linear. */
|
||||
const size_t wstart = think_hold.size() - std::min(kHoldWindow, think_hold.size());
|
||||
size_t p = std::string::npos;
|
||||
for (size_t q = think_hold.find(eom, wstart); q != std::string::npos;
|
||||
q = think_hold.find(eom, q + 1))
|
||||
p = q;
|
||||
if (p == std::string::npos) return std::string::npos;
|
||||
size_t k = p + eom.size();
|
||||
if (think_hold.compare(k, start.size(), start) == 0) k += start.size();
|
||||
while (k < think_hold.size() && is_ws((unsigned char)think_hold[k])) ++k;
|
||||
if (think_hold.compare(k, to.size(), to) != 0) return std::string::npos;
|
||||
return p; /* everything from `<|eom|>` on is the tool call's framing */
|
||||
}
|
||||
|
||||
/* Muse's channel protocol, per the reference parsers (vLLM's muse reasoning/tool
|
||||
* parsers; llama.cpp PR #26841): reasoning streams until `<|eom|>`, and the model
|
||||
* sometimes leaves the analysis channel WITHOUT it, opening a tool channel directly
|
||||
* (`<|start|>assistant to=read<|message|>`) -- a documented model-side defect. So the
|
||||
* reasoning's tail is held while it could still grow into that framing, and once the
|
||||
* handoff is detected everything from the header on is dropped: the call machinery
|
||||
* (the section + invoke tags) has already produced the tool_calls events. */
|
||||
void flush_think_hold(bool final_feed) {
|
||||
if (think_handoff) return; /* past the handoff: framing, dropped */
|
||||
size_t emit = think_hold.size();
|
||||
const size_t handoff = tool_handoff_at();
|
||||
if (handoff != std::string::npos) {
|
||||
emit = handoff;
|
||||
think_handoff = true;
|
||||
} else if (!final_feed) {
|
||||
/* Hold a tail that could still grow into the handoff framing: a partial
|
||||
* `<|eom|>` / `<|start|>` / `<|message|>` marker, or a trailing ` to=NAME`. */
|
||||
static const std::string markers[] = {"<|eom|>", "<|start|>", "<|message|>"};
|
||||
for (const std::string& mk : markers)
|
||||
for (size_t k = std::min(mk.size(), think_hold.size()); k > 0; --k)
|
||||
if (think_hold.compare(think_hold.size() - k, k, mk, 0, k) == 0)
|
||||
emit = std::min(emit, think_hold.size() - k);
|
||||
const size_t wstart_t = think_hold.size() - std::min(kHoldWindow, think_hold.size());
|
||||
size_t at = std::string::npos;
|
||||
for (size_t q = think_hold.find("to=", wstart_t); q != std::string::npos;
|
||||
q = think_hold.find("to=", q + 1))
|
||||
at = q;
|
||||
if (at != std::string::npos) {
|
||||
bool tail = true;
|
||||
for (size_t k = at + 3; k < think_hold.size(); ++k)
|
||||
if (!is_name_byte((unsigned char)think_hold[k])) { tail = false; break; }
|
||||
if (tail) {
|
||||
size_t a = at;
|
||||
while (a > 0 && is_ws((unsigned char)think_hold[a - 1])) --a;
|
||||
emit = std::min(emit, a);
|
||||
}
|
||||
}
|
||||
if (emit >= think_hold.size()) {
|
||||
emit_reasoning_upto(emit);
|
||||
think_hold.clear(); /* nothing held: everything goes out now */
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (emit > 0) emit_reasoning_upto(emit);
|
||||
think_hold.erase(0, emit);
|
||||
if (final_feed) think_hold.clear();
|
||||
}
|
||||
|
||||
/* The tail the framing scans read; a longer tail is real reasoning, never framing. */
|
||||
static constexpr size_t kHoldWindow = 160;
|
||||
|
||||
static bool is_name_byte(unsigned char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '.' || c == '-';
|
||||
}
|
||||
|
||||
void text_out(const char* p, size_t n) {
|
||||
@@ -2051,6 +2160,20 @@ struct ReplyStream::Impl {
|
||||
return p + 1;
|
||||
}
|
||||
/* No block: what was held is read again as whatever follows one. */
|
||||
st = after_no_block();
|
||||
read_again(lhold);
|
||||
lhold.clear();
|
||||
return p;
|
||||
}
|
||||
|
||||
case St::ContentOpen: {
|
||||
const unsigned char c = (unsigned char)*p;
|
||||
if (lpos < F.f.content_open.size() && (unsigned char)F.f.content_open[lpos] == c) {
|
||||
lhold.push_back((char)c);
|
||||
if (++lpos == F.f.content_open.size()) { lhold.clear(); st = after_think(); }
|
||||
return p + 1;
|
||||
}
|
||||
/* Not the header: what was held is content (or the start of the document). */
|
||||
st = after_think();
|
||||
read_again(lhold);
|
||||
lhold.clear();
|
||||
@@ -2066,10 +2189,11 @@ struct ReplyStream::Impl {
|
||||
case St::Think: {
|
||||
const Dfa& d = P.breaks ? F.think_breaks : F.think;
|
||||
p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); });
|
||||
if (hit == 0) { trail = 0; st = St::ThinkCloseWs; }
|
||||
if (hit == 0) { flush_think_hold(true); trail = 0; st = St::ThinkCloseWs; }
|
||||
else if (hit > 0) {
|
||||
const std::string& marker = d.pattern(hit);
|
||||
if (!F.section_open_core.empty() && marker == F.section_open_core) {
|
||||
flush_think_hold(true);
|
||||
open_section();
|
||||
st = St::Text;
|
||||
} else if (!F.section_open_core.empty() && !section_active) {
|
||||
@@ -2754,10 +2878,17 @@ struct ReplyStream::Impl {
|
||||
return e;
|
||||
}
|
||||
|
||||
St after_lead() const {
|
||||
St after_lead() {
|
||||
if (F.f.has_reasoning() && P.opt.extract_reasoning)
|
||||
return F.open_core.empty() ? St::Think : St::ThinkOpen;
|
||||
return after_think();
|
||||
return after_no_block();
|
||||
}
|
||||
/* The reply did not open a reasoning block: its content_open header, when the format has one,
|
||||
* is matched from the first byte (the bytes of a failed reasoning opener are read again). */
|
||||
St after_no_block() {
|
||||
if (F.f.content_open.empty()) return after_think();
|
||||
lpos = 0;
|
||||
return St::ContentOpen;
|
||||
}
|
||||
St after_think() const { return P.opt.response_format ? St::RfWs : St::Text; }
|
||||
|
||||
@@ -2887,6 +3018,14 @@ struct ReplyStream::Impl {
|
||||
rerun();
|
||||
}
|
||||
if (st == St::ObjStr || st == St::ObjQStr) str_flush();
|
||||
/* The reply ended inside a header that never completed: its bytes are the reply. */
|
||||
while (!F.f.content_open.empty() && !lhold.empty() &&
|
||||
(st == St::ContentOpen || st == St::ThinkOpen)) {
|
||||
st = st == St::ThinkOpen ? after_no_block() : after_think();
|
||||
read_again(lhold);
|
||||
lhold.clear();
|
||||
rerun();
|
||||
}
|
||||
while (in_loose_attempt()) {
|
||||
fail_attempt();
|
||||
rerun();
|
||||
@@ -2935,6 +3074,7 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
hold.clear();
|
||||
ds = 0;
|
||||
if (think_hold_on) flush_think_hold(true);
|
||||
if (!think_text) think_pend.clear();
|
||||
content.finish(msg.content);
|
||||
if (cur >= 0) publish(cur, true);
|
||||
|
||||
Reference in new issue
Block a user