radiance 1.0.10

- Four-rank Qwen3.8-Flash-Next (PRs 14 and 16 by keptn42): the all-reduce runs fused with the
  hyper-connection's write, and with the MoE gather in front of it, on decode and verify steps on
  the exact wire. The routed experts are split in four classes, so every rank computes the same
  share; moe_gemm_q_mod4 is the new grouped GEMM. The oracle now checks moe_gemm_q on w4nl and
  w5nl containers.
- --embedding-placement and --ngram-placement, each auto | vram | ram | disk. The token embedding
  can live in the pinned host pool, read in place over the link (from PR 17 by mechkbfan). An n-gram
  table can be copied into locked RAM at load instead of read from the container (from PR 15 by
  keptn42). auto takes the fastest tier with room once every other weight is placed, and startup
  prints what it chose and why. A tier that cannot be honoured stops the start with the reason; the
  embedding on disk and the n-gram table in VRAM are refused, since nothing can serve them.
- The expert_tiered placement no longer spends the pinned host pool twice when it falls back to
  layer offload, and a lossy-wire request for a four-rank fused write is a selection miss rather
  than a startup abort.
This commit is contained in:
Deadcode committed 2026-10-05 14:01:30 +02:00
1 parent 2f56e3c477
commit e466fa07e2
56 files changed
+1804 -761

No files matched your search

+8 -6
View File
@@ -684,15 +684,17 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
* A RAD_OPD_WTAB position consumes a RUN of declared weights, so the count alone does not
* say how the list divides. The rule is EQUAL DIVISION: whatever is left after the fixed
* weight positions have taken one each is split evenly across the table positions, in
* declaration order. That is exactly right for the case tables exist for -- `moe_gemm_q`'s
* declaration order. That is exactly right for the case tables exist for -- a grouped GEMM's
* codes and scale planes are one of each per expert, always the same count.
*
* WHERE IT DOES NOT COME OUT WHOLE, THE FIRST POSITIONS TAKE ONE MORE. A grouped GEMM whose
* experts are classes by number mod C -- `moe_gemm_q_mod4` -- gives its first `n % C` classes
* one expert more than the rest, and its tables are each class's codes then its scales, so
* that is exactly the first `2 * (n % C)` positions. Any other grouping is still refused, at
* issue, by the run checks: a table that is not one contiguous run of one shape. A list
* shorter than the tables is refused here. */
* n experts are C classes by number mod C, declared class by class as a codes table and a
* scales table each, gives its first `n % C` classes one expert more than the rest -- exactly
* the positions this rule lengthens. A list grouped any other way is refused at issue: the
* plugin names each table's run there, and a run other than the one this division bound is
* refused. A bound run must also be contiguous, checked when the tables are bound before the
* first step, and its entries of one shape, checked at its first issue. A list shorter than
* the tables is refused here. */
int per_tab = 0, tab_extra = 0;
if (n_tab > 0) {
const int rest = n_w - w_max;
+27 -26
View File
@@ -57,16 +57,19 @@ static const Flag g_flags[] = {
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
{ "--host-pool-mib", "N", "pinned host tier" },
{ "--host-weights", "NAMES", "embedding tables to keep in the pinned host pool, read in place\n"
" over the link: comma-separated weight names, a trailing *\n"
" matching a prefix (token_embd.weight)" },
{ "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n"
" keeps it in the pinned host pool, read over the link in place;\n"
" auto keeps it on the card unless the KV cache could then not\n"
" hold one --max-model-len sequence. disk is refused: the lookup\n"
" writes the card's activations, which no host read can reach" },
{ "--ngram-placement", "WHERE", "auto (default) | ram | disk: where an n-gram embedding table\n"
" lives (Qwen3.8-Flash-Next: 47.7 GiB). disk reads its rows from\n"
" the container; ram copies it into locked memory at load; auto\n"
" takes ram when free memory, the memlock limit and the cgroup\n"
" allow it. vram is refused: only a host kernel reads the table" },
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
" container on disk (O_DIRECT); a routed expert is read a layer\n"
" at a time, so a step is paced by the drive" },
{ "--ngram-table", "MODE", "disk (default) or ram: where the n-gram embedding's host gather\n"
" reads its rows. ram copies the table into locked host memory\n"
" in the background from the first request and reads the copy\n"
" (Qwen3.8-Flash-Next: 47.7 GiB; needs a memlock limit that large)" },
{ "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
" so their VRAM can go to experts and a return restores\n"
" instead of re-prefilling. 0 is off. Part of it holds\n"
@@ -217,6 +220,17 @@ void config_usage(const char* argv0) {
"benchmarks do not reproduce.\n");
}
/* The four names exactly, lower case: what a table's placement costs is the operator's to state,
* so a spelling this build does not know stops the server rather than picking a tier. */
static bool parse_table_placement(const char* v, TablePlacement* out) {
if (!std::strcmp(v, "auto")) *out = TablePlacement::Auto;
else if (!std::strcmp(v, "vram")) *out = TablePlacement::Vram;
else if (!std::strcmp(v, "ram")) *out = TablePlacement::Ram;
else if (!std::strcmp(v, "disk")) *out = TablePlacement::Disk;
else return false;
return true;
}
static std::vector<std::string> split_commas(const std::string& s) {
std::vector<std::string> out;
size_t i = 0;
@@ -384,30 +398,17 @@ int config_parse(int argc, char** argv, Config* c) {
}
}
else if (S("--host-pool-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); }
else if (S("--host-weights")) {
else if (S("--embedding-placement") || S("--ngram-placement")) {
const bool emb = S("--embedding-placement");
if (!(v = need(i))) return RAD_E_INVAL;
c->host_weights.clear();
for (std::string p : split_commas(v)) {
p.erase(0, p.find_first_not_of(" \t"));
p.erase(p.find_last_not_of(" \t") + 1);
if (p.empty() || p == "*") {
RAD_ERR("--host-weights: '%s' is not a weight name", p.c_str());
return RAD_E_INVAL;
}
c->host_weights.push_back(p);
}
if (c->host_weights.empty()) {
RAD_ERR("--host-weights: no weight names in '%s'", v);
TablePlacement p;
if (!parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
return RAD_E_INVAL;
}
(emb ? c->embedding_placement : c->ngram_placement) = p;
}
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
else if (S("--ngram-table")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "disk")) c->ngram_table_ram = false;
else if (!std::strcmp(v, "ram")) c->ngram_table_ram = true;
else { RAD_ERR("--ngram-table takes disk or ram, not '%s'", v); return RAD_E_INVAL; }
}
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
else if (S("--prefix-cache-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_dir = v; }
else if (S("--prefix-cache-disk-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_disk_mib = atoll(v); }
+8 -1
View File
@@ -80,6 +80,8 @@ Engine::~Engine() {
for (auto& r : ranks_) r->ctx.shutdown();
step_state_fini();
ranks_.clear();
for (TableCopy& c : table_copies_) table_copy_free(&c);
table_copies_.clear();
rad_tools_registry().close();
}
@@ -1619,7 +1621,12 @@ std::string Engine::engine_info() const {
e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb;
e["max_num_batched_tokens"] = cfg_.max_tok;
e["placement"] = cfg_.placement;
e["host_weights"] = cfg_.host_weights;
/* What each lookup table was asked for and where it went: auto's answer is the one a
* dashboard reading this needs, and the request is the one the command line shows. */
e["embedding_placement"] = { { "asked", table_placement_name(cfg_.embedding_placement) },
{ "resolved", table_placement_name(cfg_.embedding_resolved) } };
e["ngram_placement"] = { { "asked", table_placement_name(cfg_.ngram_placement) },
{ "resolved", table_placement_name(cfg_.ngram_resolved) } };
e["prefix_cache"] = cfg_.prefix_cache;
e["checkpoint_slots"] = cfg_.checkpoint_slots;
e["deterministic"] = cfg_.deterministic;
+15
View File
@@ -28,6 +28,7 @@
#include "runtime/rank_barrier.h"
#include "text/tokenizer.h"
#include "format/radfile.h"
#include "format/table_copy.h"
#include <atomic>
#include <chrono>
@@ -44,6 +45,8 @@ struct TierPump;
struct TierJob;
struct StepSlot;
struct VramFacts; /* mem/vram_budget.h */
class Engine {
public:
explicit Engine(Config cfg);
@@ -115,6 +118,18 @@ private:
int read_checkpoint_metadata();
int declare();
int plan();
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
* (engine_bringup.cpp says how auto chooses). */
int resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
int64_t ngram_bytes, bool ngram_device);
/* --ngram-placement ram: the locked copy of the container's [src, src + n), file offset `foff`,
* made once and shared by every rank. */
int lock_table_copy(const uint8_t* src, int64_t n, int64_t foff, void** out, std::string* why);
/* The copies made, each [base, base + bytes), and the container address each one copies.
* Unlocked and unmapped in ~Engine after the ranks that read them are gone. */
std::vector<TableCopy> table_copies_;
std::vector<std::pair<const void*, void*>> table_copy_of_;
int load_weights();
int configure_kv();
/* One sampled row's worth of bookkeeping, so the step loop can map a logits row back to the
+304 -2
View File
@@ -15,6 +15,7 @@
#include "device/directio.h"
#include "format/radfile.h"
#include "format/share.h"
#include "format/table_copy.h"
#include "rad_plugin.h"
#include "mem/vram_budget.h"
#include "runtime/arena.h"
@@ -23,6 +24,7 @@
#include "text/tokenizer.h"
#include <sys/mman.h>
#include <sys/resource.h>
#include <unistd.h>
#include <cstring>
@@ -240,6 +242,261 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
}
}
/* ------------------------------------------------------------------ locked host memory */
/* WHAT EVERYTHING ELSE ON THE HOST STILL NEEDS beside a table locked whole: the process's own
* unpooled allocations, the load's staging windows and the page cache the container's hot pages
* live in. A copy that spends the last of it trades a faster gather for the kernel reclaiming
* the files this engine reads, and then for the OOM killer. */
static const int64_t kLockMargin = (int64_t)4 << 30;
/* A cgroup limit and what its members use that reclaim cannot give back: memory.current less its
* file pages (cgroup v2) or usage_in_bytes less its cache (v1), since page cache yields to a
* locked allocation and anonymous memory does not. "max" and v1's near-INT64_MAX sentinel are no
* limit. True with `room` set when `dir` holds one. */
static bool cgroup_room(const std::string& dir, bool v2, int64_t* room) {
auto read_ll = [](const std::string& f, long long* v) {
std::ifstream in(f);
std::string t;
if (!(in >> t)) return false;
char* e = nullptr;
*v = std::strtoll(t.c_str(), &e, 10);
return e && *e == '\0';
};
auto stat_ll = [](const std::string& f, const char* key, long long* v) {
std::ifstream in(f);
std::string k;
long long x = 0;
while (in >> k >> x) if (k == key) { *v = x; return true; }
return false;
};
long long lim = 0, used = 0, file = 0;
if (v2) {
if (!read_ll(dir + "/memory.max", &lim)) return false; /* "max" fails to parse */
if (!read_ll(dir + "/memory.current", &used)) return false;
(void)stat_ll(dir + "/memory.stat", "file", &file);
} else {
if (!read_ll(dir + "/memory.limit_in_bytes", &lim) || lim >= ((long long)1 << 62))
return false;
if (!read_ll(dir + "/memory.usage_in_bytes", &used)) return false;
if (!stat_ll(dir + "/memory.stat", "total_cache", &file))
(void)stat_ll(dir + "/memory.stat", "cache", &file);
}
const long long hard = used > file ? used - file : 0;
*room = lim > hard ? (int64_t)(lim - hard) : 0;
return true;
}
/* WHETHER `need` MORE BYTES CAN BE LOCKED IN HOST MEMORY, after `still` more that this process
* will allocate before the copy is made, or why not. Each limit is one a copy would otherwise meet
* part way through: RLIMIT_MEMLOCK (unless the process holds CAP_IPC_LOCK), the memory the kernel
* reports available, and every memory cgroup from the process's own up to the root it can see,
* which is the limit Docker's --memory sets and the kernel enforces by killing the process. A
* limit that cannot be read is not one; a limit that can is never guessed at. */
static bool lockable_room(int64_t need, int64_t still, std::string* why) {
long long locked_kb = 0;
unsigned long long caps = 0;
{
std::ifstream f("/proc/self/status");
std::string line;
while (std::getline(f, line)) {
(void)std::sscanf(line.c_str(), "VmLck: %lld", &locked_kb);
(void)std::sscanf(line.c_str(), "CapEff: %llx", &caps);
}
}
struct rlimit rl {};
if (!((caps >> 14) & 1) && ::getrlimit(RLIMIT_MEMLOCK, &rl) == 0 &&
rl.rlim_cur != RLIM_INFINITY && (int64_t)rl.rlim_cur < locked_kb * 1024 + need) {
*why = fmt("RLIMIT_MEMLOCK allows %s locked and the copy locks %s (Docker: --ulimit "
"memlock=-1; systemd: LimitMEMLOCK=infinity)", humanb((int64_t)rl.rlim_cur).c_str(),
humanb(need).c_str());
return false;
}
{
std::ifstream f("/proc/meminfo");
std::string line;
long long kb = -1;
while (std::getline(f, line))
if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) break;
if (kb >= 0 && kb * 1024 - still - kLockMargin < need) {
*why = fmt("%s of memory is available, %s more is still to be allocated (the pinned "
"host pools and the prefix cache's host tier), and the copy wants %s with %s "
"to spare", humanb(kb * 1024).c_str(), humanb(still).c_str(),
humanb(need).c_str(), humanb(kLockMargin).c_str());
return false;
}
}
/* /proc/self/cgroup: "0::/path" on v2, "N:memory:/path" (or a comma list naming memory) on v1.
* Each level up to the root of the hierarchy this process can see is a limit of its own. */
std::ifstream f("/proc/self/cgroup");
std::string line;
while (std::getline(f, line)) {
const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1);
if (b == std::string::npos) continue;
const std::string ctrl = line.substr(a + 1, b - a - 1);
std::string path = line.substr(b + 1);
const bool v2 = ctrl.empty();
bool memory = v2;
for (size_t i = 0; !memory && i < ctrl.size();) {
const size_t j = std::min(ctrl.find(',', i), ctrl.size());
memory = ctrl.compare(i, j - i, "memory") == 0;
i = j + 1;
}
if (!memory) continue;
const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory";
for (;;) {
const std::string dir = root + (path == "/" ? std::string() : path);
int64_t room = 0;
if (cgroup_room(dir, v2, &room) && room - still - kLockMargin < need) {
*why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
"and the copy wants %s with %s to spare", dir.c_str(),
humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
humanb(kLockMargin).c_str());
return false;
}
if (path.empty() || path == "/") break;
const size_t up = path.find_last_of('/');
path = up == 0 || up == std::string::npos ? "/" : path.substr(0, up);
}
}
return true;
}
/* --ngram-placement ram: the copy is table_copy_make's (core/format/table_copy.h); this keeps one
* a container address, shared by every rank, and frees them after the ranks in ~Engine. */
int Engine::lock_table_copy(const uint8_t* src, int64_t n, int64_t foff, 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();
TableCopy tc;
const int rc = table_copy_make(*file_, src, n, foff, &tc, why);
if (rc != RAD_OK) return rc;
RAD_INFO("placement: n-gram table copied into locked memory, %s in %.1f s",
humanb(n).c_str(),
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
table_copies_.push_back(tc);
table_copy_of_.push_back({ src, tc.base });
*out = tc.base;
return RAD_OK;
}
/* WHERE THE TWO LOOKUP TABLES GO (--embedding-placement, --ngram-placement), decided once for every
* rank before the card is split, and written into Config for the planner and the load phase.
*
* THE EMBEDDING: Auto keeps it on the card -- where every other weight a step reads lives --
* unless that leaves the split unable to hold the fixed weights, or leaves a derived KV pool
* unable to hold one --max-model-len sequence (`kv_floor`); then the pinned host pool takes it if
* --host-pool-mib can, the card's lookup reading it over the link in place. Disk is refused: the
* lookup writes the activations a card reads, which a host kernel reading the container cannot
* reach -- an architecture declares a buffer's domain, and the token embedding's is the device.
*
* THE N-GRAM TABLE: only a host kernel reads one today, so Vram is refused and the choice is
* between a locked copy in RAM and the container. Auto takes RAM when lockable_room says the
* memory, the memlock limit and every cgroup allow it after the pools still to be allocated. */
int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
int64_t ngram_bytes, bool ngram_device) {
const int64_t MiB = (int64_t)1 << 20;
int64_t emb_max = 0;
for (int64_t b : emb_bytes) emb_max = std::max(emb_max, b);
TablePlacement emb = cfg_.embedding_placement;
std::string emb_why;
if (emb == TablePlacement::Disk) {
RAD_ERR("--embedding-placement disk: the token embedding's lookup writes activations the "
"card reads, and a host kernel reading the container cannot write them -- the "
"architecture declares that buffer on the device. Use vram, ram or auto.");
return RAD_E_INVAL;
}
if (emb_max == 0) {
if (emb == TablePlacement::Ram) {
RAD_ERR("--embedding-placement ram: this model has no token embedding table that only "
"embed_lookup reads. An output head tied to the table reads it too, and would "
"stream it over the link every step.");
return RAD_E_INVAL;
}
emb = TablePlacement::Vram;
emb_why = "no table only embed_lookup reads";
} else if (emb == TablePlacement::Auto) {
VramBudget tb;
const int st = vram_budget_trial(cfg_, facts, &tb);
const bool holds = st == RAD_OK && (!tb.derived_kv || tb.kv >= kv_floor);
const bool host = cfg_.host_pool_mib * MiB >= emb_max;
if (holds) {
emb = TablePlacement::Vram;
emb_why = "the card holds it beside the other weights and a KV pool for one "
"--max-model-len sequence";
} else if (host) {
emb = TablePlacement::Ram;
emb_why = st != RAD_OK
? "the card cannot hold the other weights with it, and the pinned host pool can"
: fmt("with it on the card the KV pool is %s, short of the %s one --max-model-len "
"sequence needs, and the pinned host pool can hold it",
humanb(tb.kv).c_str(), humanb(kv_floor).c_str());
} else {
emb = TablePlacement::Vram;
emb_why = fmt("the card is short of room for it, and --host-pool-mib %lld cannot hold "
"%s either", (long long)cfg_.host_pool_mib, humanb(emb_max).c_str());
}
} else {
emb_why = "as asked";
}
cfg_.embedding_resolved = emb;
TablePlacement ng = cfg_.ngram_placement;
std::string ng_why;
if (ngram_device) {
if (ng == TablePlacement::Ram || ng == TablePlacement::Disk) {
RAD_ERR("--ngram-placement %s: a device kernel reads this model's n-gram table, so the "
"placement strategy places it with the other weights; only vram or auto apply",
table_placement_name(ng));
return RAD_E_INVAL;
}
ng = TablePlacement::Vram;
ng_why = "a device kernel reads it; placed with the other weights";
} else if (ngram_bytes == 0) {
if (ng != TablePlacement::Auto)
RAD_WARN("--ngram-placement %s: this model has no n-gram table, so there is nothing to "
"place", table_placement_name(ng));
ng = TablePlacement::Disk;
} else if (ng == TablePlacement::Vram) {
RAD_ERR("--ngram-placement vram: no loaded kernel plugin reads an n-gram table on a card "
"(embed_lookup_q has host kernels only), so it is read from host memory or the "
"container: ram or disk");
return RAD_E_INVAL;
} else if (ng == TablePlacement::Ram || ng == TablePlacement::Auto) {
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
cfg_.prefix_cache_host_mib * MiB;
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
std::string why;
const bool room = lockable_room(need, still, &why);
if (ng == TablePlacement::Ram && !room) {
RAD_ERR("--ngram-placement ram: the n-gram table (%s) cannot be locked in memory: %s",
humanb(ngram_bytes).c_str(), why.c_str());
return RAD_E_NOMEM;
}
if (ng == TablePlacement::Auto)
ng_why = room ? "the memory, the memlock limit and the cgroups allow a locked copy"
: "a locked copy does not fit: " + why;
else
ng_why = "as asked";
ng = room ? TablePlacement::Ram : TablePlacement::Disk;
} else {
ng_why = "as asked";
}
cfg_.ngram_resolved = ng;
if (emb_max > 0)
RAD_INFO("placement: token embedding (%s a rank) %s%s: %s", humanb(emb_max).c_str(),
table_placement_name(emb),
cfg_.embedding_placement == TablePlacement::Auto ? " (auto)" : "", emb_why.c_str());
if (ngram_bytes > 0 || ngram_device)
RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(),
table_placement_name(ng),
cfg_.ngram_placement == TablePlacement::Auto ? " (auto)" : "", ng_why.c_str());
return RAD_OK;
}
/* ================================================================== 2. metadata */
/* The model's metadata ONLY -- architecture id, dimensions, quantisation, vocab. Not the weights:
* which weights exist is the architecture plugin's answer, not the container's, and reading them
@@ -413,7 +670,6 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
/* A row at every token of the step and the sampler's row a sequence before them
* (core/kld.h); the KL mode has no speculation, so a sequence samples one. */
bc.max_out_rows = cfg_.kld() ? max_tok + cfg_.max_seqs : 0;
bc.ngram_table_ram = cfg_.ngram_table_ram ? 1 : 0;
return bc;
}
@@ -707,6 +963,11 @@ int Engine::plan() {
std::vector<VramFacts> facts;
facts.reserve(ranks_.size());
late_step_bytes_ = late_lazy_bytes_ = 0;
/* The placement flags' tables, per rank where they are sharded (the embedding) and once
* where they are not (the n-gram table every rank reads from the one mapping). */
std::vector<int64_t> emb_bytes;
int64_t ngram_bytes = 0, kv_floor = 0;
bool ngram_device = false;
const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
for (auto& r : ranks_) {
RAD_TRY(rad_dev_set(r->device));
@@ -744,9 +1005,23 @@ int Engine::plan() {
* already this card's even share of the static weights: declare ran once per rank
* with every dimension divided. */
WeightFootprint wf;
weight_footprint(r->program, &wf, cfg_.host_weights);
weight_footprint(r->program, &wf, TablePlacement::Vram);
f.statics = wf.statics;
f.experts = wf.experts;
emb_bytes.push_back(wf.embedding);
ngram_bytes = std::max(ngram_bytes, wf.ngram);
ngram_device = ngram_device || wf.ngram_device;
/* ONE --max-model-len SEQUENCE'S CACHE: the same groups planned for a single
* sequence, which is the least a KV pool can hold and still serve every request the
* API accepts (configure_kv warns below it). --embedding-placement auto keeps the
* table off the card only to stay above it. */
{
Config one = cfg_;
one.max_seqs = 1;
KVManager single;
if (single.plan_groups(r->program.kv_groups, one) == RAD_OK)
kv_floor = std::max(kv_floor, single.ceiling(ctx));
}
/* THE STAGING REGION IS SIZED ONLY WHERE THE ARENA LENDS ITS TOP: with no smaller level
* nothing gives the region back to the slab at decode, and a deterministic plan moves
* nothing, so neither can stage or recover what a region would cost. */
@@ -793,6 +1068,9 @@ int Engine::plan() {
late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
facts.push_back(f);
}
RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device));
if (cfg_.embedding_resolved == TablePlacement::Ram)
for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i];
VramBudget vb;
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
@@ -1812,6 +2090,30 @@ int Engine::load_weights() {
}
w.ptr = (void*)file_->data(p0);
w.host_ptr = w.ptr;
/* --ngram-placement ram: the host kernel reads the locked copy instead of the
* mapping. A copy auto chose and could not make leaves the table where it was, and
* says so; one the operator asked for refuses the start. */
if (cfg_.ngram_resolved == TablePlacement::Ram &&
is_ngram_table(r->program, (rad_weight)i)) {
void* copy = nullptr;
std::string why;
const int cs = lock_table_copy((const uint8_t*)w.ptr, n, (int64_t)p0.offset,
&copy, &why);
if (cs == RAD_OK) {
w.ptr = copy;
w.host_ptr = copy;
r->mover.publish_mapped((rad_weight)i, w.ptr);
continue; /* reported once, by lock_table_copy, and not as mapped */
}
if (cfg_.ngram_placement == TablePlacement::Ram) {
RAD_ERR("--ngram-placement ram: '%s' could not be copied into locked "
"memory: %s", w.name.c_str(), why.c_str());
return cs;
}
RAD_WARN("--ngram-placement auto: '%s' could not be copied into locked memory "
"(%s); it is read from the container", w.name.c_str(), why.c_str());
cfg_.ngram_resolved = TablePlacement::Disk;
}
/* NO READAHEAD ON A MAPPED WEIGHT. What reads one is a host kernel gathering rows
* out of it, and the only reason a weight is on this tier at all is that it is far
* too big to be resident -- so a fault is a real read from the file and the pages
+87
View File
@@ -0,0 +1,87 @@
/* table_copy.cpp -- see table_copy.h. */
#include "table_copy.h"
#include "../rad_internal.h"
#include <sys/mman.h>
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <cstring>
#include <thread>
#include <vector>
namespace rad {
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
TableCopy* out, std::string* why) {
if (!out || !why || !src || n <= 0) return RAD_E_INVAL;
*out = TableCopy{};
const size_t huge = (size_t)2 << 20;
const size_t sz = ((size_t)n + huge - 1) & ~(huge - 1);
void* m = ::mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
-1, 0);
if (m == MAP_FAILED) {
*why = fmt("mmap of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno));
return RAD_E_NOMEM;
}
(void)::madvise(m, sz, MADV_HUGEPAGE);
if (::mlock2(m, sz, MLOCK_ONFAULT) != 0) {
*why = fmt("mlock2 of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno));
::munmap(m, sz);
return RAD_E_NOMEM;
}
uint8_t* buf = static_cast<uint8_t*>(m);
/* A reader per hardware thread up to sixteen, each reading its own contiguous span in pieces of
* 64 MiB: a drive serves sixteen queued reads at full rate, and the span keeps each reader's
* reads sequential on the file. */
const int nt = (int)std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
const int64_t piece = (int64_t)64 << 20;
const int64_t span = ((n + nt - 1) / nt + (int64_t)huge - 1) & ~((int64_t)huge - 1);
std::atomic<int> err{RAD_OK};
std::vector<std::thread> rd;
for (int i = 0; i < nt; ++i) {
const int64_t lo = (int64_t)i * span, hi = std::min(n, lo + span);
if (lo >= hi) break;
rd.emplace_back([&, lo, hi] {
for (int64_t o = lo; o < hi && err.load() == RAD_OK; o += piece) {
const int64_t b = std::min(piece, hi - o);
const int rc = file.read_at(buf + o, b, foff + o);
if (rc < 0) { err.store(rc); return; }
file.drop_range(foff + o, b);
}
});
}
for (std::thread& t : rd) t.join();
bool same = err.load() == RAD_OK;
if (same) {
const int64_t probe = std::min<int64_t>(n, 4096);
same = std::memcmp(buf, src, (size_t)probe) == 0 &&
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
same = std::memcmp(buf + o, src + o, 4096) == 0;
if (!same) *why = "the copy does not match the container's mapping";
} else {
*why = fmt("reading the container failed (%s)", rad_strerror(err.load()));
}
if (!same) {
::munlock(m, sz);
::munmap(m, sz);
return RAD_E_IO;
}
out->base = m;
out->bytes = sz;
return RAD_OK;
}
void table_copy_free(TableCopy* c) {
if (!c || !c->base) return;
::munlock(c->base, c->bytes);
::munmap(c->base, c->bytes);
*c = TableCopy{};
}
} /* namespace rad */
+34
View File
@@ -0,0 +1,34 @@
/* table_copy.h -- a container table copied into locked host memory (--ngram-placement ram).
*
* A COPY IN HUGE PAGES, NOT THE MAPPING LOCKED. Faulting a container's mapping in costs a fault every
* 4 KiB page and leaves every row behind a 4 KiB translation, so a gather of scattered rows walks
* the page tables on nearly every row; an anonymous MADV_HUGEPAGE region covers thousands of rows a
* page. The region is locked as each page is first touched (MLOCK_ONFAULT), so nothing filled is
* swapped out while the rest fills; it is read from the container by parallel positional reads, the
* container's pages dropped behind them so the table is not held twice; and it is checked against
* the mapping before anyone is handed it, because a wrong offset would serve every row from the
* wrong place without an error. A host kernel reads an address no file backs as the memory it is
* (libavx's table_file), so no plugin takes part. */
#pragma once
#include "radfile.h"
#include <cstddef>
#include <cstdint>
#include <string>
namespace rad {
struct TableCopy {
void* base = nullptr;
size_t bytes = 0; /* the mapping's length: the table rounded up to 2 MiB */
};
/* Copies [src, src + n) of `file`'s mapping, which lies at file offset `foff`, into a new locked
* region. RAD_OK with `out` filled, or a refusal with `why` saying what failed and nothing held. */
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
TableCopy* out, std::string* why);
/* Unlocks and unmaps it; a copy never made is a no-op. */
void table_copy_free(TableCopy* c);
} /* namespace rad */
+16 -4
View File
@@ -33,7 +33,10 @@ static double paged_share(const VramBudget& b) {
return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0;
}
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out) {
/* The resolver, with its three log lines behind `log`: vram_budget_trial asks the same question
* of a configuration it may not use, and a refusal printed for a split nobody takes reads as the
* startup failing. */
static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out, bool log) {
VramBudget b;
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
@@ -115,7 +118,7 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(),
humanb(-b.claimable).c_str());
RAD_ERR("%s", b.report.c_str());
if (log) RAD_ERR("%s", b.report.c_str());
if (out) *out = b;
return RAD_E_NOMEM;
}
@@ -134,7 +137,7 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
/* Not fatal: the planner will demote what does not fit and the model still serves,
* badly. Name it, because "why is this model 8x slower than it should be" has no other
* answer at startup. */
RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
"give. Every expert will stream from host memory and the KV cache has "
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
"--max-num-batched-tokens.",
@@ -234,7 +237,7 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
* because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
* context no single request can complete is a configuration error however much slack the pool
* has (core/engine_bringup.cpp, configure_kv). */
if (b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
if (log && b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
"%.1f full-length sessions. That is concurrency at length before the scheduler "
"preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
@@ -351,4 +354,13 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
return RAD_OK;
}
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out) {
return resolve(cfg, per_rank, out, true);
}
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out) {
Config c = cfg;
return resolve(c, per_rank, out, false);
}
} /* namespace rad */
+8 -1
View File
@@ -24,7 +24,9 @@
*
* THE STATIC WEIGHTS COME OFF THE TOP. Everything that is not an expert -- the attention
* projections, the norms, the embedding, the head -- has to be resident for the model to run at a
* sensible speed at all, and under tensor parallel each rank already holds its own even share of
* sensible speed at all (the one exception is a token embedding --embedding-placement puts in the
* pinned host pool, which a lookup reads a few rows of in place; weight_footprint counts it out of
* the statics then), and under tensor parallel each rank already holds its own even share of
* them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a
* share of anything: applying a ratio to the weights as a whole would let --expert-vs-cache-ratio
* 0.3 demote the attention projections to host memory to make room for a cache nothing will fill.
@@ -114,4 +116,9 @@ struct VramBudget {
* Refuses, by name and by how much, when the fixed terms alone exceed the card. */
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
/* The same split worked out on a copy of `cfg`, written nowhere and printed nowhere: for a caller
* deciding between two programs before it resolves the one it keeps (Engine::plan's table
* placement). */
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
} /* namespace rad */
+4 -4
View File
@@ -293,10 +293,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
*
* A staging slot only ever receives a unit read from the container, so sizing it off every
* class charges the host pool for classes that are never staged. The widest class is
* typically the embedding table -- its own class, gigabytes wide, and resident in VRAM for
* the whole run -- so sizing on it reserves several times that in pinned memory to receive
* a weight that never arrives, and the file tier is then refused for want of memory it
* did not need. */
* typically the embedding table -- its own class, gigabytes wide, and never on the file
* tier: in VRAM, or in the pinned host pool by --embedding-placement -- so sizing on it
* reserves several times that in pinned memory to receive a weight that never arrives, and
* the file tier is then refused for want of memory it did not need. */
int64_t widest = 0;
for (const MoveUnit& mu : plan.units) {
if (mu.tier != Tier::SSD || mu.slab_class < 0) continue;
+93 -75
View File
@@ -37,6 +37,16 @@ const char* tier_name(Tier t) {
return "?";
}
const char* table_placement_name(TablePlacement p) {
switch (p) {
case TablePlacement::Auto: return "auto";
case TablePlacement::Vram: return "vram";
case TablePlacement::Ram: return "ram";
case TablePlacement::Disk: return "disk";
}
return "?";
}
const char* site_name(Site s) {
switch (s) {
case Site::Device: return "device";
@@ -91,8 +101,7 @@ int64_t weight_bytes(const WeightInfo& w) {
/* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over
* the same program without allocating a Plan -- the budget resolver calls this before a Planner
* exists. Kept adjacent to the three so a change to any of them has this in the same diff. */
void weight_footprint(const Program& prog, WeightFootprint* out,
const std::vector<std::string>& host_weights) {
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding) {
if (!out) return;
*out = WeightFootprint{};
@@ -110,7 +119,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out,
/* build_units: a model-level weight is its own unit, everything else groups by the declared
* (layer, expert). Ordered, for the same reason build_units is. */
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
bool hosted = true; };
bool emb = false, ngram = false; };
std::map<std::pair<int32_t, int32_t>, size_t> by_group;
std::vector<U> units;
@@ -139,10 +148,11 @@ void weight_footprint(const Program& prog, WeightFootprint* out,
mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi);
/* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */
if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
/* pin_host_weights: a named model-level weight only lookups read. */
if (layer >= 0 || !host_weight_match(host_weights, wi.name) ||
!read_only_by_lookups(prog, w))
mu.hosted = false;
/* The placement flags' tables: model-level, so the unit is this one weight. */
if (layer < 0) {
mu.emb = is_embedding_table(prog, w);
mu.ngram = is_ngram_table(prog, w);
}
}
/* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off =
@@ -151,8 +161,12 @@ void weight_footprint(const Program& prog, WeightFootprint* out,
std::map<int32_t, int64_t> layer_experts;
for (const U& mu : units) {
const int64_t b = align_up(mu.bytes, RAD_ALIGN_UNIT);
/* pin_embedding moves a table out of the statics only where nothing has mapped it. */
if (mu.emb && !mu.mapped) out->embedding += b;
if (mu.ngram && mu.mapped) out->ngram += b;
if (mu.ngram && !mu.mapped) out->ngram_device = true;
if (mu.mapped) out->mapped += b;
else if (mu.hosted && mu.layer < 0) out->hosted += b;
else if (mu.emb && embedding == TablePlacement::Ram) out->hosted += b;
else if (mu.expert >= 0) { out->experts += b; layer_experts[mu.layer] += b; }
else out->statics += b;
}
@@ -244,6 +258,14 @@ void Planner::pin_mapped(const Program& prog, Plan* p) {
mu.site = Site::Host;
mu.movable = false;
mu.reason = "no device kernel for its op; read from the container's mapping";
/* --ngram-placement ram: the load phase copies an n-gram table out of the mapping into
* locked memory and publishes the copy, so the host kernel reads RAM instead of the file.
* Every pool still sees the mapped tier; the report shows what the copy costs. */
if (in_.config->ngram_resolved == TablePlacement::Ram && mu.layer < 0 &&
!mu.weights.empty() && is_ngram_table(prog, mu.weights.front())) {
mu.reason = "--ngram-placement ram: a locked copy in RAM, made at load";
p->ngram_copy_bytes += mu.bytes;
}
/* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping:
* a weight its kernel rearranges at load, or a shard of one, has no place in the file
* that already looks the way the kernel reads it (spec §5.1). */
@@ -521,8 +543,10 @@ struct HostFall {
int Planner::assign_all_vram(Plan* p) {
int64_t used = 0;
for (MoveUnit& mu : p->units) {
/* A MAPPED UNIT IS ALREADY PLACED and no strategy may move it: there is no device kernel
* that could read it anywhere else. Every assignment pass below begins with this line. */
/* A PREPLACED UNIT IS ALREADY PLACED and no strategy may move it: a mapped one has no
* device kernel that could read it anywhere else, and a token embedding
* --embedding-placement put in the host pool is read there in place. Every assignment pass
* below begins with this line. */
if (mu.preplaced()) continue;
mu.tier = Tier::VRAM;
mu.site = Site::Device;
@@ -665,6 +689,15 @@ int Planner::assign_expert_tiered(Plan* p) {
for (const MoveUnit& mu : p->units)
if (mu.access != RAD_ACCESS_CONDITIONAL && mu.tier == Tier::VRAM) fixed += mu.slot_bytes;
}
/* WHAT LAYER OFFLOAD ALREADY PUT IN THE HOST POOL: the dense units of the layers it spilled.
* The routed experts below are placed again whatever it did with them, but the dense units
* stay where it put them, so the expert fill spends the pool that is left and not the whole
* of --host-pool-mib a second time. */
int64_t host_spent = 0;
for (const MoveUnit& mu : p->units)
if (!mu.preplaced() && mu.access != RAD_ACCESS_CONDITIONAL &&
(mu.tier == Tier::HostPinned || mu.tier == Tier::HostPageable))
host_spent += mu.slot_bytes;
std::vector<int32_t> order;
rank_units(p, &order);
@@ -677,7 +710,7 @@ int Planner::assign_expert_tiered(Plan* p) {
* Two passes, and the second is enough: the reserve depends only on the first pass's slot
* counts, and the first pass over-counts (it had more room), so the reserve it produces is an
* upper bound. A third pass can only give slots back, never take more. */
HostFall fall{0, p->host_budget, ssd_};
HostFall fall{host_spent, p->host_budget, ssd_};
int rc = RAD_OK;
/* ONE FILL: the conditional units in rank order, at most `cap` of them resident and the rest to
@@ -695,7 +728,7 @@ int Planner::assign_expert_tiered(Plan* p) {
}
for (SlabClass& sc : p->classes) sc.n_shadow = 0;
p->unfit.clear();
fall = HostFall{0, p->host_budget, ssd_};
fall = HostFall{host_spent, p->host_budget, ssd_};
rc = RAD_OK;
for (int32_t ui : order) {
@@ -967,91 +1000,72 @@ void Planner::finish(const Program& prog, Plan* p) {
pl.reason = mu.reason;
pl.bytes = weight_bytes(prog.weights[w]);
p->totals.bytes[(int)mu.tier] += pl.bytes;
if (mu.host_forced) p->embedding_host_used += pl.bytes;
}
}
}
/* ------------------------------------------------------------------ --host-weights */
/* AN EMBEDDING TABLE THE OPERATOR NAMED goes to the pinned host pool before any strategy runs, and
* stays there. The site is DeviceZeroCopy: the host pool is mapped (Pools::configure), so the
* lookup kernel is handed the pool's device-side address and reads its M rows of n_embd over the
* link in place -- a few KiB a decode step, against a table that is the largest model-level weight
* a dense model has. Measured on Qwen3.8-27B at tp 2, 1.18 GiB a card: decode and prefill within
* noise of the table in VRAM.
*
* ONLY A LOOKUP'S WEIGHT. A GEMM operand placed this way would stream its whole shard every step,
* so a named weight any other op reads is refused rather than served slowly. And a layer unit is
* never eligible: layers belong to the offload strategies. */
bool host_weight_match(const std::vector<std::string>& list, const std::string& name) {
for (const std::string& pat : list) {
if (pat.empty()) continue;
if (pat.back() == '*') {
if (name.compare(0, pat.size() - 1, pat, 0, pat.size() - 1) == 0) return true;
} else if (pat == name) {
return true;
}
}
return false;
}
bool read_only_by_lookups(const Program& prog, rad_weight w) {
/* ------------------------------------------------------------------ the lookup tables */
bool read_only_by(const Program& prog, rad_weight w, const char* op) {
bool read = false;
for (const OpInfo& o : prog.ops)
for (rad_weight ow : o.weights)
if (ow == w) {
if (o.op.compare(0, 12, "embed_lookup") != 0) return false;
if (o.op != op) return false;
read = true;
}
return read;
}
int Planner::pin_host_weights(const Program& prog, const Config& cfg, Plan* p) const {
if (cfg.host_weights.empty()) return RAD_OK;
std::vector<int> hits(cfg.host_weights.size(), 0);
int rc = RAD_OK;
/* --embedding-placement ram: THE TOKEN EMBEDDING goes to the pinned host pool before any strategy
* runs, and stays there. The site is DeviceZeroCopy: the host pool is mapped (Pools::configure),
* so the lookup kernel is handed the pool's device-side address and reads its M rows of n_embd
* over the link in place -- a few KiB a decode step -- while the table, the largest model-level
* weight a dense model has, gives its VRAM to the KV cache. Every strategy and every VRAM total
* skips the unit through MoveUnit::preplaced(), as they skip the mapped tier, and weight_footprint
* has already counted it out of the statics with the same test, so the budget the card was split
* by is the one the planner spends. A layer unit is never one: is_embedding_table asks for a
* model-level weight, and a layer belongs to the offload strategies. */
int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) const {
if (cfg.embedding_resolved != TablePlacement::Ram) return RAD_OK;
int rc = RAD_OK, found = 0;
for (MoveUnit& mu : p->units) {
/* build_units gives a model-level weight a unit of its own: it is the unit's one weight. */
if (mu.layer >= 0 || mu.weights.empty()) continue;
if (mu.layer >= 0 || mu.weights.empty() || mu.tier == Tier::Mapped) continue;
const rad_weight w = mu.weights.front();
if (!is_embedding_table(prog, w)) continue;
++found;
const std::string& name = prog.weights[w].name;
bool named = false;
for (size_t i = 0; i < cfg.host_weights.size(); ++i)
if (host_weight_match({ cfg.host_weights[i] }, name)) { ++hits[i]; named = true; }
if (!named || mu.tier == Tier::Mapped) continue; /* mapped is further off the card */
if (!read_only_by_lookups(prog, w)) {
RAD_ERR("placement: --host-weights names '%s', which an op other than an embedding "
"lookup reads; it would stream over the link every step", name.c_str());
p->notes.push_back(fmt("--host-weights: '%s' is not only an embedding lookup's",
name.c_str()));
rc = RAD_E_INVAL;
continue;
}
if (mu.slot_bytes > p->host_budget) {
RAD_ERR("placement: --host-weights '%s' needs %s of pinned host pool and %s of "
"--host-pool-mib is left%s", name.c_str(), humanb(mu.slot_bytes).c_str(),
humanb(p->host_budget).c_str(),
RAD_ERR("placement: --embedding-placement ram: '%s' needs %s of the pinned host pool "
"and %s of --host-pool-mib is left%s", name.c_str(),
humanb(mu.slot_bytes).c_str(), humanb(p->host_budget).c_str(),
p->file_stage_reserve ? " after the file tier's staging" : "");
p->notes.push_back(fmt("--host-weights: '%s' (%s) does not fit the host pool",
name.c_str(), humanb(mu.slot_bytes).c_str()));
p->notes.push_back(fmt("--embedding-placement ram: '%s' (%s) does not fit the host "
"pool", name.c_str(), humanb(mu.slot_bytes).c_str()));
rc = RAD_E_NOMEM;
continue;
}
p->host_budget -= mu.slot_bytes;
p->host_weights_bytes += mu.slot_bytes;
p->embedding_host_bytes += mu.slot_bytes;
mu.tier = Tier::HostPinned;
mu.site = Site::DeviceZeroCopy;
mu.movable = false;
mu.host_forced = true;
mu.reason = "--host-weights; read over the link in place";
RAD_INFO("placement: '%s' (%s) kept in the pinned host pool by --host-weights",
name.c_str(), humanb(mu.bytes).c_str());
mu.reason = "--embedding-placement ram; read over the link in place";
RAD_INFO("placement: '%s' (%s) in the pinned host pool, read in place "
"(--embedding-placement %s)", name.c_str(), humanb(mu.bytes).c_str(),
cfg.embedding_placement == TablePlacement::Auto ? "auto" : "ram");
}
/* Engine::plan resolves Ram only where weight_footprint found a table with this same test,
* so an empty pass is a plan built from a different program than the budget was: a wiring
* fault, said by name rather than leaving the table on the card the budget split without it. */
if (!found) {
RAD_ERR("placement: --embedding-placement ram, and this rank's program has no model-level "
"weight that only embed_lookup reads");
p->notes.push_back("--embedding-placement ram: no token embedding table to place");
rc = RAD_E_STATE;
}
/* A NAME THAT MATCHED NOTHING is the operator's intent lost: with a derived budget the weight
* silently stays on the card. Each one is named. */
for (size_t i = 0; i < hits.size(); ++i)
if (!hits[i])
RAD_WARN("placement: --host-weights '%s' matched no model-level weight",
cfg.host_weights[i].c_str());
return rc;
}
@@ -1129,7 +1143,7 @@ int Planner::plan(Plan* out) {
}
/* NOT a RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
const int hrc = pin_host_weights(prog, cfg, out);
const int hrc = pin_embedding(prog, cfg, out);
int rc = assign(out);
enforce_op_site_agreement(prog, out);
@@ -1230,7 +1244,7 @@ std::string Plan::report(const Program& prog) const {
humanb(totals.bytes[(int)Tier::VRAM]).c_str());
s += fmt(" host pinned %12s %12s\n",
host_budget > 0 ? humanb(host_budget).c_str() : "none",
humanb(totals.bytes[(int)Tier::HostPinned] - host_weights_bytes).c_str());
humanb(totals.bytes[(int)Tier::HostPinned] - embedding_host_used).c_str());
if (totals.bytes[(int)Tier::HostPageable])
s += fmt(" host pageable %12s %12s\n", "-",
humanb(totals.bytes[(int)Tier::HostPageable]).c_str());
@@ -1250,10 +1264,14 @@ std::string Plan::report(const Program& prog) const {
s += fmt(" file staging %12s %12s (%d slots%s, pinned)\n", "-",
humanb(file_stage_reserve).c_str(), RAD_PLACE_FILE_STAGE_SLOTS,
file_windows ? fmt(" and %d read windows", RAD_PLACE_FILE_WINDOWS).c_str() : "");
/* The same, for --host-weights: out of --host-pool-mib before any strategy, read in place. */
if (host_weights_bytes)
s += fmt(" host weights %12s %12s (--host-weights, pinned, read in place)\n", "-",
humanb(host_weights_bytes).c_str());
/* The same, for --embedding-placement ram: out of --host-pool-mib before any strategy, read
* in place. And the n-gram copy, which no pool holds: locked RAM the load phase fills. */
if (embedding_host_bytes)
s += fmt(" embedding %12s %12s (--embedding-placement ram, pinned, read in place)\n",
"-", humanb(embedding_host_bytes).c_str());
if (ngram_copy_bytes)
s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, locked RAM, filled at load)\n",
"-", humanb(ngram_copy_bytes).c_str());
/* Out of the VRAM weight budget, beside the residents and not among them: the two buffers a
* routed layer's file-tier experts are read into, each sized to the layer that puts the most
* there. */
+35 -17
View File
@@ -95,10 +95,10 @@ struct MoveUnit {
Site site = Site::Device;
int32_t slab_slot = -1;
bool movable = false; /* may the heat engine relocate it after load */
bool host_forced = false; /* --host-weights put it in the pinned pool; no strategy moves it */
bool host_forced = false; /* --embedding-placement ram put it in the pinned pool */
/* PLACED BEFORE ANY STRATEGY RAN, so every assignment pass skips it and no VRAM total counts
* it: the mapped tier (no device kernel can read it) and --host-weights. */
* it: the mapped tier (no device kernel can read it) and --embedding-placement ram. */
bool preplaced() const { return tier == Tier::Mapped || host_forced; }
const char* reason = "fits in vram"; /* a fixed string, so the report never guesses */
@@ -244,9 +244,14 @@ public:
int64_t vram_budget = 0, host_budget = 0;
int64_t file_stage_reserve = 0;
int64_t file_windows = 0; /* the read windows' part of it */
/* --host-weights: taken out of --host-pool-mib before any strategy ran, like the file staging
* above, and reported beside it rather than among the pooled units. */
int64_t host_weights_bytes = 0;
/* --embedding-placement ram: the pool slots taken out of --host-pool-mib before any strategy
* ran, like the file staging above, and reported beside it rather than among the pooled units.
* `embedding_host_used` is the same tables' weight bytes, the unit the tier totals count in. */
int64_t embedding_host_bytes = 0;
int64_t embedding_host_used = 0;
/* --ngram-placement ram: the n-gram tables the load phase copies into locked memory. They stay
* on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM. */
int64_t ngram_copy_bytes = 0;
/* ROUTED EXPERTS ON THE FILE TIER have no address of their own: a routed layer's are read into
* one of two VRAM buffers before the layer's first expert op and published there until the next
* routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's
@@ -325,7 +330,7 @@ private:
void resolve_sites(const Program& prog);
void build_units(const Program& prog, Plan* p);
void pin_mapped(const Program& prog, Plan* p);
int pin_host_weights(const Program& prog, const Config& cfg, Plan* p) const;
int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const;
void build_classes(Plan* p);
void rank_units(Plan* p, std::vector<int32_t>* order) const;
int assign(Plan* p);
@@ -370,20 +375,33 @@ struct WeightFootprint {
int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */
int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */
int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */
int64_t hosted = 0; /* --host-weights: in the pinned host pool, never on the card */
int64_t hosted = 0; /* --embedding-placement ram: in the pinned host pool, off the card */
/* The tables the two placement flags move, wherever the buckets above count them: `embedding`
* is inside statics or hosted, `ngram` inside mapped. */
int64_t embedding = 0;
int64_t ngram = 0;
/* An n-gram table some device kernel reads, which the strategies place like any weight. No
* plugin has one today; it is what makes --ngram-placement vram mean something. */
bool ngram_device = false;
int64_t n_units = 0;
};
void weight_footprint(const Program& prog, WeightFootprint* out,
const std::vector<std::string>& host_weights = {});
/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the
* statics. Stated by every caller, so the budget and the planner cannot count it differently. */
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding);
/* Does `name` match the --host-weights list: comma-separated, a trailing '*' matching a prefix.
* One definition, because Planner::pin_host_weights and weight_footprint must agree on it or the
* budget is resolved for weights the planner then puts somewhere else. */
bool host_weight_match(const std::vector<std::string>& list, const std::string& name);
/* Is every op that reads weight `w` an embedding lookup? Only those read a few rows a step; any
* other reader (a GEMM) would stream the whole weight over the link on every step. */
bool read_only_by_lookups(const Program& prog, rad_weight w);
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
* makes a tier below the card usable for it at all; a weight a GEMM also reads -- an output head
* tied to the embedding -- would stream whole over the link every step, and is neither. One
* definition, because the budget resolver and the planner must pick the same weights. */
bool read_only_by(const Program& prog, rad_weight w, const char* op);
inline bool is_embedding_table(const Program& prog, rad_weight w) {
return read_only_by(prog, w, "embed_lookup");
}
inline bool is_ngram_table(const Program& prog, rad_weight w) {
return read_only_by(prog, w, "embed_lookup_q");
}
/* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight". The report's grouping key:
* one line per weight class rather than per weight (spec §16). */
+19
View File
@@ -103,6 +103,19 @@ static const RadOperandSpec kOpdNorm[] = {
static const RadOperandSpec kOpdAttn[] = {
{ "q", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, { "out", RAD_OPD_OUT, 0 },
};
/* A grouped GEMM's operand list in miniature: one fixed weight, then four classes of experts as
* table pairs -- codes, then scales -- with an activation operand between the first pair and the
* rest, the way `moe_gemm_q_mod4` lays its classes out. It is here for the declaration's division
* of one weight list over several table positions (tests/build_test.cpp). */
static const RadOperandSpec kOpdMoe[] = {
{ "a", RAD_OPD_IN, 0 }, { "g", RAD_OPD_WEIGHT, 0 },
{ "w", RAD_OPD_WTAB, 0 }, { "w_scale", RAD_OPD_WTAB, 0 },
{ "sorted", RAD_OPD_IN, 0 },
{ "w_1", RAD_OPD_WTAB, 0 }, { "w_1_scale", RAD_OPD_WTAB, 0 },
{ "w_2", RAD_OPD_WTAB, 0 }, { "w_2_scale", RAD_OPD_WTAB, 0 },
{ "w_3", RAD_OPD_WTAB, 0 }, { "w_3_scale", RAD_OPD_WTAB, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
/* ------------------------------------------------------------------ schemas */
static const RadParamSpec kPGemm[] = {
@@ -206,6 +219,8 @@ static const RadOpSchema kSchemas[] = {
"a peer kernel with a fallback beneath it" },
{ "t_peer_only", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm),
"a peer kernel and nothing else" },
{ "t_moe", kPTie, NELEM(kPTie), kOpdMoe, NELEM(kOpdMoe),
"one weight list over eight table operands" },
};
static const RadKernelInfo kKernels[] = {
@@ -298,6 +313,10 @@ static const RadKernelInfo kKernels[] = {
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
.constraints = kCEqM32, .n_constraints = NELEM(kCEqM32),
.init = t_init_fails, .launch = t_launch },
{ .name = "t_moe_any", .op = "t_moe", .family = "moe",
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch },
};
/* The name is a -D so that two of these can load side by side, and one of them can declare itself
+20 -13
View File
@@ -113,6 +113,20 @@ struct Band {
* planner assigns this tier where, and only where, no device kernel for the op exists at all
* (embed_lookup_q, libavx/avx_ngram.cpp, is the one such op in this tree). */
enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped = 4 };
/* WHERE A LOOKUP TABLE LIVES: the token embedding (--embedding-placement) and an n-gram embedding
* (--ngram-placement), each a model-level weight that only a row lookup reads, so a step touches M
* of its rows and never the whole table. That is what makes every tier below the card usable for
* it, and why the operator gets to choose.
*
* Vram resident on the card, a weight like any other.
* Ram in host memory the card or a host kernel reads in place: the embedding in the pinned
* host pool, read over the link; an n-gram table as a locked copy made at load.
* Disk read from the container on demand.
* Auto the fastest of the three that has room once every other weight is placed; Engine::plan
* decides it and writes the answer into Config, so every rank plans from one choice. */
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
const char* table_placement_name(TablePlacement p);
enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 };
/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and
@@ -614,21 +628,14 @@ struct Config {
* is a server that is correct and several orders of magnitude slow. The tier needs no directory
* of its own; the container is the file. */
bool weights_disk_tier = false;
/* --ngram-table disk|ram: where the host gather of a table too large for any card -- the n-gram
* embedding, 47.7 GiB in Qwen3.8-Flash-Next -- reads its rows. disk, the default, reads them
* from the container through a row cache and holds no more of the table than that. ram copies
* the table once into locked host memory, in the background from the first request, and reads
* the copy: a faster prefill and a few percent of throughput, for the table's size in RAM. A
* process that cannot lock that much says so and stays on disk. A deployment choice and not a
* tuning one, because only the operator knows what else the host's memory is for. */
bool ngram_table_ram = false;
std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */
/* MODEL-LEVEL WEIGHTS KEPT IN THE PINNED HOST POOL by name, comma-separated (a trailing '*'
* matches a prefix). The device kernel reads them over the link in place (DeviceZeroCopy), so
* this is for a gather -- the embedding table, of which a step reads a few rows -- and not for
* a GEMM operand. Charged to --host-pool-mib; every strategy leaves them where they are. */
std::vector<std::string> host_weights;
/* --embedding-placement and --ngram-placement, as asked (TablePlacement says what each tier
* is), and what Engine::plan resolved them to before any rank planned: never Auto. */
TablePlacement embedding_placement = TablePlacement::Auto;
TablePlacement ngram_placement = TablePlacement::Auto;
TablePlacement embedding_resolved = TablePlacement::Vram;
TablePlacement ngram_resolved = TablePlacement::Disk;
bool deterministic = false;
int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */
/* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge.
+5 -2
View File
@@ -483,9 +483,12 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip
}
RadOpdDesc d{};
if (shape(dip.args.p, dip.args.n_p, i, &d) != RAD_OK || d.rank == 0) {
/* A shape hook declines without a reason (RadShapeFn), so the geometry it declined is
* printed, the dtype with it -- a description refuses a dtype it knows no grid for. */
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. nothing could describe the logical form "
"of '%s' at this geometry, so there is nothing to invert its layout into.",
(long long)seq, oi.op.c_str(), w.name.c_str());
"of '%s' at this geometry {%s}, so there is nothing to invert its layout "
"into.", (long long)seq, oi.op.c_str(), w.name.c_str(),
oi.base.str().c_str());
return false;
}
RadTensor lg{};