Merge upstream main (v1.12 -> v1.15.1, 408 commits) into the SYCL port

Conflicts from the old m2xfp branch take upstream's version. Two libxe2 fixes the merge needs:
- rad_plugin_abi_layout: the plugin now exports the ABI layout hash the loader checks.
- gemm_nt_q_w4a16: upstream 492d33c sends bf16 activations to the w4a16 GEMM (the separate cast
  is gone); the fast kernel took only f16, so every call fell back to the exact path (decode
  ~2.5 tok/s). A bf16 activation is narrowed to f16 (round to nearest even) into a workspace first,
  the dropped cast bit for bit; decode back to ~57 tok/s on one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-02 00:25:57 +01:00
commit 7580ec3d17
937 files changed
+285776 -8914

No files matched your search

+483 -76
View File
@@ -7,6 +7,7 @@
#include "engine_priv.h"
#include "rad_internal.h"
#include "engine_hostmem.h"
#include "kld.h"
#include "gen/driver.h"
#include "gen/audio_driver.h"
#include "gen/video_driver.h"
@@ -19,8 +20,11 @@
#include "format/rope_override.h"
#include "format/share.h"
#include "format/table_copy.h"
#include "format/table_share.h"
#include "rad_plugin.h"
#include "mem/vram_budget.h"
#include "kvstream/bringup.h"
#include "kvstream/plan.h"
#include "runtime/arena.h"
#include "runtime/kvbind.h"
#include "runtime/xprefetch.h"
@@ -35,6 +39,7 @@
#include <cstring>
#include <fstream>
#include <numeric>
#include <sstream>
#include <cstdint>
#include <cstdlib>
@@ -329,14 +334,9 @@ static void memory_cgroups(const std::function<bool(const std::string&, int64_t)
}
}
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
* first and `margin` (--host-headroom-mib) stays free, or why not. Checks MemAvailable; every
* memory cgroup from the process's own up to the visible root (Docker's --memory, enforced by
* the OOM killer); and, for an mlock()ed copy (`mlocks`), RLIMIT_MEMLOCK unless the process has
* CAP_IPC_LOCK. Pinned memory a card reads is a driver userptr mapping, which RLIMIT_MEMLOCK
* does not count. An unreadable limit is ignored, never guessed. */
static bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks,
std::string* why) {
/* See engine_hostmem.h. */
bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks,
std::string* why) {
long long locked_kb = 0;
unsigned long long caps = 0;
{
@@ -401,15 +401,59 @@ static int64_t lockable_bytes(int64_t still, int64_t margin, std::string* limit)
}
/* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). One copy
* per container address, shared by every rank; freed in ~Engine. */
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). With
* --ngram-placement ram=DIR the pinned memory is a file in DIR mapped shared (core/format/
* table_share.h): this engine fills it or, if another engine did, checks samples of it against the
* container, and pins it either way. Only a table of kTableShareMin or more is shared: the gather's
* scale is an n-gram weight too, since it moves with the table between gather sites, and as a file
* its two bytes would cost the 2 MiB header and a 2 MiB page. One copy per container address,
* shared by every rank; freed in ~Engine. */
int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
std::string* why) {
for (const auto& c : table_copy_of_)
if (c.first == src) { *out = c.second; return RAD_OK; }
const auto t0 = std::chrono::steady_clock::now();
auto since = [&] {
return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
};
void* base = nullptr;
if (card) {
if (card && !cfg_.ngram_share_dir.empty() && n >= kTableShareMin) {
const std::string id = table_share_id(file_->path(), foff, n);
if (id.empty()) {
*why = fmt("the container %s cannot be stat'ed, which names the shared table",
file_->path());
return RAD_E_IO;
}
TableShare s;
int rc = table_share_open(cfg_.ngram_share_dir, id, n, &s, why);
if (rc != RAD_OK) return rc;
base = rad_dev_map_file(s.fd, kTableShareHeader, n);
if (!base) {
*why = fmt("pinning %s of %s: %s", humanb(n).c_str(), s.path.c_str(),
rad_dev_last_error());
table_share_close(&s);
return RAD_E_NOMEM;
}
if (s.filler) {
rc = table_copy_fill(*file_, src, n, foff, static_cast<uint8_t*>(base), why);
if (rc == RAD_OK) rc = table_share_mark_ready(&s, n, id, why);
} else {
rc = table_copy_check(src, n, static_cast<const uint8_t*>(base), why);
if (rc != RAD_OK)
*why = fmt("the shared file %s does not match the container (%s)", s.path.c_str(),
why->c_str());
}
if (rc != RAD_OK) {
rad_dev_free(base, RAD_MEM_HOST_MAPPED);
table_share_close(&s);
return rc;
}
card_copies_.push_back(base);
table_shares_.push_back(s);
RAD_INFO("placement: n-gram table in pinned memory the cards read, %s in shared file %s, "
"%s in %.1f s", humanb(n).c_str(), s.path.c_str(),
s.filler ? "filled" : "reused (probes match)", since());
} else if (card) {
base = rad_dev_alloc(n, RAD_MEM_HOST_MAPPED);
if (!base) {
*why = fmt("pinning %s: %s", humanb(n).c_str(), rad_dev_last_error());
@@ -421,16 +465,17 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
return rc;
}
card_copies_.push_back(base);
RAD_INFO("placement: n-gram table copied into pinned memory the cards read, %s in %.1f s",
humanb(n).c_str(), since());
} else {
TableCopy tc;
const int rc = table_copy_make(*file_, src, n, foff, &tc, why);
if (rc != RAD_OK) return rc;
table_copies_.push_back(tc);
base = tc.base;
RAD_INFO("placement: n-gram table copied into locked memory, %s in %.1f s",
humanb(n).c_str(), since());
}
RAD_INFO("placement: n-gram table copied into %s, %s in %.1f s",
card ? "pinned memory the cards read" : "locked memory", humanb(n).c_str(),
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
table_copy_of_.push_back({ src, base });
*out = base;
return RAD_OK;
@@ -566,8 +611,43 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
* then the container. */
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_total_mib() * MiB +
cfg_.prefix_cache_mib * MiB + host_late;
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
/* ram=DIR: the copy is a file other engines map too. One already complete costs this engine
* no host memory for the table; a weight under kTableShareMin beside it (the scale) is a
* private copy either way. */
std::string share_note;
if (!cfg_.ngram_share_dir.empty() && ngram_bytes > 0) {
if (!ngram_device) {
RAD_ERR("--ngram-placement ram=%s: only the pinned copy a card reads is shared, and no "
"loaded kernel plugin reads an n-gram table on a card (embed_lookup_q has host "
"kernels only), so the host gather would read a private locked copy. Use ram "
"or disk.", cfg_.ngram_share_dir.c_str());
return RAD_E_INVAL;
}
share_note = fmt("a file in %s that other engines share", cfg_.ngram_share_dir.c_str());
if (file_ && !ranks_.empty()) {
const Program& prog = ranks_.front()->program;
for (size_t i = 1; i < prog.weights.size(); ++i) {
const WeightInfo& w = prog.weights[i];
if (!is_ngram_table(prog, (rad_weight)i) || w.n_sel < 1) continue;
const RadFileEntry* e = file_->find(w.source);
if (!e) continue;
const RadFilePlane& p0 = file_->plane(*e, w.sel[0]);
if ((int64_t)p0.bytes < kTableShareMin) continue;
const std::string id =
table_share_id(file_->path(), (int64_t)p0.offset, (int64_t)p0.bytes);
if (table_share_is_ready(cfg_.ngram_share_dir, id, (int64_t)p0.bytes)) {
need = align_up(std::max<int64_t>(ngram_bytes - (int64_t)p0.bytes, 0),
(int64_t)2 << 20);
share_note = fmt("a complete shared file in %s already holds it, which "
"takes no memory of this engine's own for the table",
cfg_.ngram_share_dir.c_str());
}
break;
}
}
}
auto card_holds = [&](std::string* why) {
std::vector<VramFacts> with = facts;
int64_t fixed = 0;
@@ -642,7 +722,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
"%s: %s", humanb(ngram_bytes).c_str(), copy, ram_why.c_str());
return RAD_E_NOMEM;
}
ng_why = "as asked";
ng_why = share_note.empty() ? std::string("as asked") : "as asked, as " + share_note;
} else if (card) {
ng = TablePlacement::Vram;
ng_why = "the card holds it beside the other weights and a KV pool for one "
@@ -898,6 +978,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
bc.max_seqs = cfg_.max_seqs;
bc.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
bc.max_spec = cfg_.n_spec;
bc.draft_tree = draft_tree_ ? 1 : 0;
bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1;
/* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for
* other callers and means the plugin's default. */
@@ -905,6 +986,16 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
bc.kv_quant = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4
: cfg_.kv_cache_dtype == "k6_v4" ? RAD_KVQ_K6V4 : RAD_KVQ_NONE;
bc.attn_prefill_fp8 = cfg_.attn_prefill_fp8;
bc.tp_attn_rows = cfg_.tp_attn_rows;
bc.weight_prefetch_off = cfg_.weight_prefetch ? 0 : 1;
bc.calib_dir = cfg_.calib_dir.empty() ? nullptr : cfg_.calib_dir.c_str();
bc.calib_layer_lo = cfg_.calib_layer_lo;
bc.calib_layer_hi = cfg_.calib_layer_hi;
bc.calib_tokens = calib_ ? calib_->n_tokens() : calib_tokens_;
bc.gen_max_pixels = cfg_.image_gen_max_pixels;
bc.gen_max_refs = cfg_.image_gen_max_refs;
bc.state_dtype = cfg_.state_cache_dtype == "f16" ? RAD_F16 : 0;
bc.draft_coupling = cfg_.draft_coupling ? 1 : 0;
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
bc.scope = "";
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
@@ -915,6 +1006,15 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
/* Under --prefill-span every step but a lone prefill is planned at the shared budget
* (Scheduler::step), so a wider step is one sequence; 0 without a span. */
bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0;
/* --kv-resident in tokens, raised to kStreamFloorTokens as kvstream_ring_shape raises it: the
* arch declares kv_resolve's ring depth from this, and the kernel refuses a carve deeper than
* the declared table. */
bc.kv_resident_blocks = cfg_.kv_resident > 0 && cfg_.kv_resident < kStreamFloorTokens
? kStreamFloorTokens
: cfg_.kv_resident;
/* A streamed-only op is declared only when the architecture streams and the flag asks
* (kvstream_op_gated). */
bc.kv_stream_ok = arch_probe_.kv_stream_ok;
/* The control vector, when one is loaded: this rank's view, or null. A plugin reads it at
* declare only (the direction table never changes); the per-request switch rides the derived
* mask, not this struct. */
@@ -925,6 +1025,15 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
}
int Engine::declare() {
/* An architecture that declares no streamed ops cannot stream, so with --kv-resident set on one
* the flag is turned off here, with the decision named, before anything is planned for it. */
(void)rad_tools_probe(plugins_, meta_, &arch_probe_, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (cfg_.kv_resident > 0 && arch_probe_.kv_stream_ok == 0) {
cfg_.kv_resident = 0;
decide("--kv-resident", "0",
std::string("architecture '") + (meta_.arch_id ? meta_.arch_id : "?") +
"' has no streamed KV path");
}
RAD_TRY(lora_targets());
/* KL mode measures the trunk (core/kld.h): a drafter writes no scored rows and a prefix hit
* would skip positions the reference holds, so both are off, and an explicit depth is refused
@@ -943,13 +1052,43 @@ int Engine::declare() {
"the KL mode: a prefix hit would start a document past positions the reference holds";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
}
/* --calib-corpus: every token of the corpus through prefill exactly once, so no prefix hit
* skips any and no drafter adds rows; the corpus is loaded here, before the plugins declare,
* because they are told its size. */
if (cfg_.calib()) {
if (cfg_.n_spec > 0) {
RAD_ERR("--num-speculative-tokens %d: a calibration run drafts nothing; leave it at "
"auto or 0", cfg_.n_spec);
return RAD_E_INVAL;
}
cfg_.n_spec = 0;
cfg_.prefix_cache = false;
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
decide("--num-speculative-tokens", "0", "a calibration run records the trunk's rows only");
prefix_off_why_ = "a calibration run: a prefix hit would skip tokens the statistics must count";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
calib_ = std::make_unique<Kld>();
RAD_TRY(calib_->load(cfg_.calib_corpus, vocab_));
RAD_INFO("calib: %zu documents, %lld tokens from %s", calib_->n_docs(),
(long long)calib_->n_tokens(), cfg_.calib_corpus.c_str());
}
/* --kld-record beside --calib-dir: the reference's run records the statistics too, over the
* KL corpus, whose size the plugins are told here; run_kld then feeds the documents so that
* none is preempted. */
if (!cfg_.kld_record.empty() && !cfg_.calib_dir.empty()) {
Kld count;
RAD_TRY(count.load(cfg_.kld_corpus, vocab_));
calib_tokens_ = count.n_tokens();
RAD_INFO("calib: recorded beside the reference, %zu documents, %lld tokens from %s",
count.n_docs(), (long long)calib_tokens_, cfg_.kld_corpus.c_str());
}
/* An image generator sizes the step itself (RadArchProbe::gen_rows): a denoise pass carries all
* of an image's latent rows (twice with guidance), and a conditioning pass encodes every
* reference picture of a request. Operator-given values are kept. No drafting (no tokens) and
* no prefix cache (a conditioning is read only by its own request). */
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (pb.gen_rows > 0 && pb.gen_audio) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
@@ -987,7 +1126,14 @@ int Engine::declare() {
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"a video generator: a step's rows");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
/* A video generator with a vision tower takes a pass of its patches, the size its
* plugin states. */
if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) {
cfg_.mm_max_patches = pb.gen_patches;
decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches),
"a video generator: every reference media patch of one conditioning, "
"the pass size the plugin states");
}
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0) {
@@ -1022,20 +1168,54 @@ int Engine::declare() {
if (cfg_.kv_cache_dtype == "fp8_v4" || cfg_.kv_cache_dtype == "k6_v4") {
const int q = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4 : RAD_KVQ_K6V4;
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (!(pb.kv_quant_ok & (1 << q))) {
RAD_ERR("--kv-cache-dtype %s: the '%s' plugin does not serve it for this model "
"(fp8 does)", cfg_.kv_cache_dtype.c_str(), plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
}
/* The row split is a graph only the plugin can declare, and it splits over ranks. A plugin
* that does not say it serves it (RadArchProbe::tp_attn_rows_ok), or a single rank, would
* serve the head split under a name that promised the other, so the flag is refused rather
* than ignored. */
if (cfg_.tp_attn_rows) {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (!pb.tp_attn_rows_ok) {
RAD_ERR("--tp-attn-split rows: the '%s' plugin does not split attention by rows for "
"this model (heads does)", plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
if (cfg_.tp < 2) {
RAD_ERR("--tp-attn-split rows splits a prefill's attention over tensor-parallel ranks, "
"and --tp %d has none to split over (heads does)", cfg_.tp);
return RAD_E_INVAL;
}
RAD_WARN("attention: a prefill-sized step splits by rows over the %d ranks "
"(--tp-attn-split rows): every card holds the attention's projections at full "
"width, and the result is not bit-identical to the head split", cfg_.tp);
}
/* Likewise an f16 recurrent state: a plugin that does not say it declares one would keep f32
* under a flag that promised half the state memory. */
if (cfg_.state_cache_dtype == "f16") {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (!pb.state_f16_ok) {
RAD_ERR("--state-cache-dtype f16: the '%s' plugin does not declare its recurrent state "
"at f16 for this model (f32 does)", plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
RAD_INFO("recurrent state cache: f16 (--state-cache-dtype), half the state memory; lossy, "
"the generated text differs from f32");
}
/* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is
* selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel
* bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of
* drafter configuration. */
if (cfg_.n_spec < 0) {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
cfg_.n_spec = pb.draft_depth > 0 ? pb.draft_depth : 0;
if (cfg_.n_spec > 0)
RAD_INFO("speculation: depth %d, this drafter's own operating point "
@@ -1053,7 +1233,7 @@ int Engine::declare() {
* speculatively. */
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
const bool pays = cfg_.n_spec > 0 && pb.chain_pays;
rad_dev_chain_infer(pays);
const bool on = rad_dev_chain_enabled() != 0;
@@ -1064,13 +1244,29 @@ int Engine::declare() {
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
decide("chained launches", on ? "on" : "off", why);
}
/* Trees: a block drafter's proposals verified as a tree, where the model's plugin measured a
* gain with one (RadArchProbe::tree_pays; the Gemma 4 31B with DFlash2: +7% single-stream
* decode, +6-9% aggregate at 1-16 users on 4x R9700) and the drafter decodes speculatively.
* A tree changes no token, only how many drafts land a step. */
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
/* A tree is verified only behind a step issued ahead (step_loop). The KL mode, which issues
* none, drafts nothing either (n_spec is 0 there by now), so this never runs under it. */
draft_tree_ = cfg_.n_spec > 0 && pb.tree_pays != 0;
if (draft_tree_) {
const char* why = "the model's plugin measured a gain with them";
RAD_INFO("draft trees: asked -- %s", why);
decide("draft trees", "asked", why);
}
}
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
if (cfg_.mm_audio_frames < 0) {
const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
const bool named = enc && std::strstr(enc, "audio") != nullptr;
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
const bool text_only = cfg_.mm_max_patches == 0;
cfg_.mm_audio_frames = !text_only && pb.audio_frames > 0 && (named || !file_)
? pb.audio_frames : 0;
@@ -1088,7 +1284,7 @@ int Engine::declare() {
cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0;
/* Whole output rows a pass: the plugin's merge, when it states one. */
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (cfg_.mm_max_patches > 0 && pb.enc_merge > 1)
cfg_.mm_max_patches -= cfg_.mm_max_patches % pb.enc_merge;
if (cfg_.mm_max_patches == 0 && tower)
@@ -1114,7 +1310,7 @@ int Engine::declare() {
"refused");
} else {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (!pb.control_vector_ok) {
RAD_ERR("--control-vector %s: the '%s' plugin does not apply control vectors for this "
"model", cfg_.control_vector.c_str(), plugins_.arch_plugin.c_str());
@@ -1318,6 +1514,46 @@ int Engine::declare() {
drafter_name_ = p0.drafter_name;
drafter_.name = drafter_name_.c_str();
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
/* A tree drafter (rad_drafter_tree): its parents plane rides with the proposal. */
tree_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && p0.drafter_tree;
tree_parents_ = tree_ ? p0.drafter_parents : 0;
/* --draft-short-from auto: a chain keeps its own block, a tree runs its short block from two
* decoding sequences on. Its nodes are verify rows every drafting sequence pays for, which a
* wide tree's extra nodes repay at one sequence and not at many. */
short_from_ = cfg_.draft_short_from >= 0 ? cfg_.draft_short_from : (tree_ ? 2 : 0);
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && short_from_ > 0
? p0.drafter_short_block : 0;
if (cfg_.draft_short_from > 0 && drafter_.kind == RAD_DRAFT_NONE)
RAD_WARN("--draft-short-from %lld: this deployment runs no drafter, so there is no block "
"to shorten", (long long)cfg_.draft_short_from);
else if (cfg_.draft_short_from > 0 && !drafter_short_)
RAD_WARN("--draft-short-from %lld: '%s' %s", (long long)cfg_.draft_short_from,
drafter_name_.c_str(),
drafter_.kind == RAD_DRAFT_BLOCK ? "declares no shorter block, so it keeps its own"
: "is a serial head, which proposes no block");
if (drafter_short_ && tree_)
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
"row(s), a tree of %lld node(s) over it", (long long)short_from_,
drafter_name_.c_str(), (long long)drafter_short_,
(long long)std::min<int64_t>(drafter_.depth, drafter_short_ - 1));
else if (drafter_short_)
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
"row(s), %lld token(s)", (long long)short_from_,
drafter_name_.c_str(),
(long long)drafter_short_,
(long long)(drafter_short_ - ((drafter_.block > 0 ? drafter_.block
: drafter_.depth + 1) -
drafter_.depth)));
if (tree_)
RAD_INFO("speculation: '%s' proposes a tree of %d node(s); each verify follows the deepest "
"path the target agrees with, and that path's K and V move into place",
drafter_.name, drafter_.depth);
if (cfg_.spec_ngram > 0 && drafter_.kind != RAD_DRAFT_NONE) {
RAD_ERR("--spec-ngram drafts by prompt lookup alone, and this container declares the draft "
"head '%s'; serve it with --num-speculative-tokens N, where prompt lookup fills in "
"for the sequences the head declines", drafter_.name);
return RAD_E_INVAL;
}
if (drafter_.kind != RAD_DRAFT_NONE) {
/* A zero proposal handle means the sampler's token buffer: the head's logits go through
* the ordinary sampler chain. */
@@ -1362,7 +1598,7 @@ static constexpr int64_t kArenaGuard = 1ll << 20;
void Engine::probe_arena_levels() {
for (auto& r : ranks_) r->arena_levels.clear();
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (!pb.shape_probe_ok) {
RAD_INFO("activation arena: not lent -- the '%s' plugin does not declare at a smaller step "
"size (RadArchProbe::shape_probe_ok)", plugins_.arch_plugin.c_str());
@@ -1520,6 +1756,10 @@ int Engine::plan() {
rad_dev_props(r->device, &props);
f.capacity = props.vram_bytes;
f.free = props.vram_free;
/* Unified memory: the pinned host pool is the same RAM as the card, so the
* budget charges it against the one ledger. */
f.unified = props.unified != 0;
f.host_pinned = f.unified ? cfg_.host_pool_mib * ((int64_t)1 << 20) : 0;
/* On integrated graphics an eighth of host memory stays the host's, on top of the free
* figure's own bound (core/device/hip.cpp), so the OS is not driven to reclaim and
* kill. */
@@ -1546,9 +1786,22 @@ int Engine::plan() {
* memory, and the real pool does not exist yet. */
KVManager probe;
host_arenas += arena_host_bytes(r->program);
probe.set_drafter_window_snapshot(drafter_window_snap(r->program));
if (declare_ring_windows(probe, r->program) == RAD_OK &&
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
ck_slot += probe.checkpoint_bytes();
/* The budget must see the streamed plan before it sizes the pool: a streamed group's
* ceiling is max(ring, one layer of its context), not its whole cache
* (docs/KV-STREAMING.md §4.1). */
RAD_TRY(kvstream_cap_probe(probe, cfg_, r->program, ctx));
/* No prefix-cache entry holding a streamed group can be demoted (its mirror is its only
* cold copy), so the host tier would be pinned and never used: turned off before
* the tables and the checkpoint store are sized. */
if (const int64_t off = kvstream_prefix_host_off(cfg_)) {
RAD_INFO("a streamed KV group has no host cache: --prefix-cache-mib %lld is off, "
"since no entry holding the group could be demoted",
(long long)off);
}
f.kv_ceiling = probe.ceiling(ctx);
f.kv_fixed = probe.fixed_bytes();
/* One --max-model-len sequence's pool, as the inverse of the real plan: its
@@ -1577,16 +1830,21 @@ int Engine::plan() {
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
/* The KV tiers' copy staging, built by TierExec::device_init on the first copy out.
* The cached groups are settled later, so every paged group is counted (an upper
* bound). */
* bound), each with the blocks an entry at the lcm of their block sizes holds
* (PrefixCache::entry_groups). */
if (cfg_.prefix_cache_mib > 0) {
int64_t entry = 0, bs = 0;
int ng = 0;
for (size_t g = 0; g < r->program.kv_groups.size(); ++g) {
const KVGroupPlan* p = probe.plan((int32_t)g);
if (!p || !p->paged() || p->bytes_per_block <= 0) continue;
entry += p->bytes_per_block;
bs = bs > 0 ? std::min<int64_t>(bs, p->block_size) : p->block_size;
++ng;
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
bs = bs > 0 ? std::lcm<int64_t>(bs, p->block_size) : p->block_size;
}
for (size_t g = 0; g < r->program.kv_groups.size() && bs > 0; ++g) {
const KVGroupPlan* p = probe.plan((int32_t)g);
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
entry += p->bytes_per_block * (bs / p->block_size);
ng += (int)(bs / p->block_size);
}
const int64_t tier = TierExec::device_bytes(entry, ng, TierExec::sizes(entry, ctx, bs));
f.staging += tier;
@@ -1620,6 +1878,38 @@ int Engine::plan() {
for (VramFacts& f : facts) f.held_out = cvec_bytes;
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
ngram_device, ngram_host, ck_store + host_arenas));
/* --draft-expert-placement host: the drafter's experts are pinned in the host pool before
* the strategy runs, so they leave the elastic plane the card must hold and the pool must
* have room for them on top of the trunk's spill. The pool grows here, before the split,
* so a drafter fits beside a trunk that already fills the card. */
if (cfg_.draft_expert_placement == "host") {
const int64_t MiB = (int64_t)1 << 20;
int64_t draft_max = 0;
for (const WeightFootprint& wf : wfs) draft_max = std::max(draft_max, wf.draft_experts);
if (draft_max == 0 && cfg_.draft_expert_placement_given) {
RAD_ERR("--draft-expert-placement host: this model declares no draft head with "
"routed experts");
return RAD_E_INVAL;
}
if (draft_max > 0) {
/* The pool grows by the drafter's bytes, and each rank's floor is recomputed
* against that room with the drafter out of the plane the card places. */
const int64_t add = align_up(draft_max, MiB) / MiB;
cfg_.host_pool_mib += add;
for (size_t i = 0; i < facts.size(); ++i) {
int64_t room = cfg_.host_pool_mib * MiB;
if (cfg_.weights_disk_tier)
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
facts[i].expert_floor = expert_vram_floor_draft_hosted(
wfs[i], std::max<int64_t>(room - align_up(wfs[i].draft_experts, MiB), 0));
facts[i].experts = std::max<int64_t>(wfs[i].experts - wfs[i].draft_experts, 0);
}
RAD_INFO("placement: --draft-expert-placement host pins %s of drafter experts a "
"rank in the host pool; --host-pool-mib grows by %lld to hold them, and "
"the card places only the trunk's experts",
humanb(draft_max).c_str(), (long long)add);
}
}
/* The n-gram table was counted off the card; on it, every rank holds the whole table. */
if (cfg_.ngram_resolved == TablePlacement::Vram)
for (VramFacts& f : facts) f.statics += ngram_bytes;
@@ -1683,6 +1973,7 @@ int Engine::plan() {
* its carve). */
for (size_t i = 0; i < ranks_.size(); ++i) {
probes[i] = std::make_unique<KVManager>();
probes[i]->set_drafter_window_snapshot(drafter_window_snap(ranks_[i]->program));
if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK ||
probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
@@ -1768,6 +2059,28 @@ int Engine::plan() {
in.profile = file_->profile();
in.n_profile = (int64_t)file_->header().prof_count;
}
/* --expert-profile replaces the container's activation profile, which is prefill-heavy
* while decode-hot experts differ (--expert-pin-top keeps them resident). Loaded once, at
* the first rank's plan, so every rank ranks the same way. */
if (!cfg_.expert_profile.empty()) {
if (expert_profile_.empty() && ri == 0) {
int32_t trunk = -1;
const int pr = xs_profile_load(cfg_.expert_profile, &expert_profile_, &trunk);
if (pr < 0) return pr;
/* A profile from another model would rank its layers onto this one's. */
if (trunk >= 0 && trunk != (int32_t)meta_.n_layers) {
RAD_ERR("--expert-profile: %s counts %d trunk layers and this model has %d: "
"it was recorded on another model", cfg_.expert_profile.c_str(),
(int)trunk, (int)meta_.n_layers);
expert_profile_.clear();
return RAD_E_INVAL;
}
}
if (!expert_profile_.empty()) {
in.profile = expert_profile_.data();
in.n_profile = (int64_t)expert_profile_.size();
}
}
in.container = file_ != nullptr;
in.host_backend = device_is_host();
Planner planner(in);
@@ -1789,7 +2102,8 @@ int Engine::plan() {
humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()),
r->plan.forced_host_used > 0
? fmt("the host pool holds the %s the placement flags put there (the token "
"embedding, the encoder towers) beside the weights placed in it",
"embedding, the encoder towers, the drafter's experts) beside the "
"weights placed in it",
humanb(r->plan.forced_host_used).c_str())
: std::string());
}
@@ -1833,10 +2147,10 @@ struct LoadRun {
/* ================================================================== the relayout pool
*
* Weights the loader must rearrange (spec §4.3): the resolved kernel stores something other than
* the canonical planes (a fragment order, a per-row scale tail), or the declaration widens bf16 to
* f32. The sweep copies the weight's planes into a host input; once all bytes arrive, a worker
* produces the stored form, directly into its host pool slot or, for VRAM, through the worker's
* pinned bounce buffers.
* the canonical planes (a fragment order, a per-row scale tail), or the declaration converts bf16
* to f32, or f32 to bf16. The sweep copies the weight's planes into a host input; once all bytes
* arrive, a worker produces the stored form, directly into its host pool slot or, for VRAM,
* through the worker's pinned bounce buffers.
*
* It must keep pace with the disk (Qwen3.8-27B-FP8 rearranges 24 GiB of 29 per load; one thread
* runs at a fraction of 7 GB/s), so it is a thread pool and the sweep only reads. The copies out
@@ -2173,8 +2487,8 @@ private:
const int fs = s.fill(s.in);
if (fs < 0) return fs;
}
/* Stored as read (only reached by a weight with no sweep). */
if (w.identity && !w.widen) {
/* Stored as read (only reached by a weight with no sweep, no dtype conversion). */
if (w.identity && !w.widen && !w.narrow) {
const int64_t n = w.stored_bytes;
if (!s.dev) { std::memcpy(s.dst, s.in, (size_t)n); return RAD_OK; }
const int us = b.upload(s.dst, s.in, n, s.device);
@@ -2202,11 +2516,15 @@ private:
int st = RAD_OK;
const char* who = "the loader";
if (w.widen) {
/* Exact: every bf16 and f16 value is representable in f32. */
if (w.widen || w.narrow) {
/* Exact: every bf16 and f16 value is representable in f32, and f32 rounds to bf16 to
* nearest even. */
const int64_t cnt = w.sel_rows[0] * w.sel_cols[0];
if (cnt * 4 != n) st = RAD_E_SHAPE;
else for (int64_t e = 0; e < cnt; ++e) ((float*)out)[e] = rad_load_f32(pt[0].data, pt[0].dtype, e);
const int64_t esz = (int64_t)rad_dtype_bytes(w.stored_dtype, 1);
if (cnt * esz != n) st = RAD_E_SHAPE;
else for (int64_t e = 0; e < cnt; ++e)
rad_store_f32(out, w.stored_dtype, e,
rad_load_f32(pt[0].data, pt[0].dtype, e));
} else {
const Resolved& r = s.prog->ops[(size_t)w.lay_op].bands[(size_t)w.lay_band].dom[w.lay_dom];
const RadKernelInfo* ki = r.row->info;
@@ -2669,8 +2987,10 @@ int Engine::load_weights() {
RAD_ERR("rank %d: '%s' was placed on the %s tier, which reads the container where "
"it lies, and its stored form is not the container's (%s)", r->index,
w.name.c_str(), tier_name(w.tier),
w.widen ? "widened at load" : w.identity ? "a shard of it"
: w.layout_tag.c_str());
w.widen ? "widened at load"
: w.narrow ? "narrowed at load"
: w.identity ? "a shard of it"
: w.layout_tag.c_str());
return RAD_E_STATE;
}
@@ -2787,7 +3107,8 @@ int Engine::load_weights() {
total += sh[k].dense_bytes();
}
sw.in_bytes = in_bytes;
if (w.identity && !w.widen && sh[0].dense_bytes() != w.stored_bytes) {
if (w.identity && !w.widen && !w.narrow &&
sh[0].dense_bytes() != w.stored_bytes) {
RAD_ERR("rank %d: '%s': this rank's share is %lld bytes and the slot %lld",
r->index, w.name.c_str(), (long long)sh[0].dense_bytes(),
(long long)w.stored_bytes);
@@ -2809,7 +3130,7 @@ int Engine::load_weights() {
* by plane for the relayout pool, which writes the slot. */
int32_t stage = -1;
int64_t in_bytes = 0;
if (!w.identity || w.widen) {
if (!w.identity || w.widen || w.narrow) {
stage = (int32_t)staged.size();
staged.emplace_back();
StagedWeight& sw = staged.back();
@@ -2951,22 +3272,50 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) {
int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20);
for (const auto& r : ranks_) still += arena_host_bytes(r->program);
std::string limit;
int64_t room = lockable_bytes(still, host_headroom_bytes(), &limit);
if (!device_is_host()) {
bool lifted = false;
if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) {
int64_t pinned = 0, mapped = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
const int64_t left = std::max<int64_t>(cap - pinned - mapped - still, 0);
if (left < room) {
room = left;
limit = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s "
"and still pins %s", humanb(cap).c_str(),
humanb(pinned + mapped).c_str(), humanb(still).c_str());
/* The fewest snapshots the store means to hold, in bytes: the count below which prefix reuse
* is not worth the pinning. It is what the reserve below must not decide away, and it scales
* with the model's own state -- any hybrid's linear layers, any KV encoding's mirror -- since
* it is measured from this rank's slot and the host's own spare memory. */
const int64_t floor_slots =
std::min<int64_t>(checkpoint_slots_want(*pol, cfg_.max_seqs, ctx, interval),
kCheckpointSlotsFloor);
const int64_t floor_bytes =
slot > INT64_MAX / std::max<int64_t>(floor_slots, 1) ? INT64_MAX : floor_slots * slot;
const int64_t asked = host_headroom_bytes();
int64_t margin = asked;
std::string limit, gave_way;
/* What the host can pin with `marg` held free: spare memory (MemAvailable and every memory
* cgroup), then the driver's own pin cap. Both are the host's own measurement, so a wider
* mirror, a bigger pool or a larger slot never needs a second rule here. */
auto room_with = [&](int64_t marg, std::string* why) {
int64_t r = lockable_bytes(still, marg, why);
if (!device_is_host()) {
bool lifted = false;
if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) {
int64_t pinned = 0, mapped = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
const int64_t left = std::max<int64_t>(cap - pinned - mapped - still, 0);
if (left < r) {
r = left;
*why = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s "
"and still pins %s", humanb(cap).c_str(),
humanb(pinned + mapped).c_str(), humanb(still).c_str());
}
}
}
return r;
};
int64_t room = room_with(margin, &limit);
if (const int64_t keep = host_reserve_for_floor(floor_bytes, room, margin); keep < margin) {
/* The host has the bytes, but the reserve stood between them and a store that works.
* Take back exactly the shortfall and say so; a host that cannot pin the floor even
* then still gets the honest warning below. */
const int64_t wider = room_with(keep, &limit);
gave_way = fmt("; the host reserve gave back %s of its %s for the floor of %lld "
"snapshot(s), holding %s", humanb(margin - keep).c_str(),
humanb(asked).c_str(), (long long)floor_slots, humanb(keep).c_str());
room = wider;
}
const int64_t total = meminfo_bytes("MemTotal");
const int64_t share = total > 0 ? total / 8 : room;
@@ -2986,19 +3335,19 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) {
else if (c.bound == CheckpointSlots::Bound::Room)
bound = fmt("; %lld wanted, held to what the host can pin: %s", (long long)c.want,
limit.c_str());
decide("--checkpoint-slots", std::to_string(c.slots), need + bound);
decide("--checkpoint-slots", std::to_string(c.slots), need + bound + gave_way);
if (c.slots == 0) {
RAD_WARN("checkpoint slots: auto finds no room for one %s snapshot of %s (%s), so every "
"prefix hit on this model prefills from the start. Free host memory, or lower "
"--host-pool-mib or --prefix-cache-mib", what, humanb(slot).c_str(),
limit.c_str());
RAD_WARN("checkpoint slots: the host cannot pin one %s snapshot of %s: %s%s. Every prefix "
"hit on this model prefills from the start. Free host memory, or lower "
"--host-pool-mib, --prefix-cache-mib or --host-headroom-mib", what,
humanb(slot).c_str(), limit.c_str(), gave_way.c_str());
return RAD_OK;
}
const std::string line =
fmt("checkpoint slots: auto: %lld %s snapshot(s) of %s in pinned host memory (%s), none of "
"it on the card; %s%s", (long long)c.slots, what, humanb(slot).c_str(),
humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str());
if (c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str());
"it on the card; %s%s%s", (long long)c.slots, what, humanb(slot).c_str(),
humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str(), gave_way.c_str());
if (c.slots < floor_slots || c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str());
else RAD_INFO("%s", line.c_str());
return RAD_OK;
}
@@ -3014,6 +3363,14 @@ int Engine::configure_kv() {
"block and the linear-state chunk), so a checkpoint is a legal chunk split",
(long long)geo_.quantum)
: std::string("the model keeps no linear state to checkpoint"));
/* KV streaming's policy, refusals and ring (kvstream/bringup.h), decided once from rank 0's
* declarations: a streamed group must be the same group on every rank. */
KVStreamSetup stream;
if (!ranks_.empty())
RAD_TRY(kvstream_configure(cfg_, cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train,
ranks_[0]->program.kv_groups, ranks_[0]->program, &stream));
if (stream.group >= 0)
for (auto& r : ranks_) r->kv.cap_resident_tokens(stream.group, stream.ring_tokens);
/* One block table serves every rank (serve() checks it), so every rank carves the same number
* of paged blocks. Under an uneven split the pools differ (more delta-net heads, or zero
* attention weights), so each rank is planned first and all are capped at the least before
@@ -3023,7 +3380,9 @@ int Engine::configure_kv() {
auto& r = ranks_[i];
LogRank lr(r->index);
RAD_TRY(declare_ring_windows(r->kv, r->program));
r->kv.set_drafter_window_snapshot(drafter_window_snap(r->program));
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
if (i == 0) drafter_snap_ = r->kv.drafter_window_snapshot();
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
/* A rank plan() re-sized for the common token count must page at least that count (same
* plan, same bytes); anything less is a broken invariant. */
@@ -3037,6 +3396,22 @@ int Engine::configure_kv() {
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
if (least < 0 || t < least) least = t;
}
/* The mirrors are checked once, before any rank pins one, against the host tiers still to be
* pinned after them: the prefix cache's, the activation arenas and, when sized already, the
* checkpoint store. */
KVStreamHostUse stream_host;
for (auto& r : ranks_) kvstream_host_add(&stream_host, r->kv);
if (stream_host.sum.host_bytes > 0) {
const int64_t MiB = (int64_t)1 << 20;
int64_t still = cfg_.prefix_cache_mib * MiB;
for (auto& r : ranks_) still += arena_host_bytes(r->program);
if (cfg_.checkpoint_slots > 0) {
int64_t slot = 0;
for (auto& r : ranks_) slot += r->kv.checkpoint_bytes();
still += slot * cfg_.checkpoint_slots;
}
RAD_TRY(kvstream_host_gate(stream_host, (int)ranks_.size(), still, host_headroom_bytes()));
}
for (auto& r : ranks_) {
LogRank lr(r->index);
RAD_TRY(rad_dev_set(r->device)); /* allocates on the current device; see plan() */
@@ -3048,7 +3423,13 @@ int Engine::configure_kv() {
(long long)least);
r->kv.cap_paged_tokens(least);
}
/* Before the carve, which refuses a streamed plan with no mirror and maps. The maps come out
* of this rank's KV pool, so the paged split sees them taken. */
const KVManager::StreamCost sc = r->kv.stream_cost();
if (sc.groups > 0)
RAD_TRY(r->kv.alloc_stream(rad_device_allocator(), r->pools.kv()));
RAD_TRY(r->kv.carve(r->pools.kv()));
if (sc.groups > 0) RAD_TRY(kvstream_fill(r->kv)); /* the maps, after the elastic pool */
/* Without virtual memory management the cache cannot lend: everything still works, but
* the expert slab never grows, which no counter shows, so log it once. */
if (r->index == 0 && !r->pools.kv().elastic())
@@ -3072,8 +3453,12 @@ int Engine::configure_kv() {
shard_off[i] = slot;
slot += ranks_[i]->kv.checkpoint_bytes();
}
/* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */
const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state";
/* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both; a block
* drafter's window rides beside a trunk's window where the engine snapshots it. */
bool linear = false;
for (const KVGroupPlan& p : ranks_[0]->kv.plans()) linear = linear || p.stateful();
const char* what = !ranks_[0]->kv.has_window_snapshot() ? "linear-state"
: linear ? "linear-state + sliding-window" : "sliding-window";
const bool sized_auto = cfg_.checkpoint_slots < 0;
if (sized_auto) RAD_TRY(size_checkpoint_store(slot, what));
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
@@ -3096,7 +3481,14 @@ int Engine::configure_kv() {
};
if (!sized) return refuse("no host has");
std::string why;
if (!lockable_room(slot * n, 0, host_headroom_bytes(), false, &why))
/* The same reserve rule the sizing used, or a count that auto could fit by giving the
* reserve back would be refused a few lines after it was chosen. */
std::string guard_why;
const int64_t want_bytes = slot * n;
const int64_t marg = host_reserve_for_floor(
want_bytes, lockable_bytes(0, host_headroom_bytes(), &guard_why),
host_headroom_bytes());
if (!lockable_room(want_bytes, 0, marg, false, &why))
return refuse("does not fit: " + why);
if (ck_store_.open(slot, slot * n) != RAD_OK)
return refuse(std::string("the host did not pin: ") + rad_dev_last_error());
@@ -3123,7 +3515,9 @@ int Engine::configure_kv() {
* sessions view reads. The flags gate only the mover, below. */
{
const bool tier_asked = cfg_.prefix_cache_mib > 0;
const std::vector<int32_t>& cg = ranks_[0]->prefix.cached_groups();
/* An entry's blocks, one group per block: a cached group whose blocks are shorter than
* the entry appears once for each of its blocks (PrefixCache::entry_groups). */
const std::vector<int32_t>& cg = ranks_[0]->prefix.entry_groups();
/* One slot holds the whole engine's entry: the groups every rank holds alike
* (rad_kv_group_replicated) once, at the front, then every rank's own shard in its own
* window. Shards can differ or be empty (uneven heads, rad_kv_group_zero). The layout is
@@ -3146,7 +3540,11 @@ int Engine::configure_kv() {
"to move. --prefix-cache-mib does nothing here.");
} else {
IdleTiers::Config tc;
tc.host_cap_bytes = cfg_.prefix_cache_mib << 20;
/* Unified memory: the host tier is the same RAM as the device tier, so the
* tiers collapse to resident -- no capacity on the host side, nothing moves. */
RadDeviceProps tprops{};
rad_dev_props(ranks_[0]->device, &tprops);
tc.host_cap_bytes = tprops.unified ? 0 : (cfg_.prefix_cache_mib << 20);
tc.entry_bytes = slot_bytes;
tc.ckpt_bytes = ck_slot_bytes;
tc.ckpt_slots = ck_store_.capacity();
@@ -3249,6 +3647,7 @@ int Engine::configure_kv() {
}
RAD_INFO("kv: %s", ranks_[0]->kv.report().c_str());
kvstream_report(stream, stream_host, (int)ranks_.size());
/* The prefix cache's report: on or off, groups covered and skipped. It names the two things
* that silently disable caching on a hybrid model: a windowed group cannot be served a prefix,
* and a linear model with no checkpoint interval replays from zero. */
@@ -3334,6 +3733,9 @@ int Engine::start() {
cfg_.tp, cfg_.tp, devs.size(), inventory.c_str());
return RAD_E_DEVICE;
}
/* The machine before the model: a refusal here costs a second, after the load it costs the
* load. */
RAD_TRY(check_configuration(devs));
RAD_TRY(read_metadata());
if (cfg_.max_ctx == 0)
@@ -3503,8 +3905,13 @@ int Engine::start() {
r->stager.n_layers(), (int)PrefillStager::lead());
}
/* The file stager, wherever a routed expert is on the file tier (static or dynamic plan;
* such a unit has no other address). */
RAD_TRY(r->fstager.init(r->program, r->plan, &r->mover));
* such a unit has no other address). Routing-aware reads take this
* rank's routing reports: the trigger runs after the layer's router on the same stream. */
RAD_TRY(r->fstager.init(r->program, r->plan, &r->mover,
[](void* ud, int32_t layer, int64_t* n) -> const int32_t* {
return ((Ctx*)ud)->route_counts_device(layer, n);
},
&r->ctx));
if (r->fstager.enabled() && r->index == 0)
RAD_INFO("file stager: %zu routed layers hold experts read from the container; each "
"pass reads a layer's (up to %s) into one of two VRAM buffers before its "
@@ -3539,8 +3946,8 @@ int Engine::start() {
const int64_t lbpb = p.layer_bytes_per_block(), stripe = p.layer_stride();
for (int64_t L = 0; L < p.n_layers; ++L) {
LoanStrip st;
st.top = (char*)p.base + L * stripe + p.n_blocks * lbpb;
st.bytes = p.n_blocks * lbpb;
st.top = (char*)p.base + L * stripe + p.pool_blocks() * lbpb;
st.bytes = p.pool_blocks() * lbpb;
st.unit_bytes = lbpb;
st.unit_tokens = p.block_size;
strips.push_back(st);